diff --git a/readme.txt b/readme.txt index 3fd3181..3900f7f 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Donate link: https://scanfully.com Tags: monitoring, site health, broken links, broken media, activity log Requires at least: 6.0 Tested up to: 7.1.0 -Stable tag: 1.8.1 +Stable tag: 1.9.0 License: GPLv3 or later License URI: http://www.gnu.org/licenses/gpl-3.0.html Requires PHP: 7.4 diff --git a/scanfully.php b/scanfully.php index 72f804f..efa243d 100644 --- a/scanfully.php +++ b/scanfully.php @@ -8,7 +8,7 @@ * * @wordpress-plugin * Plugin Name: Scanfully - * Version: 1.8.1 + * Version: 1.9.0 * Plugin URI: https://scanfully.com/wp-plugin * Description: Scanfully is your favorite WordPress performance and health monitoring tool. * Author: Scanfully @@ -68,7 +68,7 @@ function Scanfully(): \Scanfully\Main { // phpcs:ignore WordPress.NamingConventi function () { // meta. define( 'SCANFULLY_PLUGIN_FILE', __FILE__ ); - define( 'SCANFULLY_VERSION', '1.8.1' ); + define( 'SCANFULLY_VERSION', '1.9.0' ); // boot. require __DIR__ . '/vendor/autoload.php'; diff --git a/src/API/FailedLoginsRequest.php b/src/API/FailedLoginsRequest.php new file mode 100644 index 0000000..784d568 --- /dev/null +++ b/src/API/FailedLoginsRequest.php @@ -0,0 +1,50 @@ +is_connected && Health\MuPlugins::changed_since_last_sync() ) { + self::schedule_health_sync(); + } + } + + /** + * Send the failed login counts. Runs on the recurring hourly schedule. + * Refreshes the access token if needed. + * + * @return void + */ + public static function send_failed_logins(): void { + self::refresh_access_token_if_needed(); + \Scanfully\Events\FailedLogins\Reporter::send(); } /** diff --git a/src/Events/AppPasswordCreated.php b/src/Events/AppPasswordCreated.php new file mode 100644 index 0000000..b0c98c0 --- /dev/null +++ b/src/Events/AppPasswordCreated.php @@ -0,0 +1,57 @@ + self::plain_text( is_scalar( $item['name'] ?? null ) ? $item['name'] : '' ), + 'app_id' => is_scalar( $item['uuid'] ?? null ) ? (string) $item['uuid'] : '', + ]; + } +} diff --git a/src/Events/AppPasswordFirstUsed.php b/src/Events/AppPasswordFirstUsed.php new file mode 100644 index 0000000..4e56ead --- /dev/null +++ b/src/Events/AppPasswordFirstUsed.php @@ -0,0 +1,95 @@ + $last_used > 0 ? gmdate( 'Y-m-d\TH:i:s\Z', $last_used ) : '', + ] + ); + } + + /** + * A check if a event should fire + * + * @param array $data The event data: user ID, the password's record. + * + * @return bool + */ + public function should_fire( array $data ): bool { + if ( ! is_array( $data[1] ?? null ) || null === self::elevated_owner( $data[0] ?? 0 ) ) { + return false; + } + + return ! self::is_rate_limited(); + } +} diff --git a/src/Events/Content/Builder.php b/src/Events/Content/Builder.php new file mode 100644 index 0000000..47c0a16 --- /dev/null +++ b/src/Events/Content/Builder.php @@ -0,0 +1,181 @@ + $data The event data, with the content as the Collector noted it. + * + * @return array + */ + private static function file_edit( array $data ): array { + $content = is_array( $data['changes']['content'] ?? null ) ? $data['changes']['content'] : []; + if ( isset( $content['stash'] ) && is_array( $content['stash'] ) ) { + $diff = ContentDiff::compare_code( (string) ( $content['stash']['old'] ?? '' ), (string) ( $content['stash']['new'] ?? '' ) ); + } else { + $diff = ContentDiff::unchanged_text( ! empty( $content['too_large'] ) ? 'too_large' : 'unavailable' ); + } + $data['changes'] = [ 'content' => $diff ]; + + return $data; + } + + /** + * The event data with names added; [] when nothing is left to send. + * + * @param string $type The event type. + * @param array $data The event data. + * + * @return array + */ + public static function resolve( string $type, array $data ): array { + switch ( $type ) { + case 'PostBulkAction': + if ( isset( $data['terms'] ) && is_array( $data['terms'] ) ) { + $terms = PostBuilder::terms( $data['terms'] ); + if ( [] !== $terms ) { + $data['terms'] = $terms; + } else { + unset( $data['terms'] ); + } + } + break; + case 'TermCreated': + if ( isset( $data['parent']['id'] ) ) { + $data['parent'] = self::term( (int) $data['parent']['id'], (string) ( $data['taxonomy'] ?? '' ) ); + } + break; + case 'SiteOptionChanged': + $data = Settings::resolve( $data ); + break; + case 'MenuCreated': + case 'MenuChanged': + case 'MenuDeleted': + $data = MenuBuilder::resolve( $type, $data ); + break; + case 'WidgetsChanged': + $data = WidgetBuilder::resolve( $data ); + break; + case 'ThemeSettingsChanged': + $data = ThemeBuilder::resolve( $data ); + break; + case 'StylesChanged': + case 'TemplateChanged': + case 'TemplateDeleted': + $data = SiteEditorBuilder::resolve( $type, $data ); + break; + case 'PluginFileEdited': + case 'ThemeFileEdited': + $data = self::file_edit( $data ); + break; + case 'TermChanged': + foreach ( [ 'old', 'new' ] as $side ) { + if ( isset( $data['changes']['parent'][ $side ]['id'] ) ) { + $data['changes']['parent'][ $side ] = self::term( (int) $data['changes']['parent'][ $side ]['id'], (string) ( $data['taxonomy'] ?? '' ) ); + } + } + break; + } + + return $data; + } + + /** + * A term by ID and name; the name is '' for none (0) or a term that no + * longer exists. + * + * @param int $term_id The term ID. + * @param string $taxonomy The taxonomy. + * + * @return array{id: int, name: string} + */ + private static function term( int $term_id, string $taxonomy ): array { + $term = $term_id > 0 ? get_term( $term_id, $taxonomy ) : null; + + return [ + 'id' => $term_id, + 'name' => $term instanceof \WP_Term ? html_entity_decode( (string) $term->name, ENT_QUOTES, 'UTF-8' ) : '', + ]; + } +} diff --git a/src/Events/Content/Limiter.php b/src/Events/Content/Limiter.php new file mode 100644 index 0000000..cbdeb00 --- /dev/null +++ b/src/Events/Content/Limiter.php @@ -0,0 +1,98 @@ + 'scanfully_term_events_per_minute', + self::KIND_SETTING => 'scanfully_settings_events_per_minute', + self::KIND_MENU => 'scanfully_menu_events_per_minute', + self::KIND_WIDGET => 'scanfully_widget_events_per_minute', + self::KIND_THEME => 'scanfully_theme_settings_events_per_minute', + self::KIND_SITE_EDITOR => 'scanfully_site_editor_events_per_minute', + ]; + + /** + * Take room for events in this minute's cap: how many of them may be + * sent now. One transient read and write per request, however many + * events it has. + * + * @param string $kind Report::KIND_POST, Report::KIND_TERM or one of the + * kinds above. + * @param int $wanted How many events the request has. + * + * @return int + */ + public static function take( string $kind, int $wanted ): int { + if ( $wanted < 1 ) { + return 0; + } + + $limit = (int) apply_filters( self::FILTERS[ $kind ] ?? 'scanfully_post_saved_events_per_minute', self::PER_MINUTE ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- The filters start with scanfully_. + if ( $limit < 1 ) { + return $wanted; + } + + $bucket = 'scanfully_' . $kind . '_events_' . (int) floor( time() / MINUTE_IN_SECONDS ); + $count = (int) get_transient( $bucket ); + $taken = max( 0, min( $wanted, $limit - $count ) ); + if ( $taken > 0 ) { + set_transient( $bucket, $count + $taken, 2 * MINUTE_IN_SECONDS ); + } + + return $taken; + } +} diff --git a/src/Events/Content/MinuteStore.php b/src/Events/Content/MinuteStore.php new file mode 100644 index 0000000..89bebf5 --- /dev/null +++ b/src/Events/Content/MinuteStore.php @@ -0,0 +1,118 @@ + $entry The entry. + * @param string $hook The job's Action Scheduler hook. + * @param array $args The job's arguments before the minute. + * + * @return bool Whether the entry was stored. + */ + public static function add( string $kind, array $entry, string $hook, array $args = [] ): bool { + $bucket = self::bucket(); + $key = str_replace( '-', '', wp_generate_uuid4() ); + if ( ! add_option( self::PREFIX . $kind . '_' . $bucket . '_' . $key, $entry, '', false ) ) { + return false; + } + + // One transient read per request; two requests that both find it + // missing schedule the job twice, which is harmless (see take()). + $marker = self::PREFIX . $kind . '_' . $bucket . '_job'; + if ( false === get_transient( $marker ) ) { + set_transient( $marker, 1, HOUR_IN_SECONDS ); + as_schedule_single_action( ( $bucket + 1 ) * MINUTE_IN_SECONDS + self::DELAY, $hook, array_merge( $args, [ $bucket ] ), 'scanfully' ); + } + + return true; + } + + /** + * Take the entries of a kind stored up to and including a minute, oldest + * first, and remove them. Earlier minutes are included so entries whose + * job never ran are not left behind. + * + * @param string $kind What the entries are about. + * @param int $bucket The minute. + * + * @return array> + */ + public static function take( string $kind, int $bucket ): array { + global $wpdb; + + $prefix = self::PREFIX . $kind . '_'; + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The entries are found by name prefix, which the options API can't do; the object cache is skipped on purpose (see the class comment). + $rows = $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s ORDER BY option_id", $wpdb->esc_like( $prefix ) . '%' ) ); + + $entries = []; + foreach ( (array) $rows as $row ) { + $name = (string) ( $row->option_name ?? '' ); + if ( 1 !== preg_match( '/^(\d+)_[a-f0-9]{32}$/', substr( $name, strlen( $prefix ) ), $match ) || (int) $match[1] > $bucket ) { + continue; + } + + // Another run of the job took it first. + if ( ! delete_option( $name ) ) { + continue; + } + + $entry = maybe_unserialize( $row->option_value ?? '' ); + if ( is_array( $entry ) ) { + $entries[] = $entry; + } + } + + delete_transient( self::PREFIX . $kind . '_' . $bucket . '_job' ); + + return $entries; + } + + /** + * The current minute. + * + * @return int + */ + public static function bucket(): int { + return (int) floor( time() / MINUTE_IN_SECONDS ); + } +} diff --git a/src/Events/Content/Overflow.php b/src/Events/Content/Overflow.php new file mode 100644 index 0000000..c37f5ac --- /dev/null +++ b/src/Events/Content/Overflow.php @@ -0,0 +1,102 @@ +> $items The items. + * @param array{id: int, name: string} $user Who changed them. + * + * @return void + */ + public static function add( string $kind, array $items, array $user ): void { + $items = array_map( + static function ( array $item ): array { + unset( $item['event'] ); + return $item; + }, + $items + ); + + MinuteStore::add( + self::store_kind( $kind ), + [ + 'user' => $user, + 'items' => $items, + ], + Controller::ACTION_SEND_OVERFLOW, + [ $kind ] + ); + } + + /** + * Action Scheduler callback: report a minute's stored items as summary + * rows, per person, action and type. + * + * @param string $kind Report::KIND_POST or Report::KIND_TERM. + * @param int $bucket The minute. + * + * @return void + */ + public static function send( string $kind, int $bucket ): void { + $by_user = []; + foreach ( MinuteStore::take( self::store_kind( $kind ), $bucket ) as $entry ) { + if ( ! is_array( $entry['items'] ?? null ) ) { + continue; + } + + $user = [ + 'id' => (int) ( $entry['user']['id'] ?? 0 ), + 'name' => (string) ( $entry['user']['name'] ?? '' ), + ]; + $who = $user['id'] . '|' . $user['name']; + + $by_user[ $who ]['user'] = $user; + foreach ( $entry['items'] as $item ) { + $by_user[ $who ]['items'][] = $item; + } + } + + foreach ( $by_user as $entry ) { + foreach ( Summary::group( $entry['items'] ?? [] ) as $group ) { + foreach ( Summary::rows( $kind, $group, true ) as $row ) { + ContentEvent::queue( $row['type'], $entry['user'], $row['data'] ); + } + } + } + } + + /** + * The MinuteStore kind of a kind of item. + * + * @param string $kind Report::KIND_POST or Report::KIND_TERM. + * + * @return string + */ + private static function store_kind( string $kind ): string { + return 'overflow_' . ( Report::KIND_TERM === $kind ? Report::KIND_TERM : Report::KIND_POST ); + } +} diff --git a/src/Events/Content/Report.php b/src/Events/Content/Report.php new file mode 100644 index 0000000..0720931 --- /dev/null +++ b/src/Events/Content/Report.php @@ -0,0 +1,138 @@ +> $items The items (see Summary). + * + * @return void + */ + public static function send( string $kind, array $items ): void { + // A site that isn't connected has nowhere to send events. + if ( [] === $items || ! Options\Controller::get_options()->is_connected ) { + return; + } + + /** + * Filters how many posts or terms of one action and type a request + * reports on rows of their own; more become one summary row. + * + * @param int $threshold The number; 10 by default. + * @param string $kind `post` or `term`. + */ + $threshold = max( 0, (int) apply_filters( 'scanfully_activity_bulk_threshold', self::THRESHOLD, $kind ) ); + + $rows = []; + $singles = []; + foreach ( Summary::group( $items ) as $group ) { + if ( count( $group ) > $threshold || self::has_light( $group ) ) { + array_push( $rows, ...Summary::rows( $kind, $group ) ); + } else { + array_push( $singles, ...$group ); + } + } + + // Summary rows first: each one covers many items. + $room = Limiter::take( $kind, count( $rows ) + count( $singles ) ); + $over = []; + foreach ( $rows as $row ) { + if ( $room > 0 ) { + --$room; + do_action( ContentEvent::hook( $row['type'] ), $row['data'] ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- The hooks start with scanfully_. + } else { + array_push( $over, ...$row['items'] ); + } + } + foreach ( $singles as $item ) { + if ( $room > 0 ) { + --$room; + do_action_ref_array( (string) $item['event']['hook'], (array) $item['event']['args'] ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- The hooks start with scanfully_. + } else { + $over[] = $item; + } + } + + if ( [] !== $over ) { + Overflow::add( $kind, $over, self::current_user() ); + } + } + + /** + * Whether a group has items that can't be reported on their own (the + * request only counted them). + * + * @param array> $group The items. + * + * @return bool + */ + private static function has_light( array $group ): bool { + foreach ( $group as $item ) { + if ( ! isset( $item['event'] ) ) { + return true; + } + } + + return false; + } + + /** + * The signed-in user, as events report it. + * + * @return array{id: int, name: string} + */ + private static function current_user(): array { + $user = wp_get_current_user(); + + return [ + 'id' => (int) $user->ID, + 'name' => ContentEvent::user_name( $user ), + ]; + } +} diff --git a/src/Events/Content/Summary.php b/src/Events/Content/Summary.php new file mode 100644 index 0000000..f5ce16e --- /dev/null +++ b/src/Events/Content/Summary.php @@ -0,0 +1,321 @@ + 'PostBulkAction', + Report::KIND_TERM => 'TermBulkAction', + Report::KIND_MEDIA => 'MediaBulkAction', + ]; + + /** + * The longest title or name kept in a summary row. + */ + public const MAX_TITLE = 200; + + /** + * The most term taxonomy IDs kept per taxonomy and side (added, removed) + * in a row about posts. + */ + private const MAX_TERM_IDS = 50; + + /** + * A title or name as summary rows keep it: plain text, cut. + * + * @param string $title The title, as WordPress stores it. + * + * @return string + */ + public static function title( string $title ): string { + $title = html_entity_decode( $title, ENT_QUOTES, 'UTF-8' ); + + return mb_strlen( $title ) > self::MAX_TITLE ? mb_substr( $title, 0, self::MAX_TITLE ) : $title; + } + + /** + * Items grouped by what happened to them: action, post type or + * taxonomy, and (for deletes) whether WordPress emptied the trash itself. + * + * @param array> $items The items. + * + * @return array>> + */ + public static function group( array $items ): array { + $groups = []; + foreach ( $items as $item ) { + $key = $item['action'] . '|' . $item['group'] . ( ! empty( $item['expired'] ) ? '|expired' : '' ); + $groups[ $key ][] = $item; + } + + return $groups; + } + + /** + * The summary rows of one group: the event type, its data and the + * items in it. + * + * @param string $kind Report::KIND_POST, Report::KIND_TERM or Report::KIND_MEDIA. + * @param array> $items The items of the group. + * @param bool $overflow Whether these were over the per-minute cap. + * + * @return array, items: array>}> + */ + public static function rows( string $kind, array $items, bool $overflow = false ): array { + if ( [] === $items ) { + return []; + } + + $chunks = array_chunk( $items, self::MAX_ITEMS_PER_ROW ); + $rows = []; + foreach ( $chunks as $index => $chunk ) { + switch ( $kind ) { + case Report::KIND_TERM: + $data = self::term_row( $chunk ); + break; + case Report::KIND_MEDIA: + $data = self::media_row( $chunk ); + break; + default: + $data = self::post_row( $chunk ); + } + if ( count( $chunks ) > 1 ) { + $data['part'] = $index + 1; + $data['parts'] = count( $chunks ); + $data['total'] = count( $items ); + } + if ( $overflow ) { + $data['overflow'] = true; + } + + $rows[] = [ + 'type' => self::TYPES[ $kind ] ?? 'PostBulkAction', + 'data' => $data, + 'items' => $chunk, + ]; + } + + return $rows; + } + + /** + * The data of a row about posts. + * + * @param array> $items The posts. + * + * @return array + */ + private static function post_row( array $items ): array { + $first = $items[0]; + $post_type = (string) $first['group']; + $object = get_post_type_object( $post_type ); + + $data = [ + 'action' => (string) $first['action'], + 'post_type' => $post_type, + 'type_label' => is_object( $object ) && isset( $object->labels->name ) ? self::title( (string) $object->labels->name ) : $post_type, + 'count' => count( $items ), + 'posts' => self::list( $items, 'title' ), + ]; + + $changed = self::changed( $items ); + if ( [] !== $changed ) { + $data['changed'] = $changed; + } + + $terms = self::terms( $items ); + if ( [] !== $terms ) { + $data['terms'] = $terms; + } + + if ( ! empty( $first['expired'] ) ) { + $data['expired'] = true; + $data['trash_days'] = defined( 'EMPTY_TRASH_DAYS' ) ? (int) EMPTY_TRASH_DAYS : 30; + } + + return $data; + } + + /** + * The data of a row about terms. + * + * @param array> $items The terms. + * + * @return array + */ + private static function term_row( array $items ): array { + $first = $items[0]; + $taxonomy = (string) $first['group']; + $object = get_taxonomy( $taxonomy ); + + $data = [ + 'action' => (string) $first['action'], + 'taxonomy' => $taxonomy, + 'label' => is_object( $object ) && isset( $object->labels->name ) ? self::title( (string) $object->labels->name ) : $taxonomy, + 'count' => count( $items ), + 'terms' => self::list( $items, 'name' ), + ]; + + $changed = self::changed( $items ); + if ( [] !== $changed ) { + $data['changed'] = $changed; + } + + if ( 'deleted' === $data['action'] ) { + $data['posts'] = array_sum( array_map( static fn( array $item ): int => (int) ( $item['posts'] ?? 0 ), $items ) ); + } + + return $data; + } + + /** + * The data of a row about files. + * + * @param array> $items The files. + * + * @return array + */ + private static function media_row( array $items ): array { + $first = $items[0]; + $data = [ + 'action' => (string) $first['action'], + 'count' => count( $items ), + 'files' => array_map( + static fn( array $item ): array => [ + 'id' => (int) $item['id'], + 'name' => (string) ( $item['name'] ?? '' ), + 'title' => (string) $item['title'], + ], + $items + ), + ]; + + $changed = self::changed( $items ); + if ( [] !== $changed ) { + $data['changed'] = $changed; + } + + // Files attached to one post at once, as the media library does. + $parents = array_unique( array_map( static fn( array $item ): int => (int) ( $item['parent']['id'] ?? 0 ), $items ) ); + if ( 'attached' === $data['action'] && 1 === count( $parents ) && isset( $first['parent'] ) ) { + $data['parent'] = $first['parent']; + } + + if ( ! empty( $first['expired'] ) ) { + $data['expired'] = true; + $data['trash_days'] = defined( 'EMPTY_TRASH_DAYS' ) ? (int) EMPTY_TRASH_DAYS : 30; + } + + return $data; + } + + /** + * Every item by ID and title (or name). + * + * @param array> $items The items. + * @param string $name The key of the title: `title` or `name`. + * + * @return array> + */ + private static function list( array $items, string $name ): array { + return array_map( + static fn( array $item ): array => [ + 'id' => (int) $item['id'], + $name => (string) $item['title'], + ], + $items + ); + } + + /** + * How many items each part changed in. + * + * @param array> $items The items. + * + * @return array + */ + private static function changed( array $items ): array { + $changed = []; + foreach ( $items as $item ) { + foreach ( (array) ( $item['changed'] ?? [] ) as $part ) { + $changed[ (string) $part ] = ( $changed[ (string) $part ] ?? 0 ) + 1; + } + } + + return $changed; + } + + /** + * The terms added to and removed from the posts, per taxonomy: term + * taxonomy IDs, which the job names. + * + * @param array> $items The posts. + * + * @return array + */ + private static function terms( array $items ): array { + $terms = []; + foreach ( $items as $item ) { + foreach ( (array) ( $item['terms'] ?? [] ) as $taxonomy => $set ) { + foreach ( [ 'added', 'removed' ] as $side ) { + foreach ( (array) ( $set[ $side ] ?? [] ) as $id ) { + $list = $terms[ $taxonomy ][ $side ] ?? []; + if ( count( $list ) < self::MAX_TERM_IDS && ! in_array( (int) $id, $list, true ) ) { + $list[] = (int) $id; + } + $terms[ $taxonomy ][ $side ] = $list; + } + } + } + } + + foreach ( $terms as $taxonomy => $set ) { + $terms[ $taxonomy ] = [ + 'added' => $set['added'] ?? [], + 'removed' => $set['removed'] ?? [], + ]; + } + + return $terms; + } +} diff --git a/src/Events/ContentEvent.php b/src/Events/ContentEvent.php new file mode 100644 index 0000000..a946849 --- /dev/null +++ b/src/Events/ContentEvent.php @@ -0,0 +1,122 @@ + $type, + 'user' => $user, + 'data' => $data, + 'stash' => '', + ]; + + if ( strlen( (string) wp_json_encode( $args ) ) > self::MAX_ARGS_LENGTH ) { + $stash = Stash::put( [ 'data' => $data ] ); + if ( '' !== $stash ) { + $args['data'] = [ 'stashed' => true ]; + $args['stash'] = $stash; + } else { + $args = self::fit_args( $args ); + } + } + + as_schedule_single_action( time(), Controller::ACTION_BUILD_CONTENT_EVENT, $args, 'scanfully' ); + } +} diff --git a/src/Events/Controller.php b/src/Events/Controller.php index b362cd0..66947d2 100644 --- a/src/Events/Controller.php +++ b/src/Events/Controller.php @@ -22,6 +22,36 @@ class Controller { */ public const ACTION_SEND_EVENT = 'scanfully_send_event'; + /** + * Action Scheduler hook name for working out what changed in a saved + * post and sending it (PostChanges\Builder). + */ + public const ACTION_BUILD_POST_EVENT = 'scanfully_build_post_event'; + + /** + * Action Scheduler hook name for naming and sending a content event: a + * permanent delete, a term change or a summary row (Content\Builder). + */ + public const ACTION_BUILD_CONTENT_EVENT = 'scanfully_build_content_event'; + + /** + * Action Scheduler hook name for reporting the posts or terms changed + * over a minute's cap as summary rows (Content\Overflow). + */ + public const ACTION_SEND_OVERFLOW = 'scanfully_send_content_overflow'; + + /** + * Action Scheduler hook name for reporting a minute of media library + * changes (MediaChanges\Batch). + */ + public const ACTION_SEND_MEDIA = 'scanfully_send_media_changes'; + + /** + * Action Scheduler hook name for reporting a minute of Font Library + * changes (SiteEditor\Fonts). + */ + public const ACTION_SEND_FONTS = 'scanfully_send_font_changes'; + /** * The events * @@ -56,6 +86,11 @@ public static function get_events(): array { */ public static function register_send_callback(): void { add_action( self::ACTION_SEND_EVENT, [ self::class, 'send_event' ], 10, 4 ); + add_action( self::ACTION_BUILD_POST_EVENT, [ PostChanges\Builder::class, 'build' ], 10, 5 ); + add_action( self::ACTION_BUILD_CONTENT_EVENT, [ Content\Builder::class, 'build' ], 10, 5 ); + add_action( self::ACTION_SEND_OVERFLOW, [ Content\Overflow::class, 'send' ], 10, 2 ); + add_action( self::ACTION_SEND_MEDIA, [ MediaChanges\Batch::class, 'send' ], 10, 1 ); + add_action( self::ACTION_SEND_FONTS, [ SiteEditor\Fonts::class, 'send' ], 10, 1 ); } /** @@ -66,7 +101,7 @@ public static function register_send_callback(): void { /** * Seconds between retries of a failed event. */ - private const SEND_RETRY_DELAY = 5 * MINUTE_IN_SECONDS; + public const SEND_RETRY_DELAY = 5 * MINUTE_IN_SECONDS; /** * Action Scheduler callback: send a scheduled event to the API. @@ -85,6 +120,31 @@ public static function register_send_callback(): void { * @throws \RuntimeException When the API did not accept the event. */ public static function send_event( string $type, array $user, array $data, int $attempt = 0 ): void { + self::deliver( + $type, + $user, + $data, + $attempt, + static function () use ( $type, $user, $data, $attempt ): void { + as_schedule_single_action( time() + self::SEND_RETRY_DELAY, self::ACTION_SEND_EVENT, [ $type, $user, $data, $attempt + 1 ], 'scanfully' ); + } + ); + } + + /** + * Send an event to the API. On a temporary failure with retries left, + * `$retry` schedules the next attempt; every failure then throws. + * + * @param string $type The event type. + * @param array $user The user data. + * @param array $data The event data. + * @param int $attempt Retry number; 0 for the first attempt. + * @param callable $retry Schedules the next attempt. + * + * @return void + * @throws \RuntimeException When the API did not accept the event. + */ + public static function deliver( string $type, array $user, array $data, int $attempt, callable $retry ): void { $options = Options\Controller::get_options(); if ( ! $options->is_connected ) { return; @@ -105,7 +165,7 @@ public static function send_event( string $type, array $user, array $data, int $ $temporary = null === $status || 401 === $status || 429 === $status || $status >= 500; if ( $temporary && $attempt < self::MAX_SEND_RETRIES ) { - as_schedule_single_action( time() + self::SEND_RETRY_DELAY, self::ACTION_SEND_EVENT, [ $type, $user, $data, $attempt + 1 ], 'scanfully' ); + $retry(); } throw new \RuntimeException( @@ -126,6 +186,285 @@ public static function send_event( string $type, array $user, array $data, int $ public static function setup_custom_events(): void { self::plugin_update_event(); self::theme_update_event(); + self::update_failed_events(); + } + + /** + * Plugins and themes whose failed update was already reported in this + * request, keyed `plugin:` or `theme:`, so an + * automatic update that fails while installing isn't reported twice. + * + * @var array + */ + private static array $reported_failures = []; + + /** + * Failed plugin, theme and core update events. + * + * Two sources, because neither sees every failure: + * - `upgrader_install_package_result` sees a plugin or theme update that + * fails while the package is installed (an incompatible package, files + * that can't be copied), for manual, WP-CLI and automatic updates. It + * doesn't see failures before that, such as a download that fails. + * - `automatic_updates_complete` has the result of every automatic update, + * including download failures, fatal error rollbacks and core updates. + * A failed manual core update has no hook with its result, so only + * automatic core updates are reported. + * + * @return void + */ + private static function update_failed_events(): void { + add_filter( 'upgrader_package_options', [ self::class, 'remember_update_item' ], 99, 1 ); + add_filter( 'upgrader_install_package_result', [ self::class, 'install_package_failed' ], 99, 2 ); + add_action( 'automatic_updates_complete', [ self::class, 'automatic_updates_failed' ], 10, 1 ); + } + + /** + * Keep the name and the version on offer of a plugin or theme that is + * about to be updated in the upgrader's hook extras: once a failed update + * has removed the old files, they can no longer be read. + * + * @param mixed $options The upgrader package options. + * + * @return mixed + */ + public static function remember_update_item( $options ) { + if ( ! is_array( $options ) || ! isset( $options['hook_extra'] ) || ! is_array( $options['hook_extra'] ) ) { + return $options; + } + + if ( isset( $options['hook_extra']['plugin'] ) ) { + $plugin = (string) $options['hook_extra']['plugin']; + $data = get_file_data( WP_PLUGIN_DIR . '/' . $plugin, [ 'Name' => 'Plugin Name' ] ); + $offers = get_site_transient( 'update_plugins' ); + + $options['hook_extra']['scanfully_old_name'] = (string) ( $data['Name'] ?? '' ); + $options['hook_extra']['scanfully_new_version'] = (string) ( $offers->response[ $plugin ]->new_version ?? '' ); + } elseif ( isset( $options['hook_extra']['theme'] ) ) { + $theme = (string) $options['hook_extra']['theme']; + $data = get_file_data( get_theme_root( $theme ) . '/' . $theme . '/style.css', [ 'Name' => 'Theme Name' ] ); + $offers = get_site_transient( 'update_themes' ); + + $options['hook_extra']['scanfully_old_name'] = (string) ( $data['Name'] ?? '' ); + $options['hook_extra']['scanfully_new_version'] = (string) ( $offers->response[ $theme ]['new_version'] ?? '' ); + } + + return $options; + } + + /** + * Report a plugin or theme update that failed while installing the + * package. Scanfully's own failed updates are reported too: the old + * version stays in place, so the event can still be sent. + * + * @param mixed $result The install result. + * @param mixed $hook_extra The upgrader hook extras. + * + * @return mixed The install result, unchanged. + */ + public static function install_package_failed( $result, $hook_extra ) { + if ( ! is_wp_error( $result ) || ! is_array( $hook_extra ) ) { + return $result; + } + + foreach ( [ 'plugin', 'theme' ] as $type ) { + if ( ! isset( $hook_extra[ $type ] ) ) { + continue; + } + + $slug = (string) $hook_extra[ $type ]; + $name = (string) ( $hook_extra['scanfully_old_name'] ?? '' ); + + self::$reported_failures[ $type . ':' . $slug ] = true; + + do_action( + 'scanfully_' . $type . '_update_failed', + [ + 'name' => '' !== $name ? $name : $slug, + 'slug' => $slug, + 'version' => (string) ( $hook_extra['scanfully_old_version'] ?? '' ), + 'new_version' => (string) ( $hook_extra['scanfully_new_version'] ?? '' ), + 'error' => self::failure_message( $result ), + ] + ); + break; + } + + return $result; + } + + /** + * Report the automatic updates that failed. + * + * @param mixed $update_results The results per type ('core', 'plugin', + * 'theme', 'translation'), each a list of + * objects with item, result, name and + * messages. + * + * @return void + */ + public static function automatic_updates_failed( $update_results ): void { + if ( ! is_array( $update_results ) ) { + return; + } + + foreach ( [ 'plugin', 'theme' ] as $type ) { + foreach ( (array) ( $update_results[ $type ] ?? [] ) as $update ) { + // WordPress itself only counts `true` as a successful plugin or theme update. + if ( ! is_object( $update ) || true === ( $update->result ?? null ) || ! is_object( $update->item ?? null ) ) { + continue; + } + + $slug = (string) ( $update->item->$type ?? '' ); + if ( '' === $slug || isset( self::$reported_failures[ $type . ':' . $slug ] ) ) { + continue; + } + self::$reported_failures[ $type . ':' . $slug ] = true; + + // The automatic updater reads names through get_plugin_data() + // and WP_Theme, which return them HTML-encoded. + $name = html_entity_decode( (string) ( $update->name ?? '' ), ENT_QUOTES, 'UTF-8' ); + do_action( + 'scanfully_' . $type . '_update_failed', + [ + 'name' => '' !== $name ? $name : $slug, + 'slug' => $slug, + 'version' => (string) ( $update->item->current_version ?? '' ), + 'new_version' => (string) ( $update->item->new_version ?? '' ), + 'error' => self::failure_message( $update->result ?? null, (array) ( $update->messages ?? [] ) ), + ] + ); + } + } + + foreach ( (array) ( $update_results['core'] ?? [] ) as $update ) { + // A core update returns the new version on success. + if ( ! is_object( $update ) || ( ! empty( $update->result ) && ! is_wp_error( $update->result ) ) ) { + continue; + } + + $item = is_object( $update->item ?? null ) ? $update->item : new \stdClass(); + do_action( + 'scanfully_core_update_failed', + [ + 'version' => (string) ( $item->current ?? $item->version ?? '' ), + 'old_version' => (string) get_bloginfo( 'version' ), + 'error' => self::failure_message( $update->result ?? null, (array) ( $update->messages ?? [] ) ), + ] + ); + } + } + + /** + * The error message of a failed update as plain text: the message of a + * WP_Error (with its detail, such as the reason a download failed), or + * else the last message the upgrader showed. Empty when there is none. + * + * @param mixed $result The update result. + * @param array $messages The upgrader's messages. + * + * @return string + */ + private static function failure_message( $result, array $messages = [] ): string { + $message = ''; + if ( is_wp_error( $result ) ) { + $message = $result->get_error_message(); + $detail = $result->get_error_data(); + if ( is_string( $detail ) && '' !== $detail ) { + $message .= ' ' . $detail; + } + } else { + foreach ( array_reverse( $messages ) as $line ) { + if ( is_string( $line ) && '' !== trim( $line ) ) { + $message = $line; + break; + } + } + } + + return trim( self::strip_paths( html_entity_decode( wp_strip_all_tags( $message ), ENT_QUOTES, 'UTF-8' ) ) ); + } + + /** + * Remove absolute server paths from an error message. WordPress puts the + * full path in the error data of file errors (such as "Could not create + * directory." or "Destination folder already exists."). Paths under a + * known WordPress directory become relative (`wp-content/plugins/akismet/`); + * any other absolute path keeps only its last part (`…/akismet.zip`). + * URLs are left alone. + * + * @param string $message The message. + * + * @return string + */ + private static function strip_paths( string $message ): string { + foreach ( self::path_roots() as $root => $label ) { + $quoted = preg_quote( $root, '#' ); + // The root followed by a separator, then the root on its own. + $message = (string) preg_replace( '#' . $quoted . '[/\\\\]#', '' === $label ? '' : $label . '/', $message ); + $message = (string) preg_replace( '#' . $quoted . '(?=[\s\'"<>(),;:]|\.(?:\s|$)|$)#', '' === $label ? './' : $label, $message ); + } + + // Any other absolute path: Unix (not part of a URL), then Windows. + $message = (string) preg_replace( '#(?/\\\\]+/)+([^\s\'"<>/\\\\]*)#', '…/$1', $message ); + $message = (string) preg_replace( '#(?/\\\\]+[/\\\\])*([^\s\'"<>/\\\\]*)#', '…/$1', $message ); + + return $message; + } + + /** + * The known WordPress directories and the relative name each one gets in + * an error message, longest path first, without a trailing separator. + * + * @return array + */ + private static function path_roots(): array { + global $wp_filesystem; + + $candidates = [ + [ WP_PLUGIN_DIR, 'wp-content/plugins' ], + [ ABSPATH, '' ], + ]; + if ( defined( 'WP_CONTENT_DIR' ) ) { + $candidates[] = [ WP_CONTENT_DIR, 'wp-content' ]; + } + if ( function_exists( 'get_theme_root' ) ) { + $candidates[] = [ get_theme_root(), 'wp-content/themes' ]; + } + if ( function_exists( 'get_temp_dir' ) ) { + $candidates[] = [ get_temp_dir(), 'tmp' ]; + } + // The file system WordPress writes through (FTP, SSH) can see the + // site under other paths. + if ( is_object( $wp_filesystem ) ) { + if ( method_exists( $wp_filesystem, 'wp_plugins_dir' ) ) { + $candidates[] = [ $wp_filesystem->wp_plugins_dir(), 'wp-content/plugins' ]; + } + if ( method_exists( $wp_filesystem, 'wp_content_dir' ) ) { + $candidates[] = [ $wp_filesystem->wp_content_dir(), 'wp-content' ]; + } + if ( method_exists( $wp_filesystem, 'abspath' ) ) { + $candidates[] = [ $wp_filesystem->abspath(), '' ]; + } + } + + $roots = []; + foreach ( $candidates as [ $path, $label ] ) { + $path = rtrim( (string) $path, '/\\' ); + // A root of "/" (an FTP account that starts in the site) would + // match everything. + if ( strlen( $path ) > 1 && ! isset( $roots[ $path ] ) ) { + $roots[ $path ] = $label; + } + } + uksort( + $roots, + static function ( string $a, string $b ): int { + return strlen( $b ) - strlen( $a ); + } + ); + + return $roots; } /** diff --git a/src/Events/CoreUpdateFailed.php b/src/Events/CoreUpdateFailed.php new file mode 100644 index 0000000..f39a4ed --- /dev/null +++ b/src/Events/CoreUpdateFailed.php @@ -0,0 +1,25 @@ + self::old_email( $data[1] ?? null ) ] + ); + } + + /** + * A check if a event should fire + * + * @param array $data The event data: user ID, the user before the update. + * + * @return bool + */ + public function should_fire( array $data ): bool { + $user = get_userdata( (int) ( $data[0] ?? 0 ) ); + if ( ! $user instanceof \WP_User || ! is_object( $data[1] ?? null ) || ! isset( $data[1]->user_email ) ) { + return false; + } + + if ( self::old_email( $data[1] ) === (string) $user->user_email ) { + return false; + } + + if ( ! self::has_elevated_capabilities( $user ) ) { + return false; + } + + return ! self::is_rate_limited(); + } + + /** + * The email address before the update. WordPress slashes it before it + * passes the old user data to `profile_update`. + * + * @param mixed $before The user before the update. + * + * @return string + */ + private static function old_email( $before ): string { + return is_object( $before ) && isset( $before->user_email ) ? (string) wp_unslash( $before->user_email ) : ''; + } +} diff --git a/src/Events/Event.php b/src/Events/Event.php index 25a6f7e..4f87935 100644 --- a/src/Events/Event.php +++ b/src/Events/Event.php @@ -74,19 +74,81 @@ private function add_listener(): void { } /** - * Get the current user + * Get the user who made the change: the signed-in user, unless the event + * names its own actor. + * + * @param array $args The arguments passed to the action. * * @return array */ - private function get_user(): array { - $current_user = wp_get_current_user(); + private function get_user( array $args ): array { + $current_user = $this->get_actor( $args ) ?? wp_get_current_user(); return [ - 'id' => $current_user->ID, - 'name' => $current_user->display_name, + 'id' => (int) ( $current_user->ID ?? 0 ), + 'name' => self::safe_display_name( $current_user ), ]; } + /** + * The user who made the change, when that isn't the signed-in user (for + * a login, WordPress hasn't set the signed-in user yet). Null to use the + * signed-in user. + * + * @param array $args The arguments passed to the action. + * + * @return object|null + */ + protected function get_actor( array $args ): ?object { + return null; + } + + /** + * A user's display name, safe to send. WordPress defaults the display + * name to the login, which is often an email address; an email address + * is replaced by the user's first and last name, or left empty, so no + * email address leaves the site. + * + * @param object $user The user (a WP_User). + * + * @return string + */ + protected static function safe_display_name( object $user ): string { + $name = trim( (string) ( $user->display_name ?? '' ) ); + if ( ! self::looks_like_email( $name ) ) { + return $name; + } + + $name = trim( ( $user->first_name ?? '' ) . ' ' . ( $user->last_name ?? '' ) ); + + return self::looks_like_email( $name ) ? '' : $name; + } + + /** + * Plain text from a value WordPress stores or returns HTML-encoded, such + * as the site title (`Barry's Shop`) or a theme name read through + * WP_Theme (`Tom & Jerry`), so a name is spelled the same in every + * event. + * + * @param mixed $value The value. + * + * @return string + */ + protected static function plain_text( $value ): string { + return html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' ); + } + + /** + * Whether a string is an email address. + * + * @param string $value The string. + * + * @return bool + */ + private static function looks_like_email( string $value ): bool { + return false !== strpos( $value, '@' ) && false !== is_email( $value ); + } + /** * The callback for the action @@ -108,15 +170,28 @@ public function listener_callback( ...$args ): void { return; } - // Schedule the API request as a background job so it does not block the current request. + $this->schedule( $this->type, $this->get_user( $args ), $this->get_post_body( $args ) ); + } + + /** + * Schedule the API request as a background job so it does not block the + * current request. + * + * @param string $type The event type. + * @param array $user The user who made the change. + * @param array $data The event data. + * + * @return void + */ + protected function schedule( string $type, array $user, array $data ): void { as_schedule_single_action( time(), Controller::ACTION_SEND_EVENT, self::fit_args( [ - 'type' => $this->type, - 'user' => $this->get_user(), - 'data' => $this->get_post_body( $args ), + 'type' => $type, + 'user' => $user, + 'data' => $data, ] ), 'scanfully' @@ -127,7 +202,7 @@ public function listener_callback( ...$args ): void { * Action Scheduler rejects jobs whose arguments are longer than this, when * encoded as JSON; the event would be lost. */ - private const MAX_ARGS_LENGTH = 8000; + protected const MAX_ARGS_LENGTH = 8000; /** * Keep the job arguments within Action Scheduler's size limit: shorten @@ -138,7 +213,7 @@ public function listener_callback( ...$args ): void { * * @return array */ - private static function fit_args( array $args ): array { + protected static function fit_args( array $args ): array { foreach ( [ 0, 1000, 200 ] as $max_length ) { if ( $max_length > 0 ) { $args['data'] = self::shorten_strings( $args['data'], $max_length ); diff --git a/src/Events/FailedLogins/Counter.php b/src/Events/FailedLogins/Counter.php new file mode 100644 index 0000000..b87f729 --- /dev/null +++ b/src/Events/FailedLogins/Counter.php @@ -0,0 +1,207 @@ + 'wrong_password', + 'invalid_username' => 'unknown_account', + 'invalid_email' => 'unknown_account', + ]; + + /** + * The username or email address WordPress is checking in this request, + * kept in memory only, for a wrong application password (whose error + * doesn't name the account). + * + * @var string + */ + private static string $attempted = ''; + + /** + * Whether this request already counted a failure. A login attempt is one + * count, also when two hooks report it (a wrong application password over + * XML-RPC); WordPress stops an XML-RPC multicall after its first failed + * login anyway. + * + * @var bool + */ + private static bool $counted = false; + + /** + * Add the hooks. + * + * @return void + */ + public static function setup(): void { + add_filter( 'authenticate', [ self::class, 'note_attempt' ], 0, 2 ); + add_action( 'wp_login_failed', [ self::class, 'note_failure' ], 10, 2 ); + add_action( 'application_password_failed_authentication', [ self::class, 'note_application_password_failure' ], 10, 1 ); + add_action( 'scanfully_options_cleared', [ Store::class, 'delete_all' ] ); + } + + /** + * Forget that this request counted a failure (tests). + * + * @return void + */ + public static function reset(): void { + self::$counted = false; + self::$attempted = ''; + } + + /** + * `authenticate`, before WordPress checks anything: note which account + * is being tried. Never the password. + * + * @param mixed $user The authentication result so far, unchanged. + * @param mixed $username The username or email address. + * + * @return mixed + */ + public static function note_attempt( $user, $username = '' ) { + self::$attempted = is_string( $username ) ? substr( $username, 0, 200 ) : ''; + + return $user; + } + + /** + * `wp_login_failed`: a login failed. + * + * @param mixed $username The username or email address that was tried. + * @param mixed $error Why it failed (WordPress 5.4 and later). + * + * @return void + */ + public static function note_failure( $username, $error = null ): void { + self::count( (string) $username, self::error_code( $error ), self::channel() ); + } + + /** + * `application_password_failed_authentication`: a wrong application + * password (REST or XML-RPC). + * + * @param mixed $error Why it failed. + * + * @return void + */ + public static function note_application_password_failure( $error ): void { + // Over the REST API the account comes from the Authorization header; + // over XML-RPC, from the login WordPress is checking. + $username = isset( $_SERVER['PHP_AUTH_USER'] ) && is_string( $_SERVER['PHP_AUTH_USER'] ) ? substr( wp_unslash( $_SERVER['PHP_AUTH_USER'] ), 0, 200 ) : self::$attempted; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Only compared with stored logins and emails, never stored or sent. + self::count( $username, self::error_code( $error ), 'app_password' ); + } + + /** + * Count a failure: the total, the reason, the way in, and the account + * for a wrong password on an account with elevated rights. + * + * @param string $username The username or email address that was tried. + * @param string $code WordPress's error code. + * @param string $channel The way in. + * + * @return void + */ + private static function count( string $username, string $code, string $channel ): void { + if ( self::$counted || ! Options\Controller::get_options()->is_connected ) { + return; + } + self::$counted = true; + + $reason = self::reason( $code ); + $counters = [ 'total', 'r_' . $reason, 'c_' . $channel ]; + if ( 'wrong_password' === $reason ) { + $user_id = self::elevated_account( $username ); + if ( $user_id > 0 ) { + $counters[] = 'u_' . $user_id; + } + } + + Store::increment( $counters, Store::hour() ); + } + + /** + * The reason a login failed, from WordPress's error code. + * + * @param string $code The error code. + * + * @return string + */ + public static function reason( string $code ): string { + return self::REASONS[ $code ] ?? 'blocked'; + } + + /** + * The way the login came in: the login page, XML-RPC, or another form + * (such as WooCommerce's My Account). + * + * @return string + */ + public static function channel(): string { + if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) { + return 'xmlrpc'; + } + + return isset( $GLOBALS['pagenow'] ) && 'wp-login.php' === $GLOBALS['pagenow'] ? 'login_page' : 'other'; + } + + /** + * The code of a login error; '' without one. + * + * @param mixed $error The error. + * + * @return string + */ + private static function error_code( $error ): string { + return $error instanceof \WP_Error ? (string) $error->get_error_code() : ''; + } + + /** + * The ID of the account a wrong password was tried on, when it has + * elevated rights; 0 otherwise. WordPress has just looked the account up + * to check the password, so this comes from the user cache. + * + * @param string $username The username or email address that was tried. + * + * @return int + */ + private static function elevated_account( string $username ): int { + if ( '' === $username ) { + return 0; + } + + $user = get_user_by( is_email( $username ) ? 'email' : 'login', $username ); + + return $user instanceof \WP_User && UserEvent::is_elevated( $user ) ? (int) $user->ID : 0; + } +} diff --git a/src/Events/FailedLogins/Reporter.php b/src/Events/FailedLogins/Reporter.php new file mode 100644 index 0000000..bad5218 --- /dev/null +++ b/src/Events/FailedLogins/Reporter.php @@ -0,0 +1,137 @@ +is_connected ) { + return; + } + + $current = Store::hour(); + $hours = Store::hours_before( $current ); + foreach ( array_keys( $hours ) as $hour ) { + if ( $hour < $current - self::KEEP_HOURS ) { + Store::delete_hour( $hour ); + unset( $hours[ $hour ] ); + } + } + if ( [] === $hours ) { + return; + } + + $payload = []; + foreach ( $hours as $hour => $counters ) { + $entry = self::hour_entry( $hour, $counters ); + if ( null !== $entry ) { + $payload[] = $entry; + } + } + + $status = [] === $payload ? 204 : ( new FailedLoginsRequest() )->send( [ 'hours' => $payload ] ); + + // Sent, or refused as data the API will never take: either way done. + // Anything else (no answer, 401 while a token refreshes, 429, a server + // error, an API that doesn't know the endpoint yet) is tried again in + // an hour. + $done = null !== $status && ( ( $status >= 200 && $status < 300 ) || 400 === $status || 413 === $status || 422 === $status ); + if ( $done ) { + foreach ( array_keys( $hours ) as $hour ) { + Store::delete_hour( $hour ); + } + } + } + + /** + * An hour's counts as the API takes them; null without a total. + * + * @param int $hour The hour. + * @param array $counters The hour's counters. + * + * @return array|null + */ + public static function hour_entry( int $hour, array $counters ): ?array { + $total = (int) ( $counters['total'] ?? 0 ); + if ( $total < 1 ) { + return null; + } + + $reasons = []; + foreach ( self::REASONS as $reason ) { + $reasons[ $reason ] = (int) ( $counters[ 'r_' . $reason ] ?? 0 ); + } + $channels = []; + foreach ( self::CHANNELS as $channel ) { + $channels[ $channel ] = (int) ( $counters[ 'c_' . $channel ] ?? 0 ); + } + + $targeted = []; + foreach ( $counters as $counter => $count ) { + if ( 1 === preg_match( '/^u_(\d+)$/', $counter, $match ) && $count > 0 ) { + $targeted[ (int) $match[1] ] = (int) $count; + } + } + arsort( $targeted ); + + $accounts = []; + foreach ( array_slice( $targeted, 0, self::MAX_ACCOUNTS, true ) as $user_id => $count ) { + $account = UserEvent::account_summary( $user_id ); + if ( null !== $account ) { + $accounts[] = array_merge( $account, [ 'count' => $count ] ); + } + } + + return [ + 'hour' => gmdate( 'Y-m-d\TH:00:00\Z', $hour * HOUR_IN_SECONDS ), + 'total' => $total, + 'reasons' => $reasons, + 'channels' => $channels, + 'accounts' => $accounts, + ]; + } +} diff --git a/src/Events/FailedLogins/Store.php b/src/Events/FailedLogins/Store.php new file mode 100644 index 0000000..042c0ec --- /dev/null +++ b/src/Events/FailedLogins/Store.php @@ -0,0 +1,161 @@ +_`, where the hour counts hours since 1970. + * A failed login adds 1 to a few counters with one atomic query, so attempts + * that arrive at the same moment during an attack lose no counts, and no row + * is read first. The rows are never autoloaded and skip the object cache on + * purpose: they are only read and removed by the hourly job, with SQL. + * + * @package Scanfully\Events\FailedLogins + */ +final class Store { + + /** + * Prefix of the counter rows. + */ + private const PREFIX = 'scanfully_lf_'; + + /** + * The hour a time falls in, in hours since 1970 (UTC). + * + * @param int|null $time A Unix time; now when null. + * + * @return int + */ + public static function hour( ?int $time = null ): int { + return (int) floor( ( $time ?? time() ) / HOUR_IN_SECONDS ); + } + + /** + * Whether a counter name is one this store keeps. + * + * @param string $counter The counter name. + * + * @return bool + */ + private static function is_counter( string $counter ): bool { + return 1 === preg_match( '/^[a-z0-9_]{1,40}$/', $counter ); + } + + /** + * Add 1 to counters of an hour, in one query. + * + * @param string[] $counters The counter names. + * @param int $hour The hour. + * + * @return bool Whether the query ran. + */ + public static function increment( array $counters, int $hour ): bool { + global $wpdb; + + $values = []; + $names = []; + foreach ( array_unique( $counters ) as $counter ) { + if ( ! self::is_counter( (string) $counter ) ) { + continue; + } + $values[] = "(%s, '1', 'no')"; + $names[] = self::PREFIX . $hour . '_' . $counter; + } + if ( [] === $names ) { + return false; + } + + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- An atomic increment the options API can't do; the placeholders are built from the fixed fragment above. + $result = $wpdb->query( + $wpdb->prepare( + "INSERT INTO {$wpdb->options} (option_name, option_value, autoload) VALUES " . implode( ', ', $values ) . ' ON DUPLICATE KEY UPDATE option_value = option_value + 1', + $names + ) + ); + // phpcs:enable + + return false !== $result; + } + + /** + * The count of one counter in an hour; 0 when there is none. + * + * @param string $counter The counter name. + * @param int $hour The hour. + * + * @return int + */ + public static function count( string $counter, int $hour ): int { + global $wpdb; + + if ( ! self::is_counter( $counter ) ) { + return 0; + } + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The counters skip the object cache on purpose (see the class comment). + return (int) $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", self::PREFIX . $hour . '_' . $counter ) ); + } + + /** + * The counters of the hours before a given hour, oldest first. + * + * @param int $before_hour The first hour not to read (the current one). + * + * @return array> Hour to counter to count. + */ + public static function hours_before( int $before_hour ): array { + global $wpdb; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The counters are found by name prefix, which the options API can't do. + $rows = $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( self::PREFIX ) . '%' ) ); + + $hours = []; + foreach ( (array) $rows as $row ) { + $name = (string) ( $row->option_name ?? '' ); + if ( 1 !== preg_match( '/^(\d+)_([a-z0-9_]+)$/', substr( $name, strlen( self::PREFIX ) ), $match ) ) { + continue; + } + $hour = (int) $match[1]; + if ( $hour >= $before_hour ) { + continue; + } + $hours[ $hour ][ $match[2] ] = (int) ( $row->option_value ?? 0 ); + } + ksort( $hours ); + + return $hours; + } + + /** + * Remove the counters of an hour. + * + * @param int $hour The hour. + * + * @return void + */ + public static function delete_hour( int $hour ): void { + global $wpdb; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The counters are removed by name prefix, which the options API can't do. + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( self::PREFIX . $hour . '_' ) . '%' ) ); + } + + /** + * Remove every counter (when the site disconnects). + * + * @return void + */ + public static function delete_all(): void { + global $wpdb; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The counters are removed by name prefix, which the options API can't do. + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( self::PREFIX ) . '%' ) ); + } +} diff --git a/src/Events/FileEdits/Collector.php b/src/Events/FileEdits/Collector.php new file mode 100644 index 0000000..697daa1 --- /dev/null +++ b/src/Events/FileEdits/Collector.php @@ -0,0 +1,282 @@ +> + */ + private static array $pending = []; + + /** + * Whether the hooks are added. + * + * @var bool + */ + private static bool $set_up = false; + + /** + * Add the hooks. + * + * @return void + */ + public static function setup(): void { + if ( self::$set_up ) { + return; + } + self::$set_up = true; + + // WordPress's own handler runs at priority 1. + add_action( 'wp_ajax_edit-theme-plugin-file', [ self::class, 'note_ajax_save' ], 0, 0 ); + add_action( 'load-plugin-editor.php', [ self::class, 'note_form_save' ], 10, 0 ); + add_action( 'load-theme-editor.php', [ self::class, 'note_form_save' ], 10, 0 ); + add_action( 'shutdown', [ self::class, 'flush' ], 1, 0 ); + } + + /** + * Forget what was noted (tests). + * + * @return void + */ + public static function reset(): void { + self::$pending = []; + } + + /** + * `wp_ajax_edit-theme-plugin-file`: the editor is about to save. + * + * @return void + */ + public static function note_ajax_save(): void { + self::note( wp_unslash( $_POST ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- WordPress checks the nonce when it saves; this only reads the file it names. + } + + /** + * `load-plugin-editor.php`, `load-theme-editor.php`: the editor's form + * without JavaScript is about to save. + * + * @return void + */ + public static function note_form_save(): void { + if ( 'POST' !== sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? '' ) ) ) { + return; + } + + self::note( wp_unslash( $_POST ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- WordPress checks the nonce when it saves; this only reads the file it names. + } + + /** + * Note the file a save names, as it is before the save. Nothing is noted + * for a file outside the plugin or theme, or for a user who may not edit + * it. + * + * @param mixed $args The posted fields: file, and plugin or theme. + * + * @return void + */ + public static function note( $args ): void { + $target = self::target( is_array( $args ) ? $args : [] ); + if ( null === $target ) { + return; + } + + foreach ( self::$pending as $pending ) { + if ( $pending['path'] === $target['path'] ) { + return; + } + } + + $target['before'] = self::read( $target['path'] ); + self::$pending[] = $target; + } + + /** + * The file a save names: its event type, plugin or theme, the path the + * editor shows and the real path; null when it can't be edited. + * + * @param array $args The posted fields. + * + * @return array|null + */ + private static function target( array $args ): ?array { + $file = is_string( $args['file'] ?? null ) ? $args['file'] : ''; + if ( '' === $file || 0 !== validate_file( $file ) ) { + return null; + } + + $plugin = is_string( $args['plugin'] ?? null ) ? $args['plugin'] : ''; + $theme = is_string( $args['theme'] ?? null ) ? $args['theme'] : ''; + if ( '' !== $plugin ) { + if ( 0 !== validate_file( $plugin ) || ! current_user_can( 'edit_plugins' ) ) { + return null; + } + $type = 'PluginFileEdited'; + $slug = $plugin; + $root = WP_PLUGIN_DIR; + } elseif ( '' !== $theme ) { + if ( 0 !== validate_file( $theme ) || ! current_user_can( 'edit_themes' ) ) { + return null; + } + $object = wp_get_theme( $theme ); + if ( ! $object->exists() ) { + return null; + } + $type = 'ThemeFileEdited'; + $slug = $theme; + $root = $object->get_stylesheet_directory(); + } else { + return null; + } + + $real_root = realpath( $root ); + $real_file = realpath( $root . '/' . $file ); + if ( false === $real_root || false === $real_file || 0 !== strpos( $real_file, trailingslashit( $real_root ) ) || ! is_file( $real_file ) || ! is_readable( $real_file ) ) { + return null; + } + + return [ + 'type' => $type, + 'slug' => $slug, + 'file' => $file, + 'path' => $real_file, + ]; + } + + /** + * A file's content, or only its hash when it is too large to compare. + * + * @param string $path The file. + * + * @return array{content?: string, hash: string} + */ + public static function read( string $path ): array { + clearstatcache( true, $path ); + $size = @filesize( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- The file may be gone. + if ( false === $size ) { + return [ 'hash' => '' ]; + } + + if ( $size > self::MAX_CONTENT ) { + $hash = md5_file( $path ); + return [ 'hash' => false !== $hash ? $hash : '' ]; + } + + $content = file_get_contents( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- A local file the editor saves. + if ( false === $content ) { + return [ 'hash' => '' ]; + } + + return [ + 'content' => $content, + 'hash' => md5( $content ), + ]; + } + + /** + * What changed between a file before and after: the content for the job + * to compare, `too_large`, or null when the file didn't change (the save + * failed, or WordPress put the old file back). + * + * @param array $before The file before. + * @param array $after The file after. + * + * @return array|null + */ + public static function change( array $before, array $after ): ?array { + if ( '' === ( $before['hash'] ?? '' ) || '' === ( $after['hash'] ?? '' ) || $before['hash'] === $after['hash'] ) { + return null; + } + + if ( ! isset( $before['content'], $after['content'] ) ) { + return [ 'too_large' => true ]; + } + + return [ + 'stash' => [ + 'old' => $before['content'], + 'new' => $after['content'], + ], + ]; + } + + /** + * Report each noted file that changed, at the end of the request. + * + * @return void + */ + public static function flush(): void { + $pending = self::$pending; + self::$pending = []; + + foreach ( $pending as $edit ) { + $content = self::change( $edit['before'], self::read( $edit['path'] ) ); + if ( null === $content ) { + continue; + } + + $data = [ + 'name' => self::name( $edit['type'], $edit['slug'] ), + 'slug' => $edit['slug'], + 'file' => $edit['file'], + 'changes' => [ 'content' => $content ], + ]; + + do_action( ContentEvent::hook( $edit['type'] ), $data ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- The hooks start with scanfully_. + } + } + + /** + * The name of the plugin or theme a file belongs to. + * + * @param string $type The event type. + * @param string $slug The plugin's basename or the theme's folder. + * + * @return string + */ + private static function name( string $type, string $slug ): string { + if ( 'ThemeFileEdited' === $type ) { + return html_entity_decode( (string) wp_get_theme( $slug )->get( 'Name' ), ENT_QUOTES, 'UTF-8' ); + } + + if ( ! function_exists( 'get_plugin_data' ) ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + } + $path = WP_PLUGIN_DIR . '/' . $slug; + $data = is_file( $path ) ? get_plugin_data( $path, false, false ) : []; + + return html_entity_decode( (string) ( $data['Name'] ?? '' ), ENT_QUOTES, 'UTF-8' ); + } +} diff --git a/src/Events/FontDeleted.php b/src/Events/FontDeleted.php new file mode 100644 index 0000000..c0f3f39 --- /dev/null +++ b/src/Events/FontDeleted.php @@ -0,0 +1,29 @@ + (int) ( $entry['user']['id'] ?? 0 ), + 'name' => (string) ( $entry['user']['name'] ?? '' ), + ]; + $who = $user['id'] . '|' . $user['name']; + + $by_user[ $who ]['user'] = $user; + foreach ( $entry['items'] as $item ) { + if ( is_array( $item ) && isset( $item['id'] ) ) { + $by_user[ $who ]['items'][] = $item; + } + } + } + + $threshold = max( 0, (int) apply_filters( 'scanfully_activity_bulk_threshold', self::THRESHOLD, Report::KIND_MEDIA ) ); + $limit = (int) apply_filters( 'scanfully_media_events_per_minute', self::PER_MINUTE ); + $room = $limit > 0 ? $limit : PHP_INT_MAX; + + $queue = []; + foreach ( $by_user as $entry ) { + $merged = self::merge( $entry['items'] ?? [] ); + Details::prime( array_keys( $merged ) ); + + $items = []; + foreach ( $merged as $id => $file ) { + $item = self::item( (int) $id, $file ); + if ( null !== $item ) { + $items[] = $item; + } + } + + $singles = []; + foreach ( Summary::group( $items ) as $group ) { + if ( count( $group ) > $threshold ) { + foreach ( Summary::rows( Report::KIND_MEDIA, $group ) as $row ) { + $queue[] = [ $row['type'], $entry['user'], $row['data'] ]; + --$room; + } + } else { + $singles[] = $group; + } + } + + foreach ( $singles as $group ) { + $over = []; + foreach ( $group as $item ) { + if ( $room > 0 ) { + $queue[] = [ (string) $item['type'], $entry['user'], (array) $item['data'] ]; + --$room; + } else { + $over[] = $item; + } + } + // Past the cap the rest of a group is one summary row. + foreach ( Summary::rows( Report::KIND_MEDIA, $over, true ) as $row ) { + $queue[] = [ $row['type'], $entry['user'], $row['data'] ]; + } + } + } + + foreach ( $queue as [ $type, $user, $data ] ) { + ContentEvent::queue( $type, $user, $data ); + } + } + + /** + * The notes of one person merged per file, in the order each file was + * first noted. + * + * @param array> $items The notes, oldest first. + * + * @return array> + */ + public static function merge( array $items ): array { + $files = []; + foreach ( $items as $item ) { + $id = (int) $item['id']; + $file = $files[ $id ] ?? []; + + if ( isset( $item['deleted'] ) ) { + // Uploaded and deleted again: nothing happened. + $files[ $id ] = ! empty( $file['uploaded'] ) ? [ 'gone' => true ] : [ 'deleted' => (array) $item['deleted'] ]; + continue; + } + + if ( ! empty( $file['gone'] ) || isset( $file['deleted'] ) ) { + continue; + } + + if ( ! empty( $item['uploaded'] ) ) { + $files[ $id ] = $item; + continue; + } + + // An upload is reported as the file is now. + if ( ! empty( $file['uploaded'] ) ) { + continue; + } + + foreach ( (array) ( $item['new'] ?? [] ) as $field => $new ) { + if ( ! array_key_exists( $field, $file['old'] ?? [] ) ) { + $file['old'][ $field ] = $item['old'][ $field ] ?? null; + } + $file['new'][ $field ] = $new; + } + + if ( isset( $item['image'] ) ) { + $image = (array) $item['image']; + if ( empty( $image['restored'] ) && ! empty( $file['image']['edits'] ) ) { + $image['edits'] = array_values( array_unique( array_merge( (array) $file['image']['edits'], (array) ( $image['edits'] ?? [] ) ) ) ); + } + $file['image'] = $image; + } + + if ( isset( $item['replaced'] ) ) { + $file['replaced'] = [ + 'old' => (string) ( $file['replaced']['old'] ?? $item['replaced']['old'] ?? '' ), + 'new' => (string) ( $item['replaced']['new'] ?? '' ), + ]; + unset( $file['old']['file'], $file['new']['file'] ); + } + + if ( isset( $item['known'] ) ) { + $file['known'] = (array) $item['known']; + } + + $files[ $id ] = $file; + } + + return array_filter( $files, static fn( array $file ): bool => empty( $file['gone'] ) ); + } + + /** + * A merged file as a summary item with its own event; null when there is + * nothing to report. + * + * @param int $id The attachment ID. + * @param array $file The merged notes. + * + * @return array|null + */ + private static function item( int $id, array $file ): ?array { + if ( isset( $file['deleted'] ) ) { + $data = self::deleted( $id, (array) $file['deleted'] ); + $action = 'deleted'; + $type = 'MediaDeleted'; + } elseif ( ! empty( $file['uploaded'] ) ) { + $data = self::uploaded( $id, $file ); + $action = 'uploaded'; + $type = 'MediaUploaded'; + } else { + $changes = self::changes( $file ); + if ( [] === $changes ) { + return null; + } + $data = self::describe( $id, $file ); + $data['changes'] = $changes; + $action = self::action( $changes ); + $type = 'MediaChanged'; + } + + /** + * Filters whether a media change is reported to Scanfully. + * + * @param bool $should_fire Whether to report it. + * @param string $action `uploaded`, `changed`, `attached`, `detached`, + * `trashed`, `restored` or `deleted`. + * @param array $data The event data. + */ + if ( ! (bool) apply_filters( 'scanfully_media_should_fire', true, $action, $data ) ) { + return null; + } + + $item = [ + 'action' => $action, + 'group' => 'attachment', + 'id' => $id, + 'title' => Summary::title( (string) ( $data['title'] ?? '' ) ), + 'name' => Summary::title( (string) ( $data['name'] ?? '' ) ), + 'type' => $type, + 'data' => $data, + ]; + if ( 'changed' === $action ) { + $item['changed'] = array_keys( $data['changes'] ); + } + if ( 'attached' === $action ) { + $item['parent'] = $data['changes']['parent']['new']; + } + if ( ! empty( $data['expired'] ) ) { + $item['expired'] = true; + } + + return $item; + } + + /** + * The data of an upload: the file as it is now, the post it was + * uploaded to, and for the block editor's edited copy the original. + * + * @param int $id The attachment ID. + * @param array $file The merged notes. + * + * @return array + */ + private static function uploaded( int $id, array $file ): array { + $data = self::describe( $id, $file ); + $parent = (int) wp_get_post_parent_id( $id ); + if ( $parent > 0 ) { + $data['parent'] = Details::parent( $parent ); + } + + if ( isset( $file['edited_from'] ) ) { + $original = Details::describe( (int) $file['edited_from'] ); + $data['edited_from'] = [ + 'id' => (int) $file['edited_from'], + 'name' => (string) ( $original['name'] ?? '' ), + ]; + $data['edits'] = array_values( (array) ( $file['edits'] ?? [] ) ); + } + + return $data; + } + + /** + * The data of a permanent delete, from what the request noted before the + * file was gone. + * + * @param int $id The attachment ID. + * @param array $deleted The noted file. + * + * @return array + */ + private static function deleted( int $id, array $deleted ): array { + $file = (string) ( $deleted['file'] ?? '' ); + $data = array_merge( + [ + 'id' => $id, + 'name' => Details::name( $file ), + 'file' => $file, + 'title' => (string) ( $deleted['title'] ?? '' ), + 'mime_type' => (string) ( $deleted['mime_type'] ?? '' ), + ], + Details::facts( (array) ( $deleted['facts'] ?? [] ) ), + [ + 'post_status' => (string) ( $deleted['post_status'] ?? '' ), + 'featured_on' => (int) ( $deleted['featured_on'] ?? 0 ), + ] + ); + + if ( ! empty( $deleted['expired'] ) ) { + $data['expired'] = true; + $data['trash_days'] = defined( 'EMPTY_TRASH_DAYS' ) ? (int) EMPTY_TRASH_DAYS : 30; + } + + return $data; + } + + /** + * A file as it is now, or, when it is gone since (someone else deleted + * it), as far as the notes know it. + * + * @param int $id The attachment ID. + * @param array $file The merged notes. + * + * @return array + */ + private static function describe( int $id, array $file ): array { + $data = Details::describe( $id ); + if ( null !== $data ) { + return $data; + } + + $known = (array) ( $file['known'] ?? [] ); + $path = (string) ( $file['new']['file'] ?? $file['file'] ?? $known['file'] ?? '' ); + $name = Details::name( $path ); + + return [ + 'id' => $id, + 'name' => '' !== $name ? $name : (string) ( $known['name'] ?? '' ), + 'file' => $path, + 'title' => (string) ( $file['new']['title'] ?? $known['title'] ?? '' ), + 'mime_type' => (string) ( $known['mime_type'] ?? '' ), + ]; + } + + /** + * What changed in a file, for its event. + * + * @param array $file The merged notes. + * + * @return array + */ + private static function changes( array $file ): array { + $changes = []; + foreach ( (array) ( $file['new'] ?? [] ) as $field => $new ) { + $old = $file['old'][ $field ] ?? null; + if ( $old === $new ) { + continue; + } + + if ( in_array( $field, self::TEXT_FIELDS, true ) ) { + $changes[ $field ] = [ + 'old' => (string) $old, + 'new' => (string) $new, + ]; + } elseif ( 'parent' === $field ) { + $changes['parent'] = [ + 'old' => Details::parent( max( 0, (int) $old ) ), + 'new' => Details::parent( (int) $new ), + ]; + if ( $changes['parent']['old']['id'] === $changes['parent']['new']['id'] ) { + unset( $changes['parent'] ); + } + } elseif ( 'file' === $field ) { + $changes['file'] = [ + 'old' => Details::name( (string) $old ), + 'new' => Details::name( (string) $new ), + ]; + } + } + + if ( isset( $file['replaced'] ) ) { + $changes['file'] = [ + 'old' => (string) $file['replaced']['old'], + 'new' => (string) $file['replaced']['new'], + 'replaced' => true, + ]; + } + + if ( isset( $file['image'] ) ) { + $changes['image'] = ! empty( $file['image']['restored'] ) + ? [ 'restored' => true ] + : [ + 'edits' => array_values( (array) ( $file['image']['edits'] ?? [] ) ), + 'target' => (string) ( $file['image']['target'] ?? 'all' ), + ]; + } + + return $changes; + } + + /** + * The action of a change: moved to the trash or back, attached or + * detached when only the post it belongs to changed, otherwise changed. + * + * @param array $changes The changes. + * + * @return string + */ + private static function action( array $changes ): string { + if ( isset( $changes['status'] ) ) { + if ( 'trash' === $changes['status']['new'] ) { + return 'trashed'; + } + if ( 'trash' === $changes['status']['old'] ) { + return 'restored'; + } + } + + if ( [ 'parent' ] === array_keys( $changes ) ) { + return $changes['parent']['new']['id'] > 0 ? 'attached' : 'detached'; + } + + return 'changed'; + } +} diff --git a/src/Events/MediaChanges/Collector.php b/src/Events/MediaChanges/Collector.php new file mode 100644 index 0000000..2cb9be1 --- /dev/null +++ b/src/Events/MediaChanges/Collector.php @@ -0,0 +1,883 @@ + 'title', + 'post_excerpt' => 'caption', + 'post_content' => 'description', + 'post_name' => 'slug', + 'post_parent' => 'parent', + 'post_status' => 'status', + ]; + + /** + * The meta keys the collector listens to. + */ + private const ALT_KEY = '_wp_attachment_image_alt'; + private const FILE_KEY = '_wp_attached_file'; + private const META_KEY = '_wp_attachment_metadata'; + private const BACKUP_KEY = '_wp_attachment_backup_sizes'; + private const THUMBNAIL_KEY = '_thumbnail_id'; + + /** + * What happened to each file in this request, by attachment ID: + * - `uploaded`: added in this request, with `edited_from` and `edits` + * for the copy the block editor makes when an image is cropped; + * - `old` and `new`: per field, the value before the first change and + * after the last; + * - `image`: edited in the image editor (`edits`, `target`) or restored; + * - `replaced`: the file replaced through a replace plugin (`old`, `new`); + * - `deleted`: deleted permanently (`done` once it went through), with + * what the row says about it; + * - `known`: its name, title and type after its post was last saved, for + * the job should the file be deleted before it runs. + * + * @var array> + */ + private static array $notes = []; + + /** + * Files WordPress stored for attachments in this request, by ID, so the + * file of an upload needs no query. + * + * @var array + */ + private static array $files = []; + + /** + * The media REST route being served: `type` (`edit`, `sideload`, + * `finalize`), `id`, and the `edits` of an edit. + * + * @var array + */ + private static array $route = []; + + /** + * The image editor request being served: `id`, `do` (`save`, `scale`, + * `restore`), `edits` and `target`. Noted once WordPress writes the new + * metadata, so a refused or failed request is not reported. + * + * @var array + */ + private static array $image_editor = []; + + /** + * The attachment WordPress is deleting. + * + * @var int + */ + private static int $deleting = 0; + + /** + * Whether the hooks are added. + * + * @var bool + */ + private static bool $set_up = false; + + /** + * Add the hooks. + * + * @return void + */ + public static function setup(): void { + if ( self::$set_up ) { + return; + } + self::$set_up = true; + + add_action( 'add_attachment', [ self::class, 'note_added' ], 10, 1 ); + add_action( 'attachment_updated', [ self::class, 'note_updated' ], 10, 3 ); + add_action( 'update_post_meta', [ self::class, 'note_meta_updating' ], 10, 4 ); + add_action( 'added_post_meta', [ self::class, 'note_meta_added' ], 10, 4 ); + add_action( 'delete_post_meta', [ self::class, 'note_meta_deleting' ], 10, 4 ); + add_action( 'wp_media_attach_action', [ self::class, 'note_attach' ], 10, 3 ); + add_action( 'delete_attachment', [ self::class, 'note_deleting' ], 10, 2 ); + add_action( 'deleted_post', [ self::class, 'note_deleted' ], 10, 1 ); + add_action( 'wp_ajax_image-editor', [ self::class, 'note_image_editor' ], 0, 0 ); + add_filter( 'rest_request_before_callbacks', [ self::class, 'note_rest_route' ], 10, 3 ); + add_filter( 'rest_request_after_callbacks', [ self::class, 'forget_rest_route' ], 10, 1 ); + add_action( 'enable-media-replace-upload-done', [ self::class, 'note_replaced' ], 10, 3 ); + // After the post and term collectors. + add_action( 'shutdown', [ self::class, 'flush' ], 2, 0 ); + } + + /** + * Forget everything noted (tests, and after a flush). + * + * @return void + */ + public static function reset(): void { + self::$notes = []; + self::$files = []; + self::$route = []; + self::$image_editor = []; + self::$deleting = 0; + } + + /** + * Whether media changes are noted now: not during an import, which adds + * many files nobody uploaded by hand. + * + * @return bool + */ + private static function is_noting(): bool { + return ! ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ); + } + + /** + * Make sure a file has a note, when there is room for it: a request + * notes at most MAX_ITEMS files. + * + * @param int $id The attachment ID. + * + * @return bool Whether the file has a note. + */ + private static function open( int $id ): bool { + if ( isset( self::$notes[ $id ] ) ) { + return true; + } + if ( $id < 1 || count( self::$notes ) >= self::MAX_ITEMS ) { + return false; + } + + self::$notes[ $id ] = []; + + return true; + } + + /** + * Whether nothing more is noted about a file: it was added in this + * request (the job reads how it is now), or it is being deleted. + * + * @param int $id The attachment ID. + * + * @return bool + */ + private static function is_settled( int $id ): bool { + return ! empty( self::$notes[ $id ]['uploaded'] ) || isset( self::$notes[ $id ]['deleted'] ) || self::$deleting === $id; + } + + /** + * `add_attachment`: a file was added to the media library. + * + * @param mixed $post_id The attachment ID. + * + * @return void + */ + public static function note_added( $post_id ): void { + $id = (int) $post_id; + if ( ! self::is_noting() || ! self::open( $id ) ) { + return; + } + + self::$notes[ $id ] = [ 'uploaded' => true ]; + if ( 'edit' === ( self::$route['type'] ?? '' ) ) { + self::$notes[ $id ]['edited_from'] = (int) self::$route['id']; + self::$notes[ $id ]['edits'] = (array) self::$route['edits']; + } + } + + /** + * `attachment_updated`: an attachment's post was saved. + * + * @param mixed $post_id The attachment ID. + * @param mixed $after The post after the update. + * @param mixed $before The post before the update. + * + * @return void + */ + public static function note_updated( $post_id, $after, $before ): void { + $id = (int) $post_id; + if ( ! is_object( $after ) || ! is_object( $before ) || ! self::is_noting() || self::is_settled( $id ) ) { + return; + } + + // The `__trashed` slug WordPress gives a file in the trash, or getting + // the old one back, isn't a change of its own. + $trashed = 'trash' === ( $before->post_status ?? '' ) || 'trash' === ( $after->post_status ?? '' ); + + foreach ( self::POST_FIELDS as $post_field => $field ) { + if ( 'slug' === $field && $trashed ) { + continue; + } + + $old = $before->$post_field ?? ''; + $new = $after->$post_field ?? ''; + if ( 'parent' === $field ) { + $old = (int) $old; + $new = (int) $new; + } else { + $old = (string) $old; + $new = (string) $new; + } + + if ( $old !== $new ) { + self::change( $id, $field, $old, $new ); + } + } + + // What the job says about the file should someone delete it before + // the job runs, from the post WordPress passes. + if ( isset( self::$notes[ $id ] ) ) { + self::$notes[ $id ]['known'] = self::known( $id, $after ); + } + } + + /** + * A file's name, title and type from its post and the meta cache, never + * the database. + * + * @param int $id The attachment ID. + * @param object $post The attachment. + * + * @return array{name: string, file: string, title: string, mime_type: string} + */ + private static function known( int $id, object $post ): array { + $file = self::cached_value( $id, self::FILE_KEY ); + $file = is_string( $file ) ? $file : ''; + + return [ + 'name' => Details::name( $file, (string) ( $post->guid ?? '' ) ), + 'file' => $file, + 'title' => self::text( (string) ( $post->post_title ?? '' ) ), + 'mime_type' => (string) ( $post->post_mime_type ?? '' ), + ]; + } + + /** + * `update_post_meta`: a meta value is about to change. + * + * @param mixed $meta_id The meta ID. + * @param mixed $object_id The post ID. + * @param mixed $meta_key The key. + * @param mixed $value The new value. + * + * @return void + */ + public static function note_meta_updating( $meta_id, $object_id, $meta_key, $value ): void { + self::note_meta( (int) $object_id, (string) $meta_key, $value, true ); + } + + /** + * `added_post_meta`: a meta value was added. + * + * @param mixed $meta_id The meta ID. + * @param mixed $object_id The post ID. + * @param mixed $meta_key The key. + * @param mixed $value The value. + * + * @return void + */ + public static function note_meta_added( $meta_id, $object_id, $meta_key, $value ): void { + self::note_meta( (int) $object_id, (string) $meta_key, $value, false ); + } + + /** + * `delete_post_meta`: meta values are about to be removed. While a file + * is deleted, WordPress removes it as featured image from every post in + * one go: one meta ID per post. + * + * @param mixed $meta_ids The meta IDs. + * @param mixed $object_id The post ID, 0 when removed from every post. + * @param mixed $meta_key The key. + * @param mixed $value The value asked to remove, if any. + * + * @return void + */ + public static function note_meta_deleting( $meta_ids, $object_id, $meta_key, $value ): void { + $meta_key = (string) $meta_key; + if ( self::THUMBNAIL_KEY === $meta_key ) { + if ( self::$deleting > 0 && (int) $object_id < 1 && is_scalar( $value ) && (int) $value === self::$deleting && isset( self::$notes[ self::$deleting ]['deleted'] ) ) { + self::$notes[ self::$deleting ]['deleted']['featured_on'] = is_array( $meta_ids ) ? count( $meta_ids ) : 0; + } + return; + } + + if ( self::ALT_KEY === $meta_key ) { + self::note_meta( (int) $object_id, $meta_key, '', true ); + } + } + + /** + * Note a meta change of an attachment: alt text and file, and the + * metadata write that confirms an image editor request. + * + * @param int $id The attachment ID. + * @param string $key The key. + * @param mixed $value The value after the change. + * @param bool $existed Whether the key existed before the change. + * + * @return void + */ + private static function note_meta( int $id, string $key, $value, bool $existed ): void { + switch ( $key ) { + case self::ALT_KEY: + if ( self::is_noting() && ! self::is_settled( $id ) ) { + $old = $existed ? self::cached_value( $id, $key ) : ''; + if ( null !== $old ) { + self::change( $id, 'alt', (string) $old, is_scalar( $value ) ? (string) $value : '' ); + } + } + return; + case self::FILE_KEY: + self::note_file( $id, is_scalar( $value ) ? (string) $value : '', $existed ); + return; + case self::META_KEY: + case self::BACKUP_KEY: + self::note_image_edited( $id ); + return; + } + } + + /** + * Note a change of the file of an attachment. WordPress's own follow-up + * files (`-scaled`, `-rotated`), the 7.x upload steps (`sideload`, + * `finalize`) and the image editor's new file are not a change of their + * own: the upload or the image edit says it. + * + * @param int $id The attachment ID. + * @param string $file The new file, relative to the uploads folder. + * @param bool $existed Whether the attachment had a file before. + * + * @return void + */ + private static function note_file( int $id, string $file, bool $existed ): void { + if ( $id < 1 || '' === $file ) { + return; + } + + if ( ! $existed ) { + // An upload stores its file just before `add_attachment`. + if ( count( self::$files ) < self::MAX_ITEMS ) { + self::$files[ $id ] = $file; + } + return; + } + + if ( ! self::is_noting() || self::is_settled( $id ) || in_array( self::$route['type'] ?? '', [ 'sideload', 'finalize' ], true ) || ( self::$image_editor['id'] ?? 0 ) === $id ) { + return; + } + + $old = self::cached_value( $id, self::FILE_KEY ); + if ( null === $old || self::same_file( (string) $old, $file ) ) { + return; + } + + self::change( $id, 'file', (string) $old, $file ); + } + + /** + * Whether two file paths are the same file apart from the suffixes + * WordPress adds itself: `-scaled` for a big image, `-rotated` for a + * photo turned upright. + * + * @param string $before The old path. + * @param string $after The new path. + * + * @return bool + */ + public static function same_file( string $before, string $after ): bool { + $strip = static function ( string $path ): string { + return (string) preg_replace( '/(?:-scaled|-rotated)+(\.[^.\/]+)$/', '$1', $path ); + }; + + return $strip( $before ) === $strip( $after ); + } + + /** + * `wp_media_attach_action`: files attached to or detached from a post in + * the media library's list view. WordPress updates the parent with SQL, + * so no post update hook fires. + * + * @param mixed $action `attach` or `detach`. + * @param mixed $attachment_id The attachment ID. + * @param mixed $parent_id The post attached to. + * + * @return void + */ + public static function note_attach( $action, $attachment_id, $parent_id ): void { + $id = (int) $attachment_id; + if ( ! self::is_noting() || self::is_settled( $id ) ) { + return; + } + + // The post cache still holds the parent from before: WordPress read + // the attachment to check the user may edit it, and clears the cache + // right after this hook. A detach passes the post it detaches from. + $cached = wp_cache_get( $id, 'posts' ); + $new = 'attach' === $action ? (int) $parent_id : 0; + if ( is_object( $cached ) && isset( $cached->post_parent ) ) { + $old = (int) $cached->post_parent; + } else { + $old = 'attach' === $action ? 0 : (int) $parent_id; + } + if ( $old !== $new ) { + self::change( $id, 'parent', $old, $new ); + } + } + + /** + * Note a change of a field: the value before the first change and after + * the last. + * + * @param int $id The attachment ID. + * @param string $field The field. + * @param int|string $before The value before. + * @param int|string $after The value after. + * + * @return void + */ + private static function change( int $id, string $field, $before, $after ): void { + if ( ! self::open( $id ) ) { + return; + } + + if ( is_string( $before ) && is_string( $after ) && in_array( $field, [ 'title', 'caption', 'description', 'alt' ], true ) ) { + $before = self::text( $before ); + $after = self::text( $after ); + } + + if ( ! array_key_exists( $field, self::$notes[ $id ]['old'] ?? [] ) ) { + self::$notes[ $id ]['old'][ $field ] = $before; + } + self::$notes[ $id ]['new'][ $field ] = $after; + } + + /** + * `wp_ajax_image-editor`, before WordPress handles it: the image editor + * saves, scales or restores an image. What it does is read from the + * request here and only noted once WordPress has checked the nonce and + * saved the image (note_image_edited). + * + * @return void + */ + public static function note_image_editor(): void { + // phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended -- WordPress verifies the nonce right after; nothing is noted unless it saved the image. + $do = isset( $_REQUEST['do'] ) ? sanitize_key( wp_unslash( $_REQUEST['do'] ) ) : ''; + $id = isset( $_REQUEST['postid'] ) ? (int) $_REQUEST['postid'] : 0; + if ( $id < 1 || ! in_array( $do, [ 'save', 'scale', 'restore' ], true ) ) { + return; + } + + $edits = 'scale' === $do ? [ 'scale' ] : []; + if ( 'save' === $do && isset( $_REQUEST['history'] ) ) { + $history = json_decode( (string) wp_unslash( $_REQUEST['history'] ), true ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON, only read for its keys. + $edits = self::history_edits( is_array( $history ) ? $history : [] ); + } + + $target = isset( $_REQUEST['target'] ) ? sanitize_key( wp_unslash( $_REQUEST['target'] ) ) : 'all'; + // phpcs:enable + + self::$image_editor = [ + 'id' => $id, + 'do' => $do, + 'edits' => $edits, + 'target' => '' !== $target ? $target : 'all', + ]; + } + + /** + * The edits in the image editor's history: crop, rotate and flip, in + * the order first made. + * + * @param array $history The history: one object per step. + * + * @return array + */ + public static function history_edits( array $history ): array { + $names = [ + 'c' => 'crop', + 'r' => 'rotate', + 'f' => 'flip', + ]; + + $edits = []; + foreach ( $history as $step ) { + if ( ! is_array( $step ) ) { + continue; + } + foreach ( $names as $key => $name ) { + if ( isset( $step[ $key ] ) && ! in_array( $name, $edits, true ) ) { + $edits[] = $name; + } + } + } + + return $edits; + } + + /** + * Note an image editor request as done: WordPress wrote the image's new + * metadata or backup sizes. + * + * @param int $id The attachment ID. + * + * @return void + */ + private static function note_image_edited( int $id ): void { + if ( ( self::$image_editor['id'] ?? 0 ) !== $id || ! self::is_noting() || self::is_settled( $id ) || ! self::open( $id ) ) { + return; + } + + self::$notes[ $id ]['image'] = 'restore' === self::$image_editor['do'] + ? [ 'restored' => true ] + : [ + 'edits' => self::$image_editor['edits'], + 'target' => self::$image_editor['target'], + ]; + } + + /** + * `rest_request_before_callbacks`: note the media routes that make an + * edited copy (`edit`) or finish an upload in the browser (`sideload`, + * `finalize`, WordPress 7.0 and later). + * + * @param mixed $response The response so far. + * @param mixed $handler The route handler. + * @param mixed $request The request. + * + * @return mixed The response, unchanged. + */ + public static function note_rest_route( $response, $handler, $request ) { + self::$route = []; + if ( ! $request instanceof \WP_REST_Request || 1 !== preg_match( '#^/wp/v2/media/(\d+)/(edit|sideload|finalize)$#', (string) $request->get_route(), $match ) ) { + return $response; + } + + self::$route = [ + 'type' => $match[2], + 'id' => (int) $match[1], + 'edits' => 'edit' === $match[2] ? self::rest_edits( $request ) : [], + ]; + + return $response; + } + + /** + * `rest_request_after_callbacks`: the media route is done. + * + * @param mixed $response The response. + * + * @return mixed The response, unchanged. + */ + public static function forget_rest_route( $response ) { + self::$route = []; + + return $response; + } + + /** + * The edits of a block editor image edit: its `modifiers`, or the older + * `rotation` and crop parameters. + * + * @param \WP_REST_Request $request The request. + * + * @return array + */ + private static function rest_edits( \WP_REST_Request $request ): array { + $edits = []; + $modifiers = $request->get_param( 'modifiers' ); + if ( is_array( $modifiers ) ) { + foreach ( $modifiers as $modifier ) { + $type = is_array( $modifier ) ? sanitize_key( (string) ( $modifier['type'] ?? '' ) ) : ''; + if ( in_array( $type, [ 'crop', 'rotate', 'flip' ], true ) && ! in_array( $type, $edits, true ) ) { + $edits[] = $type; + } + } + + return $edits; + } + + if ( ! empty( $request->get_param( 'rotation' ) ) ) { + $edits[] = 'rotate'; + } + if ( null !== $request->get_param( 'width' ) && null !== $request->get_param( 'height' ) ) { + $edits[] = 'crop'; + } + + return $edits; + } + + /** + * `enable-media-replace-upload-done`: Enable Media Replace replaced the + * file of an attachment, under the same name or a new one. + * + * @param mixed $target_url The URL of the new file. + * @param mixed $source_url The URL of the old file. + * @param mixed $post_id The attachment ID. + * + * @return void + */ + public static function note_replaced( $target_url, $source_url, $post_id ): void { + $id = (int) $post_id; + if ( ! self::is_noting() || self::is_settled( $id ) || ! self::open( $id ) ) { + return; + } + + if ( ! isset( self::$notes[ $id ]['replaced'] ) ) { + self::$notes[ $id ]['replaced'] = [ 'old' => self::url_name( $source_url ) ]; + } + self::$notes[ $id ]['replaced']['new'] = self::url_name( $target_url ); + // The replace says what happened to the file. + unset( self::$notes[ $id ]['old']['file'], self::$notes[ $id ]['new']['file'] ); + } + + /** + * The file name in a URL. + * + * @param mixed $url The URL. + * + * @return string + */ + private static function url_name( $url ): string { + $path = is_string( $url ) ? (string) wp_parse_url( $url, PHP_URL_PATH ) : ''; + + return '' !== $path ? rawurldecode( wp_basename( $path ) ) : ''; + } + + /** + * `delete_attachment`: a file is about to be deleted permanently. Its + * file and metadata are in the meta cache: WordPress has just read them + * to know which files to remove. + * + * @param mixed $post_id The attachment ID. + * @param mixed $post The attachment. + * + * @return void + */ + public static function note_deleting( $post_id, $post = null ): void { + $id = (int) $post_id; + if ( ! is_object( $post ) || ! self::is_noting() || ! self::open( $id ) ) { + return; + } + + self::$deleting = $id; + if ( ! empty( self::$notes[ $id ]['uploaded'] ) ) { + // Added and deleted in one request: nothing to report. + self::$notes[ $id ]['deleted'] = [ 'done' => false ]; + return; + } + + $meta = self::cached_value( $id, self::META_KEY ); + $file = self::cached_value( $id, self::FILE_KEY ); + + self::$notes[ $id ]['deleted'] = [ + 'title' => self::text( (string) ( $post->post_title ?? '' ) ), + 'file' => is_string( $file ) ? $file : '', + 'mime_type' => (string) ( $post->post_mime_type ?? '' ), + 'post_status' => (string) ( $post->post_status ?? '' ), + 'parent' => (int) ( $post->post_parent ?? 0 ), + 'facts' => is_array( $meta ) ? Details::facts( $meta ) : [], + 'featured_on' => 0, + // WordPress empties the media trash in the `wp_scheduled_delete` cron job. + 'expired' => doing_action( 'wp_scheduled_delete' ), + 'done' => false, + ]; + } + + /** + * `deleted_post`: the delete went through. + * + * @param mixed $post_id The post ID. + * + * @return void + */ + public static function note_deleted( $post_id ): void { + $id = (int) $post_id; + if ( isset( self::$notes[ $id ]['deleted'] ) ) { + self::$notes[ $id ]['deleted']['done'] = true; + } + if ( self::$deleting === $id ) { + self::$deleting = 0; + } + } + + /** + * Store the notes of the request for the minute's job, once, at the end + * of the request. A request that noted nothing writes nothing. + * + * @return void + */ + public static function flush(): void { + $notes = self::$notes; + $files = self::$files; + self::reset(); + + $items = []; + foreach ( $notes as $id => $note ) { + $item = self::item( (int) $id, $note, $files ); + if ( null !== $item ) { + $items[] = $item; + } + } + + // A site that isn't connected has nowhere to send events. + if ( [] === $items || ! Options\Controller::get_options()->is_connected ) { + return; + } + + $user = wp_get_current_user(); + MinuteStore::add( + self::KIND, + [ + 'user' => [ + 'id' => (int) $user->ID, + 'name' => ContentEvent::user_name( $user ), + ], + 'items' => $items, + ], + Controller::ACTION_SEND_MEDIA + ); + } + + /** + * A file's note as the job reads it; null when there is nothing to + * report. + * + * @param int $id The attachment ID. + * @param array $note The note. + * @param array $files The files stored in the request. + * + * @return array|null + */ + private static function item( int $id, array $note, array $files ): ?array { + if ( isset( $note['deleted'] ) ) { + if ( empty( $note['deleted']['done'] ) || ! empty( $note['uploaded'] ) ) { + return null; + } + $deleted = $note['deleted']; + unset( $deleted['done'] ); + + return [ + 'id' => $id, + 'deleted' => $deleted, + ]; + } + + if ( ! empty( $note['uploaded'] ) ) { + $item = [ + 'id' => $id, + 'uploaded' => true, + ]; + if ( isset( $files[ $id ] ) ) { + $item['file'] = $files[ $id ]; + } + if ( isset( $note['edited_from'] ) ) { + $item['edited_from'] = $note['edited_from']; + $item['edits'] = $note['edits'] ?? []; + } + + return $item; + } + + $item = [ 'id' => $id ]; + foreach ( (array) ( $note['new'] ?? [] ) as $field => $new ) { + $old = $note['old'][ $field ] ?? null; + if ( $old !== $new ) { + $item['old'][ $field ] = $old; + $item['new'][ $field ] = $new; + } + } + foreach ( [ 'image', 'replaced' ] as $key ) { + if ( isset( $note[ $key ] ) ) { + $item[ $key ] = $note[ $key ]; + } + } + if ( count( $item ) < 2 ) { + return null; + } + if ( isset( $note['known'] ) ) { + $item['known'] = $note['known']; + } + + return $item; + } + + /** + * An attachment's meta value from the meta cache, without a query; null + * when it isn't cached. + * + * @param int $id The attachment ID. + * @param string $key The key. + * + * @return mixed + */ + private static function cached_value( int $id, string $key ) { + $cache = wp_cache_get( $id, 'post_meta' ); + if ( ! is_array( $cache ) ) { + return null; + } + if ( ! isset( $cache[ $key ] ) || ! is_array( $cache[ $key ] ) || [] === $cache[ $key ] ) { + // Cached, without this key: it was empty. + return ''; + } + + return maybe_unserialize( $cache[ $key ][0] ); + } + + /** + * Plain text, cut to the longest text kept. + * + * @param string $text The text, as WordPress stores it. + * + * @return string + */ + private static function text( string $text ): string { + $text = html_entity_decode( $text, ENT_QUOTES, 'UTF-8' ); + + return mb_strlen( $text ) > self::MAX_TEXT ? mb_substr( $text, 0, self::MAX_TEXT ) : $text; + } +} diff --git a/src/Events/MediaChanges/Details.php b/src/Events/MediaChanges/Details.php new file mode 100644 index 0000000..98ce1f0 --- /dev/null +++ b/src/Events/MediaChanges/Details.php @@ -0,0 +1,149 @@ + $ids The attachment IDs. + * + * @return void + */ + public static function prime( array $ids ): void { + $ids = array_values( array_unique( array_filter( array_map( 'intval', $ids ) ) ) ); + if ( [] === $ids ) { + return; + } + + _prime_post_caches( $ids, false, true ); + } + + /** + * A file as it is now; null when it no longer exists or isn't a file in + * the media library. + * + * @param int $id The attachment ID. + * + * @return array|null + */ + public static function describe( int $id ): ?array { + $post = get_post( $id ); + if ( ! $post instanceof \WP_Post || 'attachment' !== $post->post_type ) { + return null; + } + + $file = (string) get_post_meta( $id, '_wp_attached_file', true ); + $data = [ + 'id' => $id, + 'name' => self::name( $file, (string) $post->guid ), + 'file' => $file, + 'title' => self::plain( (string) $post->post_title ), + 'mime_type' => (string) $post->post_mime_type, + ]; + + $meta = wp_get_attachment_metadata( $id, true ); + $facts = is_array( $meta ) ? self::facts( $meta ) : []; + if ( ! isset( $facts['filesize'] ) ) { + $path = '' !== $file ? get_attached_file( $id, true ) : false; + if ( is_string( $path ) && is_file( $path ) ) { + $facts['filesize'] = (int) wp_filesize( $path ); + } + } + + return array_merge( $data, $facts ); + } + + /** + * The size, dimensions and length of a file from its metadata, as far + * as WordPress knows them. + * + * @param array $meta The attachment metadata. + * + * @return array + */ + public static function facts( array $meta ): array { + $facts = []; + foreach ( [ 'filesize', 'width', 'height', 'length' ] as $key ) { + if ( isset( $meta[ $key ] ) && is_numeric( $meta[ $key ] ) && (int) $meta[ $key ] > 0 ) { + $facts[ $key ] = (int) $meta[ $key ]; + } + } + + return $facts; + } + + /** + * The file name of a file in the uploads folder, or else the one in its + * URL. + * + * @param string $file The file, relative to the uploads folder. + * @param string $url The file's URL. + * + * @return string + */ + public static function name( string $file, string $url = '' ): string { + if ( '' !== $file ) { + return wp_basename( $file ); + } + + $path = (string) wp_parse_url( $url, PHP_URL_PATH ); + + return '' !== $path ? rawurldecode( wp_basename( $path ) ) : ''; + } + + /** + * A post files are attached to: ID, title and the post type's name on + * the site. The title is '' for none (0) or a post that is gone. + * + * @param int $id The post ID. + * + * @return array{id: int, title: string, type_label?: string} + */ + public static function parent( int $id ): array { + $post = $id > 0 ? get_post( $id ) : null; + if ( ! $post instanceof \WP_Post ) { + return [ + 'id' => $id, + 'title' => '', + ]; + } + + $type = get_post_type_object( $post->post_type ); + + return [ + 'id' => $id, + 'title' => Summary::title( (string) $post->post_title ), + 'type_label' => is_object( $type ) && isset( $type->labels->singular_name ) ? self::plain( (string) $type->labels->singular_name ) : (string) $post->post_type, + ]; + } + + /** + * Plain text from a value WordPress stores HTML-encoded. + * + * @param string $value The value. + * + * @return string + */ + private static function plain( string $value ): string { + return html_entity_decode( $value, ENT_QUOTES, 'UTF-8' ); + } +} diff --git a/src/Events/MediaDeleted.php b/src/Events/MediaDeleted.php new file mode 100644 index 0000000..4c7ad64 --- /dev/null +++ b/src/Events/MediaDeleted.php @@ -0,0 +1,33 @@ + $data The data the request noted. + * + * @return array + */ + public static function resolve( string $type, array $data ): array { + return 'block' === ( $data['kind'] ?? '' ) ? self::block( $type, $data ) : self::classic( $type, $data ); + } + + /** + * A classic menu's event. + * + * @param string $type The event type. + * @param array $data The data the request noted. + * + * @return array + */ + private static function classic( string $type, array $data ): array { + $menu_id = (int) ( $data['id'] ?? 0 ); + if ( 0 === $menu_id && isset( $data['_tt'] ) ) { + // The request knew the menu by its term taxonomy ID only. + $term = get_term_by( 'term_taxonomy_id', (int) $data['_tt'], 'nav_menu' ); + $menu_id = $term instanceof \WP_Term ? (int) $term->term_id : 0; + $data['id'] = $menu_id; + } elseif ( 0 === $menu_id && isset( $data['_item'] ) ) { + // Or by one of the items: the menu it is on. + $terms = wp_get_object_terms( (int) $data['_item'], 'nav_menu', [ 'fields' => 'ids' ] ); + $menu_id = is_array( $terms ) && [] !== $terms ? (int) reset( $terms ) : 0; + $data['id'] = $menu_id; + } + unset( $data['_tt'], $data['_item'] ); + if ( ! isset( $data['name'] ) ) { + $term = get_term( $menu_id, 'nav_menu' ); + $data['name'] = $term instanceof \WP_Term ? self::plain( (string) $term->name ) : ''; + } else { + $data['name'] = self::plain( (string) $data['name'] ); + } + + $locations = $data['_locations'] ?? []; + $noted = is_array( $data['_items'] ?? null ) ? $data['_items'] : []; + unset( $data['_locations'], $data['_items'] ); + + if ( 'MenuDeleted' === $type || 'MenuCreated' === $type ) { + if ( 'MenuCreated' === $type ) { + $data['items'] = count( self::current_items( $menu_id ) ); + } + if ( is_array( $locations ) && [] !== $locations ) { + $data['locations'] = self::locations( $locations ); + } + + return $data; + } + + $current = self::current_items( $menu_id ); + $changes = is_array( $data['changes'] ?? null ) ? $data['changes'] : []; + $moved = []; + if ( isset( $changes['name'] ) && is_array( $changes['name'] ) ) { + $changes['name'] = [ + 'old' => self::plain( (string) ( $changes['name']['old'] ?? '' ) ), + 'new' => self::plain( (string) ( $changes['name']['new'] ?? '' ) ), + ]; + } + + foreach ( $noted as $item_id => $entry ) { + $item_id = (int) $item_id; + $item = $current[ $item_id ] ?? null; + + if ( ! empty( $entry['added'] ) ) { + if ( null !== $item ) { + $changes['added'][] = self::describe( $item ); + } elseif ( is_array( $entry['added'] ) ) { + // Gone again or filtered out by now: as the request saw it. + $changes['added'][] = self::describe_removed( $item_id, $entry['added'] ); + } + continue; + } + + if ( isset( $entry['removed'] ) ) { + $removed = self::describe_removed( $item_id, (array) $entry['removed'] ); + if ( '' !== (string) ( $entry['removed']['reason'] ?? '' ) ) { + $removed['reason'] = (string) $entry['removed']['reason']; + } + $changes['removed'][] = $removed; + continue; + } + + if ( null === $item ) { + continue; + } + $old = (array) ( $entry['old'] ?? [] ); + $new = (array) ( $entry['new'] ?? [] ); + $label = self::describe( $item ); + + if ( array_key_exists( 'title', $new ) ) { + $before = '' !== $old['title'] ? self::plain( (string) $old['title'] ) : self::object_title( $item ); + if ( $before !== $label['label'] ) { + $changes['renamed'][] = $label + [ + 'old' => $before, + 'new' => $label['label'], + ]; + } + } + if ( array_key_exists( 'url', $new ) && 'custom' === (string) $item->type ) { + $changes['relinked'][] = $label + [ + 'old' => (string) $old['url'], + 'new' => (string) $new['url'], + ]; + } elseif ( array_key_exists( 'object_id', $new ) || array_key_exists( 'object', $new ) || array_key_exists( 'type', $new ) ) { + $changes['relinked'][] = $label + [ + 'old' => self::linked_title( (string) ( $old['type'] ?? $item->type ), (string) ( $old['object'] ?? $item->object ), (int) ( $old['object_id'] ?? $item->object_id ) ), + 'new' => self::object_title( $item ), + ]; + } + if ( array_key_exists( 'parent', $new ) ) { + $parent = (int) $new['parent']; + $moved[ $item_id ] = true; + $changes['moved'][] = $label + [ 'parent' => $parent > 0 && isset( $current[ $parent ] ) ? self::label( $current[ $parent ] ) : '' ]; + } + $details = array_values( array_intersect( self::DETAIL_FIELDS, array_keys( $new ) ) ); + if ( [] !== $details ) { + $changes['details'][] = $label + [ 'changed' => $details ]; + } + } + + // Moves: the items whose place among the others under the same + // parent changed, not every item renumbered because one above it + // moved, was added or removed. The Menus screen numbers a whole menu, + // the Customizer each parent's items, REST gives new items 1: places + // are compared within a parent, with ties broken by ID. + $groups = []; + foreach ( $current as $item_id => $item ) { + if ( ! empty( $noted[ $item_id ]['added'] ) || isset( $moved[ $item_id ] ) ) { + continue; + } + $before = isset( $noted[ $item_id ]['old']['order'] ) ? (int) $noted[ $item_id ]['old']['order'] : (int) $item->menu_order; + $groups[ (int) $item->menu_item_parent ][ $item_id ] = $before * 1000000000000 + $item_id; + } + foreach ( $groups as $sequence ) { + foreach ( self::out_of_order( $sequence ) as $item_id ) { + $parent = (int) $current[ $item_id ]->menu_item_parent; + $changes['moved'][] = self::describe( $current[ $item_id ] ) + [ 'parent' => $parent > 0 && isset( $current[ $parent ] ) ? self::label( $current[ $parent ] ) : '' ]; + } + } + + if ( is_array( $locations ) && ( [] !== ( $locations['added'] ?? [] ) || [] !== ( $locations['removed'] ?? [] ) ) ) { + $changes['locations'] = [ + 'added' => self::locations( (array) ( $locations['added'] ?? [] ) ), + 'removed' => self::locations( (array) ( $locations['removed'] ?? [] ) ), + ]; + } + + if ( [] === $changes ) { + return []; + } + + $data['items'] = count( $current ); + $data['changes'] = self::cap_lists( $changes ); + + return $data; + } + + /** + * A block menu's event. + * + * @param string $type The event type. + * @param array $data The data the request noted. + * + * @return array + */ + private static function block( string $type, array $data ): array { + $data['name'] = self::plain( (string) ( $data['name'] ?? '' ) ); + + if ( 'MenuCreated' === $type || 'MenuDeleted' === $type ) { + $data['items'] = count( self::block_items( (string) ( $data['_content'] ?? '' ) ) ); + unset( $data['_content'] ); + + return $data; + } + + $changes = is_array( $data['changes'] ?? null ) ? $data['changes'] : []; + $after = self::block_items( (string) ( $data['_after'] ?? '' ) ); + if ( isset( $data['_before'] ) ) { + $changes = array_merge( $changes, self::block_changes( self::block_items( (string) $data['_before'] ), $after ) ); + } + unset( $data['_before'], $data['_after'] ); + + if ( [] === $changes ) { + return []; + } + + $data['items'] = count( $after ); + $data['changes'] = self::cap_lists( $changes ); + + return $data; + } + + /** + * What changed between two versions of a block menu's items. + * + * @param array> $before The items before. + * @param array> $after The items after. + * + * @return array + */ + public static function block_changes( array $before, array $after ): array { + // Pair the items: the same linked post or term, else the same URL, + // else the same block with the same label. + $unmatched = []; + foreach ( $before as $index => $item ) { + $unmatched[ $item['key'] ][] = $index; + } + $pairs = []; + foreach ( $after as $index => $item ) { + if ( ! empty( $unmatched[ $item['key'] ] ) ) { + $pairs[ $index ] = array_shift( $unmatched[ $item['key'] ] ); + } + } + // A link that now goes somewhere else: the same label in the same + // submenu. + $left = []; + foreach ( $unmatched as $indexes ) { + foreach ( $indexes as $old_index ) { + $left[ $before[ $old_index ]['parent'] . "\n" . $before[ $old_index ]['label'] ][] = $old_index; + } + } + foreach ( $after as $index => $item ) { + $key = $item['parent'] . "\n" . $item['label']; + if ( isset( $pairs[ $index ] ) || empty( $left[ $key ] ) || '' === $item['url'] ) { + continue; + } + $old_index = array_shift( $left[ $key ] ); + $pairs[ $index ] = $old_index; + foreach ( $unmatched as $unmatched_key => $indexes ) { + $unmatched[ $unmatched_key ] = array_values( array_diff( $indexes, [ $old_index ] ) ); + } + } + ksort( $pairs ); + + $changes = []; + foreach ( $after as $index => $item ) { + if ( ! isset( $pairs[ $index ] ) ) { + $changes['added'][] = self::block_entry( $item ); + continue; + } + + $old = $before[ $pairs[ $index ] ]; + $entry = self::block_entry( $item ); + if ( $old['label'] !== $item['label'] ) { + $changes['renamed'][] = $entry + [ + 'old' => $old['label'], + 'new' => $item['label'], + ]; + } + if ( $old['url'] !== $item['url'] ) { + $changes['relinked'][] = $entry + [ + 'old' => $old['url'], + 'new' => $item['url'], + ]; + } + if ( $old['parent'] !== $item['parent'] ) { + $changes['moved'][] = $entry + [ 'parent' => $item['parent'] ]; + } + if ( $old['attrs'] !== $item['attrs'] ) { + $changes['details'][] = $entry + [ 'changed' => array_keys( self::differing( $old['attrs'], $item['attrs'] ) ) ]; + } + } + foreach ( $unmatched as $indexes ) { + foreach ( $indexes as $index ) { + $changes['removed'][] = self::block_entry( $before[ $index ] ); + } + } + + // Moves among the items that are in both, in the same parent. + $sequence = []; + foreach ( $pairs as $index => $old_index ) { + $sequence[ $index ] = $old_index; + } + foreach ( self::out_of_order( $sequence ) as $index ) { + if ( $before[ $pairs[ $index ] ]['parent'] === $after[ $index ]['parent'] ) { + $changes['moved'][] = self::block_entry( $after[ $index ] ) + [ 'parent' => $after[ $index ]['parent'] ]; + } + } + + return $changes; + } + + /** + * The keys whose values differ between two attribute lists. + * + * @param array $before The attributes before. + * @param array $after The attributes after. + * + * @return array + */ + private static function differing( array $before, array $after ): array { + $keys = []; + foreach ( array_unique( array_merge( array_keys( $before ), array_keys( $after ) ) ) as $key ) { + if ( ( $before[ $key ] ?? null ) !== ( $after[ $key ] ?? null ) ) { + $keys[ (string) $key ] = true; + } + } + + return $keys; + } + + /** + * The keys of a sequence (key => place before, in today's order) that + * moved: those outside its longest run that kept its order. + * + * @param array $sequence The places before, in today's order. + * + * @return array + */ + public static function out_of_order( array $sequence ): array { + $keys = array_keys( $sequence ); + $values = array_values( $sequence ); + $count = count( $values ); + if ( $count < 2 ) { + return []; + } + + // Longest increasing subsequence, n log n, keeping where each came from. + $tails = []; + $from = array_fill( 0, $count, -1 ); + $ends = []; + for ( $i = 0; $i < $count; $i++ ) { + $low = 0; + $high = count( $tails ); + while ( $low < $high ) { + $mid = intdiv( $low + $high, 2 ); + if ( $values[ $tails[ $mid ] ] < $values[ $i ] ) { + $low = $mid + 1; + } else { + $high = $mid; + } + } + $from[ $i ] = $low > 0 ? $tails[ $low - 1 ] : -1; + $tails[ $low ] = $i; + $ends[ $low ] = $i; + } + + $keep = []; + for ( $i = $ends[ count( $tails ) - 1 ]; $i >= 0; $i = $from[ $i ] ) { + $keep[ $i ] = true; + } + + $moved = []; + foreach ( $keys as $i => $key ) { + if ( ! isset( $keep[ $i ] ) ) { + $moved[] = $key; + } + } + + return $moved; + } + + /** + * The items of a block menu, in order: navigation links and submenus + * with their label, link and the submenu they are in, and other blocks + * (page list, search, social icons) by their block title. + * + * @param string $content The wp_navigation post's content. + * + * @return array> + */ + public static function block_items( string $content ): array { + $items = []; + if ( '' !== trim( $content ) ) { + self::walk( parse_blocks( $content ), '', $items ); + } + + return $items; + } + + /** + * Add the items of a list of blocks. + * + * @param array> $blocks The blocks. + * @param string $submenu The label of the submenu they are in, '' for the top. + * @param array> $items The items so far. + * + * @return void + */ + private static function walk( array $blocks, string $submenu, array &$items ): void { + foreach ( $blocks as $block ) { + $name = $block['blockName'] ?? null; + if ( ! is_string( $name ) || '' === $name ) { + continue; + } + $attrs = is_array( $block['attrs'] ?? null ) ? $block['attrs'] : []; + + if ( in_array( $name, [ 'core/navigation-link', 'core/navigation-submenu' ], true ) ) { + $type = (string) ( $attrs['type'] ?? '' ); + $id = (int) ( $attrs['id'] ?? 0 ); + $url = (string) ( $attrs['url'] ?? '' ); + $label = self::plain( (string) ( $attrs['label'] ?? '' ) ); + unset( $attrs['label'], $attrs['url'], $attrs['id'], $attrs['type'], $attrs['kind'] ); + $key = $id > 0 ? $type . ':' . $id : ( '' !== $url ? 'url:' . $url : $name . ':' . $label ); + } else { + $type = $name; + $id = 0; + $url = ''; + $label = 'core/home-link' === $name && isset( $attrs['label'] ) ? self::plain( (string) $attrs['label'] ) : self::block_title( $name ); + $key = $name . ':' . $label; + } + ksort( $attrs ); + + $items[] = [ + 'key' => $key, + 'id' => $id, + 'label' => $label, + 'url' => $url, + 'type' => $type, + 'parent' => $submenu, + 'attrs' => $attrs, + ]; + + if ( 'core/navigation-submenu' === $name && is_array( $block['innerBlocks'] ?? null ) ) { + self::walk( $block['innerBlocks'], $label, $items ); + } + } + } + + /** + * A block menu item as an event lists it. + * + * @param array $item The item. + * + * @return array{id: int, label: string, type: string} + */ + private static function block_entry( array $item ): array { + return [ + 'id' => (int) $item['id'], + 'label' => (string) $item['label'], + 'type' => self::block_type_label( (string) $item['type'] ), + ]; + } + + /** + * The type of a block menu item in words: the post type or taxonomy of + * a link, "Custom Link", or the block's title. + * + * @param string $type The link type (`page`, `post`, `category`, `tag`, `custom`) or block name. + * + * @return string + */ + private static function block_type_label( string $type ): string { + if ( false !== strpos( $type, '/' ) ) { + return self::block_title( $type ); + } + if ( '' === $type || 'custom' === $type ) { + return __( 'Custom Link', 'scanfully' ); + } + + $object = post_type_exists( $type ) ? get_post_type_object( $type ) : get_taxonomy( 'tag' === $type ? 'post_tag' : $type ); + + return is_object( $object ) && isset( $object->labels->singular_name ) ? (string) $object->labels->singular_name : $type; + } + + /** + * A block's title, or its name when it isn't registered. + * + * @param string $name The block name. + * + * @return string + */ + private static function block_title( string $name ): string { + $type = \WP_Block_Type_Registry::get_instance()->get_registered( $name ); + + return $type instanceof \WP_Block_Type && '' !== (string) $type->title ? (string) $type->title : $name; + } + + /** + * The current published items of a classic menu, by ID, in menu order. + * + * @param int $menu_id The menu's term ID. + * + * @return array + */ + private static function current_items( int $menu_id ): array { + if ( $menu_id < 1 ) { + return []; + } + + // Not wp_get_nav_menu_items(): plugins that hide items from some + // visitors filter it, and the job runs without a signed-in user. + $posts = get_posts( + [ + 'post_type' => 'nav_menu_item', + 'post_status' => 'publish', + 'numberposts' => -1, + 'orderby' => 'menu_order ID', + 'order' => 'ASC', + 'suppress_filters' => true, + 'tax_query' => [ // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- The background job; this is how WordPress reads a menu. + [ + 'taxonomy' => 'nav_menu', + 'field' => 'term_taxonomy_id', + 'terms' => [ self::menu_tt( $menu_id ) ], + ], + ], + ] + ); + $out = []; + foreach ( $posts as $post ) { + $item = wp_setup_nav_menu_item( $post ); + if ( is_object( $item ) && isset( $item->db_id ) ) { + $out[ (int) $item->db_id ] = $item; + } + } + + return $out; + } + + /** + * A classic menu's term taxonomy ID, 0 when it is gone. + * + * @param int $menu_id The menu's term ID. + * + * @return int + */ + private static function menu_tt( int $menu_id ): int { + $term = get_term( $menu_id, 'nav_menu' ); + + return $term instanceof \WP_Term ? (int) $term->term_taxonomy_id : 0; + } + + /** + * A classic item as an event lists it. + * + * @param object $item The item (wp_setup_nav_menu_item()). + * + * @return array{id: int, label: string, type: string} + */ + private static function describe( object $item ): array { + return [ + 'id' => (int) $item->db_id, + 'label' => self::label( $item ), + 'type' => (string) ( $item->type_label ?? '' ), + ]; + } + + /** + * A classic item's label: its own, or the title of what it links to. + * + * @param object $item The item. + * + * @return string + */ + private static function label( object $item ): string { + return self::plain( (string) ( $item->title ?? '' ) ); + } + + /** + * A deleted classic item as an event lists it, from what the request + * read before the delete. + * + * @param int $item_id The item ID. + * @param array $removed What the item was. + * + * @return array{id: int, label: string, type: string} + */ + private static function describe_removed( int $item_id, array $removed ): array { + $type = (string) ( $removed['type'] ?? '' ); + $object = (string) ( $removed['object'] ?? '' ); + $label = self::plain( (string) ( $removed['title'] ?? '' ) ); + if ( '' === $label ) { + $label = self::linked_title( $type, $object, (int) ( $removed['object_id'] ?? 0 ) ); + } + + return [ + 'id' => $item_id, + 'label' => $label, + 'type' => self::type_label( $type, $object ), + ]; + } + + /** + * The title of what a classic item links to now. + * + * @param object $item The item. + * + * @return string + */ + private static function object_title( object $item ): string { + if ( 'custom' === (string) $item->type ) { + return self::label( $item ); + } + + return self::linked_title( (string) $item->type, (string) $item->object, (int) $item->object_id ); + } + + /** + * The title of a post or term an item links to; '' when it is gone. + * + * @param string $type The item type (`post_type`, `taxonomy`, `post_type_archive`, `custom`). + * @param string $object_name The post type or taxonomy. + * @param int $object_id The post or term ID. + * + * @return string + */ + private static function linked_title( string $type, string $object_name, int $object_id ): string { + if ( 'post_type' === $type && $object_id > 0 ) { + $post = get_post( $object_id ); + return $post instanceof \WP_Post ? self::plain( (string) $post->post_title ) : ''; + } + if ( 'taxonomy' === $type && $object_id > 0 ) { + $term = get_term( $object_id, $object_name ); + return $term instanceof \WP_Term ? self::plain( (string) $term->name ) : ''; + } + if ( 'post_type_archive' === $type ) { + $post_type = get_post_type_object( $object_name ); + return is_object( $post_type ) ? self::plain( (string) $post_type->labels->archives ) : ''; + } + + return ''; + } + + /** + * The type of a classic item in words, as the Menus screen shows it. + * + * @param string $type The item type. + * @param string $object_name The post type or taxonomy. + * + * @return string + */ + private static function type_label( string $type, string $object_name ): string { + if ( 'post_type' === $type ) { + $post_type = get_post_type_object( $object_name ); + return is_object( $post_type ) ? (string) $post_type->labels->singular_name : $object_name; + } + if ( 'taxonomy' === $type ) { + $taxonomy = get_taxonomy( $object_name ); + return is_object( $taxonomy ) ? (string) $taxonomy->labels->singular_name : $object_name; + } + if ( 'post_type_archive' === $type ) { + return __( 'Post Type Archive', 'scanfully' ); + } + + return __( 'Custom Link', 'scanfully' ); + } + + /** + * Theme locations by slug and name. + * + * @param array $slugs The location slugs. + * + * @return array + */ + private static function locations( array $slugs ): array { + $registered = get_registered_nav_menus(); + $out = []; + foreach ( $slugs as $slug ) { + $slug = (string) $slug; + $out[] = [ + 'slug' => $slug, + 'name' => isset( $registered[ $slug ] ) ? self::plain( (string) $registered[ $slug ] ) : $slug, + ]; + } + + return $out; + } + + /** + * The changes with every list cut to MAX_LISTED entries. + * + * @param array $changes The changes. + * + * @return array + */ + private static function cap_lists( array $changes ): array { + foreach ( [ 'added', 'removed', 'renamed', 'relinked', 'moved', 'details' ] as $list ) { + if ( isset( $changes[ $list ] ) && count( $changes[ $list ] ) > self::MAX_LISTED ) { + $changes[ $list ] = array_slice( $changes[ $list ], 0, self::MAX_LISTED ); + } + } + + return $changes; + } + + /** + * Text as plain text, cut to MAX_LABEL characters. + * + * @param string $text The text, possibly with HTML and entities. + * + * @return string + */ + private static function plain( string $text ): string { + $text = trim( html_entity_decode( wp_strip_all_tags( $text ), ENT_QUOTES, 'UTF-8' ) ); + + return function_exists( 'mb_substr' ) ? mb_substr( $text, 0, self::MAX_LABEL ) : substr( $text, 0, self::MAX_LABEL ); + } +} diff --git a/src/Events/MenuChanges/Collector.php b/src/Events/MenuChanges/Collector.php new file mode 100644 index 0000000..c9f1bfd --- /dev/null +++ b/src/Events/MenuChanges/Collector.php @@ -0,0 +1,1041 @@ + 'parent', + '_menu_item_url' => 'url', + '_menu_item_object_id' => 'object_id', + '_menu_item_object' => 'object', + '_menu_item_type' => 'type', + '_menu_item_target' => 'target', + '_menu_item_classes' => 'classes', + '_menu_item_xfn' => 'xfn', + ]; + + /** + * At most this many items of one request are noted. + */ + private const MAX_ITEMS = 5000; + + /** + * Menus noted, by `classic:{term ID}` or `block:{post ID}`. + * + * @var array> + */ + private static array $menus = []; + + /** + * Classic menu items noted, by item ID: `menu` (term ID, 0 while + * unknown), `added`, `old` and `new` fields, `removed` (what the item + * was, for one deleted), `tt` (its menu's term taxonomy ID). + * + * @var array> + */ + private static array $items = []; + + /** + * Theme locations whose menu changed: the first old and the last new + * menu ID per location. + * + * @var array + */ + private static array $locations = []; + + /** + * The menus that add new top-level pages by themselves, before and + * after, or null when that didn't change. + * + * @var array{old: array, new: array}|null + */ + private static ?array $auto_add = null; + + /** + * The term taxonomy ID of each classic menu saved in this request, by + * term ID, from the term cache: it names the menu of an item deleted + * in the same save. + * + * @var array + */ + private static array $menu_tt = []; + + /** + * The page, post or term being deleted, whose menu items WordPress then + * deletes: its title or name and type, for an item that showed it. + * + * @var array{label: string, type: string, object: string}|null + */ + private static ?array $deleting = null; + + /** + * Hook into WordPress. + * + * @return void + */ + public static function setup(): void { + add_action( 'wp_create_nav_menu', [ self::class, 'note_created' ], 10, 2 ); + add_filter( 'wp_update_term_data', [ self::class, 'note_renaming' ], PHP_INT_MAX, 3 ); + add_action( 'delete_term', [ self::class, 'note_deleted' ], 10, 5 ); + add_action( 'wp_add_nav_menu_item', [ self::class, 'note_item_added' ], 10, 3 ); + add_action( 'wp_update_nav_menu_item', [ self::class, 'note_item_saved' ], 10, 2 ); + add_action( 'post_updated', [ self::class, 'note_item_updated' ], 10, 3 ); + add_action( 'update_post_meta', [ self::class, 'note_item_meta' ], 10, 4 ); + add_action( 'before_delete_post', [ self::class, 'note_deleting' ], 10, 2 ); + // Before WordPress deletes the menu items of a deleted page or term (priority 10). + add_action( 'delete_post', [ self::class, 'note_object_deleting' ], 9, 2 ); + add_action( 'delete_term', [ self::class, 'note_term_deleting' ], 9, 4 ); + add_action( 'delete_term_relationships', [ self::class, 'note_item_menu' ], 10, 3 ); + add_filter( 'pre_set_theme_mod_nav_menu_locations', [ self::class, 'note_locations' ], PHP_INT_MAX, 2 ); + add_action( 'updated_option', [ self::class, 'note_option' ], 10, 3 ); + add_action( 'added_option', [ self::class, 'note_option_added' ], 10, 2 ); + add_action( 'wp_after_insert_post', [ self::class, 'note_block_saved' ], 10, 4 ); + add_action( 'shutdown', [ self::class, 'flush' ], 1, 0 ); + } + + /** + * Forget what was noted (tests). + * + * @return void + */ + public static function reset(): void { + self::$menus = []; + self::$items = []; + self::$locations = []; + self::$auto_add = null; + self::$menu_tt = []; + self::$deleting = null; + } + + /** + * Whether this request's menu changes are left out: imports, installs, + * the remapping WordPress does when the theme is switched (the theme + * switch is its own row), and changes to another site of a multisite + * network (they would be reported on the wrong site). + * + * @return bool + */ + public static function is_quiet(): bool { + return ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) + || wp_installing() + || ( function_exists( 'ms_is_switched' ) && ms_is_switched() ) + || did_action( 'switch_theme' ) > 0 + || doing_action( 'after_switch_theme' ); + } + + /** + * Whether the request only reads: the block editor makes a fallback + * navigation menu by itself when it loads, and that is nobody's change. + * Cron runs (a scheduled Customizer change) and WP-CLI (which calls + * every command a GET) count as changes. + * + * @return bool + */ + public static function is_read_request(): bool { + if ( wp_doing_cron() || ( defined( 'WP_CLI' ) && WP_CLI ) ) { + return false; + } + + $method = isset( $_SERVER['REQUEST_METHOD'] ) && is_string( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : ''; + + return in_array( $method, [ 'GET', 'HEAD' ], true ); + } + + /** + * The note of a menu, made when missing. + * + * @param string $kind `classic` or `block`. + * @param int $id The term or post ID. + * + * @return string The key. + */ + private static function menu( string $kind, int $id ): string { + $key = $kind . ':' . $id; + if ( ! isset( self::$menus[ $key ] ) ) { + self::$menus[ $key ] = [ + 'kind' => $kind, + 'id' => $id, + ]; + } + + return $key; + } + + /** + * The note of a classic item, made when missing; null past MAX_ITEMS. + * + * @param int $item_id The item ID. + * + * @return bool Whether the item is noted. + */ + private static function item( int $item_id ): bool { + if ( isset( self::$items[ $item_id ] ) ) { + return true; + } + if ( count( self::$items ) >= self::MAX_ITEMS ) { + return false; + } + + self::$items[ $item_id ] = [ + 'menu' => 0, + 'old' => [], + 'new' => [], + ]; + + return true; + } + + /** + * `wp_create_nav_menu`: a classic menu was made. + * + * @param mixed $term_id The menu's term ID. + * @param mixed $menu_data The menu data: `menu-name`. + * + * @return void + */ + public static function note_created( $term_id, $menu_data = [] ): void { + if ( self::is_quiet() ) { + return; + } + + $key = self::menu( 'classic', (int) $term_id ); + self::$menus[ $key ]['created'] = true; + // Every core caller passes the name slashed. + self::$menus[ $key ]['name'] = is_array( $menu_data ) ? wp_unslash( (string) ( $menu_data['menu-name'] ?? '' ) ) : ''; + } + + /** + * `wp_update_term_data`: a classic menu gets a new name. The term is in + * the cache: wp_update_term() just read it. + * + * @param mixed $data The term data to be saved. + * @param mixed $term_id The term ID. + * @param mixed $taxonomy The taxonomy. + * + * @return mixed The data, unchanged. + */ + public static function note_renaming( $data, $term_id, $taxonomy ) { + if ( 'nav_menu' !== $taxonomy || ! is_array( $data ) || ! isset( $data['name'] ) || self::is_quiet() ) { + return $data; + } + + $term = get_term( (int) $term_id, 'nav_menu' ); + if ( ! $term instanceof \WP_Term || (string) $term->name === (string) $data['name'] ) { + return $data; + } + + $key = self::menu( 'classic', (int) $term_id ); + if ( ! isset( self::$menus[ $key ]['old_name'] ) ) { + self::$menus[ $key ]['old_name'] = (string) $term->name; + } + self::$menus[ $key ]['name'] = (string) $data['name']; + + return $data; + } + + /** + * `delete_term`: a classic menu was deleted. Its items were deleted just + * before (wp_delete_nav_menu()). + * + * @param mixed $term_id The term ID. + * @param mixed $tt_id The term taxonomy ID. + * @param mixed $taxonomy The taxonomy. + * @param mixed $deleted_term The term as it was. + * @param mixed $object_ids The objects it had (its items were deleted before). + * + * @return void + */ + public static function note_deleted( $term_id, $tt_id, $taxonomy, $deleted_term = null, $object_ids = [] ): void { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- The hook passes it. + if ( 'nav_menu' !== $taxonomy || self::is_quiet() ) { + return; + } + + $key = self::menu( 'classic', (int) $term_id ); + self::$menus[ $key ]['deleted'] = true; + self::$menus[ $key ]['tt'] = (int) $tt_id; + if ( is_object( $deleted_term ) && ! isset( self::$menus[ $key ]['old_name'] ) ) { + self::$menus[ $key ]['name'] = (string) ( $deleted_term->name ?? '' ); + } + } + + /** + * `wp_add_nav_menu_item`: an item was made. The Menus screen makes a + * draft as soon as one is put on the menu and publishes it on Save + * Menu; the Customizer, REST and WP-CLI make published items. + * + * @param mixed $menu_id The menu's term ID. + * @param mixed $item_id The item ID. + * @param mixed $args The item data. + * + * @return void + */ + public static function note_item_added( $menu_id, $item_id, $args = [] ): void { + if ( self::is_quiet() || ! is_array( $args ) || 'publish' !== ( $args['menu-item-status'] ?? '' ) || ! self::item( (int) $item_id ) ) { + return; + } + + self::$items[ (int) $item_id ]['added'] = true; + self::$items[ (int) $item_id ]['menu'] = (int) $menu_id; + // For the job, should the item be gone or filtered out by then. + self::$items[ (int) $item_id ]['noted'] = [ + 'title' => (string) ( $args['menu-item-title'] ?? '' ), + 'type' => (string) ( $args['menu-item-type'] ?? '' ), + 'object' => (string) ( $args['menu-item-object'] ?? '' ), + 'object_id' => (string) ( $args['menu-item-object-id'] ?? '' ), + 'url' => (string) ( $args['menu-item-url'] ?? '' ), + ]; + } + + /** + * `wp_update_nav_menu_item`: an item was saved; this names its menu. + * + * @param mixed $menu_id The menu's term ID. + * @param mixed $item_id The item ID. + * + * @return void + */ + public static function note_item_saved( $menu_id, $item_id ): void { + $menu_id = (int) $menu_id; + if ( $menu_id < 1 ) { + return; + } + if ( isset( self::$items[ (int) $item_id ] ) ) { + self::$items[ (int) $item_id ]['menu'] = $menu_id; + } + // The menu's term was just read (wp_get_nav_menu_object()); only the + // cache is asked, never the database. + if ( ! isset( self::$menu_tt[ $menu_id ] ) ) { + $term = wp_cache_get( $menu_id, 'terms' ); + if ( is_object( $term ) && isset( $term->term_taxonomy_id ) ) { + self::$menu_tt[ $menu_id ] = (int) $term->term_taxonomy_id; + } + } + } + + /** + * `post_updated`: an item's label, place, description or status + * changed; a draft becoming published was put on the menu. + * + * @param mixed $post_id The item ID. + * @param mixed $after The item after. + * @param mixed $before The item before. + * + * @return void + */ + public static function note_item_updated( $post_id, $after, $before ): void { + if ( ! is_object( $after ) || ! is_object( $before ) || 'nav_menu_item' !== ( $after->post_type ?? '' ) || self::is_quiet() ) { + return; + } + + $item_id = (int) $post_id; + if ( 'publish' !== $after->post_status ) { + // Set back to draft (REST): off the menu. + if ( 'publish' === $before->post_status && empty( self::$items[ $item_id ]['added'] ) && self::item( $item_id ) ) { + self::$items[ $item_id ]['removed'] = self::item_facts( $item_id, $before ); + } + return; + } + if ( 'publish' !== $before->post_status ) { + if ( self::item( $item_id ) ) { + self::$items[ $item_id ]['added'] = true; + self::$items[ $item_id ]['noted'] = self::item_facts( $item_id, $after ); + unset( self::$items[ $item_id ]['noted']['reason'] ); + } + return; + } + + $fields = [ + 'title' => 'post_title', + 'order' => 'menu_order', + 'attr_title' => 'post_excerpt', + 'description' => 'post_content', + ]; + foreach ( $fields as $field => $column ) { + // WordPress stores a lone space as the description of an item + // without one, and clears it again when the label changes. + $old = 'description' === $field ? trim( (string) $before->$column ) : (string) $before->$column; + $new = 'description' === $field ? trim( (string) $after->$column ) : (string) $after->$column; + if ( $old === $new ) { + continue; + } + if ( ! self::item( $item_id ) ) { + return; + } + self::change( $item_id, $field, $old, $new ); + } + } + + /** + * `update_post_meta` (before the update): an item's link, parent, + * target, classes or XFN changed. WordPress only calls this for a real + * change; the old value is taken from the meta cache, which loading the + * menu filled. + * + * @param mixed $meta_id The meta ID. + * @param mixed $object_id The item ID. + * @param mixed $meta_key The meta key. + * @param mixed $value The new value. + * + * @return void + */ + public static function note_item_meta( $meta_id, $object_id, $meta_key, $value ): void { + if ( ! is_string( $meta_key ) || ! isset( self::ITEM_META[ $meta_key ] ) || self::is_quiet() ) { + return; + } + + $item_id = (int) $object_id; + // A new item's fields are its first values, not changes. + if ( ! empty( self::$items[ $item_id ]['added'] ) ) { + return; + } + + $cache = wp_cache_get( $item_id, 'post_meta' ); + $old = is_array( $cache ) && isset( $cache[ $meta_key ][0] ) ? maybe_unserialize( $cache[ $meta_key ][0] ) : null; + if ( ! self::item( $item_id ) ) { + return; + } + + self::change( $item_id, self::ITEM_META[ $meta_key ], self::meta_string( $old ), self::meta_string( $value ) ); + } + + /** + * Keep the first old and the last new value of an item's field. + * + * @param int $item_id The item ID. + * @param string $field The field. + * @param string $before The value before. + * @param string $after The value after. + * + * @return void + */ + private static function change( int $item_id, string $field, string $before, string $after ): void { + if ( ! array_key_exists( $field, self::$items[ $item_id ]['old'] ) ) { + self::$items[ $item_id ]['old'][ $field ] = $before; + } + self::$items[ $item_id ]['new'][ $field ] = $after; + } + + /** + * A meta value as a string (the classes are a list). + * + * @param mixed $value The value. + * + * @return string + */ + private static function meta_string( $value ): string { + if ( is_array( $value ) ) { + return implode( ' ', array_filter( array_map( 'strval', $value ), static fn( string $part ): bool => '' !== $part ) ); + } + + return is_scalar( $value ) ? (string) $value : ''; + } + + /** + * `before_delete_post`: a published item is taken off its menu, or a + * block menu is deleted. What the job needs to name it is read now. + * + * @param mixed $post_id The post ID. + * @param mixed $post The post. + * + * @return void + */ + public static function note_deleting( $post_id, $post = null ): void { + if ( ! is_object( $post ) || self::is_quiet() ) { + return; + } + + if ( 'wp_navigation' === $post->post_type ) { + if ( 'auto-draft' === $post->post_status ) { + return; + } + $key = self::menu( 'block', (int) $post_id ); + if ( ! isset( self::$menus[ $key ]['before'] ) ) { + self::$menus[ $key ]['before'] = self::block_state( $post ); + } + self::$menus[ $key ]['deleted'] = true; + return; + } + + if ( 'nav_menu_item' !== $post->post_type || 'publish' !== $post->post_status ) { + return; + } + + $item_id = (int) $post_id; + if ( ! empty( self::$items[ $item_id ]['added'] ) ) { + // Put on the menu and taken off again in the same request. + unset( self::$items[ $item_id ] ); + return; + } + if ( ! self::item( $item_id ) ) { + return; + } + + self::$items[ $item_id ]['removed'] = self::item_facts( $item_id, $post ); + } + + /** + * What the job needs of an item put on or taken off its menu, should it + * be gone by then: its label and link from the post and the meta cache + * (never the database; deleting a whole menu deletes items whose meta + * isn't cached, and only counts them), and whether its page or term was + * deleted. + * + * @param int $item_id The item ID. + * @param object $post The item. + * + * @return array + */ + private static function item_facts( int $item_id, object $post ): array { + $cache = wp_cache_get( $item_id, 'post_meta' ); + $removed = [ + 'title' => (string) $post->post_title, + // The page, post or term it linked to was deleted (WordPress + // takes its items off every menu). + 'reason' => ( doing_action( 'delete_post' ) || doing_action( 'delete_term' ) ) && null !== self::$deleting ? 'object_deleted' : '', + ]; + foreach ( self::ITEM_META as $meta_key => $field ) { + if ( in_array( $field, [ 'url', 'object_id', 'object', 'type' ], true ) ) { + $removed[ $field ] = is_array( $cache ) && isset( $cache[ $meta_key ][0] ) ? (string) $cache[ $meta_key ][0] : ''; + } + } + // An item that shows the title of its page has no label of its own. + if ( 'object_deleted' === $removed['reason'] ) { + if ( '' === $removed['title'] ) { + $removed['title'] = self::$deleting['label']; + } + $removed['type'] = self::$deleting['type']; + $removed['object'] = self::$deleting['object']; + } + + return $removed; + } + + /** + * `delete_post` (priority 9): a post is being deleted; WordPress deletes + * the menu items that show it next. + * + * @param mixed $post_id The post ID. + * @param mixed $post The post. + * + * @return void + */ + public static function note_object_deleting( $post_id, $post = null ): void { + if ( is_object( $post ) && 'nav_menu_item' !== $post->post_type ) { + self::$deleting = [ + 'label' => (string) $post->post_title, + 'type' => 'post_type', + 'object' => (string) $post->post_type, + ]; + } + } + + /** + * `delete_term` (priority 9): a term is being deleted; WordPress deletes + * the menu items that show it next. + * + * @param mixed $term_id The term ID. + * @param mixed $tt_id The term taxonomy ID. + * @param mixed $taxonomy The taxonomy. + * @param mixed $deleted_term The term as it was. + * + * @return void + */ + public static function note_term_deleting( $term_id, $tt_id, $taxonomy, $deleted_term = null ): void { + if ( is_object( $deleted_term ) && 'nav_menu' !== $taxonomy ) { + self::$deleting = [ + 'label' => (string) ( $deleted_term->name ?? '' ), + 'type' => 'taxonomy', + 'object' => (string) $taxonomy, + ]; + } + } + + /** + * `delete_term_relationships`: the menu a deleted item was on (WordPress + * read it to remove the relationship). + * + * @param mixed $object_id The item ID. + * @param mixed $tt_ids The term taxonomy IDs. + * @param mixed $taxonomy The taxonomy. + * + * @return void + */ + public static function note_item_menu( $object_id, $tt_ids, $taxonomy ): void { + if ( 'nav_menu' === $taxonomy && isset( self::$items[ (int) $object_id ]['removed'] ) && is_array( $tt_ids ) && [] !== $tt_ids ) { + self::$items[ (int) $object_id ]['tt'] = (int) reset( $tt_ids ); + } + } + + /** + * `pre_set_theme_mod_nav_menu_locations`: which menu each theme location + * shows. + * + * @param mixed $value The new locations. + * @param mixed $old_value The locations before. + * + * @return mixed The new locations, unchanged. + */ + public static function note_locations( $value, $old_value ) { + if ( self::is_quiet() ) { + return $value; + } + + $new = is_array( $value ) ? $value : []; + $old = is_array( $old_value ) ? $old_value : []; + foreach ( array_unique( array_merge( array_keys( $old ), array_keys( $new ) ) ) as $location ) { + $before = (int) ( $old[ $location ] ?? 0 ); + $after = (int) ( $new[ $location ] ?? 0 ); + if ( $before === $after ) { + continue; + } + $location = (string) $location; + if ( ! isset( self::$locations[ $location ] ) ) { + self::$locations[ $location ] = [ + 'old' => $before, + 'new' => $after, + ]; + } + self::$locations[ $location ]['new'] = $after; + } + + return $value; + } + + /** + * `updated_option`: the menus that add new top-level pages by + * themselves (`nav_menu_options`). + * + * @param mixed $option The option name. + * @param mixed $old_value The value before. + * @param mixed $value The value after. + * + * @return void + */ + public static function note_option( $option, $old_value, $value ): void { + if ( 'nav_menu_options' !== $option || self::is_quiet() ) { + return; + } + + $ids = static function ( $options ): array { + $list = is_array( $options ) && is_array( $options['auto_add'] ?? null ) ? $options['auto_add'] : []; + + return array_values( array_unique( array_map( 'intval', $list ) ) ); + }; + + if ( null === self::$auto_add ) { + self::$auto_add = [ + 'old' => $ids( $old_value ), + 'new' => [], + ]; + } + self::$auto_add['new'] = $ids( $value ); + } + + /** + * `added_option`: the first save of `nav_menu_options`, on a site whose + * Menus screen was never saved (update_option() adds the missing + * option). Before it, no menu added new pages by itself. + * + * @param mixed $option The option name. + * @param mixed $value The value. + * + * @return void + */ + public static function note_option_added( $option, $value ): void { + self::note_option( $option, [], $value ); + } + + /** + * `wp_after_insert_post`: a block menu was made or saved. + * + * @param mixed $post_id The post ID. + * @param mixed $post The post. + * @param mixed $update Whether an existing post was updated. + * @param mixed $post_before The post before, or null. + * + * @return void + */ + public static function note_block_saved( $post_id, $post, $update, $post_before ): void { + if ( ! is_object( $post ) || 'wp_navigation' !== $post->post_type || 'auto-draft' === $post->post_status || self::is_quiet() ) { + return; + } + + $key = 'block:' . (int) $post_id; + $new = ! $update || ! is_object( $post_before ) || 'auto-draft' === $post_before->post_status; + if ( $new && ! isset( self::$menus[ $key ] ) && self::is_read_request() ) { + return; + } + + $key = self::menu( 'block', (int) $post_id ); + if ( $new && ! isset( self::$menus[ $key ]['before'] ) ) { + self::$menus[ $key ]['created'] = true; + } elseif ( ! isset( self::$menus[ $key ]['before'] ) && is_object( $post_before ) ) { + self::$menus[ $key ]['before'] = self::block_state( $post_before ); + } + self::$menus[ $key ]['after'] = self::block_state( $post ); + } + + /** + * What a block menu's row needs of its post. + * + * @param object $post The wp_navigation post. + * + * @return array{name: string, status: string, content: string} + */ + private static function block_state( object $post ): array { + return [ + 'name' => (string) $post->post_title, + 'status' => (string) $post->post_status, + 'content' => (string) $post->post_content, + ]; + } + + /** + * The rows for what this request changed: event type and data, which + * the background job completes (Builder). + * + * @return array}> + */ + public static function rows(): array { + $rows = []; + + // Classic items by menu: the menu ID the save named, else the menu + // a deleted item was on. + $by_menu = []; + $by_tt = []; + $unknown = []; + foreach ( self::$items as $item_id => $item ) { + if ( $item['menu'] > 0 ) { + $by_menu[ $item['menu'] ][ $item_id ] = $item; + } elseif ( isset( $item['tt'] ) ) { + $by_tt[ $item['tt'] ][ $item_id ] = $item; + } else { + // Saved with wp_update_post() rather than as a menu item. + $unknown[ $item_id ] = $item; + } + } + foreach ( self::$menus as $menu ) { + if ( 'classic' === $menu['kind'] && isset( $menu['tt'], $by_tt[ $menu['tt'] ] ) ) { + $by_menu[ $menu['id'] ] = ( $by_menu[ $menu['id'] ] ?? [] ) + $by_tt[ $menu['tt'] ]; + unset( $by_tt[ $menu['tt'] ] ); + } + } + foreach ( self::$menu_tt as $menu_id => $tt_id ) { + if ( isset( $by_tt[ $tt_id ] ) ) { + $by_menu[ $menu_id ] = ( $by_menu[ $menu_id ] ?? [] ) + $by_tt[ $tt_id ]; + unset( $by_tt[ $tt_id ] ); + } + } + // The rest (an item deleted over REST, or with its page) is named by + // the job, which may query. + + // Locations by menu. + $shown = []; + $hidden = []; + foreach ( self::$locations as $location => $change ) { + if ( $change['old'] === $change['new'] ) { + continue; + } + if ( $change['new'] > 0 ) { + $shown[ $change['new'] ][] = $location; + } + if ( $change['old'] > 0 ) { + $hidden[ $change['old'] ][] = $location; + } + } + + // Auto add pages by menu. + $auto_add = []; + if ( null !== self::$auto_add ) { + foreach ( array_diff( self::$auto_add['new'], self::$auto_add['old'] ) as $menu_id ) { + $auto_add[ $menu_id ] = true; + } + foreach ( array_diff( self::$auto_add['old'], self::$auto_add['new'] ) as $menu_id ) { + $auto_add[ $menu_id ] = false; + } + } + + $classic_ids = array_unique( array_merge( array_keys( $by_menu ), array_keys( $shown ), array_keys( $hidden ), array_keys( $auto_add ) ) ); + foreach ( self::$menus as $menu ) { + if ( 'classic' === $menu['kind'] ) { + $classic_ids[] = $menu['id']; + } + } + sort( $classic_ids ); + + foreach ( array_unique( $classic_ids ) as $menu_id ) { + $row = self::classic_row( (int) $menu_id, self::$menus[ 'classic:' . $menu_id ] ?? [], $by_menu[ $menu_id ] ?? [], $shown[ $menu_id ] ?? [], $hidden[ $menu_id ] ?? [], $auto_add[ $menu_id ] ?? null ); + if ( null !== $row ) { + $rows[] = $row; + } + } + + foreach ( $by_tt as $tt_id => $items ) { + $row = self::classic_row( 0, [ 'tt' => (int) $tt_id ], $items, [], [], null ); + if ( null !== $row ) { + $rows[] = $row; + } + } + if ( [] !== $unknown ) { + $row = self::classic_row( 0, [ 'item' => (int) array_key_first( $unknown ) ], $unknown, [], [], null ); + if ( null !== $row ) { + $rows[] = $row; + } + } + + foreach ( self::$menus as $menu ) { + if ( 'block' === $menu['kind'] ) { + $row = self::block_row( $menu ); + if ( null !== $row ) { + $rows[] = $row; + } + } + } + + return $rows; + } + + /** + * The row of a classic menu, or null when nothing about it changed. + * + * @param int $menu_id The menu's term ID. + * @param array $menu What was noted about the menu. + * @param array> $items Its items noted, by ID. + * @param array $shown Locations it now shows in. + * @param array $hidden Locations it no longer shows in. + * @param bool|null $auto_add Whether it now adds new pages by itself, null when unchanged. + * + * @return array{type: string, data: array}|null + */ + private static function classic_row( int $menu_id, array $menu, array $items, array $shown, array $hidden, ?bool $auto_add ): ?array { + $created = ! empty( $menu['created'] ); + $deleted = ! empty( $menu['deleted'] ); + if ( $created && $deleted ) { + return null; + } + + $data = [ + 'id' => $menu_id, + 'kind' => 'classic', + ]; + if ( 0 === $menu_id ) { + // The job finds the menu: by its term taxonomy ID, or by an item. + if ( isset( $menu['tt'] ) ) { + $data['_tt'] = (int) $menu['tt']; + } else { + $data['_item'] = (int) $menu['item']; + } + } + if ( isset( $menu['name'] ) ) { + $data['name'] = $menu['name']; + } + + if ( $deleted ) { + $data['items'] = count( + array_filter( $items, static fn( array $item ): bool => isset( $item['removed'] ) ) + ); + if ( [] !== $hidden ) { + $data['_locations'] = $hidden; + } + + return [ + 'type' => 'MenuDeleted', + 'data' => $data, + ]; + } + + if ( $created ) { + if ( [] !== $shown ) { + $data['_locations'] = $shown; + } + + return [ + 'type' => 'MenuCreated', + 'data' => $data, + ]; + } + + $changes = []; + if ( isset( $menu['old_name'] ) && ( $menu['name'] ?? '' ) !== $menu['old_name'] ) { + $changes['name'] = [ + 'old' => $menu['old_name'], + 'new' => $menu['name'] ?? '', + ]; + } + if ( null !== $auto_add ) { + $changes['auto_add'] = [ + 'old' => ! $auto_add, + 'new' => $auto_add, + ]; + } + + $noted = []; + foreach ( $items as $item_id => $item ) { + $entry = []; + if ( ! empty( $item['added'] ) ) { + $entry['added'] = $item['noted'] ?? true; + } elseif ( isset( $item['removed'] ) ) { + $entry['removed'] = $item['removed']; + } elseif ( 'publish' === get_post_status( $item_id ) ) { + // A draft item isn't on the menu yet (the post is cached). + foreach ( $item['new'] as $field => $value ) { + if ( ( $item['old'][ $field ] ?? null ) !== $value ) { + $entry['old'][ $field ] = $item['old'][ $field ]; + $entry['new'][ $field ] = $value; + } + } + } + if ( [] !== $entry ) { + $noted[ $item_id ] = $entry; + } + } + + if ( [] === $changes && [] === $noted && [] === $shown && [] === $hidden ) { + return null; + } + + if ( [] !== $changes ) { + $data['changes'] = $changes; + } + if ( [] !== $noted ) { + $data['_items'] = $noted; + } + if ( [] !== $shown || [] !== $hidden ) { + $data['_locations'] = [ + 'added' => $shown, + 'removed' => $hidden, + ]; + } + + return [ + 'type' => 'MenuChanged', + 'data' => $data, + ]; + } + + /** + * The row of a block menu, or null when nothing about it changed. + * + * @param array $menu What was noted about the menu. + * + * @return array{type: string, data: array}|null + */ + private static function block_row( array $menu ): ?array { + $created = ! empty( $menu['created'] ); + $deleted = ! empty( $menu['deleted'] ); + $before = $menu['before'] ?? null; + $after = $menu['after'] ?? null; + if ( $created && $deleted ) { + return null; + } + + $data = [ + 'id' => (int) $menu['id'], + 'kind' => 'block', + ]; + + if ( $deleted && is_array( $before ) ) { + $data['name'] = $before['name']; + $data['_content'] = $before['content']; + + return [ + 'type' => 'MenuDeleted', + 'data' => $data, + ]; + } + + if ( ! is_array( $after ) ) { + return null; + } + $data['name'] = $after['name']; + + if ( $created ) { + $data['_content'] = $after['content']; + + return [ + 'type' => 'MenuCreated', + 'data' => $data, + ]; + } + + if ( ! is_array( $before ) ) { + return null; + } + + $changes = []; + if ( $before['name'] !== $after['name'] ) { + $changes['name'] = [ + 'old' => $before['name'], + 'new' => $after['name'], + ]; + } + if ( $before['status'] !== $after['status'] ) { + $changes['status'] = [ + 'old' => $before['status'], + 'new' => $after['status'], + ]; + } + if ( $before['content'] !== $after['content'] ) { + $data['_before'] = $before['content']; + $data['_after'] = $after['content']; + } elseif ( [] === $changes ) { + return null; + } + if ( [] !== $changes ) { + $data['changes'] = $changes; + } + + return [ + 'type' => 'MenuChanged', + 'data' => $data, + ]; + } + + /** + * Report what this request changed, once, at the end of the request. + * + * @return void + */ + public static function flush(): void { + $rows = self::rows(); + self::reset(); + if ( [] === $rows ) { + return; + } + + $room = Limiter::take( Limiter::KIND_MENU, count( $rows ) ); + foreach ( array_slice( $rows, 0, $room ) as $row ) { + do_action( ContentEvent::hook( $row['type'] ), $row['data'] ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- The hooks start with scanfully_. + } + } +} diff --git a/src/Events/MenuCreated.php b/src/Events/MenuCreated.php new file mode 100644 index 0000000..72806fb --- /dev/null +++ b/src/Events/MenuCreated.php @@ -0,0 +1,27 @@ + 1, + 'profile' => 2, + 'reset' => 3, + ]; + + /** + * Password changes noted in this request: user ID to via. + * + * @var array + */ + private static array $pending = []; + + /** + * Users whose password is being reset with a reset link, by ID. + * + * @var array + */ + private static array $resetting = []; + + /** + * Users created in this request, by ID. + * + * @var array + */ + private static array $created = []; + + /** + * Whether a login is being checked. WordPress stores the password again + * with a newer hash when a login uses an old one; that isn't a change. + * + * @var bool + */ + private static bool $authenticating = false; + + /** + * Constructor. + */ + public function __construct() { + parent::__construct( 'PasswordChanged', self::ACTION, 10, 2 ); + + add_action( 'user_register', [ self::class, 'note_user_created' ], 0, 1 ); + add_action( 'password_reset', [ self::class, 'note_reset_started' ], 10, 1 ); + add_action( 'after_password_reset', [ self::class, 'note_reset_done' ], 10, 1 ); + add_action( 'profile_update', [ self::class, 'note_profile_update' ], 10, 2 ); + // Only the user ID is used: the plain password is never kept. + add_action( 'wp_set_password', [ self::class, 'note_password_set' ], 10, 2 ); + add_filter( 'authenticate', [ self::class, 'note_authentication_started' ], 0, 1 ); + add_filter( 'authenticate', [ self::class, 'note_authentication_done' ], PHP_INT_MAX, 1 ); + add_action( 'shutdown', [ self::class, 'flush' ], 0, 0 ); + } + + /** + * Note a password change for a user. + * + * @param int $user_id The user ID. + * @param string $via How the password was changed. + * + * @return void + */ + private static function note( int $user_id, string $via ): void { + if ( $user_id < 1 ) { + return; + } + + $current = self::$pending[ $user_id ] ?? ''; + if ( '' === $current || self::VIA_RANK[ $via ] > self::VIA_RANK[ $current ] ) { + self::$pending[ $user_id ] = $via; + } + } + + /** + * `wp_set_password`: a password was stored. + * + * @param mixed $password The plain password; ignored. + * @param mixed $user_id The user ID. + * + * @return void + */ + public static function note_password_set( $password, $user_id ): void { + if ( self::$authenticating || ! is_numeric( $user_id ) ) { + return; + } + + $user_id = (int) $user_id; + self::note( $user_id, isset( self::$resetting[ $user_id ] ) ? 'reset' : 'other' ); + } + + /** + * `profile_update`: note a change when the password hash differs. + * + * @param mixed $user_id The user ID. + * @param mixed $before The user before the update. + * + * @return void + */ + public static function note_profile_update( $user_id, $before ): void { + $user = is_numeric( $user_id ) ? get_userdata( (int) $user_id ) : false; + if ( ! $user instanceof \WP_User || ! is_object( $before ) || ! isset( $before->user_pass ) ) { + return; + } + + if ( (string) $before->user_pass !== (string) $user->user_pass ) { + self::note( (int) $user_id, 'profile' ); + } + } + + /** + * `password_reset`: a reset with a reset link starts. + * + * @param mixed $user The user. + * + * @return void + */ + public static function note_reset_started( $user ): void { + if ( $user instanceof \WP_User ) { + self::$resetting[ (int) $user->ID ] = true; + } + } + + /** + * `after_password_reset`: the reset is done (also noted here for sites + * whose own wp_set_password() doesn't fire its action). + * + * @param mixed $user The user. + * + * @return void + */ + public static function note_reset_done( $user ): void { + if ( $user instanceof \WP_User ) { + self::note( (int) $user->ID, 'reset' ); + unset( self::$resetting[ (int) $user->ID ] ); + } + } + + /** + * `user_register`: setting the first password of a new user isn't a + * change. + * + * @param mixed $user_id The new user's ID. + * + * @return void + */ + public static function note_user_created( $user_id ): void { + if ( is_numeric( $user_id ) ) { + self::$created[ (int) $user_id ] = true; + } + } + + /** + * A login is checked from here on. + * + * @param mixed $user The authentication result so far, unchanged. + * + * @return mixed + */ + public static function note_authentication_started( $user ) { + self::$authenticating = true; + + return $user; + } + + /** + * The login check is done. + * + * @param mixed $user The authentication result, unchanged. + * + * @return mixed + */ + public static function note_authentication_done( $user ) { + self::$authenticating = false; + + return $user; + } + + /** + * Send the password changes noted in this request, one per user. + * + * @return void + */ + public static function flush(): void { + $pending = self::$pending; + self::$pending = []; + + foreach ( $pending as $user_id => $via ) { + if ( ! isset( self::$created[ $user_id ] ) ) { + do_action( 'scanfully_password_changed', $user_id, $via ); + } + } + } + + /** + * Get the post body + * + * @param array $data The data to send: user ID, via. + * + * @return array + */ + public function get_post_body( array $data ): array { + $user = get_userdata( (int) ( $data[0] ?? 0 ) ); + if ( ! $user instanceof \WP_User ) { + return []; + } + + $via = is_string( $data[1] ?? null ) && isset( self::VIA_RANK[ $data[1] ] ) ? $data[1] : 'other'; + + return array_merge( self::describe_user( $user, true ), [ 'via' => $via ] ); + } + + /** + * A check if a event should fire + * + * @param array $data The event data: user ID, via. + * + * @return bool + */ + public function should_fire( array $data ): bool { + $user = get_userdata( (int) ( $data[0] ?? 0 ) ); + if ( ! $user instanceof \WP_User || ! self::has_elevated_capabilities( $user ) ) { + return false; + } + + return ! self::is_rate_limited(); + } +} diff --git a/src/Events/PermalinksChanged.php b/src/Events/PermalinksChanged.php new file mode 100644 index 0000000..603deb2 --- /dev/null +++ b/src/Events/PermalinksChanged.php @@ -0,0 +1,74 @@ +listener_callback( '', $value ); + }, + 10, + 2 + ); + } + + /** + * Get the post body + * + * @param array $data The data to send: old value, new value. + * + * @return array + */ + public function get_post_body( array $data ): array { + return [ + 'old' => self::to_string( $data[0] ?? '' ), + 'new' => self::to_string( $data[1] ?? '' ), + ]; + } + + /** + * A check if a event should fire + * + * @param array $data The event data: old value, new value. + * + * @return bool + */ + public function should_fire( array $data ): bool { + return self::to_string( $data[0] ?? '' ) !== self::to_string( $data[1] ?? '' ); + } + + /** + * The structure as a string; anything else counts as plain permalinks. + * + * @param mixed $value The option value. + * + * @return string + */ + private static function to_string( $value ): string { + return is_string( $value ) ? $value : ''; + } +} diff --git a/src/Events/PluginDeleted.php b/src/Events/PluginDeleted.php new file mode 100644 index 0000000..9c3653c --- /dev/null +++ b/src/Events/PluginDeleted.php @@ -0,0 +1,90 @@ + + */ + private static array $pending = []; + + /** + * Constructor. + */ + public function __construct() { + parent::__construct( 'PluginDeleted', 'deleted_plugin', 10, 2 ); + + add_action( 'delete_plugin', [ self::class, 'remember' ], 10, 1 ); + } + + /** + * Read the details of a plugin that is about to be deleted. + * + * @param mixed $plugin_file Plugin basename. + * + * @return void + */ + public static function remember( $plugin_file ): void { + if ( ! is_string( $plugin_file ) || '' === $plugin_file ) { + return; + } + + $plugin_data = get_file_data( + WP_PLUGIN_DIR . '/' . $plugin_file, + [ + 'Name' => 'Plugin Name', + 'Version' => 'Version', + ] + ); + + self::$pending[ $plugin_file ] = [ + 'name' => '' !== ( $plugin_data['Name'] ?? '' ) ? $plugin_data['Name'] : $plugin_file, + 'slug' => $plugin_file, + 'version' => $plugin_data['Version'] ?? '', + ]; + } + + /** + * Get the post body + * + * @param array $data The data to send: plugin basename, whether it was deleted. + * + * @return array + */ + public function get_post_body( array $data ): array { + $plugin_file = (string) ( $data[0] ?? '' ); + + return self::$pending[ $plugin_file ] ?? [ + 'name' => $plugin_file, + 'slug' => $plugin_file, + 'version' => '', + ]; + } + + /** + * A check if a event should fire + * + * @param array $data The event data: plugin basename, whether it was deleted. + * + * @return bool + */ + public function should_fire( array $data ): bool { + return is_string( $data[0] ?? null ) && '' !== $data[0] && true === ( $data[1] ?? false ); + } +} diff --git a/src/Events/PluginFileEdited.php b/src/Events/PluginFileEdited.php new file mode 100644 index 0000000..e800a84 --- /dev/null +++ b/src/Events/PluginFileEdited.php @@ -0,0 +1,30 @@ + 'Plugin Name', + 'Version' => 'Version', + 'Author' => 'Author', + ] + ); + + return [ + 'name' => '' !== ( $plugin_data['Name'] ?? '' ) ? $plugin_data['Name'] : $plugin, + 'slug' => $plugin, + 'version' => $plugin_data['Version'] ?? '', + 'author' => $plugin_data['Author'] ?? '', + ]; + } + + /** + * A check if a event should fire + * + * @param array $data The event data: the upgrader, the hook extras. + * + * @return bool + */ + public function should_fire( array $data ): bool { + return '' !== self::installed_plugin( $data ); + } + + /** + * The basename of the plugin a successful install put in place, or '' + * when this wasn't a successful plugin install. + * + * @param array $data The event data: the upgrader, the hook extras. + * + * @return string + */ + private static function installed_plugin( array $data ): string { + $upgrader = $data[0] ?? null; + $hook_extra = $data[1] ?? null; + + if ( ! is_array( $hook_extra ) || 'install' !== ( $hook_extra['action'] ?? '' ) || 'plugin' !== ( $hook_extra['type'] ?? '' ) ) { + return ''; + } + + // The upgrader's result is an array only when the install succeeded. + if ( ! is_object( $upgrader ) || ! method_exists( $upgrader, 'plugin_info' ) || ! isset( $upgrader->result ) || ! is_array( $upgrader->result ) ) { + return ''; + } + + $plugin = $upgrader->plugin_info(); + + return is_string( $plugin ) ? $plugin : ''; + } +} diff --git a/src/Events/PluginUpdateFailed.php b/src/Events/PluginUpdateFailed.php new file mode 100644 index 0000000..4f32708 --- /dev/null +++ b/src/Events/PluginUpdateFailed.php @@ -0,0 +1,25 @@ + $noted The changes as the Collector noted them. + * @param array $data The event data (summaries of the post before and after). + * + * @return array + */ + public static function resolve( array $noted, array $data ): array { + $post_id = (int) ( $data['id'] ?? 0 ); + $post_type = (string) ( $data['post']['post_type'] ?? '' ); + $changes = []; + + foreach ( [ 'title', 'slug' ] as $name ) { + if ( self::is_pair( $noted[ $name ] ?? null ) ) { + $changes[ $name ] = self::pair( $noted[ $name ] ); + } + } + + if ( isset( $noted['slug'] ) || isset( $noted['parent'] ) || isset( $noted['date'] ) ) { + $url = self::url_change( $data['post_before'] ?? null, $data['post'] ?? null ); + if ( null !== $url ) { + $changes['url'] = $url; + } + } + + if ( isset( $noted['content'] ) && is_array( $noted['content'] ) ) { + $changes['content'] = self::content( $noted['content'] ); + } + + foreach ( [ 'excerpt', 'date', 'comments', 'menu_order', 'password' ] as $name ) { + if ( self::is_pair( $noted[ $name ] ?? null ) ) { + $changes[ $name ] = self::pair( $noted[ $name ] ); + } + } + + if ( self::is_pair( $noted['parent'] ?? null ) ) { + $changes['parent'] = [ + 'old' => self::parent( (int) $noted['parent']['old'] ), + 'new' => self::parent( (int) $noted['parent']['new'] ), + ]; + } + + if ( self::is_pair( $noted['author'] ?? null ) ) { + $changes['author'] = [ + 'old' => PostSaved::author_name( (int) $noted['author']['old'] ), + 'new' => PostSaved::author_name( (int) $noted['author']['new'] ), + ]; + } + + if ( isset( $noted['fields'] ) && is_array( $noted['fields'] ) ) { + $fields = self::fields( $post_id, $post_type, $noted['fields'] ); + if ( [] !== $fields ) { + $changes['fields'] = $fields; + } + } + + if ( isset( $noted['terms'] ) && is_array( $noted['terms'] ) ) { + $terms = self::terms( $noted['terms'] ); + if ( [] !== $terms ) { + $changes['terms'] = $terms; + } + } + + return $changes; + } + + /** + * Whether a value is an old and new pair. + * + * @param mixed $value The value. + * + * @return bool + */ + private static function is_pair( $value ): bool { + return is_array( $value ) && array_key_exists( 'old', $value ) && array_key_exists( 'new', $value ); + } + + /** + * An old and new pair with nothing else. + * + * @param array $value The pair. + * + * @return array{old: mixed, new: mixed} + */ + private static function pair( array $value ): array { + return [ + 'old' => $value['old'], + 'new' => $value['new'], + ]; + } + + /** + * The content diff. + * + * @param array $source Where the content before and after is. + * + * @return array + */ + private static function content( array $source ): array { + if ( isset( $source['revisions'] ) && is_array( $source['revisions'] ) ) { + $after = get_post( (int) ( $source['revisions']['last'] ?? 0 ) ); + if ( ! $after instanceof \WP_Post || 'revision' !== $after->post_type ) { + return ContentDiff::unchanged_text( 'unavailable' ); + } + + $before = get_post( self::revision_before( (int) $after->post_parent, (int) ( $source['revisions']['first'] ?? 0 ) ) ); + if ( ! $before instanceof \WP_Post ) { + return ContentDiff::unchanged_text( 'no_earlier_version' ); + } + + return ContentDiff::compare( (string) $before->post_content, (string) $after->post_content ); + } + + if ( isset( $source['stash'] ) && is_array( $source['stash'] ) ) { + return ContentDiff::compare( (string) ( $source['stash']['old'] ?? '' ), (string) ( $source['stash']['new'] ?? '' ) ); + } + + return ContentDiff::unchanged_text( ! empty( $source['too_large'] ) ? 'too_large' : 'unavailable' ); + } + + /** + * The revision of a post made before a given one, skipping autosaves; + * 0 when there is none. + * + * @param int $post_id The post ID. + * @param int $revision_id The revision ID. + * + * @return int + */ + private static function revision_before( int $post_id, int $revision_id ): int { + global $wpdb; + + if ( $post_id < 1 || $revision_id < 1 ) { + return 0; + } + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One indexed lookup in a background job; WordPress has no API for "the revision before this one". + return (int) $wpdb->get_var( + $wpdb->prepare( + "SELECT ID FROM {$wpdb->posts} WHERE post_parent = %d AND post_type = 'revision' AND ID < %d AND post_name NOT LIKE %s ORDER BY ID DESC LIMIT 1", + $post_id, + $revision_id, + '%' . $wpdb->esc_like( '-autosave-v1' ) + ) + ); + } + + /** + * The URL before and after, when a published post's URL changed. + * + * @param mixed $before The summary of the post before. + * @param mixed $after The summary of the post after. + * + * @return array{old: string, new: string}|null + */ + private static function url_change( $before, $after ): ?array { + if ( ! is_array( $before ) || ! is_array( $after ) || 'publish' !== ( $before['post_status'] ?? '' ) || 'publish' !== ( $after['post_status'] ?? '' ) ) { + return null; + } + + $old = self::permalink( $before ); + $new = self::permalink( $after ); + if ( '' === $old || '' === $new || $old === $new ) { + return null; + } + + return [ + 'old' => $old, + 'new' => $new, + ]; + } + + /** + * The permalink of a post as a summary describes it. + * + * @param array $summary The summary. + * + * @return string + */ + private static function permalink( array $summary ): string { + unset( $summary['has_password'] ); + $summary['filter'] = 'raw'; + + $link = get_permalink( new \WP_Post( (object) $summary ) ); + + return is_string( $link ) ? $link : ''; + } + + /** + * A parent post: its ID and title. + * + * @param int $post_id The parent's ID; 0 for none. + * + * @return array{id: int, title: string} + */ + private static function parent( int $post_id ): array { + $post = $post_id > 0 ? get_post( $post_id ) : null; + + return [ + 'id' => $post_id, + 'title' => $post instanceof \WP_Post ? self::plain( $post->post_title ) : '', + ]; + } + + /** + * The custom field changes, with labels and readable values. + * + * @param int $post_id The post ID. + * @param string $post_type The post type. + * @param array> $fields The noted changes, per key. + * + * @return array> + */ + private static function fields( int $post_id, string $post_type, array $fields ): array { + $changes = []; + foreach ( $fields as $key => $field ) { + if ( ! is_array( $field ) || ! isset( $field['change'] ) ) { + continue; + } + + $key = (string) $key; + $entry = [ + 'key' => $key, + 'change' => (string) $field['change'], + ]; + + $label = self::field_label( $post_id, $key ); + if ( '' !== $label ) { + $entry['label'] = $label; + } + + foreach ( [ 'old', 'new' ] as $side ) { + if ( isset( $field[ $side ] ) ) { + $entry[ $side ] = self::field_value( $key, (string) $field[ $side ], $post_type ); + } + } + + if ( ! empty( $field['large'] ) ) { + $entry['large'] = true; + } + + $changes[] = $entry; + } + + return $changes; + } + + /** + * The label of a custom field, when WordPress knows one: an ACF field's + * label. + * + * @param int $post_id The post ID. + * @param string $key The key. + * + * @return string + */ + private static function field_label( int $post_id, string $key ): string { + if ( '_' === $key[0] || ! function_exists( 'acf_get_field' ) ) { + return ''; + } + + $reference = get_post_meta( $post_id, '_' . $key, true ); + if ( ! is_string( $reference ) || 0 !== strpos( $reference, 'field_' ) ) { + return ''; + } + + $field = acf_get_field( $reference ); + + return is_array( $field ) && isset( $field['label'] ) ? self::plain( $field['label'] ) : ''; + } + + /** + * A readable custom field value: a featured image's file name, a page + * template's name; other values as they are. + * + * @param string $key The key. + * @param string $value The value. + * @param string $post_type The post type. + * + * @return string + */ + private static function field_value( string $key, string $value, string $post_type ): string { + if ( '_thumbnail_id' === $key && ctype_digit( $value ) ) { + $file = get_attached_file( (int) $value ); + + return is_string( $file ) && '' !== $file ? basename( $file ) : $value; + } + + if ( '_wp_page_template' === $key && 'default' !== $value ) { + $templates = wp_get_theme()->get_page_templates( null, '' !== $post_type ? $post_type : 'page' ); + + return isset( $templates[ $value ] ) ? self::plain( $templates[ $value ] ) : $value; + } + + return $value; + } + + /** + * The term changes, with names. + * + * @param array $terms The noted changes, per taxonomy. + * + * @return array> + */ + public static function terms( array $terms ): array { + $changes = []; + foreach ( $terms as $taxonomy => $set ) { + $taxonomy = (string) $taxonomy; + $added = self::term_names( $taxonomy, (array) ( $set['added'] ?? [] ) ); + $removed = self::term_names( $taxonomy, (array) ( $set['removed'] ?? [] ) ); + if ( [] === $added && [] === $removed ) { + continue; + } + + $object = get_taxonomy( $taxonomy ); + $changes[] = [ + 'taxonomy' => $taxonomy, + 'label' => is_object( $object ) && isset( $object->labels->name ) ? self::plain( $object->labels->name ) : $taxonomy, + 'added' => $added, + 'removed' => $removed, + ]; + } + + return $changes; + } + + /** + * Names of terms by their term taxonomy IDs; terms that no longer exist + * are left out. + * + * @param string $taxonomy The taxonomy. + * @param array $ids Term taxonomy IDs. + * + * @return string[] + */ + private static function term_names( string $taxonomy, array $ids ): array { + $names = []; + foreach ( $ids as $id ) { + $term = get_term_by( 'term_taxonomy_id', (int) $id, $taxonomy ); + if ( $term instanceof \WP_Term ) { + $names[] = self::plain( $term->name ); + } + } + + return $names; + } + + /** + * Plain text from a value WordPress stores HTML-encoded. + * + * @param mixed $value The value. + * + * @return string + */ + private static function plain( $value ): string { + return html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' ); + } +} diff --git a/src/Events/PostChanges/Collector.php b/src/Events/PostChanges/Collector.php new file mode 100644 index 0000000..c703dab --- /dev/null +++ b/src/Events/PostChanges/Collector.php @@ -0,0 +1,960 @@ + + */ + private static array $saved = []; + + /** + * Custom field changes in this request, per post and key. + * + * @var array>> + */ + private static array $fields = []; + + /** + * Term changes in this request, per post and taxonomy: term taxonomy IDs + * before the first change and after the last. + * + * @var array> + */ + private static array $terms = []; + + /** + * Revisions made in this request, per post: the first and the last, and + * whether the post had a revision before them. + * + * @var array + */ + private static array $revisions = []; + + /** + * Posts WordPress found an earlier revision for while saving, by ID. + * + * @var array + */ + private static array $earlier_revisions = []; + + /** + * Posts saved in this request past the first MAX_POSTS, as summary + * items, by ID. + * + * @var array> + */ + private static array $counted = []; + + /** + * Posts deleted permanently in this request, by ID: what the event + * reports, noted while the post still existed, and whether the delete + * went through. + * + * @var array + */ + private static array $deleted = []; + + /** + * Term taxonomy IDs added to the posts the last flush reported, so a + * term created for one of them isn't reported again on its own. + * + * @var array + */ + private static array $added_terms = []; + + /** + * Whether the hooks are added. + * + * @var bool + */ + private static bool $set_up = false; + + /** + * Add the hooks. + * + * @return void + */ + public static function setup(): void { + if ( self::$set_up ) { + return; + } + self::$set_up = true; + + add_action( 'wp_after_insert_post', [ self::class, 'note_saved' ], 10, 4 ); + add_action( 'update_post_meta', [ self::class, 'note_meta_updated' ], 10, 4 ); + add_action( 'added_post_meta', [ self::class, 'note_meta_added' ], 10, 4 ); + add_action( 'delete_post_meta', [ self::class, 'note_meta_deleted' ], 10, 4 ); + add_action( 'set_object_terms', [ self::class, 'note_terms' ], 10, 6 ); + add_action( 'before_delete_post', [ self::class, 'note_deleting' ], 10, 2 ); + add_action( 'deleted_post', [ self::class, 'note_deleted' ], 10, 1 ); + add_action( '_wp_put_post_revision', [ self::class, 'note_revision' ], 10, 2 ); + add_filter( 'wp_save_post_revision_check_for_changes', [ self::class, 'note_earlier_revision' ], PHP_INT_MAX, 3 ); + add_action( 'shutdown', [ self::class, 'flush' ], 0, 0 ); + } + + /** + * Forget everything noted (tests, and after a flush). + * + * @return void + */ + public static function reset(): void { + self::$saved = []; + self::$fields = []; + self::$terms = []; + self::$revisions = []; + self::$earlier_revisions = []; + self::$counted = []; + self::$deleted = []; + self::$added_terms = []; + } + + /** + * Term taxonomy IDs added to the posts the last flush reported. + * + * @return array + */ + public static function added_terms(): array { + return self::$added_terms; + } + + /** + * Whether an import runs; imports save many posts and aren't edits. + * + * @return bool + */ + private static function importing(): bool { + return defined( 'WP_IMPORTING' ) && WP_IMPORTING; + } + + /** + * `wp_after_insert_post`: a post was saved, after its terms and custom + * fields. + * + * @param mixed $post_id The post ID. + * @param mixed $post The post. + * @param mixed $update Whether an existing post was updated. + * @param mixed $post_before The post before the save, or null. + * + * @return void + */ + public static function note_saved( $post_id, $post, $update, $post_before ): void { + if ( self::importing() || ! is_object( $post ) ) { + return; + } + + $post_id = (int) $post_id; + if ( isset( self::$saved[ $post_id ] ) ) { + self::$saved[ $post_id ]['after'] = clone $post; + return; + } + + if ( count( self::$saved ) >= self::MAX_POSTS ) { + self::count_saved( $post_id, $post, (bool) $update, is_object( $post_before ) ? $post_before : null ); + return; + } + + self::$saved[ $post_id ] = [ + 'before' => is_object( $post_before ) ? clone $post_before : null, + 'after' => clone $post, + 'update' => (bool) $update, + ]; + } + + /** + * A post saved past the first MAX_POSTS of the request: only counted for + * its summary row, from what this save changed. Its custom fields and + * terms were noted before the save; later changes to it in the request + * are not counted. + * + * @param int $post_id The post ID. + * @param object $post The post. + * @param bool $update Whether an existing post was updated. + * @param object|null $before The post before the save. + * + * @return void + */ + private static function count_saved( int $post_id, object $post, bool $update, ?object $before ): void { + $fields = self::$fields[ $post_id ] ?? []; + $terms = self::$terms[ $post_id ] ?? []; + unset( self::$fields[ $post_id ], self::$terms[ $post_id ], self::$revisions[ $post_id ], self::$earlier_revisions[ $post_id ] ); + + if ( isset( self::$counted[ $post_id ] ) || count( self::$counted ) >= self::MAX_ITEMS || ! PostSaved::is_reported( $post ) ) { + return; + } + + $created = self::is_new( $update, $before ); + $changes = $created || null === $before ? [] : self::changes( $before, $post, $fields, $terms, null ); + if ( null === $changes ) { + return; + } + + self::$counted[ $post_id ] = self::saved_item( $post_id, $post, $before, $changes, $created ); + } + + /** + * Whether a save made the post: a new post, or the auto-draft the editor + * opened first. + * + * @param bool $update Whether an existing post was updated. + * @param object|null $before The post before the save. + * + * @return bool + */ + private static function is_new( bool $update, ?object $before ): bool { + return ! $update || null === $before || 'auto-draft' === ( $before->post_status ?? '' ); + } + + /** + * `before_delete_post`: a post is about to be deleted permanently. What + * the event reports is read from the post WordPress passes; nothing is + * looked up. + * + * @param mixed $post_id The post ID. + * @param mixed $post The post. + * + * @return void + */ + public static function note_deleting( $post_id, $post = null ): void { + $post_id = (int) $post_id; + if ( $post_id < 1 || ! is_object( $post ) || isset( self::$deleted[ $post_id ] ) || count( self::$deleted ) >= self::MAX_ITEMS ) { + return; + } + + // What the save hooks noted about the post is no longer a change. + unset( self::$fields[ $post_id ], self::$terms[ $post_id ] ); + + if ( ! PostDeleted::is_reported( $post ) ) { + return; + } + + self::$deleted[ $post_id ] = [ + 'title' => (string) ( $post->post_title ?? '' ), + 'post_type' => (string) $post->post_type, + 'post_status' => (string) $post->post_status, + // WordPress empties the trash in the `wp_scheduled_delete` cron job. + 'expired' => doing_action( 'wp_scheduled_delete' ), + 'done' => false, + ]; + } + + /** + * `deleted_post`: the post is gone. + * + * @param mixed $post_id The post ID. + * + * @return void + */ + public static function note_deleted( $post_id ): void { + $post_id = (int) $post_id; + if ( isset( self::$deleted[ $post_id ] ) ) { + self::$deleted[ $post_id ]['done'] = true; + } + } + + /** + * `update_post_meta`: a custom field is about to change. + * + * @param mixed $meta_id The meta ID. + * @param mixed $object_id The post ID. + * @param mixed $meta_key The key. + * @param mixed $value The new value. + * + * @return void + */ + public static function note_meta_updated( $meta_id, $object_id, $meta_key, $value ): void { + // WordPress adds a field that doesn't exist yet instead of updating it. + self::note_field( (int) $object_id, (string) $meta_key, true, $value, true ); + } + + /** + * `added_post_meta`: a custom field was added. + * + * @param mixed $meta_id The meta ID. + * @param mixed $object_id The post ID. + * @param mixed $meta_key The key. + * @param mixed $value The value. + * + * @return void + */ + public static function note_meta_added( $meta_id, $object_id, $meta_key, $value ): void { + self::note_field( (int) $object_id, (string) $meta_key, true, $value, false ); + } + + /** + * `delete_post_meta`: a custom field is about to be removed. + * + * @param mixed $meta_ids The meta IDs. + * @param mixed $object_id The post ID. + * @param mixed $meta_key The key. + * @param mixed $value The value asked to remove, if any. + * + * @return void + */ + public static function note_meta_deleted( $meta_ids, $object_id, $meta_key, $value ): void { + // WordPress only fires this when it found the field. + self::note_field( (int) $object_id, (string) $meta_key, false, null, true ); + } + + /** + * Note a custom field change: the value before the first change in this + * request and after the last. + * + * @param int $post_id The post ID. + * @param string $key The key. + * @param bool $exists Whether the field exists after the change. + * @param mixed $value The value after the change. + * @param bool $existed Whether the field existed before the change. + * + * @return void + */ + private static function note_field( int $post_id, string $key, bool $exists, $value, bool $existed ): void { + if ( $post_id < 1 || self::importing() || ! Fields::is_counted( $key ) || self::is_settled( $post_id ) ) { + return; + } + + if ( ! isset( self::$fields[ $post_id ][ $key ] ) ) { + if ( ! isset( self::$fields[ $post_id ] ) && count( self::$fields ) >= self::MAX_PENDING ) { + return; + } + if ( count( self::$fields[ $post_id ] ?? [] ) >= self::MAX_FIELDS ) { + return; + } + + $cached = $existed ? self::cached_value( $post_id, $key ) : [ + 'found' => false, + 'value' => null, + ]; + + self::$fields[ $post_id ][ $key ] = [ + 'existed' => $existed, + 'old' => $existed && $cached['found'] ? Fields::describe( $cached['value'] ) : null, + 'old_hash' => $existed && $cached['found'] ? Fields::fingerprint( $cached['value'] ) : '', + ]; + } + + self::$fields[ $post_id ][ $key ]['exists'] = $exists; + self::$fields[ $post_id ][ $key ]['new'] = $exists ? Fields::describe( $value ) : null; + self::$fields[ $post_id ][ $key ]['new_hash'] = $exists ? Fields::fingerprint( $value ) : ''; + } + + /** + * Whether nothing more is noted about a post in this request: it is + * being deleted (WordPress removes its fields one by one), or it was + * already counted for a summary row. + * + * @param int $post_id The post ID. + * + * @return bool + */ + private static function is_settled( int $post_id ): bool { + return isset( self::$deleted[ $post_id ] ) || isset( self::$counted[ $post_id ] ); + } + + /** + * A post's custom field value from the meta cache, without a query. + * + * @param int $post_id The post ID. + * @param string $key The key. + * + * @return array{found: bool, value: mixed} + */ + private static function cached_value( int $post_id, string $key ): array { + $cache = wp_cache_get( $post_id, 'post_meta' ); + if ( ! is_array( $cache ) || ! isset( $cache[ $key ] ) || ! is_array( $cache[ $key ] ) || [] === $cache[ $key ] ) { + return [ + 'found' => false, + 'value' => null, + ]; + } + + return [ + 'found' => true, + 'value' => maybe_unserialize( $cache[ $key ][0] ), + ]; + } + + /** + * `set_object_terms`: the terms of an object in a taxonomy were set. + * + * @param mixed $object_id The object ID. + * @param mixed $terms The terms asked for. + * @param mixed $tt_ids The term taxonomy IDs set. + * @param mixed $taxonomy The taxonomy. + * @param mixed $append Whether the terms were added to the existing ones. + * @param mixed $old_tt_ids The term taxonomy IDs before. + * + * @return void + */ + public static function note_terms( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ): void { + $post_id = (int) $object_id; + $taxonomy = (string) $taxonomy; + if ( $post_id < 1 || self::importing() || self::is_settled( $post_id ) || ! self::is_counted_taxonomy( $taxonomy ) ) { + return; + } + + $old = array_map( 'intval', is_array( $old_tt_ids ) ? $old_tt_ids : [] ); + $new = array_map( 'intval', is_array( $tt_ids ) ? $tt_ids : [] ); + if ( $append ) { + $new = array_values( array_unique( array_merge( $old, $new ) ) ); + } + + if ( ! isset( self::$terms[ $post_id ][ $taxonomy ] ) ) { + if ( ! isset( self::$terms[ $post_id ] ) && count( self::$terms ) >= self::MAX_PENDING ) { + return; + } + self::$terms[ $post_id ][ $taxonomy ] = [ + 'old' => $old, + 'new' => $new, + ]; + return; + } + + self::$terms[ $post_id ][ $taxonomy ]['new'] = $new; + } + + /** + * Whether term changes in a taxonomy count: taxonomies with an admin + * screen, and post formats. + * + * @param string $taxonomy The taxonomy. + * + * @return bool + */ + private static function is_counted_taxonomy( string $taxonomy ): bool { + if ( 'post_format' === $taxonomy ) { + return true; + } + + $object = get_taxonomy( $taxonomy ); + + return is_object( $object ) && ! empty( $object->show_ui ); + } + + /** + * `_wp_put_post_revision`: a revision of a post was made. + * + * @param mixed $revision_id The revision ID. + * @param mixed $post_id The post ID (WordPress 6.4 and later). + * + * @return void + */ + public static function note_revision( $revision_id, $post_id = null ): void { + $revision_id = (int) $revision_id; + if ( $revision_id < 1 || self::importing() ) { + return; + } + + $post_id = null !== $post_id ? (int) $post_id : (int) wp_get_post_parent_id( $revision_id ); + if ( $post_id < 1 ) { + return; + } + + if ( isset( self::$revisions[ $post_id ] ) ) { + self::$revisions[ $post_id ]['last'] = $revision_id; + return; + } + + self::$revisions[ $post_id ] = [ + 'first' => $revision_id, + 'last' => $revision_id, + 'earlier' => isset( self::$earlier_revisions[ $post_id ] ), + ]; + } + + /** + * `wp_save_post_revision_check_for_changes`: WordPress only asks this + * when the post already has a revision, so it tells for free whether the + * content before this save is in a revision. A post's first revision + * (its first edit after it was created) has nothing before it. + * + * @param mixed $check_for_changes Whether to check for changes; unchanged. + * @param mixed $latest_revision The latest revision. + * @param mixed $post The post being saved. + * + * @return mixed + */ + public static function note_earlier_revision( $check_for_changes, $latest_revision, $post ) { + $post_id = is_object( $post ) && isset( $post->ID ) ? (int) $post->ID : 0; + if ( $post_id > 0 && ! isset( self::$revisions[ $post_id ] ) ) { + self::$earlier_revisions[ $post_id ] = true; + } + + return $check_for_changes; + } + + /** + * Report each saved post that changed and each deleted post, once, at + * the end of the request. + * + * @return void + */ + public static function flush(): void { + $saved = self::$saved; + $fields = self::$fields; + $terms = self::$terms; + $revisions = self::$revisions; + $counted = self::$counted; + $deleted = self::$deleted; + self::reset(); + + $items = []; + $created = []; + foreach ( $saved as $post_id => $save ) { + $before = $save['before']; + $after = $save['after']; + $new = self::is_new( $save['update'], $before ); + if ( $new ) { + $created[ $post_id ] = true; + } + // A deleted post's saves are not reported: only its delete, or + // nothing when it was also made in this request. + if ( isset( $deleted[ $post_id ] ) || ! PostSaved::is_reported( $after ) ) { + continue; + } + + $changes = $new || null === $before ? [] : self::changes( $before, $after, $fields[ $post_id ] ?? [], $terms[ $post_id ] ?? [], $revisions[ $post_id ] ?? null ); + if ( null === $changes ) { + continue; + } + + $item = self::saved_item( $post_id, $after, $before, $changes, $new ); + $item['event'] = [ + 'hook' => self::ACTION, + 'args' => [ $post_id, $after, $save['update'], $before, $changes ], + ]; + $items[] = $item; + } + + foreach ( $counted as $post_id => $item ) { + if ( 'created' === $item['action'] ) { + $created[ $post_id ] = true; + } + if ( ! isset( $deleted[ $post_id ] ) ) { + $items[] = $item; + } + } + + foreach ( $deleted as $post_id => $delete ) { + if ( $delete['done'] && ! isset( $created[ $post_id ] ) ) { + $items[] = self::deleted_item( $post_id, $delete ); + } + } + + foreach ( $items as $item ) { + foreach ( (array) ( $item['terms'] ?? [] ) as $set ) { + foreach ( (array) ( $set['added'] ?? [] ) as $tt_id ) { + self::$added_terms[ (int) $tt_id ] = true; + } + } + } + + Report::send( Report::KIND_POST, $items ); + } + + /** + * A saved post as a summary item (see Content\Summary). + * + * @param int $post_id The post ID. + * @param object $after The post after its saves. + * @param object|null $before The post before. + * @param array $changes What changed (empty for a new post or a status change only). + * @param bool $created Whether the post was made in this request. + * + * @return array + */ + private static function saved_item( int $post_id, object $after, ?object $before, array $changes, bool $created ): array { + $item = [ + 'action' => $created ? 'created' : self::action( (string) ( $before->post_status ?? '' ), (string) ( $after->post_status ?? '' ) ), + 'group' => (string) ( $after->post_type ?? '' ), + 'id' => $post_id, + 'title' => Summary::title( (string) ( $after->post_title ?? '' ) ), + ]; + if ( [] !== $changes ) { + $item['changed'] = array_keys( $changes ); + } + if ( isset( $changes['terms'] ) ) { + $item['terms'] = $changes['terms']; + } + + return $item; + } + + /** + * What a save did to an existing post, by its status before and after. + * + * @param string $from The status before. + * @param string $to The status after. + * + * @return string + */ + private static function action( string $from, string $to ): string { + if ( $from === $to ) { + return 'updated'; + } + if ( 'trash' === $to ) { + return 'trashed'; + } + if ( 'trash' === $from ) { + return 'restored'; + } + + switch ( $to ) { + case 'publish': + return 'published'; + case 'draft': + return 'drafted'; + case 'private': + return 'privated'; + default: + return 'updated'; + } + } + + /** + * A deleted post as a summary item, with its own `PostDeleted` event. + * + * @param int $post_id The post ID. + * @param array $delete What was noted before the delete. + * + * @return array + */ + private static function deleted_item( int $post_id, array $delete ): array { + $object = get_post_type_object( $delete['post_type'] ); + $data = [ + 'id' => $post_id, + 'title' => $delete['title'], + 'post_type' => $delete['post_type'], + 'type_label' => is_object( $object ) && isset( $object->labels->singular_name ) ? Summary::title( (string) $object->labels->singular_name ) : $delete['post_type'], + 'post_status' => $delete['post_status'], + ]; + if ( $delete['expired'] ) { + $data['expired'] = true; + $data['trash_days'] = defined( 'EMPTY_TRASH_DAYS' ) ? (int) EMPTY_TRASH_DAYS : 30; + } + + return [ + 'action' => 'deleted', + 'group' => $delete['post_type'], + 'id' => $post_id, + 'title' => Summary::title( $delete['title'] ), + 'expired' => $delete['expired'], + 'event' => [ + 'hook' => ContentEvent::hook( 'PostDeleted' ), + 'args' => [ $data ], + ], + ]; + } + + /** + * What changed between a post before and after its saves in this + * request, as the background job expects it. Null when nothing tracked + * changed; an empty array when only the status changed. + * + * @param object $before The post before. + * @param object $after The post after. + * @param array> $fields Custom field changes, per key. + * @param array $terms Term changes, per taxonomy. + * @param array|null $revisions Revisions made in this request (first, last, earlier). + * + * @return array|null + */ + public static function changes( object $before, object $after, array $fields, array $terms, ?array $revisions ): ?array { + $changes = []; + + foreach ( [ + 'post_title' => 'title', + 'post_excerpt' => 'excerpt', + 'comment_status' => 'comments', + ] as $field => $name ) { + $old = (string) ( $before->$field ?? '' ); + $new = (string) ( $after->$field ?? '' ); + if ( $old !== $new ) { + $changes[ $name ] = [ + 'old' => self::cap( $old ), + 'new' => self::cap( $new ), + ]; + } + } + + // A draft has no slug until it is published; getting one isn't a + // change. Neither is the `__trashed` slug WordPress gives a post in + // the trash, or getting the old one back. + $old_slug = (string) ( $before->post_name ?? '' ); + $new_slug = (string) ( $after->post_name ?? '' ); + $trashed = 'trash' === ( $before->post_status ?? '' ) || 'trash' === ( $after->post_status ?? '' ); + if ( '' !== $old_slug && $old_slug !== $new_slug && ! $trashed ) { + $changes['slug'] = [ + 'old' => $old_slug, + 'new' => $new_slug, + ]; + } + + foreach ( [ + 'post_parent' => 'parent', + 'post_author' => 'author', + 'menu_order' => 'menu_order', + ] as $field => $name ) { + $old = (int) ( $before->$field ?? 0 ); + $new = (int) ( $after->$field ?? 0 ); + if ( $old !== $new ) { + $changes[ $name ] = [ + 'old' => $old, + 'new' => $new, + ]; + } + } + + if ( in_array( (string) ( $before->post_status ?? '' ), self::FIXED_DATE_STATUSES, true ) && (string) ( $before->post_date ?? '' ) !== (string) ( $after->post_date ?? '' ) ) { + $changes['date'] = [ + 'old' => (string) ( $before->post_date ?? '' ), + 'new' => (string) ( $after->post_date ?? '' ), + ]; + } + + // Never the password itself: only whether the post has one, and + // whether it changed. + $old_password = (string) ( $before->post_password ?? '' ); + $new_password = (string) ( $after->post_password ?? '' ); + if ( $old_password !== $new_password ) { + $changes['password'] = [ + 'old' => '' !== $old_password, + 'new' => '' !== $new_password, + ]; + } + + $old_content = (string) ( $before->post_content ?? '' ); + $new_content = (string) ( $after->post_content ?? '' ); + if ( $old_content !== $new_content ) { + $changes['content'] = self::content_source( $after, $old_content, $new_content, $revisions ); + } + + $field_changes = self::field_changes( $fields ); + if ( [] !== $field_changes ) { + $changes['fields'] = $field_changes; + } + + $term_changes = self::term_changes( $terms ); + if ( [] !== $term_changes ) { + $changes['terms'] = $term_changes; + } + + if ( [] !== $changes ) { + return $changes; + } + + return (string) ( $before->post_status ?? '' ) !== (string) ( $after->post_status ?? '' ) ? [] : null; + } + + /** + * Where the background job finds the content before and after: the + * revisions WordPress made, or (without them) the content itself, which + * the event stores once for the job. + * + * @param object $after The post after. + * @param string $old_content The content before. + * @param string $new_content The content after. + * @param array|null $revisions Revisions made in this request (first, last, earlier). + * + * @return array + */ + private static function content_source( object $after, string $old_content, string $new_content, ?array $revisions ): array { + // The content before is in a revision only when the post had one + // before this request. + if ( null !== $revisions && ! empty( $revisions['earlier'] ) && self::keeps_earlier_revision( $after ) ) { + return [ + 'revisions' => [ + 'first' => (int) $revisions['first'], + 'last' => (int) $revisions['last'], + ], + ]; + } + + if ( strlen( $old_content ) > self::MAX_CONTENT || strlen( $new_content ) > self::MAX_CONTENT ) { + return [ 'too_large' => true ]; + } + + return [ + 'stash' => [ + 'old' => $old_content, + 'new' => $new_content, + ], + ]; + } + + /** + * Whether WordPress keeps the revision before the newest one, which the + * job compares against. + * + * @param object $post The post. + * + * @return bool + */ + private static function keeps_earlier_revision( object $post ): bool { + if ( ! $post instanceof \WP_Post ) { + return false; + } + + $keep = wp_revisions_to_keep( $post ); + + return $keep < 0 || $keep >= 2; + } + + /** + * The custom field changes to report, per key. + * + * @param array> $fields Noted changes, per key. + * + * @return array> + */ + private static function field_changes( array $fields ): array { + $changes = []; + foreach ( $fields as $key => $field ) { + $existed = (bool) ( $field['existed'] ?? false ); + $exists = (bool) ( $field['exists'] ?? false ); + + if ( $existed && $exists ) { + if ( '' !== $field['old_hash'] && $field['old_hash'] === $field['new_hash'] ) { + continue; + } + $change = 'changed'; + } elseif ( $existed ) { + $change = 'removed'; + } elseif ( $exists ) { + $change = 'added'; + } else { + continue; + } + + $entry = [ 'change' => $change ]; + foreach ( [ 'old', 'new' ] as $side ) { + $value = $field[ $side ] ?? null; + if ( ! is_array( $value ) ) { + continue; + } + if ( $value['large'] ) { + $entry['large'] = true; + } elseif ( null !== $value['value'] ) { + $entry[ $side ] = $value['value']; + } + } + $changes[ (string) $key ] = $entry; + } + + return $changes; + } + + /** + * The term changes to report, per taxonomy: term taxonomy IDs added and + * removed. + * + * @param array $terms Noted changes, per taxonomy. + * + * @return array + */ + private static function term_changes( array $terms ): array { + $changes = []; + foreach ( $terms as $taxonomy => $sets ) { + $added = array_values( array_diff( $sets['new'], $sets['old'] ) ); + $removed = array_values( array_diff( $sets['old'], $sets['new'] ) ); + if ( [] !== $added || [] !== $removed ) { + $changes[ (string) $taxonomy ] = [ + 'added' => $added, + 'removed' => $removed, + ]; + } + } + + return $changes; + } + + /** + * A text cut to the longest kept. + * + * @param string $text The text. + * + * @return string + */ + private static function cap( string $text ): string { + return mb_strlen( $text ) > self::MAX_TEXT ? mb_substr( $text, 0, self::MAX_TEXT ) : $text; + } +} diff --git a/src/Events/PostChanges/ContentDiff.php b/src/Events/PostChanges/ContentDiff.php new file mode 100644 index 0000000..eec3758 --- /dev/null +++ b/src/Events/PostChanges/ContentDiff.php @@ -0,0 +1,323 @@ + + */ + public static function compare( string $before, string $after, ?callable $differ = null ): array { + if ( strlen( $before ) > self::MAX_CONTENT || strlen( $after ) > self::MAX_CONTENT ) { + return self::unchanged_text( 'too_large' ); + } + + $old_lines = self::text_lines( $before ); + $new_lines = self::text_lines( $after ); + if ( count( $old_lines ) > self::MAX_LINES || count( $new_lines ) > self::MAX_LINES ) { + return self::unchanged_text( 'too_large' ); + } + + // Only markup changed (a class, an attribute, a block setting). + if ( $old_lines === $new_lines ) { + return self::unchanged_text( 'markup' ); + } + + $operations = null === $differ ? self::text_diff( $old_lines, $new_lines ) : $differ( $old_lines, $new_lines ); + + return self::summarize( $operations ); + } + + /** + * Compare two versions of a code file (a plugin or theme file edited in + * WordPress's file editor), line by line as it is written. + * + * @param string $before The file before. + * @param string $after The file after. + * @param callable|null $differ As for compare(). + * + * @return array + */ + public static function compare_code( string $before, string $after, ?callable $differ = null ): array { + if ( strlen( $before ) > self::MAX_CONTENT || strlen( $after ) > self::MAX_CONTENT ) { + return self::unchanged_text( 'too_large' ); + } + + $old_lines = self::code_lines( $before ); + $new_lines = self::code_lines( $after ); + if ( count( $old_lines ) > self::MAX_LINES || count( $new_lines ) > self::MAX_LINES ) { + return self::unchanged_text( 'too_large' ); + } + + // Only line endings or spaces at the end of lines changed. + if ( $old_lines === $new_lines ) { + return self::unchanged_text( 'whitespace' ); + } + + $operations = null === $differ ? self::text_diff( $old_lines, $new_lines ) : $differ( $old_lines, $new_lines ); + + return self::summarize( $operations ); + } + + /** + * A code file's lines as written, without line endings or spaces at the + * end of a line. + * + * @param string $content The file. + * + * @return string[] + */ + public static function code_lines( string $content ): array { + if ( '' === $content ) { + return []; + } + + $lines = preg_split( '/\R/u', $content ); + if ( false === $lines ) { + $lines = explode( "\n", $content ); + } + + return array_map( 'rtrim', $lines ); + } + + /** + * A content change without a diff, and why. + * + * @param string $reason Why there is no diff. + * + * @return array + */ + public static function unchanged_text( string $reason ): array { + return [ + 'changed' => true, + 'reason' => $reason, + ]; + } + + /** + * Post content as plain text, one line per block, paragraph or list + * item. Images are named by their file. + * + * @param string $content The content. + * + * @return string[] + */ + public static function text_lines( string $content ): array { + $content = (string) preg_replace( '//s', "\n", $content ); + $content = (string) preg_replace( '@<(script|style)[^>]*?>.*?@si', '', $content ); + $content = (string) preg_replace_callback( '/]*>/i', [ self::class, 'image_text' ], $content ); + $content = (string) preg_replace( '#|#i', "\n", $content ); + $content = wp_strip_all_tags( $content ); + $content = html_entity_decode( $content, ENT_QUOTES, 'UTF-8' ); + + $lines = []; + $split = preg_split( '/\R/u', $content ); + foreach ( false !== $split ? $split : [] as $line ) { + $line = trim( (string) preg_replace( '/[\s\x{00A0}]+/u', ' ', $line ) ); + if ( '' !== $line ) { + $lines[] = $line; + } + } + + return $lines; + } + + /** + * An image tag as text: `[image: photo.jpg]`. + * + * @param array $matches The image tag. + * + * @return string + */ + private static function image_text( array $matches ): string { + if ( preg_match( '/\bsrc\s*=\s*(["\'])(.*?)\1/i', $matches[0], $src ) ) { + $path = (string) wp_parse_url( $src[2], PHP_URL_PATH ); + $file = '' !== $path ? basename( $path ) : ''; + if ( '' !== $file ) { + return "\n[image: " . $file . "]\n"; + } + } + + return "\n[image]\n"; + } + + /** + * Compare two lists of lines with WordPress's Text_Diff. + * + * @param string[] $old_lines The lines before. + * @param string[] $new_lines The lines after. + * + * @return array + */ + private static function text_diff( array $old_lines, array $new_lines ): array { + if ( ! class_exists( 'Text_Diff', false ) ) { + require_once ABSPATH . 'wp-includes/wp-diff.php'; + } + + $operations = []; + $diff = new \Text_Diff( 'auto', [ $old_lines, $new_lines ] ); + foreach ( $diff->getDiff() as $edit ) { + if ( $edit instanceof \Text_Diff_Op_copy ) { + $operations[] = [ '=', (array) $edit->orig ]; + } elseif ( $edit instanceof \Text_Diff_Op_delete ) { + $operations[] = [ '-', (array) $edit->orig ]; + } elseif ( $edit instanceof \Text_Diff_Op_add ) { + $operations[] = [ '+', (array) $edit->final ]; + } elseif ( $edit instanceof \Text_Diff_Op_change ) { + $operations[] = [ '-', (array) $edit->orig ]; + $operations[] = [ '+', (array) $edit->final ]; + } + } + + return $operations; + } + + /** + * The changed lines with one line of context around each change, the + * unchanged lines in between as a count, and the number of lines added + * and removed. + * + * @param array $operations The diff. + * + * @return array + */ + public static function summarize( array $operations ): array { + $added = 0; + $removed = 0; + $lines = []; + $size = 0; + $truncated = false; + $last = count( $operations ) - 1; + + $keep = static function ( array $line ) use ( &$lines, &$size, &$truncated ): void { + if ( $truncated ) { + return; + } + $length = isset( $line['text'] ) ? strlen( $line['text'] ) : 0; + if ( $size + $length > self::MAX_DIFF ) { + $truncated = true; + return; + } + $size += $length; + $lines[] = $line; + }; + + foreach ( $operations as $index => $operation ) { + [ $op, $chunk ] = $operation; + $chunk = array_values( $chunk ); + + if ( '=' !== $op ) { + foreach ( $chunk as $text ) { + if ( '+' === $op ) { + ++$added; + } else { + ++$removed; + } + $keep( + [ + 'op' => $op, + 'text' => self::cut( (string) $text ), + ] + ); + } + continue; + } + + // One line of context after the change before and before the next. + $count = count( $chunk ); + $head = $index > 0 ? 1 : 0; + $tail = $index < $last ? 1 : 0; + if ( $count <= $head + $tail ) { + $head = $count; + $tail = 0; + } + + for ( $i = 0; $i < $head; $i++ ) { + $keep( + [ + 'op' => '=', + 'text' => self::cut( (string) $chunk[ $i ] ), + ] + ); + } + $skipped = $count - $head - $tail; + if ( $skipped > 0 ) { + $keep( + [ + 'op' => 'skip', + 'count' => $skipped, + ] + ); + } + if ( $tail > 0 ) { + $keep( + [ + 'op' => '=', + 'text' => self::cut( (string) $chunk[ $count - 1 ] ), + ] + ); + } + } + + return [ + 'added' => $added, + 'removed' => $removed, + 'lines' => $lines, + 'truncated' => $truncated, + ]; + } + + /** + * A line cut to the longest kept. + * + * @param string $text The line. + * + * @return string + */ + private static function cut( string $text ): string { + return mb_strlen( $text ) > self::MAX_LINE ? mb_substr( $text, 0, self::MAX_LINE ) . '…' : $text; + } +} diff --git a/src/Events/PostChanges/Fields.php b/src/Events/PostChanges/Fields.php new file mode 100644 index 0000000..939039e --- /dev/null +++ b/src/Events/PostChanges/Fields.php @@ -0,0 +1,129 @@ + null, + 'large' => false, + ]; + } + + if ( is_bool( $value ) ) { + $text = $value ? '1' : '0'; + } elseif ( is_scalar( $value ) ) { + $text = (string) $value; + } elseif ( is_array( $value ) ) { + $text = (string) wp_json_encode( $value ); + } else { + $text = null; + } + + if ( null === $text || mb_strlen( $text ) > self::MAX_VALUE_LENGTH ) { + return [ + 'value' => null, + 'large' => true, + ]; + } + + return [ + 'value' => $text, + 'large' => false, + ]; + } + + /** + * A fingerprint of a meta value, to tell whether a value set again is + * the same. + * + * @param mixed $value The meta value. + * + * @return string + */ + public static function fingerprint( $value ): string { + if ( is_scalar( $value ) || null === $value ) { + return 's:' . md5( (string) $value ); + } + + try { + return 'x:' . md5( serialize( $value ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Only hashed, never stored. + } catch ( \Throwable $e ) { + return 'u:' . md5( (string) wp_rand() ); + } + } +} diff --git a/src/Events/PostChanges/Stash.php b/src/Events/PostChanges/Stash.php new file mode 100644 index 0000000..ef69781 --- /dev/null +++ b/src/Events/PostChanges/Stash.php @@ -0,0 +1,81 @@ + $value The value. + * + * @return string + */ + public static function put( array $value ): string { + $key = str_replace( '-', '', wp_generate_uuid4() ); + + return set_transient( self::PREFIX . $key, $value, DAY_IN_SECONDS ) ? $key : ''; + } + + /** + * A stored value, or null when it is gone. + * + * @param string $key The key. + * + * @return array|null + */ + public static function get( string $key ): ?array { + if ( ! self::is_key( $key ) ) { + return null; + } + + $value = get_transient( self::PREFIX . $key ); + + return is_array( $value ) ? $value : null; + } + + /** + * Remove a stored value. + * + * @param string $key The key. + * + * @return void + */ + public static function delete( string $key ): void { + if ( self::is_key( $key ) ) { + delete_transient( self::PREFIX . $key ); + } + } + + /** + * Whether a key is one put() makes. + * + * @param string $key The key. + * + * @return bool + */ + private static function is_key( string $key ): bool { + return 1 === preg_match( '/^[a-f0-9]{32}$/', $key ); + } +} diff --git a/src/Events/PostDeleted.php b/src/Events/PostDeleted.php new file mode 100644 index 0000000..f6affda --- /dev/null +++ b/src/Events/PostDeleted.php @@ -0,0 +1,70 @@ +post_type, $post->post_status ) || in_array( (string) $post->post_status, self::IGNORED_STATUSES, true ) ) { + return false; + } + + if ( ! PostSaved::is_tracked_post_type( (string) $post->post_type ) ) { + return false; + } + + /** + * Filters whether a permanent delete of a post is reported to Scanfully. + * + * @param bool $should_fire Whether to report the delete. + * @param object $post The post, before it is deleted. + */ + return (bool) apply_filters( 'scanfully_post_deleted_should_fire', true, $post ); + } +} diff --git a/src/Events/PostSaved.php b/src/Events/PostSaved.php index e415b97..21708fe 100644 --- a/src/Events/PostSaved.php +++ b/src/Events/PostSaved.php @@ -7,8 +7,19 @@ namespace Scanfully\Events; +use Scanfully\Events\PostChanges\Collector; +use Scanfully\Events\PostChanges\Stash; + /** - * Class ActivatedPlugin + * Class PostSaved + * + * A post was saved and something changed: it was created, its status + * changed, or its title, slug, content, custom fields, terms or other + * fields changed. The Collector notes the changes while the post is saved + * and reports each changed post once, at the end of the request; a save + * that changes nothing is not reported. The background job + * (PostChanges\Builder) works out the content diff and names and sends the + * event. * * @package Scanfully\Events */ @@ -18,13 +29,15 @@ class PostSaved extends Event { * Constructor. */ public function __construct() { - parent::__construct( 'PostSaved', 'wp_after_insert_post', 10, 4 ); + parent::__construct( 'PostSaved', Collector::ACTION, 10, 5 ); + + Collector::setup(); } /** * Get the post body * - * @param array $data The data to send. + * @param array $data The data passed to the action: post ID, post, update, post before, changes. * * @return array */ @@ -33,14 +46,102 @@ public function get_post_body( array $data ): array { $post = $data[1]; // $update = $data[2]; $post_before = $data[3]; + $changes = $data[4] ?? []; - return [ + $body = [ 'id' => $post_id, 'title' => $post->post_title, 'post_status' => $post->post_status, 'post_before' => self::summarize_post( $post_before ), 'post' => self::summarize_post( $post ), ]; + + if ( is_array( $changes ) && [] !== $changes ) { + $body['changes'] = $changes; + } + + return $body; + } + + /** + * Schedule the background job that works out what changed and sends + * the event. What doesn't fit in the job's arguments (the content of a + * post without revisions, many changed fields) is stored for the job. + * + * @param string $type The event type. + * @param array $user The user who made the change. + * @param array $data The event data. + * + * @return void + */ + protected function schedule( string $type, array $user, array $data ): void { + $stash = ''; + if ( isset( $data['changes'] ) && ( isset( $data['changes']['content']['stash'] ) || self::args_length( $type, $user, $data ) > self::MAX_ARGS_LENGTH ) ) { + $stash = Stash::put( [ 'changes' => $data['changes'] ] ); + $data['changes'] = '' !== $stash ? [ 'stashed' => true ] : self::without_stashed_content( $data['changes'] ); + } + + $args = self::fit_args( + [ + 'type' => $type, + 'user' => $user, + 'data' => $data, + 'stash' => $stash, + ] + ); + + as_schedule_single_action( time(), Controller::ACTION_BUILD_POST_EVENT, $args, 'scanfully' ); + } + + /** + * The length of a job's arguments as JSON. + * + * @param string $type The event type. + * @param array $user The user. + * @param array $data The event data. + * + * @return int + */ + private static function args_length( string $type, array $user, array $data ): int { + return strlen( + (string) wp_json_encode( + [ + 'type' => $type, + 'user' => $user, + 'data' => $data, + ] + ) + ); + } + + /** + * Changes without the content to compare, for when it could not be + * stored: the content is only reported as changed. + * + * @param array $changes The changes. + * + * @return array + */ + private static function without_stashed_content( array $changes ): array { + if ( isset( $changes['content']['stash'] ) ) { + $changes['content'] = [ 'unavailable' => true ]; + } + + return $changes; + } + + /** + * A user's name as events report it (never an email address); '' when + * the user doesn't exist. + * + * @param int $user_id The user ID. + * + * @return string + */ + public static function author_name( int $user_id ): string { + $user = $user_id > 0 ? get_userdata( $user_id ) : false; + + return $user instanceof \WP_User ? self::safe_display_name( $user ) : ''; } /** @@ -88,34 +189,12 @@ private static function summarize_post( $post ): ?array { } // Never send the password itself, only whether the post has one. - $password = is_object( $post ) ? ( $post->post_password ?? '' ) : ( $post['post_password'] ?? '' ); + $password = is_object( $post ) ? ( $post->post_password ?? '' ) : ( $post['post_password'] ?? '' ); $summary['has_password'] = '' !== (string) $password; return $summary; } - /** - * Track post ID and status pairs that have already had an event scheduled - * in this request, to prevent duplicate events when wp_after_insert_post - * fires multiple times for the same save. - * - * @var array - */ - private static array $fired_ids = []; - - /** - * Transient TTL in seconds used to deduplicate rapid cross-request saves - * (e.g. Gutenberg firing two REST API saves in quick succession). - */ - private const DEDUP_TTL = 5; - - /** - * Default maximum number of post events per minute, so bulk edits and - * similar mass saves can't queue thousands of jobs. Filterable via - * `scanfully_post_saved_events_per_minute`. - */ - private const MAX_EVENTS_PER_MINUTE = 30; - /** * Internal post types that are saved in the background and never * represent content an editor changed. @@ -124,6 +203,8 @@ private static function summarize_post( $post ): ?array { 'revision', 'attachment', 'nav_menu_item', + // Block theme menus are menu events (MenuChanges). + 'wp_navigation', 'wp_template', 'wp_template_part', 'oembed_cache', @@ -131,6 +212,8 @@ private static function summarize_post( $post ): ?array { 'user_request', 'acf-field', 'acf-field-group', + // SEOPress logs every request for a missing URL as a post. + 'seopress_404', ]; /** @@ -141,7 +224,25 @@ private static function summarize_post( $post ): ?array { * @return bool */ public function should_fire( array $data ): bool { + $post = $data[1] ?? null; + // Repeated saves need no deduplication here: the Collector reports a + // post once per request, and only when something changed. The + // per-minute cap and bulk actions are handled when it reports + // (Content\Report). + return is_object( $post ) && self::is_reported( $post ); + } + + /** + * Whether a save of a post is reported: not an autosave, Heartbeat or + * import, a status and post type that are activity, and not excluded by + * the `scanfully_post_saved_should_fire` filter. + * + * @param object $post The saved post. + * + * @return bool + */ + public static function is_reported( object $post ): bool { if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return false; } @@ -158,8 +259,7 @@ public function should_fire( array $data ): bool { return false; } - $post = $data[1] ?? null; - if ( ! is_object( $post ) || ! isset( $post->post_status, $post->post_type ) ) { + if ( ! isset( $post->post_status, $post->post_type ) ) { return false; } @@ -178,37 +278,7 @@ public function should_fire( array $data ): bool { * @param bool $should_fire Whether to report the save. * @param object $post The saved post. */ - if ( ! apply_filters( 'scanfully_post_saved_should_fire', true, $post ) ) { - return false; - } - - $post_id = (int) $data[0]; - - // Duplicates are tracked per post and status: a save that changes the - // status (draft, then publish) is always reported, while repeated - // saves with the same status collapse into one event. - $dedup_key = $post_id . '_' . $post->post_status; - - // Prevent duplicate events for the same save within a single request. - if ( isset( self::$fired_ids[ $dedup_key ] ) ) { - return false; - } - - // Prevent duplicate events across rapid successive requests (e.g. Gutenberg's - // publish flow can fire two REST saves within a second of each other). - $transient_key = 'scanfully_post_event_' . $dedup_key; - if ( get_transient( $transient_key ) ) { - return false; - } - - if ( self::is_rate_limited() ) { - return false; - } - - set_transient( $transient_key, 1, self::DEDUP_TTL ); - self::$fired_ids[ $dedup_key ] = true; - - return true; + return (bool) apply_filters( 'scanfully_post_saved_should_fire', true, $post ); } /** @@ -222,7 +292,7 @@ public function should_fire( array $data ): bool { * * @return bool */ - private static function is_tracked_post_type( string $post_type ): bool { + public static function is_tracked_post_type( string $post_type ): bool { if ( in_array( $post_type, self::IGNORED_POST_TYPES, true ) ) { return false; } @@ -235,27 +305,4 @@ private static function is_tracked_post_type( string $post_type ): bool { return is_object( $type_object ) && ! empty( $type_object->show_ui ); } - - /** - * Count this event against the per-minute cap. Returns true when the cap - * is reached and the event should be dropped. - * - * @return bool - */ - private static function is_rate_limited(): bool { - $limit = (int) apply_filters( 'scanfully_post_saved_events_per_minute', self::MAX_EVENTS_PER_MINUTE ); - if ( $limit < 1 ) { - return false; - } - - $bucket = 'scanfully_post_events_' . (int) floor( time() / MINUTE_IN_SECONDS ); - $count = (int) get_transient( $bucket ); - if ( $count >= $limit ) { - return true; - } - - set_transient( $bucket, $count + 1, 2 * MINUTE_IN_SECONDS ); - - return false; - } } diff --git a/src/Events/RewriteRules.php b/src/Events/RewriteRules.php deleted file mode 100644 index 4d67f87..0000000 --- a/src/Events/RewriteRules.php +++ /dev/null @@ -1,76 +0,0 @@ -> + */ + private static array $changes = []; + + /** + * Per site, the admin email request pending before this request deleted + * it. + * + * @var array> + */ + private static array $request_deleted = []; + + /** + * Per site, the update services as stored before this request's update, + * while WordPress reads them as empty (see note_updating()); null when + * that value wasn't cached. + * + * @var array + */ + private static array $stored_ping_sites = []; + + /** + * Hook into WordPress. + * + * @return void + */ + public static function setup(): void { + add_action( 'update_option', [ self::class, 'note_updating' ], 10, 1 ); + add_action( 'updated_option', [ self::class, 'note_updated' ], 10, 3 ); + add_action( 'added_option', [ self::class, 'note_added' ], 10, 2 ); + add_action( 'delete_option', [ self::class, 'note_deleting' ], 10, 1 ); + add_action( 'shutdown', [ self::class, 'flush' ], 1, 0 ); + } + + /** + * Forget what was noted (tests). + * + * @return void + */ + public static function reset(): void { + self::$changes = []; + self::$request_deleted = []; + self::$stored_ping_sites = []; + } + + /** + * Whether an option is one this collector notes. + * + * @param string $option The option name. + * + * @return bool + */ + private static function is_noted( string $option ): bool { + return Settings::is_reported( $option ) + || in_array( $option, Settings::TIMEZONE_OPTIONS, true ) + || Settings::ADMIN_EMAIL_REQUEST === $option; + } + + /** + * Whether this request's option changes are left out: installs and + * database upgrades (a core update is its own row) and imports. + * + * @return bool + */ + private static function is_quiet(): bool { + return wp_installing() || ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ); + } + + /** + * Whether WordPress reads the update services as empty: it does while + * the site discourages search engines (privacy_ping_filter()). + * + * @return bool + */ + private static function hides_ping_sites(): bool { + return false !== has_filter( 'option_ping_sites', 'privacy_ping_filter' ) && '0' === get_option( 'blog_public' ); + } + + /** + * The update services as stored, from the options cache that + * get_option() filled (no query); null when they aren't cached. + * + * @return string|null + */ + private static function stored_ping_sites(): ?string { + $all = wp_load_alloptions(); + $value = $all['ping_sites'] ?? wp_cache_get( 'ping_sites', 'options' ); + + return is_string( $value ) ? $value : null; + } + + /** + * `update_option` (before the update): while WordPress reads the update + * services as empty, the old value update_option() passes on is empty + * too, so every service would show as added. The stored value is read + * now, before the update replaces it in the cache. + * + * @param string $option The option name. + * + * @return void + */ + public static function note_updating( $option ): void { + if ( 'ping_sites' !== $option ) { + return; + } + + // An update that changed nothing in the database left one behind. + unset( self::$stored_ping_sites[ get_current_blog_id() ] ); + if ( ! self::is_quiet() && self::hides_ping_sites() ) { + self::$stored_ping_sites[ get_current_blog_id() ] = self::stored_ping_sites(); + } + } + + /** + * `updated_option`: note a changed setting. + * + * @param string $option The option name. + * @param mixed $old_value The value before. + * @param mixed $value The value after. + * + * @return void + */ + public static function note_updated( $option, $old_value, $value ): void { + if ( ! is_string( $option ) || ! self::is_noted( $option ) || self::is_quiet() ) { + return; + } + + $blog = get_current_blog_id(); + if ( 'ping_sites' === $option && array_key_exists( $blog, self::$stored_ping_sites ) ) { + $old_value = self::$stored_ping_sites[ $blog ]; + unset( self::$stored_ping_sites[ $blog ] ); + if ( null === $old_value ) { + // What it was can't be known: no row rather than a wrong one. + return; + } + } + + self::note( $option, $old_value, $value ); + } + + /** + * `added_option`: a setting saved for the first time changed from + * nothing. + * + * @param string $option The option name. + * @param mixed $value The value. + * + * @return void + */ + public static function note_added( $option, $value ): void { + if ( ! is_string( $option ) || ! self::is_noted( $option ) || self::is_quiet() ) { + return; + } + + self::note( $option, null, $value ); + } + + /** + * `delete_option` (before the delete): a setting is emptied (deleting + * the site icon's file deletes `site_icon`; REST and WP-CLI can delete + * any), or the admin email request is withdrawn or confirmed. The value + * is autoloaded, so reading it costs nothing. + * + * @param string $option The option name. + * + * @return void + */ + public static function note_deleting( $option ): void { + if ( ! is_string( $option ) || self::is_quiet() ) { + return; + } + + if ( Settings::is_reported( $option ) ) { + $old_value = 'ping_sites' === $option && self::hides_ping_sites() ? self::stored_ping_sites() : get_option( $option ); + self::note( $option, $old_value, null ); + return; + } + + if ( Settings::ADMIN_EMAIL_REQUEST !== $option ) { + return; + } + + $blog = get_current_blog_id(); + $pending = get_option( Settings::ADMIN_EMAIL_REQUEST ); + if ( is_array( $pending ) && '' !== (string) ( $pending['newemail'] ?? '' ) ) { + self::$request_deleted[ $blog ] = $pending + [ 'user' => get_current_user_id() ]; + } + unset( self::$changes[ $blog ][ Settings::ADMIN_EMAIL_REQUEST ] ); + } + + /** + * Keep the first old and the last new value of an option. + * + * @param string $option The option name. + * @param mixed $old_value The value before. + * @param mixed $value The value after. + * + * @return void + */ + private static function note( string $option, $old_value, $value ): void { + $blog = get_current_blog_id(); + if ( isset( self::$changes[ $blog ][ $option ] ) ) { + self::$changes[ $blog ][ $option ]['new'] = $value; + return; + } + + self::$changes[ $blog ][ $option ] = [ + 'old' => $old_value, + 'new' => $value, + // A scheduled Customizer change is published by cron as the + // person who made it, who is signed out again by shutdown. + 'user' => get_current_user_id(), + ]; + } + + /** + * The rows for what this request changed on the current site: the key + * settings first, then the rest in the order of the settings screens. + * A row made by someone other than the signed-in user names them in + * `_actor`. + * + * @return array> + */ + public static function rows(): array { + $blog = get_current_blog_id(); + $changes = self::$changes[ $blog ] ?? []; + $deleted = self::$request_deleted[ $blog ] ?? null; + if ( [] === $changes && null === $deleted ) { + return []; + } + + $rows = []; + foreach ( Settings::KINDS as $option => $kind ) { + if ( ! isset( $changes[ $option ] ) ) { + continue; + } + $row = Settings::change( $option, $changes[ $option ]['old'], $changes[ $option ]['new'] ); + if ( [] !== $row ) { + $rows[] = self::with_actor( $row, $changes[ $option ]['user'] ); + } + } + + $timezone = self::timezone_row( $changes ); + if ( [] !== $timezone ) { + $rows[] = $timezone; + } + + $request = self::admin_email_row( $changes, $deleted ); + if ( [] !== $request ) { + $rows[] = $request; + } + + usort( + $rows, + static fn( array $a, array $b ): int => (int) ! in_array( $a['option'], self::KEY_SETTINGS, true ) <=> (int) ! in_array( $b['option'], self::KEY_SETTINGS, true ) + ); + + return $rows; + } + + /** + * Report what this request changed, once, at the end of the request, + * on each site it changed. + * + * @return void + */ + public static function flush(): void { + $blogs = array_unique( array_merge( array_keys( self::$changes ), array_keys( self::$request_deleted ) ) ); + if ( [] === $blogs ) { + return; + } + + $current = get_current_blog_id(); + foreach ( $blogs as $blog ) { + $switched = $blog !== $current && function_exists( 'switch_to_blog' ) && switch_to_blog( $blog ); + if ( $blog === $current || $switched ) { + self::report( self::rows() ); + } + if ( $switched ) { + restore_current_blog(); + } + } + self::reset(); + } + + /** + * Fire the rows of the current site: the key settings always, the rest + * within the per-minute cap. + * + * @param array> $rows The rows. + * + * @return void + */ + private static function report( array $rows ): void { + if ( [] === $rows || ! Options\Controller::get_options()->is_connected ) { + return; + } + + $key = array_values( array_filter( $rows, static fn( array $row ): bool => in_array( $row['option'], self::KEY_SETTINGS, true ) ) ); + $other = array_values( array_filter( $rows, static fn( array $row ): bool => ! in_array( $row['option'], self::KEY_SETTINGS, true ) ) ); + $room = [] !== $other ? Limiter::take( Limiter::KIND_SETTING, count( $other ) ) : 0; + + foreach ( array_merge( $key, array_slice( $other, 0, $room ) ) as $row ) { + do_action( ContentEvent::hook( 'SiteOptionChanged' ), $row ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- The hooks start with scanfully_. + } + } + + /** + * A row naming the person who made the change when that isn't the + * signed-in user. + * + * @param array $row The row. + * @param int $user The user who made the change. + * + * @return array + */ + private static function with_actor( array $row, int $user ): array { + if ( $user > 0 && get_current_user_id() !== $user ) { + $row['_actor'] = $user; + } + + return $row; + } + + /** + * One row for the timezone, from whichever of its two options changed. + * + * @param array $changes The site's changes. + * + * @return array + */ + private static function timezone_row( array $changes ): array { + [ $zone_option, $offset_option ] = Settings::TIMEZONE_OPTIONS; + if ( ! isset( $changes[ $zone_option ] ) && ! isset( $changes[ $offset_option ] ) ) { + return []; + } + + $value = static function ( string $option, string $side ) use ( $changes ) { + return isset( $changes[ $option ] ) ? $changes[ $option ][ $side ] : get_option( $option ); + }; + + $old = Settings::timezone( $value( $zone_option, 'old' ), $value( $offset_option, 'old' ) ); + $new = Settings::timezone( $value( $zone_option, 'new' ), $value( $offset_option, 'new' ) ); + if ( $old === $new ) { + return []; + } + + return self::with_actor( + [ + 'option' => 'timezone', + 'old' => $old, + 'new' => $new, + ], + ( $changes[ $zone_option ] ?? $changes[ $offset_option ] )['user'] + ); + } + + /** + * The row for an admin email change someone asked for (WordPress mailed + * a confirmation link) or withdrew. A request that is confirmed shows + * as the admin email changing. + * + * @param array $changes The site's changes. + * @param array|null $deleted The request withdrawn or confirmed, or null. + * + * @return array + */ + private static function admin_email_row( array $changes, ?array $deleted ): array { + if ( isset( $changes[ Settings::ADMIN_EMAIL_REQUEST ] ) ) { + $request = $changes[ Settings::ADMIN_EMAIL_REQUEST ]['new']; + $address = is_array( $request ) ? (string) ( $request['newemail'] ?? '' ) : ''; + if ( '' === $address ) { + return []; + } + + return self::with_actor( + [ + 'option' => 'new_admin_email', + 'old' => (string) get_option( 'admin_email' ), + 'new' => $address, + ], + $changes[ Settings::ADMIN_EMAIL_REQUEST ]['user'] + ); + } + + if ( null !== $deleted && ! isset( $changes['admin_email'] ) ) { + return self::with_actor( + [ + 'option' => 'new_admin_email', + 'old' => (string) get_option( 'admin_email' ), + 'new' => (string) $deleted['newemail'], + 'cancelled' => true, + ], + (int) $deleted['user'] + ); + } + + return []; + } +} diff --git a/src/Events/SettingsChanges/Settings.php b/src/Events/SettingsChanges/Settings.php new file mode 100644 index 0000000..b25df6a --- /dev/null +++ b/src/Events/SettingsChanges/Settings.php @@ -0,0 +1,491 @@ + self::KIND_TEXT, + 'blogdescription' => self::KIND_TEXT, + 'site_icon' => self::KIND_FILE, + 'siteurl' => self::KIND_TEXT, + 'home' => self::KIND_TEXT, + 'admin_email' => self::KIND_TEXT, + 'users_can_register' => self::KIND_BOOL, + 'default_role' => self::KIND_TEXT, + 'WPLANG' => self::KIND_TEXT, + 'date_format' => self::KIND_FORMAT, + 'time_format' => self::KIND_FORMAT, + 'start_of_week' => self::KIND_INT, + // Writing. + 'default_category' => self::KIND_CATEGORY, + 'default_post_format' => self::KIND_TEXT, + 'mailserver_url' => self::KIND_TEXT, + 'mailserver_port' => self::KIND_INT, + 'mailserver_login' => self::KIND_SECRET, + 'mailserver_pass' => self::KIND_SECRET, + 'default_email_category' => self::KIND_CATEGORY, + 'ping_sites' => self::KIND_URLS, + 'default_link_category' => self::KIND_LINK_CATEGORY, + 'use_smilies' => self::KIND_BOOL, + 'use_balanceTags' => self::KIND_BOOL, + // Reading. + 'show_on_front' => self::KIND_TEXT, + 'page_on_front' => self::KIND_PAGE, + 'page_for_posts' => self::KIND_PAGE, + 'posts_per_page' => self::KIND_INT, + 'posts_per_rss' => self::KIND_INT, + 'rss_use_excerpt' => self::KIND_BOOL, + 'blog_public' => self::KIND_LEVEL, + 'blog_charset' => self::KIND_TEXT, + // Discussion. + 'default_pingback_flag' => self::KIND_BOOL, + 'default_ping_status' => self::KIND_OPEN, + 'default_comment_status' => self::KIND_OPEN, + 'comment_registration' => self::KIND_BOOL, + 'require_name_email' => self::KIND_BOOL, + 'close_comments_for_old_posts' => self::KIND_BOOL, + 'close_comments_days_old' => self::KIND_INT, + 'show_comments_cookies_opt_in' => self::KIND_BOOL, + 'thread_comments' => self::KIND_BOOL, + 'thread_comments_depth' => self::KIND_INT, + 'page_comments' => self::KIND_BOOL, + 'comments_per_page' => self::KIND_INT, + 'default_comments_page' => self::KIND_TEXT, + 'comment_order' => self::KIND_TEXT, + 'comments_notify' => self::KIND_BOOL, + 'moderation_notify' => self::KIND_BOOL, + 'wp_notes_notify' => self::KIND_BOOL, + 'comment_moderation' => self::KIND_BOOL, + 'comment_previously_approved' => self::KIND_BOOL, + 'comment_max_links' => self::KIND_INT, + 'moderation_keys' => self::KIND_LINES, + 'disallowed_keys' => self::KIND_LINES, + 'show_avatars' => self::KIND_BOOL, + 'avatar_rating' => self::KIND_TEXT, + 'avatar_default' => self::KIND_TEXT, + // Media. + 'thumbnail_size_w' => self::KIND_INT, + 'thumbnail_size_h' => self::KIND_INT, + 'thumbnail_crop' => self::KIND_BOOL, + 'medium_size_w' => self::KIND_INT, + 'medium_size_h' => self::KIND_INT, + 'large_size_w' => self::KIND_INT, + 'large_size_h' => self::KIND_INT, + 'image_default_size' => self::KIND_TEXT, + 'image_default_align' => self::KIND_TEXT, + 'image_default_link_type' => self::KIND_TEXT, + 'uploads_use_yearmonth_folders' => self::KIND_BOOL, + 'upload_path' => self::KIND_TEXT, + 'upload_url_path' => self::KIND_TEXT, + // Permalinks (the structure is PermalinksChanged). + 'category_base' => self::KIND_TEXT, + 'tag_base' => self::KIND_TEXT, + // Privacy. + 'wp_page_for_privacy_policy' => self::KIND_PAGE, + ]; + + /** + * The two options the timezone is stored in; one save can change both, + * so they are reported together as `timezone`. + */ + public const TIMEZONE_OPTIONS = [ 'timezone_string', 'gmt_offset' ]; + + /** + * The option a requested admin email change is stored in (with the + * confirmation hash, which is never sent), reported as + * `new_admin_email`. + */ + public const ADMIN_EMAIL_REQUEST = 'adminhash'; + + /** + * Values longer than this are cut. + */ + public const MAX_VALUE = 1000; + + /** + * At most this many URLs added or removed are listed. + */ + private const MAX_URLS = 50; + + /** + * A fixed moment for the date and time format examples: 31 January 2026, + * 15:04:05 UTC. The day is above 12 and the hour after noon, so the + * order of day and month and a 12 or 24 hour clock both show. + */ + private const EXAMPLE_TIME = 1769871845; + + /** + * Whether a setting is reported on its own row. + * + * @param string $option The option name. + * + * @return bool + */ + public static function is_reported( string $option ): bool { + return isset( self::KINDS[ $option ] ); + } + + /** + * The kind of a reported setting, or '' for any other option. + * + * @param string $option The option name. + * + * @return string + */ + public static function kind( string $option ): string { + return self::KINDS[ $option ] ?? ''; + } + + /** + * A setting's value as a string, so a value that only changed type + * (WordPress saves '0' as 0) is no change. + * + * @param string $option The option name. + * @param mixed $value The value. + * + * @return string + */ + public static function to_string( string $option, $value ): string { + switch ( self::kind( $option ) ) { + case self::KIND_BOOL: + return ! empty( $value ) ? '1' : '0'; + case self::KIND_OPEN: + return 'open' === $value ? 'open' : 'closed'; + case self::KIND_INT: + case self::KIND_LEVEL: + case self::KIND_PAGE: + case self::KIND_CATEGORY: + case self::KIND_LINK_CATEGORY: + case self::KIND_FILE: + return is_scalar( $value ) ? (string) (int) $value : '0'; + } + + if ( is_scalar( $value ) ) { + // The site title and tagline are stored HTML-encoded + // (`Barry's Shop`). + return html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' ); + } + if ( null === $value ) { + return ''; + } + + return (string) wp_json_encode( $value ); + } + + /** + * The event data for a setting that changed, or [] when it didn't. + * + * @param string $option The option name. + * @param mixed $old_value The value before. + * @param mixed $new_value The value after. + * + * @return array + */ + public static function change( string $option, $old_value, $new_value ): array { + $old = self::to_string( $option, $old_value ); + $new = self::to_string( $option, $new_value ); + if ( $old === $new ) { + return []; + } + + $kind = self::kind( $option ); + if ( self::KIND_SECRET === $kind ) { + return [ + 'option' => $option, + 'secret' => true, + ]; + } + + $added = []; + $removed = []; + if ( self::KIND_LINES === $kind || self::KIND_URLS === $kind ) { + [ $added, $removed ] = self::line_changes( $old, $new ); + // Only blank lines, spaces or line endings changed. + if ( [] === $added && [] === $removed ) { + return []; + } + } + + switch ( $kind ) { + case self::KIND_LINES: + return [ + 'option' => $option, + 'added' => count( $added ), + 'removed' => count( $removed ), + ]; + case self::KIND_URLS: + return [ + 'option' => $option, + 'added' => array_map( [ self::class, 'cut' ], array_slice( $added, 0, self::MAX_URLS ) ), + 'removed' => array_map( [ self::class, 'cut' ], array_slice( $removed, 0, self::MAX_URLS ) ), + ]; + } + + return [ + 'option' => $option, + 'old' => self::cut( $old ), + 'new' => self::cut( $new ), + ]; + } + + /** + * The timezone as WordPress shows it: the city zone, or the offset from + * UTC (`UTC+2`, `UTC-3:30`) when none is set. + * + * @param mixed $timezone_string The `timezone_string` option. + * @param mixed $gmt_offset The `gmt_offset` option. + * + * @return string + */ + public static function timezone( $timezone_string, $gmt_offset ): string { + if ( is_string( $timezone_string ) && '' !== $timezone_string ) { + return $timezone_string; + } + + $offset = is_numeric( $gmt_offset ) ? (float) $gmt_offset : 0.0; + $hours = (int) floor( abs( $offset ) ); + $minutes = (int) round( ( abs( $offset ) - $hours ) * 60 ); + + return 'UTC' . ( $offset < 0 ? '-' : '+' ) . $hours . ( $minutes > 0 ? sprintf( ':%02d', $minutes ) : '' ); + } + + /** + * The event data with the names the background job looks up: page + * titles, category names, the site icon's file name, and an example of + * a date or time format. + * + * @param array $data The event data. + * + * @return array + */ + public static function resolve( array $data ): array { + $option = (string) ( $data['option'] ?? '' ); + $kind = self::kind( $option ); + foreach ( [ 'old', 'new' ] as $side ) { + if ( ! isset( $data[ $side ] ) || ! is_string( $data[ $side ] ) ) { + continue; + } + $value = $data[ $side ]; + + $name = ''; + switch ( $kind ) { + case self::KIND_PAGE: + $name = self::post_title( (int) $value ); + break; + case self::KIND_CATEGORY: + $name = self::term_name( (int) $value, 'category' ); + break; + case self::KIND_LINK_CATEGORY: + $name = self::term_name( (int) $value, 'link_category' ); + break; + case self::KIND_FILE: + $name = self::file_name( (int) $value ); + break; + case self::KIND_FORMAT: + if ( '' !== $value ) { + $data[ $side . '_example' ] = wp_date( $value, self::EXAMPLE_TIME, new \DateTimeZone( 'UTC' ) ); + } + break; + } + if ( '' !== $name ) { + $data[ $side . '_name' ] = $name; + } + } + + return $data; + } + + /** + * The lines added to and removed from a list, one entry a line (blank + * lines and surrounding spaces don't count). + * + * @param string $before_text The list before. + * @param string $after_text The list after. + * + * @return array{0: array, 1: array} + */ + public static function line_changes( string $before_text, string $after_text ): array { + $before = self::lines( $before_text ); + $after = self::lines( $after_text ); + + return [ self::minus( $after, $before ), self::minus( $before, $after ) ]; + } + + /** + * The non-empty lines of a list. + * + * @param string $text The list. + * + * @return array + */ + private static function lines( string $text ): array { + return array_values( array_filter( array_map( 'trim', explode( "\n", str_replace( "\r", '', $text ) ) ), static fn( string $line ): bool => '' !== $line ) ); + } + + /** + * The lines of one list that the other doesn't have, as often as they + * are extra (a line listed twice and kept once was removed once). + * + * @param array $lines The list. + * @param array $other The list to take away. + * + * @return array + */ + private static function minus( array $lines, array $other ): array { + $left = array_count_values( $other ); + $out = []; + foreach ( $lines as $line ) { + if ( ( $left[ $line ] ?? 0 ) > 0 ) { + --$left[ $line ]; + continue; + } + $out[] = $line; + } + + return $out; + } + + /** + * A value cut to MAX_VALUE characters. + * + * @param string $value The value. + * + * @return string + */ + private static function cut( string $value ): string { + return function_exists( 'mb_substr' ) ? mb_substr( $value, 0, self::MAX_VALUE ) : substr( $value, 0, self::MAX_VALUE ); + } + + /** + * A page's title as plain text; '' for none or a page that is gone. + * + * @param int $id The page ID. + * + * @return string + */ + private static function post_title( int $id ): string { + $post = $id > 0 ? get_post( $id ) : null; + + return $post instanceof \WP_Post ? html_entity_decode( (string) $post->post_title, ENT_QUOTES, 'UTF-8' ) : ''; + } + + /** + * A term's name as plain text; '' for none or a term that is gone. + * + * @param int $id The term ID. + * @param string $taxonomy The taxonomy. + * + * @return string + */ + private static function term_name( int $id, string $taxonomy ): string { + $term = $id > 0 ? get_term( $id, $taxonomy ) : null; + + return $term instanceof \WP_Term ? html_entity_decode( (string) $term->name, ENT_QUOTES, 'UTF-8' ) : ''; + } + + /** + * A media library item's file name; '' for none or a file that is gone. + * + * @param int $id The attachment ID. + * + * @return string + */ + private static function file_name( int $id ): string { + $file = $id > 0 ? get_post_meta( $id, '_wp_attached_file', true ) : ''; + + return is_string( $file ) && '' !== $file ? wp_basename( $file ) : ''; + } +} diff --git a/src/Events/SiteEditor/Builder.php b/src/Events/SiteEditor/Builder.php new file mode 100644 index 0000000..8cacda2 --- /dev/null +++ b/src/Events/SiteEditor/Builder.php @@ -0,0 +1,757 @@ + 'slug', + 'core/pattern' => 'slug', + 'core/block' => 'ref', + 'core/navigation' => 'ref', + ]; + + /** + * The row with what changed; [] when nothing is left to report. + * + * @param string $type The type the request reported. + * @param array $data The row as the Collector noted it. + * + * @return array + */ + public static function resolve( string $type, array $data ): array { + return 'StylesChanged' === $type ? self::styles( $data ) : self::template( $data ); + } + + /** + * A styles row. + * + * @param array $data The row as the Collector noted it. + * + * @return array + */ + private static function styles( array $data ): array { + $stylesheet = (string) ( $data['stylesheet'] ?? '' ); + $row = [ + 'stylesheet' => $stylesheet, + 'name' => self::theme_name( $stylesheet ), + ]; + + $content = is_array( $data['content'] ?? null ) ? $data['content'] : []; + if ( ! isset( $content['stash'] ) || ! is_array( $content['stash'] ) ) { + $row['changes'] = [ 'reason' => ! empty( $content['too_large'] ) ? 'too_large' : 'unavailable' ]; + return $row; + } + + $old = self::config( (string) ( $content['stash']['old'] ?? '' ) ); + $new = self::config( (string) ( $content['stash']['new'] ?? '' ) ); + // A client may send the style variation's title, which the REST + // endpoint stores as the post's title. + if ( isset( $data['title'] ) && is_array( $data['title'] ) ) { + foreach ( [ 'old', 'new' ] as $side ) { + $title = (string) ( $data['title'][ $side ] ?? '' ); + if ( '' !== $title && self::DEFAULT_STYLES_TITLE !== $title ) { + ${$side}['title'] = $title; + } + } + } + // The Site Editor itself stores only the variation's styles and + // settings; it is found by comparing them with the theme's. + if ( ! isset( $new['title'] ) && $stylesheet === get_stylesheet() && class_exists( '\WP_Theme_JSON_Resolver' ) ) { + $variations = \WP_Theme_JSON_Resolver::get_style_variations(); + $variation = self::matching_variation( $old, $new, $variations ); + if ( '' !== $variation ) { + $new['title'] = $variation; + $before = self::variation_in( $old, $variations ); + if ( '' !== $before && ! isset( $old['title'] ) ) { + $old['title'] = $before; + } + } + } + + $changes = self::style_changes( $old, $new ); + if ( [] === $changes ) { + return []; + } + $row['changes'] = $changes; + + return $row; + } + + /** + * The title of the theme's style variation the new styles took on: one + * whose every setting the new styles have and the old ones didn't all + * have. The one with the most settings wins, so a whole variation is + * named rather than the colour or typography preset inside it; '' for + * none. + * + * @param array $old The config before. + * @param array $new The config after. + * @param array> $variations The theme's style variations. + * + * @return string + */ + public static function matching_variation( array $old, array $new, array $variations ): string { + $old_paths = self::paths( $old ); + $new_paths = self::paths( $new ); + $best = ''; + $most = 0; + foreach ( $variations as $variation ) { + $title = is_array( $variation ) && is_string( $variation['title'] ?? null ) ? $variation['title'] : ''; + $paths = '' !== $title ? self::paths( $variation ) : []; + if ( [] === $paths || count( $paths ) <= $most ) { + continue; + } + if ( array_intersect_assoc( $paths, $new_paths ) !== $paths || array_intersect_assoc( $paths, $old_paths ) === $paths ) { + continue; + } + $best = $title; + $most = count( $paths ); + } + + return self::plain( $best ); + } + + /** + * The title of the theme's style variation a config holds in full, the + * one with the most settings; '' for none. + * + * @param array $config The config. + * @param array> $variations The theme's style variations. + * + * @return string + */ + public static function variation_in( array $config, array $variations ): string { + $paths = self::paths( $config ); + $best = ''; + $most = 0; + foreach ( $variations as $variation ) { + $title = is_array( $variation ) && is_string( $variation['title'] ?? null ) ? $variation['title'] : ''; + $settings = '' !== $title ? self::paths( $variation ) : []; + if ( [] !== $settings && count( $settings ) > $most && array_intersect_assoc( $settings, $paths ) === $settings ) { + $best = $title; + $most = count( $settings ); + } + } + + return self::plain( $best ); + } + + /** + * A global styles config decoded; [] for none or not JSON. + * + * @param string $json The post content. + * + * @return array + */ + private static function config( string $json ): array { + $config = json_decode( '' !== $json ? $json : '{}', true ); + + return is_array( $config ) ? $config : []; + } + + /** + * What changed between two global styles configs. + * + * @param array $old The config before. + * @param array $new The config after. + * + * @return array + */ + public static function style_changes( array $old, array $new ): array { + $changes = []; + + $old_title = is_string( $old['title'] ?? null ) ? $old['title'] : ''; + $new_title = is_string( $new['title'] ?? null ) ? $new['title'] : ''; + if ( $old_title !== $new_title && '' !== $new_title ) { + $changes['variation'] = [ + 'old' => self::plain( $old_title ), + 'new' => self::plain( $new_title ), + ]; + } + + if ( Collector::is_empty_styles( $new ) && ! Collector::is_empty_styles( $old ) ) { + $changes['reset'] = true; + return $changes; + } + + $old_css = self::css( $old ); + $new_css = self::css( $new ); + if ( $old_css !== $new_css ) { + $changes['css'] = ContentDiff::compare_code( $old_css, $new_css ); + } + + $old_paths = self::paths( $old ); + $new_paths = self::paths( $new ); + $styles = []; + $more = 0; + foreach ( array_keys( $old_paths + $new_paths ) as $path ) { + $before = $old_paths[ $path ] ?? null; + $after = $new_paths[ $path ] ?? null; + if ( $before === $after ) { + continue; + } + if ( count( $styles ) >= self::MAX_PATHS ) { + ++$more; + continue; + } + $styles[] = self::path_change( (string) $path, $before, $after ); + } + if ( [] !== $styles ) { + $changes['styles'] = $styles; + } + if ( $more > 0 ) { + $changes['more'] = $more; + } + + return $changes; + } + + /** + * One style setting's change. + * + * @param string $path The setting's path. + * @param string|null $before The value before; null when it wasn't set. + * @param string|null $after The value after; null when it was removed. + * + * @return array + */ + private static function path_change( string $path, ?string $before, ?string $after ): array { + $change = [ + 'path' => $path, + 'change' => null === $before ? 'added' : ( null === $after ? 'removed' : 'changed' ), + ]; + foreach ( [ + 'old' => $before, + 'new' => $after, + ] as $side => $value ) { + if ( null === $value ) { + continue; + } + if ( mb_strlen( $value ) > self::MAX_VALUE_LENGTH ) { + $change['large'] = true; + } else { + $change[ $side ] = $value; + } + } + + return $change; + } + + /** + * Every style setting of a config as a path and its value, without the + * Additional CSS (compared on its own). Lists, such as a colour palette, + * are one value. + * + * @param array $config The config. + * + * @return array + */ + private static function paths( array $config ): array { + $paths = []; + foreach ( [ 'styles', 'settings' ] as $root ) { + if ( isset( $config[ $root ] ) && is_array( $config[ $root ] ) ) { + self::flatten( $config[ $root ], $root, $paths ); + } + } + + return $paths; + } + + /** + * Add the leaves of a tree to the paths. + * + * @param array $tree The tree. + * @param string $prefix The path so far. + * @param array $paths The paths found. + * + * @return void + */ + private static function flatten( array $tree, string $prefix, array &$paths ): void { + foreach ( $tree as $key => $value ) { + $path = $prefix . '.' . $key; + if ( 'css' === $key && 0 === strpos( $prefix, 'styles' ) ) { + continue; + } + if ( is_array( $value ) && [] !== $value && array_keys( $value ) !== range( 0, count( $value ) - 1 ) ) { + self::flatten( $value, $path, $paths ); + continue; + } + if ( is_bool( $value ) ) { + $paths[ $path ] = $value ? 'true' : 'false'; + } elseif ( is_scalar( $value ) || null === $value ) { + $paths[ $path ] = (string) $value; + } else { + $paths[ $path ] = (string) wp_json_encode( $value ); + } + } + } + + /** + * A config's Additional CSS: the global CSS and each block's, under a + * comment naming the block. + * + * @param array $config The config. + * + * @return string + */ + private static function css( array $config ): string { + $parts = []; + if ( is_string( $config['styles']['css'] ?? null ) && '' !== trim( $config['styles']['css'] ) ) { + $parts[] = $config['styles']['css']; + } + $blocks = $config['styles']['blocks'] ?? null; + if ( is_array( $blocks ) ) { + foreach ( $blocks as $block => $styles ) { + if ( is_array( $styles ) && is_string( $styles['css'] ?? null ) && '' !== trim( $styles['css'] ) ) { + $parts[] = '/* ' . $block . " */\n" . $styles['css']; + } + } + } + + return implode( "\n", $parts ); + } + + /** + * A template row: what the request saw, completed with the theme's or + * plugin's own version. A first save of a template the theme or a plugin + * has is its first customization; of any other a new template + * (TemplateCreated). A delete of one the theme or a plugin still has is + * a reset (TemplateReset); of any other a delete. + * + * @param array $data The row as the Collector noted it. + * + * @return array + */ + private static function template( array $data ): array { + $kind = 'template_part' === ( $data['kind'] ?? '' ) ? 'template_part' : 'template'; + $post_type = 'template_part' === $kind ? 'wp_template_part' : 'wp_template'; + $slug = (string) ( $data['slug'] ?? '' ); + $post_id = (int) ( $data['post_id'] ?? 0 ); + $post = $post_id > 0 ? get_post( $post_id ) : null; + $post = $post instanceof \WP_Post ? $post : null; + $stylesheet = (string) ( $data['stylesheet'] ?? '' ); + if ( '' === $stylesheet ) { + $stylesheet = self::term_name( $post, 'wp_theme' ); + } + if ( '' === $stylesheet ) { + $stylesheet = (string) get_stylesheet(); + } + + $provided = self::provided( $stylesheet, $slug, $post_type ); + $title = trim( (string) ( $data['title'] ?? '' ) ); + if ( '' === $title && null !== $provided ) { + $title = $provided['title']; + } + + $row = [ + 'name' => self::plain( '' !== $title ? $title : $slug ), + 'kind' => $kind, + 'slug' => $slug, + 'stylesheet' => $stylesheet, + 'theme' => self::theme_name( $stylesheet ), + 'source' => null !== $provided ? $provided['source'] : 'custom', + ]; + if ( 'template_part' === $kind ) { + $area = (string) ( $data['area'] ?? '' ); + if ( '' === $area ) { + $area = self::term_name( $post, 'wp_template_part_area' ); + } + if ( '' !== $area ) { + $row['area'] = $area; + } + } + + $content = is_array( $data['content'] ?? null ) ? $data['content'] : []; + $stash = is_array( $content['stash'] ?? null ) ? $content['stash'] : null; + $old = null !== $stash ? (string) ( $stash['old'] ?? '' ) : null; + $new = null !== $stash ? (string) ( $stash['new'] ?? '' ) : null; + + if ( ! empty( $data['removed'] ) ) { + if ( null === $provided ) { + return $row; + } + $row['_type'] = 'TemplateReset'; + $row['changes'] = [ 'blocks' => null !== $old ? self::blocks_diff( $old, $provided['content'] ) : self::no_diff( $content ) ]; + return $row; + } + + if ( ! empty( $data['inserted'] ) ) { + if ( null === $provided ) { + $row['_type'] = 'TemplateCreated'; + $row['blocks'] = null !== $new ? count( self::outline( $new, 0 ) ) : 0; + return $row; + } + $row['first_customization'] = true; + $changes = [ 'blocks' => null !== $new ? self::blocks_diff( $provided['content'], $new ) : self::no_diff( $content ) ]; + if ( '' !== $title && $title !== $provided['title'] ) { + $changes['title'] = [ + 'old' => self::plain( $provided['title'] ), + 'new' => self::plain( $title ), + ]; + } + $row['changes'] = $changes; + return $row; + } + + $changes = []; + $noted = is_array( $data['changes'] ?? null ) ? $data['changes'] : []; + foreach ( [ 'title', 'description' ] as $field ) { + if ( isset( $noted[ $field ] ) && is_array( $noted[ $field ] ) ) { + $changes[ $field ] = [ + 'old' => self::plain( $noted[ $field ]['old'] ?? '' ), + 'new' => self::plain( $noted[ $field ]['new'] ?? '' ), + ]; + } + } + if ( isset( $noted['area'] ) && is_array( $noted['area'] ) ) { + $changes['area'] = [ + 'old' => self::area_name( (array) ( $noted['area']['old'] ?? [] ) ), + 'new' => self::area_name( (array) ( $noted['area']['new'] ?? [] ) ), + ]; + } + if ( [] !== $content ) { + $changes['blocks'] = null !== $stash ? self::blocks_diff( (string) $old, (string) $new ) : self::no_diff( $content ); + } + if ( [] === $changes ) { + return []; + } + $row['changes'] = $changes; + + return $row; + } + + /** + * The template or template part a theme or plugin has for a slug, with + * where it comes from, its title and its content; null when there is + * none (a custom template, or a theme that isn't active). + * + * @param string $stylesheet The theme. + * @param string $slug The slug. + * @param string $post_type `wp_template` or `wp_template_part`. + * + * @return array{source: string, title: string, content: string}|null + */ + private static function provided( string $stylesheet, string $slug, string $post_type ): ?array { + if ( '' === $slug || ! function_exists( 'get_block_file_template' ) ) { + return null; + } + + $template = get_block_file_template( $stylesheet . '//' . $slug, $post_type ); + if ( $template instanceof \WP_Block_Template ) { + return [ + 'source' => 'theme' === $template->source ? 'theme' : 'plugin', + 'title' => (string) $template->title, + 'content' => (string) $template->content, + ]; + } + + if ( 'wp_template' === $post_type && class_exists( '\WP_Block_Templates_Registry' ) ) { + $registered = \WP_Block_Templates_Registry::get_instance()->get_by_slug( $slug ); + if ( $registered instanceof \WP_Block_Template ) { + return [ + 'source' => 'plugin', + 'title' => (string) $registered->title, + 'content' => (string) $registered->content, + ]; + } + } + + return null; + } + + /** + * Why a block diff couldn't be made. + * + * @param array $content What the Collector noted of the content. + * + * @return array + */ + private static function no_diff( array $content ): array { + return ContentDiff::unchanged_text( ! empty( $content['too_large'] ) ? 'too_large' : 'unavailable' ); + } + + /** + * The blocks added and removed between two versions of a template, as + * outline lines; `markup` when only something the outline doesn't show + * changed. + * + * @param string $before The content before. + * @param string $after The content after. + * + * @return array + */ + public static function blocks_diff( string $before, string $after ): array { + $old = self::outline( $before, 0 ); + $new = self::outline( $after, 0 ); + if ( $old === $new ) { + return ContentDiff::unchanged_text( 'markup' ); + } + + return ContentDiff::compare_code( implode( "\n", $old ), implode( "\n", $new ) ); + } + + /** + * A template's blocks as an outline: one line per block, indented by + * depth, with the block's name, what it shows (a template part's slug, a + * pattern, a menu's title, a query's post type, an image's file), its + * text and its other attributes. + * + * @param string $content The block markup. + * @param int $depth The depth to start at. + * + * @return string[] + */ + public static function outline( string $content, int $depth ): array { + if ( '' === trim( $content ) || ! function_exists( 'parse_blocks' ) ) { + return []; + } + + $blocks = parse_blocks( $content ); + // The editor saves a template with its patterns written out, as the + // REST endpoint gives them; a theme's file names them. + if ( function_exists( 'resolve_pattern_blocks' ) ) { + $blocks = resolve_pattern_blocks( $blocks ); + } + + $lines = []; + self::walk( $blocks, $depth, $lines ); + + return $lines; + } + + /** + * Add the outline lines of blocks. + * + * @param array $blocks The parsed blocks. + * @param int $depth Their depth. + * @param string[] $lines The lines so far. + * + * @return void + */ + private static function walk( array $blocks, int $depth, array &$lines ): void { + foreach ( $blocks as $block ) { + if ( ! is_array( $block ) || count( $lines ) >= self::MAX_OUTLINE_LINES ) { + return; + } + + $indent = str_repeat( ' ', $depth ); + $name = is_string( $block['blockName'] ?? null ) ? $block['blockName'] : ''; + $html = is_string( $block['innerHTML'] ?? null ) ? $block['innerHTML'] : ''; + $inner = is_array( $block['innerBlocks'] ?? null ) ? $block['innerBlocks'] : []; + + if ( '' === $name ) { + $text = self::text( $html ); + if ( '' !== $text ) { + $lines[] = $indent . 'html: ' . $text; + } + continue; + } + + $attrs = is_array( $block['attrs'] ?? null ) ? $block['attrs'] : []; + $line = $indent . ( 0 === strpos( $name, 'core/' ) ? substr( $name, 5 ) : $name ); + + $identifier = self::identifier( $name, $attrs, $html ); + if ( '' !== $identifier ) { + $line .= ' ' . $identifier; + } + // A block's own name (List View) says which it is; the rest of its + // metadata is where a pattern came from. + if ( is_string( $attrs['metadata']['name'] ?? null ) && '' !== $attrs['metadata']['name'] ) { + $line .= ' “' . self::plain( $attrs['metadata']['name'] ) . '”'; + } + unset( $attrs['metadata'] ); + if ( [] === $inner ) { + $text = self::text( $html ); + if ( '' !== $text ) { + $line .= ': ' . $text; + } + } + + $key = self::IDENTIFIERS[ $name ] ?? ''; + if ( '' !== $key ) { + unset( $attrs[ $key ] ); + } + if ( 'core/query' === $name && isset( $attrs['query']['postType'] ) ) { + unset( $attrs['query']['postType'] ); + if ( [] === $attrs['query'] ) { + unset( $attrs['query'] ); + } + } + if ( [] !== $attrs ) { + $encoded = (string) wp_json_encode( $attrs, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); + $line .= ' · ' . ( mb_strlen( $encoded ) > self::MAX_ATTRIBUTES ? mb_substr( $encoded, 0, self::MAX_ATTRIBUTES ) . '…' : $encoded ); + } + + $lines[] = $line; + self::walk( $inner, $depth + 1, $lines ); + } + } + + /** + * What a block shows, in words: a template part's or pattern's slug, the + * title of a synced pattern or menu, a query's post type, an image's + * file; '' for other blocks. + * + * @param string $name The block name. + * @param array $attrs The block's attributes. + * @param string $html The block's HTML. + * + * @return string + */ + private static function identifier( string $name, array $attrs, string $html ): string { + switch ( $name ) { + case 'core/template-part': + case 'core/pattern': + return is_string( $attrs['slug'] ?? null ) ? $attrs['slug'] : ''; + case 'core/block': + case 'core/navigation': + $id = (int) ( $attrs['ref'] ?? 0 ); + if ( $id < 1 ) { + return ''; + } + $title = get_the_title( $id ); + return '' !== $title ? '“' . self::plain( $title ) . '”' : '#' . $id; + case 'core/query': + return is_string( $attrs['query']['postType'] ?? null ) ? $attrs['query']['postType'] : ''; + case 'core/image': + case 'core/cover': + case 'core/media-text': + if ( 1 === preg_match( '/\bsrc\s*=\s*(["\'])(.*?)\1/i', $html, $match ) ) { + $path = (string) wp_parse_url( $match[2], PHP_URL_PATH ); + return '' !== $path ? wp_basename( $path ) : ''; + } + return ''; + default: + return ''; + } + } + + /** + * A block's text: no tags, one line, cut short. + * + * @param string $html The block's HTML. + * + * @return string + */ + private static function text( string $html ): string { + $text = trim( (string) preg_replace( '/\s+/u', ' ', self::plain( wp_strip_all_tags( $html ) ) ) ); + + return mb_strlen( $text ) > self::MAX_TEXT ? mb_substr( $text, 0, self::MAX_TEXT ) . '…' : $text; + } + + /** + * The name of a template part area from term taxonomy IDs; '' for none. + * + * @param array $ids Term taxonomy IDs. + * + * @return string + */ + private static function area_name( array $ids ): string { + foreach ( $ids as $id ) { + $term = get_term_by( 'term_taxonomy_id', (int) $id, 'wp_template_part_area' ); + if ( $term instanceof \WP_Term ) { + return (string) $term->name; + } + } + + return ''; + } + + /** + * The name of a post's first term in a taxonomy; '' for none. + * + * @param \WP_Post|null $post The post. + * @param string $taxonomy The taxonomy. + * + * @return string + */ + private static function term_name( ?\WP_Post $post, string $taxonomy ): string { + if ( null === $post ) { + return ''; + } + $terms = get_the_terms( $post, $taxonomy ); + + return is_array( $terms ) && isset( $terms[0]->name ) ? (string) $terms[0]->name : ''; + } + + /** + * A theme's name; its stylesheet when it isn't installed. + * + * @param string $stylesheet The theme. + * + * @return string + */ + private static function theme_name( string $stylesheet ): string { + $theme = '' !== $stylesheet ? wp_get_theme( $stylesheet ) : null; + $name = is_object( $theme ) && $theme->exists() ? self::plain( $theme->get( 'Name' ) ) : ''; + + return '' !== $name ? $name : $stylesheet; + } + + /** + * Plain text from a value WordPress stores HTML-encoded. + * + * @param mixed $value The value. + * + * @return string + */ + private static function plain( $value ): string { + return html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' ); + } +} diff --git a/src/Events/SiteEditor/Collector.php b/src/Events/SiteEditor/Collector.php new file mode 100644 index 0000000..cb9f2a8 --- /dev/null +++ b/src/Events/SiteEditor/Collector.php @@ -0,0 +1,572 @@ + 'template', + 'wp_template_part' => 'template_part', + ]; + + /** + * Global styles saved in this request, per post: the theme, the content + * and title before the first save and after the last. The title is the + * style variation picked (the REST endpoint stores it as the post's + * title). + * + * @var array + */ + private static array $styles = []; + + /** + * Templates and template parts saved or removed in this request, per + * post. + * + * @var array> + */ + private static array $templates = []; + + /** + * Template part areas set in this request, per post: term taxonomy IDs + * before the first change and after the last. + * + * @var array + */ + private static array $areas = []; + + /** + * Font families and variants added or removed in this request, per + * family post. + * + * @var array> + */ + private static array $fonts = []; + + /** + * Hook into WordPress. + * + * @return void + */ + public static function setup(): void { + add_action( 'wp_after_insert_post', [ self::class, 'note_saved' ], 10, 4 ); + add_action( 'before_delete_post', [ self::class, 'note_deleting' ], 10, 2 ); + add_action( 'set_object_terms', [ self::class, 'note_terms' ], 10, 6 ); + add_action( 'shutdown', [ self::class, 'flush' ], 1, 0 ); + } + + /** + * Forget what was noted (tests, and after a flush). + * + * @return void + */ + public static function reset(): void { + self::$styles = []; + self::$templates = []; + self::$areas = []; + self::$fonts = []; + } + + /** + * Whether installs, imports or another site of a network are at work. + * + * @return bool + */ + private static function is_setup_work(): bool { + return ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) + || wp_installing() + || ( function_exists( 'ms_is_switched' ) && ms_is_switched() ); + } + + /** + * `wp_after_insert_post`: a post was saved. + * + * @param mixed $post_id The post ID. + * @param mixed $post The post. + * @param mixed $update Whether an existing post was updated. + * @param mixed $post_before The post before the save, or null. + * + * @return void + */ + public static function note_saved( $post_id, $post, $update, $post_before ): void { + if ( ! is_object( $post ) || self::is_setup_work() ) { + return; + } + + $post_id = (int) $post_id; + $type = (string) ( $post->post_type ?? '' ); + $before = $update && is_object( $post_before ) ? $post_before : null; + + if ( 'wp_global_styles' === $type ) { + self::note_styles( $post_id, $post, $before ); + } elseif ( isset( self::TEMPLATE_TYPES[ $type ] ) ) { + self::note_template( $post_id, $post, $before ); + } elseif ( ! $update && ( 'wp_font_family' === $type || 'wp_font_face' === $type ) ) { + self::note_font( $post, 'added' ); + } + } + + /** + * `before_delete_post`: a post is about to be deleted. + * + * @param mixed $post_id The post ID. + * @param mixed $post The post. + * + * @return void + */ + public static function note_deleting( $post_id, $post ): void { + if ( ! is_object( $post ) || self::is_setup_work() ) { + return; + } + + $type = (string) ( $post->post_type ?? '' ); + if ( isset( self::TEMPLATE_TYPES[ $type ] ) ) { + self::note_template_removed( (int) $post_id, $post ); + } elseif ( 'wp_font_family' === $type || 'wp_font_face' === $type ) { + self::note_font( $post, 'removed' ); + } + } + + /** + * `set_object_terms`: a template part's area changed. + * + * @param mixed $object_id The object ID. + * @param mixed $terms The terms asked for. + * @param mixed $tt_ids The term taxonomy IDs set. + * @param mixed $taxonomy The taxonomy. + * @param mixed $append Whether the terms were added to the existing ones. + * @param mixed $old_tt_ids The term taxonomy IDs before. + * + * @return void + */ + public static function note_terms( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ): void { + if ( 'wp_template_part_area' !== $taxonomy || self::is_setup_work() ) { + return; + } + + $post_id = (int) $object_id; + $new = array_map( 'intval', is_array( $tt_ids ) ? $tt_ids : [] ); + $old = array_map( 'intval', is_array( $old_tt_ids ) ? $old_tt_ids : [] ); + if ( ! isset( self::$areas[ $post_id ] ) ) { + self::$areas[ $post_id ] = [ + 'old' => $old, + 'new' => $new, + ]; + return; + } + self::$areas[ $post_id ]['new'] = $new; + } + + /** + * Note a global styles save. + * + * @param int $post_id The post ID. + * @param object $post The post. + * @param object|null $before The post before, or null for a new post. + * + * @return void + */ + private static function note_styles( int $post_id, object $post, ?object $before ): void { + $new = (string) ( $post->post_content ?? '' ); + $new_title = (string) ( $post->post_title ?? '' ); + if ( isset( self::$styles[ $post_id ] ) ) { + self::$styles[ $post_id ]['new'] = $new; + self::$styles[ $post_id ]['new_title'] = $new_title; + return; + } + + self::$styles[ $post_id ] = [ + 'stylesheet' => self::styles_stylesheet( $post ), + 'old' => null !== $before ? (string) ( $before->post_content ?? '' ) : '', + 'new' => $new, + 'old_title' => null !== $before ? (string) ( $before->post_title ?? '' ) : $new_title, + 'new_title' => $new_title, + ]; + } + + /** + * The theme of a global styles post, from its name + * (`wp-global-styles-{stylesheet}`), without a query. + * + * @param object $post The post. + * + * @return string + */ + public static function styles_stylesheet( object $post ): string { + $name = (string) ( $post->post_name ?? '' ); + $prefix = 'wp-global-styles-'; + + return 0 === strpos( $name, $prefix ) ? urldecode( substr( $name, strlen( $prefix ) ) ) : (string) get_stylesheet(); + } + + /** + * Note a template or template part save. + * + * @param int $post_id The post ID. + * @param object $post The post. + * @param object|null $before The post before, or null for a new post. + * + * @return void + */ + private static function note_template( int $post_id, object $post, ?object $before ): void { + if ( 'auto-draft' === ( $post->post_status ?? '' ) ) { + return; + } + + if ( ! isset( self::$templates[ $post_id ] ) ) { + self::$templates[ $post_id ] = [ + 'kind' => self::TEMPLATE_TYPES[ (string) $post->post_type ], + 'inserted' => null === $before, + 'old' => null !== $before ? self::template_fields( $before ) : null, + ]; + } + self::$templates[ $post_id ]['slug'] = (string) ( $post->post_name ?? '' ); + self::$templates[ $post_id ]['new'] = self::template_fields( $post ); + } + + /** + * Note a template or template part about to be deleted: a reset to the + * theme's version, or a custom one removed. Its theme and area are read + * now, from the term cache the delete has just filled. + * + * @param int $post_id The post ID. + * @param object $post The post. + * + * @return void + */ + private static function note_template_removed( int $post_id, object $post ): void { + self::$templates[ $post_id ] = [ + 'kind' => self::TEMPLATE_TYPES[ (string) $post->post_type ], + 'slug' => (string) ( $post->post_name ?? '' ), + 'removed' => self::template_fields( $post ), + 'stylesheet' => self::term_name( $post_id, 'wp_theme' ), + 'area' => 'wp_template_part' === $post->post_type ? self::term_name( $post_id, 'wp_template_part_area' ) : '', + ]; + } + + /** + * The fields of a template the row compares. + * + * @param object $post The template's post. + * + * @return array{title: string, description: string, content: string, status: string} + */ + private static function template_fields( object $post ): array { + return [ + 'title' => (string) ( $post->post_title ?? '' ), + 'description' => (string) ( $post->post_excerpt ?? '' ), + 'content' => (string) ( $post->post_content ?? '' ), + 'status' => (string) ( $post->post_status ?? '' ), + ]; + } + + /** + * The name of a post's first term in a taxonomy; '' for none. + * + * @param int $post_id The post ID. + * @param string $taxonomy The taxonomy. + * + * @return string + */ + private static function term_name( int $post_id, string $taxonomy ): string { + $terms = get_the_terms( $post_id, $taxonomy ); + + return is_array( $terms ) && isset( $terms[0]->name ) ? (string) $terms[0]->name : ''; + } + + /** + * Note a font family or variant added or removed. + * + * @param object $post The family's or variant's post. + * @param string $action `added` or `removed`. + * + * @return void + */ + private static function note_font( object $post, string $action ): void { + if ( 'wp_font_family' === $post->post_type ) { + $family_id = (int) ( $post->ID ?? 0 ); + self::font_family( $family_id, $post ); + self::$fonts[ $family_id ]['family'] = $action; + return; + } + + $family_id = (int) ( $post->post_parent ?? 0 ); + if ( $family_id < 1 ) { + return; + } + if ( ! isset( self::$fonts[ $family_id ] ) ) { + // The family's post is in the cache: the REST request loaded it. + $family = get_post( $family_id ); + if ( ! $family instanceof \WP_Post ) { + return; + } + self::font_family( $family_id, $family ); + } + + $settings = json_decode( (string) ( $post->post_content ?? '' ), true ); + self::$fonts[ $family_id ]['faces'][] = [ + 'action' => $action, + 'style' => is_array( $settings ) ? (string) ( $settings['fontStyle'] ?? 'normal' ) : 'normal', + 'weight' => is_array( $settings ) ? (string) ( $settings['fontWeight'] ?? '400' ) : '400', + ]; + } + + /** + * The note of a font family, made when missing. + * + * @param int $family_id The family's post ID. + * @param object $family The family's post. + * + * @return void + */ + private static function font_family( int $family_id, object $family ): void { + if ( isset( self::$fonts[ $family_id ] ) ) { + return; + } + + self::$fonts[ $family_id ] = [ + 'id' => $family_id, + 'name' => (string) ( $family->post_title ?? '' ), + 'slug' => (string) ( $family->post_name ?? '' ), + 'family' => '', + 'faces' => [], + ]; + } + + /** + * Whether a global styles config holds nothing the user changed. + * + * @param mixed $config The decoded config. + * + * @return bool + */ + public static function is_empty_styles( $config ): bool { + return ! is_array( $config ) || ( empty( $config['styles'] ) && empty( $config['settings'] ) ); + } + + /** + * The rows of the styles saved in this request. + * + * @return array> + */ + public static function styles_rows(): array { + $rows = []; + foreach ( self::$styles as $styles ) { + $title_changed = $styles['old_title'] !== $styles['new_title']; + if ( $styles['old'] === $styles['new'] && ! $title_changed ) { + continue; + } + // Core makes the post with empty styles when an editor first asks + // for it; that is nobody's change. + if ( ! $title_changed && self::is_empty_styles( json_decode( $styles['new'], true ) ) && self::is_empty_styles( json_decode( '' !== $styles['old'] ? $styles['old'] : '{}', true ) ) ) { + continue; + } + + $row = [ + 'stylesheet' => $styles['stylesheet'], + 'content' => self::content( $styles['old'], $styles['new'] ), + ]; + if ( $title_changed ) { + $row['title'] = [ + 'old' => $styles['old_title'], + 'new' => $styles['new_title'], + ]; + } + $rows[] = $row; + } + + return $rows; + } + + /** + * The rows of the templates saved or removed in this request: the type + * to report and the data. A first save is a provisional TemplateChanged + * and a delete a provisional TemplateDeleted; the job tells a first + * customization from a new template and a reset from a delete. + * + * @return array}> + */ + public static function template_rows(): array { + $rows = []; + foreach ( self::$templates as $post_id => $template ) { + $row = [ + 'post_id' => (int) $post_id, + 'kind' => (string) $template['kind'], + 'slug' => (string) ( $template['slug'] ?? '' ), + ]; + + $removed = $template['removed'] ?? null; + $new = $template['new'] ?? null; + if ( null === $removed && is_array( $new ) && 'trash' === $new['status'] ) { + $removed = $new; + } + + if ( is_array( $removed ) ) { + $row['removed'] = true; + $row['title'] = $removed['title']; + $row['content'] = self::content( $removed['content'], '' ); + foreach ( [ 'stylesheet', 'area' ] as $key ) { + if ( '' !== (string) ( $template[ $key ] ?? '' ) ) { + $row[ $key ] = (string) $template[ $key ]; + } + } + $rows[] = [ 'TemplateDeleted', $row ]; + continue; + } + + if ( ! is_array( $new ) ) { + continue; + } + $row['title'] = $new['title']; + + if ( ! empty( $template['inserted'] ) ) { + $row['inserted'] = true; + $row['content'] = self::content( '', $new['content'] ); + $rows[] = [ 'TemplateChanged', $row ]; + continue; + } + + $old = is_array( $template['old'] ?? null ) ? $template['old'] : $new; + $changes = []; + foreach ( [ 'title', 'description' ] as $field ) { + if ( $old[ $field ] !== $new[ $field ] ) { + $changes[ $field ] = [ + 'old' => $old[ $field ], + 'new' => $new[ $field ], + ]; + } + } + $area = self::$areas[ $post_id ] ?? null; + if ( null !== $area && ( [] !== array_diff( $area['old'], $area['new'] ) || [] !== array_diff( $area['new'], $area['old'] ) ) ) { + $changes['area'] = $area; + } + if ( $old['content'] !== $new['content'] ) { + $row['content'] = self::content( $old['content'], $new['content'] ); + } + if ( [] === $changes && ! isset( $row['content'] ) ) { + continue; + } + if ( [] !== $changes ) { + $row['changes'] = $changes; + } + $rows[] = [ 'TemplateChanged', $row ]; + } + + return $rows; + } + + /** + * The content before and after for the job, or that it is too large. + * + * @param string $old The content before. + * @param string $new The content after. + * + * @return array + */ + private static function content( string $old, string $new ): array { + if ( strlen( $old ) > self::MAX_CONTENT || strlen( $new ) > self::MAX_CONTENT ) { + return [ 'too_large' => true ]; + } + + return [ + 'stash' => [ + 'old' => $old, + 'new' => $new, + ], + ]; + } + + /** + * The font notes of this request, as the minute's job reads them. + * + * @return array> + */ + public static function font_items(): array { + $items = []; + foreach ( self::$fonts as $font ) { + if ( '' !== $font['family'] || [] !== $font['faces'] ) { + $items[] = $font; + } + } + + return $items; + } + + /** + * Report what this request changed, once, at the end of the request. + * + * @return void + */ + public static function flush(): void { + $styles = self::styles_rows(); + $templates = self::template_rows(); + $fonts = self::font_items(); + self::reset(); + + if ( [] !== $fonts && Options\Controller::get_options()->is_connected ) { + $user = wp_get_current_user(); + MinuteStore::add( + self::KIND_FONTS, + [ + 'user' => [ + 'id' => (int) $user->ID, + 'name' => ContentEvent::user_name( $user ), + ], + 'items' => $fonts, + ], + Controller::ACTION_SEND_FONTS + ); + } + + $rows = []; + foreach ( $styles as $row ) { + $rows[] = [ 'StylesChanged', $row ]; + } + $rows = array_merge( $rows, $templates ); + + $room = Limiter::take( Limiter::KIND_SITE_EDITOR, count( $rows ) ); + foreach ( array_slice( $rows, 0, $room ) as [ $type, $data ] ) { + do_action( ContentEvent::hook( $type ), $data ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- The hooks start with scanfully_. + } + } +} diff --git a/src/Events/SiteEditor/Fonts.php b/src/Events/SiteEditor/Fonts.php new file mode 100644 index 0000000..b83095b --- /dev/null +++ b/src/Events/SiteEditor/Fonts.php @@ -0,0 +1,195 @@ += self::MAX_ROWS ) { + break; + } + $rows[] = [ $type, $user, $data ]; + } + + foreach ( $rows as [ $type, $user, $data ] ) { + ContentEvent::queue( $type, $user, $data ); + } + } + + /** + * The rows of a minute's entries: per person and family, what was + * installed and what was removed. + * + * @param array> $entries The entries, oldest first. + * + * @return array}> + */ + public static function rows( array $entries ): array { + $families = []; + foreach ( $entries as $entry ) { + if ( ! is_array( $entry['items'] ?? null ) ) { + continue; + } + $user = [ + 'id' => (int) ( $entry['user']['id'] ?? 0 ), + 'name' => (string) ( $entry['user']['name'] ?? '' ), + ]; + + foreach ( $entry['items'] as $item ) { + if ( ! is_array( $item ) || (int) ( $item['id'] ?? 0 ) < 1 ) { + continue; + } + $key = $user['id'] . '|' . $user['name'] . '|' . (int) $item['id']; + if ( ! isset( $families[ $key ] ) ) { + $families[ $key ] = [ + 'user' => $user, + 'name' => (string) ( $item['name'] ?? '' ), + 'slug' => (string) ( $item['slug'] ?? '' ), + 'added' => false, + 'removed' => false, + 'faces' => [], + ]; + } + if ( 'added' === ( $item['family'] ?? '' ) ) { + $families[ $key ]['added'] = true; + } elseif ( 'removed' === ( $item['family'] ?? '' ) ) { + $families[ $key ]['removed'] = true; + } + foreach ( (array) ( $item['faces'] ?? [] ) as $face ) { + if ( ! is_array( $face ) ) { + continue; + } + $variant = (string) ( $face['style'] ?? 'normal' ) . '|' . (string) ( $face['weight'] ?? '400' ); + $step = 'added' === ( $face['action'] ?? '' ) ? 1 : -1; + $families[ $key ]['faces'][ $variant ] = ( $families[ $key ]['faces'][ $variant ] ?? 0 ) + $step; + } + } + } + + $rows = []; + foreach ( $families as $family ) { + // Installed and removed again within the minute. + if ( $family['added'] && $family['removed'] ) { + continue; + } + + $added = []; + $removed = []; + foreach ( $family['faces'] as $variant => $count ) { + if ( $count > 0 ) { + $added[] = self::variant( (string) $variant ); + } elseif ( $count < 0 ) { + $removed[] = self::variant( (string) $variant ); + } + } + + $base = [ + 'name' => $family['name'], + 'slug' => $family['slug'], + ]; + if ( $family['removed'] ) { + $rows[] = [ + 'FontDeleted', + $family['user'], + $base + [ + 'family' => true, + 'variants' => self::sorted( $removed ), + ], + ]; + continue; + } + if ( $family['added'] || [] !== $added ) { + $rows[] = [ + 'FontInstalled', + $family['user'], + $base + [ + 'family' => $family['added'], + 'variants' => self::sorted( $added ), + ], + ]; + } + if ( [] !== $removed ) { + $rows[] = [ + 'FontDeleted', + $family['user'], + $base + [ + 'family' => false, + 'variants' => self::sorted( $removed ), + ], + ]; + } + } + + return $rows; + } + + /** + * A variant from its key. + * + * @param string $key `style|weight`. + * + * @return array{style: string, weight: string} + */ + private static function variant( string $key ): array { + [ $style, $weight ] = array_pad( explode( '|', $key, 2 ), 2, '400' ); + + return [ + 'style' => $style, + 'weight' => $weight, + ]; + } + + /** + * Variants by weight, then upright before italic. + * + * @param array $variants The variants. + * + * @return array + */ + private static function sorted( array $variants ): array { + usort( + $variants, + static function ( array $a, array $b ): int { + $weight = (int) $a['weight'] <=> (int) $b['weight']; + + return 0 !== $weight ? $weight : strcmp( 'normal' === $a['style'] ? '0' : $a['style'], 'normal' === $b['style'] ? '0' : $b['style'] ); + } + ); + + return $variants; + } +} diff --git a/src/Events/SiteOptionChanged.php b/src/Events/SiteOptionChanged.php new file mode 100644 index 0000000..3db72eb --- /dev/null +++ b/src/Events/SiteOptionChanged.php @@ -0,0 +1,66 @@ + 0 ? get_userdata( $user_id ) : false; + + return $user instanceof \WP_User ? $user : null; + } + + /** + * Get the post body + * + * @param array $data The data passed to the action: the event data. + * + * @return array + */ + public function get_post_body( array $data ): array { + $body = parent::get_post_body( $data ); + unset( $body['_actor'] ); + + return $body; + } +} diff --git a/src/Events/StylesChanged.php b/src/Events/StylesChanged.php new file mode 100644 index 0000000..659d3d2 --- /dev/null +++ b/src/Events/StylesChanged.php @@ -0,0 +1,32 @@ + + */ + private static array $inserting = []; + + /** + * The term wp_update_term() is changing, per taxonomy: its values before + * and the new ones. + * + * @var array> + */ + private static array $updating = []; + + /** + * Terms created in this request, by term taxonomy ID. + * + * @var array> + */ + private static array $created = []; + + /** + * Terms changed in this request, by term taxonomy ID: the values before + * the first change and after the last. + * + * @var array> + */ + private static array $changed = []; + + /** + * Terms deleted in this request, by term taxonomy ID. + * + * @var array> + */ + private static array $deleted = []; + + /** + * Whether the hooks are added. + * + * @var bool + */ + private static bool $set_up = false; + + /** + * Add the hooks. + * + * @return void + */ + public static function setup(): void { + if ( self::$set_up ) { + return; + } + self::$set_up = true; + + add_filter( 'wp_insert_term_data', [ self::class, 'note_inserting' ], PHP_INT_MAX, 3 ); + add_action( 'created_term', [ self::class, 'note_created' ], 10, 3 ); + add_filter( 'wp_update_term_parent', [ self::class, 'note_updating' ], PHP_INT_MAX, 4 ); + add_filter( 'wp_update_term_data', [ self::class, 'note_update_data' ], PHP_INT_MAX, 3 ); + add_action( 'edited_term', [ self::class, 'note_edited' ], 10, 3 ); + add_action( 'delete_term', [ self::class, 'note_deleted' ], 10, 5 ); + // After the post Collector, which tells which new terms its posts got. + add_action( 'shutdown', [ self::class, 'flush' ], 1, 0 ); + } + + /** + * Forget everything noted (tests, and after a flush). + * + * @return void + */ + public static function reset(): void { + self::$inserting = []; + self::$updating = []; + self::$created = []; + self::$changed = []; + self::$deleted = []; + } + + /** + * Whether changes to the terms of a taxonomy are reported: taxonomies + * with an admin screen, not during an import. Post formats have no + * screen; WordPress makes their terms when a format is first used. + * + * @param string $taxonomy The taxonomy. + * + * @return bool + */ + private static function is_counted( string $taxonomy ): bool { + if ( 'post_format' === $taxonomy || ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) ) { + return false; + } + + $object = get_taxonomy( $taxonomy ); + + return is_object( $object ) && ! empty( $object->show_ui ); + } + + /** + * `wp_insert_term_data`: a term is about to be added. + * + * @param mixed $data The term's name, slug and group. + * @param mixed $taxonomy The taxonomy. + * @param mixed $args The arguments, with the parent. + * + * @return mixed The data, unchanged. + */ + public static function note_inserting( $data, $taxonomy, $args ) { + if ( is_array( $data ) && is_string( $taxonomy ) && self::is_counted( $taxonomy ) ) { + self::$inserting[ $taxonomy ] = [ + 'name' => (string) ( $data['name'] ?? '' ), + 'slug' => (string) ( $data['slug'] ?? '' ), + 'parent' => (int) ( is_array( $args ) ? ( $args['parent'] ?? 0 ) : 0 ), + ]; + } + + return $data; + } + + /** + * `created_term`: the term was added. + * + * @param mixed $term_id The term ID. + * @param mixed $tt_id The term taxonomy ID. + * @param mixed $taxonomy The taxonomy. + * + * @return void + */ + public static function note_created( $term_id, $tt_id, $taxonomy ): void { + $taxonomy = (string) $taxonomy; + if ( ! isset( self::$inserting[ $taxonomy ] ) ) { + return; + } + $term = self::$inserting[ $taxonomy ]; + unset( self::$inserting[ $taxonomy ] ); + + if ( count( self::$created ) < self::MAX_TERMS ) { + self::$created[ (int) $tt_id ] = array_merge( + $term, + [ + 'id' => (int) $term_id, + 'taxonomy' => $taxonomy, + ] + ); + } + } + + /** + * `wp_update_term_parent`: a term is about to change. The term is still + * in the cache as it was: wp_update_term() has just read it. The parent + * passed here is the one that will be saved, and the arguments carry the + * new description. + * + * @param mixed $parent_id The new parent. + * @param mixed $term_id The term ID. + * @param mixed $taxonomy The taxonomy. + * @param mixed $parsed_args The update arguments. + * + * @return mixed The parent, unchanged. + */ + public static function note_updating( $parent_id, $term_id, $taxonomy, $parsed_args ) { + $taxonomy = (string) $taxonomy; + if ( ! self::is_counted( $taxonomy ) ) { + return $parent_id; + } + + $cached = wp_cache_get( (int) $term_id, 'terms' ); + if ( ! is_object( $cached ) || ! isset( $cached->name ) ) { + unset( self::$updating[ $taxonomy ] ); + return $parent_id; + } + + self::$updating[ $taxonomy ] = [ + 'old' => [ + 'name' => (string) $cached->name, + 'slug' => (string) ( $cached->slug ?? '' ), + 'parent' => (int) ( $cached->parent ?? 0 ), + 'description' => (string) ( $cached->description ?? '' ), + ], + 'new' => [ + 'parent' => (int) $parent_id, + 'description' => (string) ( is_array( $parsed_args ) ? ( $parsed_args['description'] ?? '' ) : '' ), + ], + ]; + + return $parent_id; + } + + /** + * `wp_update_term_data`: the new name and slug of the term. + * + * @param mixed $data The name, slug and group. + * @param mixed $term_id The term ID. + * @param mixed $taxonomy The taxonomy. + * + * @return mixed The data, unchanged. + */ + public static function note_update_data( $data, $term_id, $taxonomy ) { + $taxonomy = (string) $taxonomy; + if ( is_array( $data ) && isset( self::$updating[ $taxonomy ] ) ) { + self::$updating[ $taxonomy ]['new']['name'] = (string) ( $data['name'] ?? '' ); + self::$updating[ $taxonomy ]['new']['slug'] = (string) ( $data['slug'] ?? '' ); + } + + return $data; + } + + /** + * `edited_term`: the term was changed. + * + * @param mixed $term_id The term ID. + * @param mixed $tt_id The term taxonomy ID. + * @param mixed $taxonomy The taxonomy. + * + * @return void + */ + public static function note_edited( $term_id, $tt_id, $taxonomy ): void { + $taxonomy = (string) $taxonomy; + if ( ! isset( self::$updating[ $taxonomy ]['new']['name'] ) ) { + return; + } + $update = self::$updating[ $taxonomy ]; + unset( self::$updating[ $taxonomy ] ); + + $tt_id = (int) $tt_id; + $new = $update['new']; + + // A term made in this request is reported once, as it is now. + if ( isset( self::$created[ $tt_id ] ) ) { + self::$created[ $tt_id ] = array_merge( self::$created[ $tt_id ], array_intersect_key( $new, array_flip( [ 'name', 'slug', 'parent' ] ) ) ); + return; + } + + if ( isset( self::$changed[ $tt_id ] ) ) { + self::$changed[ $tt_id ]['new'] = $new; + return; + } + + if ( count( self::$changed ) < self::MAX_TERMS ) { + self::$changed[ $tt_id ] = [ + 'id' => (int) $term_id, + 'taxonomy' => $taxonomy, + 'old' => $update['old'], + 'new' => $new, + ]; + } + } + + /** + * `delete_term`: a term was deleted. WordPress passes a copy of it and + * the posts (or other objects) that had it. + * + * @param mixed $term_id The term ID. + * @param mixed $tt_id The term taxonomy ID. + * @param mixed $taxonomy The taxonomy. + * @param mixed $deleted_term The deleted term. + * @param mixed $object_ids The objects that had it. + * + * @return void + */ + public static function note_deleted( $term_id, $tt_id, $taxonomy, $deleted_term, $object_ids ): void { + $taxonomy = (string) $taxonomy; + $tt_id = (int) $tt_id; + if ( ! $deleted_term instanceof \WP_Term || ! self::is_counted( $taxonomy ) ) { + return; + } + + unset( self::$changed[ $tt_id ] ); + // A term made and deleted in one request is no change. + if ( isset( self::$created[ $tt_id ] ) ) { + unset( self::$created[ $tt_id ] ); + return; + } + + if ( count( self::$deleted ) < self::MAX_TERMS ) { + self::$deleted[ $tt_id ] = [ + 'id' => (int) $term_id, + 'taxonomy' => $taxonomy, + 'name' => (string) $deleted_term->name, + 'slug' => (string) $deleted_term->slug, + 'posts' => is_array( $object_ids ) ? count( $object_ids ) : 0, + ]; + } + } + + /** + * Report the terms created, changed and deleted, once, at the end of + * the request. + * + * @return void + */ + public static function flush(): void { + $created = self::$created; + $changed = self::$changed; + $deleted = self::$deleted; + self::reset(); + + // A term made for a post saved in this request is on that post's row. + $on_posts = PostCollector::added_terms(); + + $items = []; + foreach ( $created as $tt_id => $term ) { + if ( isset( $on_posts[ $tt_id ] ) ) { + continue; + } + + $data = self::describe( $term ); + if ( $term['parent'] > 0 ) { + $data['parent'] = [ 'id' => $term['parent'] ]; + } + $items[] = self::item( 'created', $term, $data ); + } + + foreach ( $changed as $term ) { + $changes = self::changes( $term['old'], $term['new'] ); + if ( [] === $changes ) { + continue; + } + + $data = self::describe( array_merge( $term, $term['new'] ) ); + $data['changes'] = $changes; + $item = self::item( 'changed', array_merge( $term, $term['new'] ), $data ); + $item['changed'] = array_keys( $changes ); + $items[] = $item; + } + + foreach ( $deleted as $term ) { + $data = self::describe( $term ); + $data['posts'] = $term['posts']; + $item = self::item( 'deleted', $term, $data ); + $item['posts'] = $term['posts']; + $items[] = $item; + } + + Report::send( Report::KIND_TERM, $items ); + } + + /** + * What a term's event says about it: ID, name, slug, taxonomy and the + * taxonomy's singular name on the site. + * + * @param array $term The term as noted. + * + * @return array + */ + private static function describe( array $term ): array { + $object = get_taxonomy( (string) $term['taxonomy'] ); + + return [ + 'id' => (int) $term['id'], + 'name' => self::plain( (string) $term['name'] ), + 'slug' => (string) $term['slug'], + 'taxonomy' => (string) $term['taxonomy'], + 'label' => is_object( $object ) && isset( $object->labels->singular_name ) ? self::plain( (string) $object->labels->singular_name ) : (string) $term['taxonomy'], + ]; + } + + /** + * A term as a summary item, with its own event. + * + * @param string $action `created`, `changed` or `deleted`. + * @param array $term The term as noted. + * @param array $data Its event's data. + * + * @return array + */ + private static function item( string $action, array $term, array $data ): array { + $types = [ + 'created' => 'TermCreated', + 'changed' => 'TermChanged', + 'deleted' => 'TermDeleted', + ]; + + return [ + 'action' => $action, + 'group' => (string) $term['taxonomy'], + 'id' => (int) $term['id'], + 'title' => Summary::title( (string) $term['name'] ), + 'event' => [ + 'hook' => ContentEvent::hook( $types[ $action ] ), + 'args' => [ $data ], + ], + ]; + } + + /** + * What changed in a term: name, slug and description as old and new, + * the parent by ID (the job adds the names). + * + * @param array $before The values before. + * @param array $after The values after. + * + * @return array + */ + public static function changes( array $before, array $after ): array { + $changes = []; + foreach ( [ 'name', 'slug', 'description' ] as $field ) { + $old = (string) ( $before[ $field ] ?? '' ); + $new = (string) ( $after[ $field ] ?? '' ); + if ( $old !== $new ) { + $changes[ $field ] = [ + 'old' => self::cut( self::plain( $old ) ), + 'new' => self::cut( self::plain( $new ) ), + ]; + } + } + + $old_parent = (int) ( $before['parent'] ?? 0 ); + $new_parent = (int) ( $after['parent'] ?? 0 ); + if ( $old_parent !== $new_parent ) { + $changes['parent'] = [ + 'old' => [ 'id' => $old_parent ], + 'new' => [ 'id' => $new_parent ], + ]; + } + + return $changes; + } + + /** + * Plain text from a value WordPress stores HTML-encoded. + * + * @param string $value The value. + * + * @return string + */ + private static function plain( string $value ): string { + return html_entity_decode( $value, ENT_QUOTES, 'UTF-8' ); + } + + /** + * A text cut to the longest description kept. + * + * @param string $text The text. + * + * @return string + */ + private static function cut( string $text ): string { + return mb_strlen( $text ) > self::MAX_DESCRIPTION ? mb_substr( $text, 0, self::MAX_DESCRIPTION ) : $text; + } +} diff --git a/src/Events/TermCreated.php b/src/Events/TermCreated.php new file mode 100644 index 0000000..e810fea --- /dev/null +++ b/src/Events/TermCreated.php @@ -0,0 +1,30 @@ + + */ + private static array $pending = []; + + /** + * Constructor. + */ + public function __construct() { + parent::__construct( 'ThemeDeleted', 'deleted_theme', 10, 2 ); + + add_action( 'delete_theme', [ self::class, 'remember' ], 10, 1 ); + } + + /** + * Read the details of a theme that is about to be deleted. + * + * @param mixed $stylesheet The theme's stylesheet (directory name). + * + * @return void + */ + public static function remember( $stylesheet ): void { + if ( ! is_string( $stylesheet ) || '' === $stylesheet ) { + return; + } + + $theme = wp_get_theme( $stylesheet ); + $name = $theme->exists() ? self::plain_text( $theme->get( 'Name' ) ) : ''; + + self::$pending[ $stylesheet ] = [ + 'name' => '' !== $name ? $name : $stylesheet, + 'slug' => $stylesheet, + 'version' => $theme->exists() ? (string) $theme->get( 'Version' ) : '', + ]; + } + + /** + * Get the post body + * + * @param array $data The data to send: stylesheet, whether it was deleted. + * + * @return array + */ + public function get_post_body( array $data ): array { + $stylesheet = (string) ( $data[0] ?? '' ); + + return self::$pending[ $stylesheet ] ?? [ + 'name' => $stylesheet, + 'slug' => $stylesheet, + 'version' => '', + ]; + } + + /** + * A check if a event should fire + * + * @param array $data The event data: stylesheet, whether it was deleted. + * + * @return bool + */ + public function should_fire( array $data ): bool { + return is_string( $data[0] ?? null ) && '' !== $data[0] && true === ( $data[1] ?? false ); + } +} diff --git a/src/Events/ThemeFileEdited.php b/src/Events/ThemeFileEdited.php new file mode 100644 index 0000000..2060b0f --- /dev/null +++ b/src/Events/ThemeFileEdited.php @@ -0,0 +1,30 @@ +get( 'Name' ) ); + + return [ + 'name' => '' !== $name ? $name : $theme->get_stylesheet(), + 'slug' => $theme->get_stylesheet(), + 'version' => (string) $theme->get( 'Version' ), + 'author' => self::plain_text( $theme->get( 'Author' ) ), + ]; + } + + /** + * A check if a event should fire + * + * @param array $data The event data: the upgrader, the hook extras. + * + * @return bool + */ + public function should_fire( array $data ): bool { + return null !== self::installed_theme( $data ); + } + + /** + * The theme a successful install put in place, or null when this wasn't a + * successful theme install. + * + * @param array $data The event data: the upgrader, the hook extras. + * + * @return \WP_Theme|null + */ + private static function installed_theme( array $data ): ?\WP_Theme { + $upgrader = $data[0] ?? null; + $hook_extra = $data[1] ?? null; + + if ( ! is_array( $hook_extra ) || 'install' !== ( $hook_extra['action'] ?? '' ) || 'theme' !== ( $hook_extra['type'] ?? '' ) ) { + return null; + } + + // The upgrader's result is an array only when the install succeeded. + if ( ! is_object( $upgrader ) || ! method_exists( $upgrader, 'theme_info' ) || ! isset( $upgrader->result ) || ! is_array( $upgrader->result ) ) { + return null; + } + + $theme = $upgrader->theme_info(); + + return $theme instanceof \WP_Theme && $theme->exists() ? $theme : null; + } +} diff --git a/src/Events/ThemeSettings/Builder.php b/src/Events/ThemeSettings/Builder.php new file mode 100644 index 0000000..140f2d6 --- /dev/null +++ b/src/Events/ThemeSettings/Builder.php @@ -0,0 +1,153 @@ + $data The row as the Collector noted it. + * + * @return array + */ + public static function resolve( array $data ): array { + $stylesheet = (string) ( $data['stylesheet'] ?? '' ); + $theme = '' !== $stylesheet ? wp_get_theme( $stylesheet ) : null; + $name = is_object( $theme ) && $theme->exists() ? self::plain( $theme->get( 'Name' ) ) : ''; + $data['name'] = '' !== $name ? $name : $stylesheet; + + if ( isset( $data['settings'] ) && is_array( $data['settings'] ) ) { + foreach ( $data['settings'] as $index => $setting ) { + if ( is_array( $setting ) && 'media' === ( $setting['kind'] ?? '' ) ) { + $data['settings'][ $index ] = self::with_files( $setting ); + } elseif ( is_array( $setting ) && 'page' === ( $setting['kind'] ?? '' ) ) { + $data['settings'][ $index ] = self::with_page_titles( $setting ); + } + } + } + + if ( isset( $data['logo'] ) && is_array( $data['logo'] ) ) { + $data['logo'] = [ + 'old' => self::attachment( (string) ( $data['logo']['old'] ?? '' ) ), + 'new' => self::attachment( (string) ( $data['logo']['new'] ?? '' ) ), + ]; + } + + if ( isset( $data['css'] ) && is_array( $data['css'] ) ) { + $css = $data['css']; + if ( isset( $css['stash'] ) && is_array( $css['stash'] ) ) { + $data['css'] = ContentDiff::compare_code( (string) ( $css['stash']['old'] ?? '' ), (string) ( $css['stash']['new'] ?? '' ) ); + } else { + $data['css'] = ContentDiff::unchanged_text( ! empty( $css['too_large'] ) ? 'too_large' : 'unavailable' ); + } + } + + return isset( $data['settings'] ) || isset( $data['logo'] ) || isset( $data['css'] ) ? $data : []; + } + + /** + * A setting with the file names of its old and new image or video. + * + * @param array $setting The setting's row. + * + * @return array + */ + private static function with_files( array $setting ): array { + foreach ( [ 'old', 'new' ] as $side ) { + if ( ! isset( $setting[ $side ] ) ) { + continue; + } + $file = self::file_name( (string) $setting[ $side ] ); + if ( '' !== $file ) { + $setting[ $side . '_file' ] = $file; + } + } + + return $setting; + } + + /** + * A setting with the titles of its old and new page (a page dropdown; + * 0 is no page). + * + * @param array $setting The setting's row. + * + * @return array + */ + private static function with_page_titles( array $setting ): array { + foreach ( [ 'old', 'new' ] as $side ) { + $id = (string) ( $setting[ $side ] ?? '' ); + $post = ctype_digit( $id ) && (int) $id > 0 ? get_post( (int) $id ) : null; + if ( $post instanceof \WP_Post ) { + $setting[ $side . '_name' ] = self::plain( $post->post_title ); + } + } + + return $setting; + } + + /** + * An attachment by ID and file name; empty for none. + * + * @param string $id The attachment ID. + * + * @return array{id: string, file: string} + */ + private static function attachment( string $id ): array { + return [ + 'id' => $id, + 'file' => ctype_digit( $id ) && (int) $id > 0 ? self::file_name( $id ) : '', + ]; + } + + /** + * The file name of an attachment ID or an upload URL; '' for anything + * else (`remove-header`, a random header). + * + * @param string $value The ID or URL. + * + * @return string + */ + public static function file_name( string $value ): string { + if ( ctype_digit( $value ) && (int) $value > 0 ) { + $file = get_attached_file( (int) $value ); + + return is_string( $file ) && '' !== $file ? wp_basename( $file ) : ''; + } + + if ( 1 !== preg_match( '#^https?://#i', $value ) ) { + return ''; + } + $path = (string) wp_parse_url( $value, PHP_URL_PATH ); + + return '' !== $path ? wp_basename( $path ) : ''; + } + + /** + * Plain text from a value WordPress stores HTML-encoded. + * + * @param mixed $value The value. + * + * @return string + */ + private static function plain( $value ): string { + return html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' ); + } +} diff --git a/src/Events/ThemeSettings/Collector.php b/src/Events/ThemeSettings/Collector.php new file mode 100644 index 0000000..c005f7d --- /dev/null +++ b/src/Events/ThemeSettings/Collector.php @@ -0,0 +1,769 @@ + 'header_image', + 'header_image_data' => 'header_image', + ]; + + /** + * The option that holds the logo's attachment ID. + */ + public const LOGO_OPTION = 'site_logo'; + + /** + * The Customizer setting of the logo. + */ + private const LOGO_SETTING = 'custom_logo'; + + /** + * Additional CSS larger than this (per side) is not compared. + */ + public const MAX_CSS = 256 * 1024; + + /** + * At most this many settings are listed in one row. + */ + private const MAX_SETTINGS = 50; + + /** + * The Customizer publish of this request: per setting ID the value + * before, the user who changed it and, for settings read from a theme + * mod, that mod; null without a publish. + * + * @var array|null + */ + private static ?array $customizer = null; + + /** + * The rows of a finished Customizer publish. + * + * @var array> + */ + private static array $customizer_settings = []; + + /** + * The theme a Customizer publish saved, and who made it when cron + * published a scheduled change. + * + * @var array{stylesheet: string, actor: int, scheduled: bool}|null + */ + private static ?array $customizer_publish = null; + + /** + * Theme mods changed outside the Customizer, per stylesheet: first old + * and last new value of the option. + * + * @var array + */ + private static array $mods = []; + + /** + * The logo: first old and last new attachment ID; null when unchanged. + * + * @var array{old: mixed, new: mixed}|null + */ + private static ?array $logo = null; + + /** + * Additional CSS: first old and last new CSS of the theme's post. + * + * @var array{old: string, new: string, stylesheet: string}|null + */ + private static ?array $css = null; + + /** + * Hook into WordPress. + * + * @return void + */ + public static function setup(): void { + add_action( 'customize_save', [ self::class, 'note_publish_start' ], 10, 1 ); + add_action( 'customize_save_after', [ self::class, 'note_publish_done' ], 10, 1 ); + add_action( 'updated_option', [ self::class, 'note_updated' ], 10, 3 ); + add_action( 'added_option', [ self::class, 'note_added' ], 10, 2 ); + add_action( 'delete_option', [ self::class, 'note_deleting' ], 10, 1 ); + add_action( 'wp_after_insert_post', [ self::class, 'note_post_saved' ], 10, 4 ); + add_action( 'shutdown', [ self::class, 'flush' ], 1, 0 ); + } + + /** + * Forget what was noted (tests, and after a flush). + * + * @return void + */ + public static function reset(): void { + self::$customizer = null; + self::$customizer_settings = []; + self::$customizer_publish = null; + self::$mods = []; + self::$logo = null; + self::$css = null; + } + + /** + * Whether installs, upgrades or imports run. + * + * @return bool + */ + private static function is_setup_work(): bool { + return ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) || wp_installing(); + } + + /** + * Whether option changes outside a Customizer publish are left out: + * page views (some themes write defaults when a page loads), theme + * switches, installs and imports. + * + * @return bool + */ + private static function is_quiet(): bool { + return MenuCollector::is_quiet() || MenuCollector::is_read_request(); + } + + /** + * Whether a Customizer setting is reported by another collector, or is + * no change of its own. + * + * @param string $id The setting ID. + * @param object $setting The setting (a WP_Customize_Setting). + * + * @return bool + */ + public static function is_reported_elsewhere( string $id, object $setting ): bool { + if ( in_array( $id, self::SKIPPED_SETTINGS, true ) ) { + return true; + } + foreach ( self::OTHER_PREFIXES as $prefix ) { + if ( 0 === strpos( $id, $prefix ) ) { + return true; + } + } + // A filter setting stores nothing (the header text checkbox sets + // `header_textcolor`). + if ( $setting instanceof \WP_Customize_Filter_Setting ) { + return true; + } + + $type = (string) ( $setting->type ?? '' ); + $base = method_exists( $setting, 'id_data' ) ? (string) ( $setting->id_data()['base'] ?? $id ) : $id; + + return 'option' === $type && Settings::is_reported( $base ); + } + + /** + * `customize_save`: a changeset is about to be published. Notes the + * value of every changed setting before it is saved. + * + * @param mixed $manager The Customizer (a WP_Customize_Manager). + * + * @return void + */ + public static function note_publish_start( $manager ): void { + if ( ! is_object( $manager ) || ! method_exists( $manager, 'unsanitized_post_values' ) || self::is_setup_work() ) { + return; + } + + $values = $manager->unsanitized_post_values( + [ + 'exclude_post_data' => true, + 'exclude_changeset' => false, + ] + ); + $users = self::setting_users( $manager ); + + self::$customizer = []; + foreach ( array_keys( is_array( $values ) ? $values : [] ) as $id ) { + $id = (string) $id; + if ( isset( self::MOD_SETTINGS[ $id ] ) ) { + $mod = self::MOD_SETTINGS[ $id ]; + if ( ! isset( self::$customizer[ $mod ] ) ) { + self::$customizer[ $mod ] = [ + 'old' => get_theme_mod( $mod, self::mod_default( $mod ) ), + 'user' => $users[ $id ] ?? 0, + 'mod' => $mod, + ]; + } + continue; + } + $setting = $manager->get_setting( $id ); + if ( ! is_object( $setting ) || self::is_reported_elsewhere( $id, $setting ) ) { + continue; + } + self::$customizer[ $id ] = [ + 'old' => $setting->value(), + 'user' => $users[ $id ] ?? 0, + ]; + } + } + + /** + * The value a theme mod has while it isn't set: for the header image the + * theme's default image, which is what the site showed. + * + * @param string $mod The theme mod. + * + * @return mixed + */ + private static function mod_default( string $mod ) { + return 'header_image' === $mod ? get_theme_support( 'custom-header', 'default-image' ) : false; + } + + /** + * Who changed each setting of the changeset being published, by + * setting ID (theme mods are stored as `{stylesheet}::{id}`). + * + * @param object $manager The Customizer. + * + * @return array + */ + private static function setting_users( object $manager ): array { + if ( ! method_exists( $manager, 'changeset_data' ) ) { + return []; + } + + $users = []; + foreach ( (array) $manager->changeset_data() as $raw_id => $params ) { + if ( ! is_array( $params ) || ! isset( $params['user_id'] ) ) { + continue; + } + $id = preg_match( '/^.+?::(.+)$/', (string) $raw_id, $matches ) ? $matches[1] : (string) $raw_id; + $users[ $id ] = (int) $params['user_id']; + } + + return $users; + } + + /** + * `customize_save_after`: the changeset is published. Notes the value + * after, and the label and section of each changed setting. + * + * @param mixed $manager The Customizer (a WP_Customize_Manager). + * + * @return void + */ + public static function note_publish_done( $manager ): void { + if ( null === self::$customizer || ! is_object( $manager ) || ! method_exists( $manager, 'get_setting' ) ) { + return; + } + + $noted = self::$customizer; + self::$customizer = null; + $controls = self::controls_by_setting( $manager ); + $users = []; + + foreach ( $noted as $id => $before ) { + if ( isset( $before['mod'] ) ) { + $after = get_theme_mod( $before['mod'], self::mod_default( $before['mod'] ) ); + } else { + $setting = $manager->get_setting( $id ); + if ( ! is_object( $setting ) ) { + continue; + } + $after = $setting->value(); + } + if ( Fields::fingerprint( $before['old'] ) === Fields::fingerprint( $after ) ) { + continue; + } + + if ( self::LOGO_SETTING === $id ) { + self::$logo = [ + 'old' => $before['old'], + 'new' => $after, + ]; + continue; + } + + $control = $controls[ $id ] ?? null; + $row = self::setting_row( $id, $before['old'], $after, $control, $manager ); + if ( null !== $row && count( self::$customizer_settings ) < self::MAX_SETTINGS ) { + self::$customizer_settings[] = $row; + } + if ( $before['user'] > 0 ) { + $users[] = $before['user']; + } + } + + // Cron publishes a scheduled change signed out: the row names the + // person who made most of the changes. + $actor = 0; + if ( get_current_user_id() < 1 && [] !== $users ) { + $counts = array_count_values( $users ); + arsort( $counts ); + $actor = (int) array_key_first( $counts ); + } + + self::$customizer_publish = [ + 'stylesheet' => method_exists( $manager, 'get_stylesheet' ) ? (string) $manager->get_stylesheet() : (string) get_stylesheet(), + 'actor' => $actor, + 'scheduled' => wp_doing_cron(), + ]; + } + + /** + * The Customizer's controls by the ID of the setting they edit. When + * several edit one setting (core's "Display Site Title and Tagline" + * checkbox edits the header text colour), the control named after the + * setting gives the label. + * + * @param object $manager The Customizer. + * + * @return array + */ + private static function controls_by_setting( object $manager ): array { + if ( ! method_exists( $manager, 'controls' ) ) { + return []; + } + + $controls = []; + foreach ( (array) $manager->controls() as $control ) { + if ( ! is_object( $control ) || ! isset( $control->settings ) || ! is_array( $control->settings ) ) { + continue; + } + foreach ( $control->settings as $setting ) { + $id = is_object( $setting ) && isset( $setting->id ) ? (string) $setting->id : ''; + if ( '' !== $id && ( ! isset( $controls[ $id ] ) || ( $control->id ?? '' ) === $id ) ) { + $controls[ $id ] = $control; + } + } + } + + return $controls; + } + + /** + * The row of a changed Customizer setting, or null when nothing shows. + * + * @param string $id The setting ID. + * @param mixed $old The value before. + * @param mixed $new The value after. + * @param object|null $control The control that edits it. + * @param object $manager The Customizer. + * + * @return array|null + */ + public static function setting_row( string $id, $old, $new, ?object $control, object $manager ): ?array { + $row = [ 'id' => $id ]; + + if ( null !== $control ) { + $label = self::plain( $control->label ?? '' ); + if ( '' !== $label ) { + $row['label'] = $label; + } + $section_id = (string) ( $control->section ?? '' ); + $section = '' !== $section_id && method_exists( $manager, 'get_section' ) ? $manager->get_section( $section_id ) : null; + $title = is_object( $section ) ? self::plain( $section->title ?? '' ) : ''; + if ( '' !== $title ) { + $row['section'] = $title; + } + } + + $kind = self::control_kind( $id, $control ); + if ( '' !== $kind ) { + $row['kind'] = $kind; + } + + if ( null !== $control && 'password' === ( $control->type ?? '' ) ) { + $row['change'] = 'changed'; + $row['secret'] = true; + + return $row; + } + + return self::with_values( $row, $old, $new ); + } + + /** + * What a setting holds, for the dashboard: `color`, `media` (an + * attachment ID or a URL), `page` (a page ID, from a page dropdown) or + * ''. + * + * @param string $id The setting or theme mod ID. + * @param object|null $control The control that edits it, if any. + * + * @return string + */ + private static function control_kind( string $id, ?object $control ): string { + if ( in_array( $id, self::COLOR_MODS, true ) || ( null !== $control && $control instanceof \WP_Customize_Color_Control ) ) { + return 'color'; + } + if ( in_array( $id, self::MEDIA_MODS, true ) || ( null !== $control && $control instanceof \WP_Customize_Media_Control ) ) { + return 'media'; + } + if ( null !== $control && 'dropdown-pages' === ( $control->type ?? '' ) ) { + return 'page'; + } + + return ''; + } + + /** + * A row with its change and values as custom fields show them: short + * values as they are, long ones and arrays only as large. + * + * @param array $row The row so far. + * @param mixed $old The value before. + * @param mixed $new The value after. + * + * @return array|null + */ + private static function with_values( array $row, $old, $new ): ?array { + $had = null !== $old && '' !== $old; + $has = null !== $new && '' !== $new; + if ( ! $had && ! $has ) { + return null; + } + $row['change'] = $had && $has ? 'changed' : ( $has ? 'added' : 'removed' ); + + foreach ( [ + 'old' => $had ? $old : null, + 'new' => $has ? $new : null, + ] as $side => $value ) { + if ( null === $value ) { + continue; + } + $described = Fields::describe( $value ); + if ( $described['large'] ) { + $row['large'] = true; + } elseif ( null !== $described['value'] ) { + $row[ $side ] = $described['value']; + } + } + + return $row; + } + + /** + * The stylesheet of a theme mods option, or '' for any other option. + * + * @param string $option The option name. + * + * @return string + */ + private static function mods_stylesheet( string $option ): string { + return 0 === strpos( $option, 'theme_mods_' ) ? substr( $option, strlen( 'theme_mods_' ) ) : ''; + } + + /** + * `updated_option`: theme mods or the logo changed. + * + * @param mixed $option The option name. + * @param mixed $old_value The value before. + * @param mixed $value The value after. + * + * @return void + */ + public static function note_updated( $option, $old_value, $value ): void { + if ( ! is_string( $option ) ) { + return; + } + self::note_option( $option, $old_value, $value ); + } + + /** + * `added_option`: the first theme mod of a theme, or a logo set. + * + * @param mixed $option The option name. + * @param mixed $value The value. + * + * @return void + */ + public static function note_added( $option, $value ): void { + if ( ! is_string( $option ) ) { + return; + } + self::note_option( $option, self::LOGO_OPTION === $option ? null : [], $value ); + } + + /** + * `delete_option`: the logo is removed, or every theme mod of a theme + * (remove_theme_mods()). The value before comes from the options cache. + * + * @param mixed $option The option name. + * + * @return void + */ + public static function note_deleting( $option ): void { + if ( ! is_string( $option ) || ( self::LOGO_OPTION !== $option && '' === self::mods_stylesheet( $option ) ) ) { + return; + } + + $all = wp_load_alloptions(); + $value = $all[ $option ] ?? wp_cache_get( $option, 'options' ); + if ( false === $value ) { + return; + } + self::note_option( $option, maybe_unserialize( $value ), self::LOGO_OPTION === $option ? null : [] ); + } + + /** + * Note a change of the logo or of the active theme's mods. + * + * @param string $option The option name. + * @param mixed $old The value before. + * @param mixed $new The value after. + * + * @return void + */ + private static function note_option( string $option, $old, $new ): void { + if ( self::LOGO_OPTION === $option ) { + if ( self::is_quiet() ) { + return; + } + if ( null === self::$logo ) { + self::$logo = [ + 'old' => $old, + 'new' => $new, + ]; + return; + } + self::$logo['new'] = $new; + return; + } + + $stylesheet = self::mods_stylesheet( $option ); + if ( '' === $stylesheet || get_stylesheet() !== $stylesheet || self::is_quiet() ) { + return; + } + if ( ! isset( self::$mods[ $stylesheet ] ) ) { + self::$mods[ $stylesheet ] = [ + 'old' => $old, + 'new' => $new, + ]; + return; + } + self::$mods[ $stylesheet ]['new'] = $new; + } + + /** + * `wp_after_insert_post`: the Additional CSS of a theme was saved. + * + * @param mixed $post_id The post ID. + * @param mixed $post The post. + * @param mixed $update Whether an existing post was updated. + * @param mixed $post_before The post before the save, or null. + * + * @return void + */ + public static function note_post_saved( $post_id, $post, $update, $post_before ): void { + if ( ! is_object( $post ) || 'custom_css' !== ( $post->post_type ?? '' ) || self::is_setup_work() ) { + return; + } + + $stylesheet = (string) ( $post->post_title ?? '' ); + $old = is_object( $post_before ) ? (string) ( $post_before->post_content ?? '' ) : ''; + $new = (string) ( $post->post_content ?? '' ); + + if ( null === self::$css ) { + self::$css = [ + 'old' => $old, + 'new' => $new, + 'stylesheet' => $stylesheet, + ]; + return; + } + self::$css['new'] = $new; + } + + /** + * The rows of the theme mods changed outside the Customizer. + * + * @param mixed $old The theme mods before. + * @param mixed $new The theme mods after. + * + * @return array> + */ + public static function mod_rows( $old, $new ): array { + $old = is_array( $old ) ? $old : []; + $new = is_array( $new ) ? $new : []; + $rows = []; + foreach ( array_unique( array_merge( array_keys( $old ), array_keys( $new ) ) ) as $key ) { + $key = (string) $key; + if ( '' === $key || is_numeric( $key ) || in_array( $key, self::SKIPPED_MODS, true ) ) { + continue; + } + $before = $old[ $key ] ?? null; + $after = $new[ $key ] ?? null; + if ( Fields::fingerprint( $before ) === Fields::fingerprint( $after ) ) { + continue; + } + $row = [ 'id' => $key ]; + $kind = self::control_kind( $key, null ); + if ( '' !== $kind ) { + $row['kind'] = $kind; + } + $row = self::with_values( $row, $before, $after ); + if ( null !== $row ) { + $rows[] = $row; + } + if ( count( $rows ) >= self::MAX_SETTINGS ) { + break; + } + } + + return $rows; + } + + /** + * The row's data for what this request changed (the job completes it), + * or [] when nothing changed. + * + * @return array + */ + public static function row(): array { + $publish = self::$customizer_publish; + $settings = self::$customizer_settings; + + // A Customizer publish writes the theme mods itself; what it doesn't + // list (caches a theme writes when it saves) is no change of its own. + if ( null === $publish ) { + foreach ( self::$mods as $mods ) { + $settings = array_merge( $settings, self::mod_rows( $mods['old'], $mods['new'] ) ); + } + } + + $row = [ + 'stylesheet' => null !== $publish ? $publish['stylesheet'] : (string) get_stylesheet(), + 'source' => null !== $publish ? 'customizer' : 'other', + ]; + if ( null !== $publish && $publish['scheduled'] ) { + $row['scheduled'] = true; + } + if ( null !== $publish && $publish['actor'] > 0 ) { + $row['_actor'] = $publish['actor']; + } + + if ( [] !== $settings ) { + $row['settings'] = array_slice( $settings, 0, self::MAX_SETTINGS ); + } + + $logo = self::$logo; + if ( null !== $logo && (int) $logo['old'] !== (int) $logo['new'] ) { + $row['logo'] = [ + 'old' => (int) $logo['old'] > 0 ? (string) (int) $logo['old'] : '', + 'new' => (int) $logo['new'] > 0 ? (string) (int) $logo['new'] : '', + ]; + } + + $css = self::$css; + if ( null !== $css && $css['old'] !== $css['new'] ) { + $row['css'] = strlen( $css['old'] ) > self::MAX_CSS || strlen( $css['new'] ) > self::MAX_CSS + ? [ 'too_large' => true ] + : [ + 'stash' => [ + 'old' => $css['old'], + 'new' => $css['new'], + ], + ]; + if ( null === $publish ) { + $row['stylesheet'] = '' !== $css['stylesheet'] ? $css['stylesheet'] : $row['stylesheet']; + } + } + + return isset( $row['settings'] ) || isset( $row['logo'] ) || isset( $row['css'] ) ? $row : []; + } + + /** + * Report what this request changed, once, at the end of the request. + * + * @return void + */ + public static function flush(): void { + $row = self::row(); + self::reset(); + if ( [] === $row || Limiter::take( Limiter::KIND_THEME, 1 ) < 1 ) { + return; + } + + do_action( ContentEvent::hook( 'ThemeSettingsChanged' ), $row ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- The hooks start with scanfully_. + } + + /** + * Plain text from a label the Customizer may give with HTML or + * entities. + * + * @param mixed $value The label. + * + * @return string + */ + private static function plain( $value ): string { + return trim( html_entity_decode( wp_strip_all_tags( (string) $value ), ENT_QUOTES, 'UTF-8' ) ); + } +} diff --git a/src/Events/ThemeSettingsChanged.php b/src/Events/ThemeSettingsChanged.php new file mode 100644 index 0000000..004d6a4 --- /dev/null +++ b/src/Events/ThemeSettingsChanged.php @@ -0,0 +1,66 @@ + 0 ? get_userdata( $user_id ) : false; + + return $user instanceof \WP_User ? $user : null; + } + + /** + * Get the post body + * + * @param array $data The data passed to the action: the event data. + * + * @return array + */ + public function get_post_body( array $data ): array { + $body = parent::get_post_body( $data ); + unset( $body['_actor'] ); + + return $body; + } +} diff --git a/src/Events/ThemeSwitched.php b/src/Events/ThemeSwitched.php new file mode 100644 index 0000000..d010050 --- /dev/null +++ b/src/Events/ThemeSwitched.php @@ -0,0 +1,65 @@ +get( 'Name' ) ) : ''; + if ( '' === $name && is_string( $data[0] ?? null ) ) { + $name = self::plain_text( $data[0] ); + } + + return [ + 'name' => $name, + 'slug' => $new_theme instanceof \WP_Theme ? $new_theme->get_stylesheet() : '', + 'old_name' => $old_theme instanceof \WP_Theme ? self::plain_text( $old_theme->get( 'Name' ) ) : '', + 'old_slug' => $old_theme instanceof \WP_Theme ? $old_theme->get_stylesheet() : '', + ]; + } + + /** + * A check if a event should fire + * + * @param array $data The event data: new theme name, new theme, old theme. + * + * @return bool + */ + public function should_fire( array $data ): bool { + $new_theme = $data[1] ?? null; + $old_theme = $data[2] ?? null; + + if ( ! $new_theme instanceof \WP_Theme ) { + return false; + } + + return ! $old_theme instanceof \WP_Theme || $old_theme->get_stylesheet() !== $new_theme->get_stylesheet(); + } +} diff --git a/src/Events/ThemeUpdateFailed.php b/src/Events/ThemeUpdateFailed.php new file mode 100644 index 0000000..d0f5cc5 --- /dev/null +++ b/src/Events/ThemeUpdateFailed.php @@ -0,0 +1,25 @@ + + */ + protected static function describe_user( \WP_User $user, ?bool $elevated = null ): array { + $data = [ + 'id' => (int) $user->ID, + 'name' => self::safe_display_name( $user ), + ]; + if ( $elevated ?? self::has_elevated_capabilities( $user ) ) { + $data['email'] = (string) $user->user_email; + } + $data['roles'] = self::role_list( $user->roles ); + + return $data; + } + + /** + * A list of role names. + * + * @param mixed $roles Roles, as WordPress passes them. + * + * @return array + */ + protected static function role_list( $roles ): array { + $list = []; + foreach ( (array) $roles as $role ) { + if ( is_string( $role ) && '' !== $role ) { + $list[] = $role; + } + } + + return $list; + } + + /** + * Capabilities that make an account more than a plain sign-up: an account + * with any of them can edit content, manage users or change the site. + */ + private const ELEVATED_CAPABILITIES = [ + 'edit_posts', + 'list_users', + 'edit_users', + 'promote_users', + 'manage_options', + 'install_plugins', + ]; + + /** + * Whether a user can do more than a plain sign-up (a subscriber or a + * shop customer) can, whatever role that takes. + * + * @param \WP_User $user The user. + * + * @return bool + */ + protected static function has_elevated_capabilities( \WP_User $user ): bool { + foreach ( self::ELEVATED_CAPABILITIES as $capability ) { + if ( user_can( $user, $capability ) ) { // phpcs:ignore WordPress.WP.Capabilities.Undetermined -- Core capabilities from ELEVATED_CAPABILITIES. + return true; + } + } + + return false; + } + + /** + * Whether a user has elevated rights, for code outside the user events + * (the failed login counts). + * + * @param \WP_User $user The user. + * + * @return bool + */ + public static function is_elevated( \WP_User $user ): bool { + return self::has_elevated_capabilities( $user ); + } + + /** + * An account as the failed login counts name it: ID, display name (never + * an email address) and roles; null when it no longer exists. + * + * @param int $user_id The user ID. + * + * @return array{id: int, name: string, roles: string[]}|null + */ + public static function account_summary( int $user_id ): ?array { + $user = $user_id > 0 ? get_userdata( $user_id ) : false; + if ( ! $user instanceof \WP_User ) { + return null; + } + + return [ + 'id' => (int) $user->ID, + 'name' => self::safe_display_name( $user ), + 'roles' => self::role_list( $user->roles ), + ]; + } + + /** + * Whether any of these roles has elevated rights. + * + * @param array $roles Role names. + * + * @return bool + */ + protected static function roles_have_elevated_capabilities( array $roles ): bool { + foreach ( $roles as $role_name ) { + $role = get_role( $role_name ); + if ( ! $role instanceof \WP_Role ) { + continue; + } + foreach ( self::ELEVATED_CAPABILITIES as $capability ) { + if ( $role->has_cap( $capability ) ) { + return true; + } + } + } + + return false; + } + + /** + * Whether a change to a user is self-service: made outside WP-CLI with + * nobody signed in but (at most) the user themselves, such as a visitor + * registering or a customer account created at checkout. + * + * @param int $user_id The user ID. + * + * @return bool + */ + protected static function is_self_service( int $user_id ): bool { + if ( defined( 'WP_CLI' ) && WP_CLI ) { + return false; + } + + $current_user_id = get_current_user_id(); + + return 0 === $current_user_id || $user_id === $current_user_id; + } + + /** + * Whether a new account is a plain sign-up: self-service and without any + * elevated capability. A sign-up that ends up with one (for instance + * because the default role for new users was set to Administrator) is + * never a plain sign-up. + * + * @param \WP_User $user The user. + * + * @return bool + */ + protected static function is_plain_sign_up( \WP_User $user ): bool { + return self::is_self_service( (int) $user->ID ) && ! self::has_elevated_capabilities( $user ); + } + + /** + * Where the current request came from: the connecting address (`ip`), + * the visitor's address as a proxy or CDN reports it (`forwarded_for`) + * and the browser (`user_agent`, at most 500 characters). + * + * @return array{ip: string, forwarded_for: string, user_agent: string} + */ + protected static function request_origin(): array { + return [ + 'ip' => self::valid_ip( self::server_value( 'REMOTE_ADDR' ) ), + 'forwarded_for' => self::forwarded_for(), + 'user_agent' => mb_substr( self::server_value( 'HTTP_USER_AGENT' ), 0, self::MAX_USER_AGENT_LENGTH ), + ]; + } + + /** + * The visitor's address as a proxy or CDN in front of the site reports + * it: the first address of the first of these headers that is present, + * when it is a valid IP address. The client can send these headers too, + * so this is what the visitor claims, not proof. + * + * @return string + */ + private static function forwarded_for(): string { + foreach ( self::FORWARDED_HEADERS as $header ) { + $value = self::server_value( $header ); + if ( '' === $value ) { + continue; + } + + $first = self::valid_ip( trim( explode( ',', $value )[0] ) ); + if ( '' !== $first ) { + return $first; + } + } + + return ''; + } + + /** + * The value if it is a valid IP address, else ''. + * + * @param string $value The value. + * + * @return string + */ + private static function valid_ip( string $value ): string { + return false !== filter_var( $value, FILTER_VALIDATE_IP ) ? $value : ''; + } + + /** + * A request header or server value as plain text, or ''. + * + * @param string $key The $_SERVER key. + * + * @return string + */ + private static function server_value( string $key ): string { + if ( ! isset( $_SERVER[ $key ] ) || ! is_string( $_SERVER[ $key ] ) ) { + return ''; + } + + return sanitize_text_field( wp_unslash( $_SERVER[ $key ] ) ); + } + + /** + * Count this event against the per-minute cap. Returns true when the cap + * is reached and the event should be dropped. + * + * @return bool + */ + protected static function is_rate_limited(): bool { + $limit = (int) apply_filters( 'scanfully_user_events_per_minute', self::MAX_EVENTS_PER_MINUTE ); + if ( $limit < 1 ) { + return false; + } + + // One transient holding the current minute and its count, instead of + // a new transient every minute. + $minute = (int) floor( time() / MINUTE_IN_SECONDS ); + $state = get_transient( self::RATE_TRANSIENT ); + $count = is_array( $state ) && (int) ( $state[0] ?? -1 ) === $minute ? (int) ( $state[1] ?? 0 ) : 0; + if ( $count >= $limit ) { + return true; + } + + set_transient( self::RATE_TRANSIENT, [ $minute, $count + 1 ], 2 * MINUTE_IN_SECONDS ); + + return false; + } +} diff --git a/src/Events/UserLogin.php b/src/Events/UserLogin.php new file mode 100644 index 0000000..af26248 --- /dev/null +++ b/src/Events/UserLogin.php @@ -0,0 +1,92 @@ +ID ); + if ( $failed > 0 ) { + $data['failed_before'] = $failed; + } + + return $data; + } + + /** + * The wrong passwords tried on an account in this hour and the one before: + * a login that follows them may be someone who guessed it. + * + * @param int $user_id The user ID. + * + * @return int + */ + private static function failed_before( int $user_id ): int { + $hour = FailedLogins\Store::hour(); + + return FailedLogins\Store::count( 'u_' . $user_id, $hour ) + FailedLogins\Store::count( 'u_' . $user_id, $hour - 1 ); + } + + /** + * A check if a event should fire + * + * @param array $data The event data: login, user. + * + * @return bool + */ + public function should_fire( array $data ): bool { + $user = $data[1] ?? null; + if ( ! $user instanceof \WP_User || ! self::has_elevated_capabilities( $user ) ) { + return false; + } + + return ! self::is_rate_limited(); + } +} diff --git a/src/Events/UserRoleChanged.php b/src/Events/UserRoleChanged.php new file mode 100644 index 0000000..a6f97f9 --- /dev/null +++ b/src/Events/UserRoleChanged.php @@ -0,0 +1,166 @@ + + */ + private static array $created_user_ids = []; + + /** + * Role changes already reported in this request. + * + * @var array + */ + private static array $fired = []; + + /** + * Constructor. + */ + public function __construct() { + parent::__construct( 'UserRoleChanged', 'set_user_role', 10, 3 ); + + add_filter( 'wp_pre_insert_user_data', [ self::class, 'note_user_insert' ], 10, 2 ); + add_action( 'user_register', [ self::class, 'note_user_registered' ], 0, 1 ); + } + + /** + * Note the login of a new user that is about to be inserted. + * + * @param mixed $data The user data, returned unchanged. + * @param mixed $update Whether an existing user is updated. + * + * @return mixed + */ + public static function note_user_insert( $data, $update ) { + self::$creating_login = ! $update && is_array( $data ) ? (string) ( $data['user_login'] ?? '' ) : ''; + + return $data; + } + + /** + * The new user is in place: remember it was created in this request. + * + * @param mixed $user_id The new user's ID. + * + * @return void + */ + public static function note_user_registered( $user_id = 0 ): void { + self::$creating_login = ''; + if ( is_numeric( $user_id ) && (int) $user_id > 0 ) { + self::$created_user_ids[ (int) $user_id ] = true; + } + } + + /** + * Get the post body + * + * @param array $data The data to send: user ID, new role, old roles. + * + * @return array + */ + public function get_post_body( array $data ): array { + $user = get_userdata( (int) ( $data[0] ?? 0 ) ); + if ( ! $user instanceof \WP_User ) { + return []; + } + + $role = (string) ( $data[1] ?? '' ); + $old_roles = self::role_list( $data[2] ?? [] ); + + // Elevated after the change, or before it: an administrator who is + // demoted still shows who it was. + $elevated = self::has_elevated_capabilities( $user ) || self::roles_have_elevated_capabilities( $old_roles ); + + return array_merge( + self::describe_user( $user, $elevated ), + [ + 'roles' => self::role_list( '' !== $role ? [ $role ] : [] ), + 'old_roles' => $old_roles, + ] + ); + } + + /** + * A check if a event should fire + * + * @param array $data The event data: user ID, new role, old roles. + * + * @return bool + */ + public function should_fire( array $data ): bool { + $user_id = (int) ( $data[0] ?? 0 ); + $role = (string) ( $data[1] ?? '' ); + $old_roles = self::role_list( $data[2] ?? [] ); + + if ( $user_id < 1 ) { + return false; + } + + $user = get_userdata( $user_id ); + if ( ! $user instanceof \WP_User ) { + return false; + } + + // The first role of a user that is being created; only once. + if ( [] === $old_roles && '' !== self::$creating_login && $user->user_login === self::$creating_login ) { + self::$creating_login = ''; + return false; + } + + $roles = self::role_list( '' !== $role ? [ $role ] : [] ); + sort( $old_roles ); + if ( $roles === $old_roles ) { + return false; + } + + $key = $user_id . '|' . $role . '|' . implode( ',', $old_roles ); + if ( isset( self::$fired[ $key ] ) ) { + return false; + } + + // A role set right after a plain sign-up, by another plugin or by + // multisite adding the new user to the site. + if ( isset( self::$created_user_ids[ $user_id ] ) && self::is_plain_sign_up( $user ) ) { + return false; + } + + if ( self::is_rate_limited() ) { + return false; + } + + self::$fired[ $key ] = true; + + return true; + } +} diff --git a/src/Events/WidgetChanges/Builder.php b/src/Events/WidgetChanges/Builder.php new file mode 100644 index 0000000..113428c --- /dev/null +++ b/src/Events/WidgetChanges/Builder.php @@ -0,0 +1,239 @@ + $data The data the request noted. + * + * @return array + */ + public static function resolve( array $data ): array { + $widgets = []; + $areas = []; + foreach ( (array) ( $data['widgets'] ?? [] ) as $widget ) { + if ( ! is_array( $widget ) ) { + continue; + } + $widget = self::widget( $widget ); + $widgets[] = $widget; + foreach ( [ 'area', 'old_area' ] as $side ) { + if ( isset( $widget[ $side ]['id'] ) ) { + $areas[ $widget[ $side ]['id'] ] = $widget[ $side ]; + } + } + } + + $order = []; + foreach ( (array) ( $data['order_changed'] ?? [] ) as $area ) { + $order[] = self::area( (string) $area ); + $areas[ (string) $area ] = end( $order ); + } + + $out = []; + if ( 1 === count( $widgets ) && [] === $order ) { + $out['name'] = '' !== ( $widgets[0]['title'] ?? '' ) ? $widgets[0]['title'] : $widgets[0]['type_label']; + } elseif ( 1 === count( $areas ) ) { + $out['name'] = (string) reset( $areas )['name']; + } + if ( 1 === count( $areas ) ) { + $out['area'] = reset( $areas ); + } + $out['widgets'] = $widgets; + if ( [] !== $order ) { + $out['order_changed'] = $order; + } + + return $out; + } + + /** + * One widget with its names and content diff. + * + * @param array $widget The widget as noted. + * + * @return array + */ + private static function widget( array $widget ): array { + $type = (string) ( $widget['type'] ?? '' ); + $id = (string) ( $widget['id'] ?? '' ); + $content = $widget['_content'] ?? ( $widget['_text']['new'] ?? null ); + $title = isset( $widget['title'] ) ? (string) $widget['title'] : null; + // A widget moved or removed without a change to its settings: the + // request had none of them, so they are read as stored now. + if ( 'block' === $type && ! is_string( $content ) ) { + $stored = self::stored_instance( $type, $id ); + $content = isset( $stored['content'] ) && is_string( $stored['content'] ) ? $stored['content'] : null; + } elseif ( 'block' !== $type && null === $title ) { + $stored = self::stored_instance( $type, $id ); + $title = isset( $stored['title'] ) && is_scalar( $stored['title'] ) ? (string) $stored['title'] : null; + } + + $out = [ + 'id' => $id, + 'type' => $type, + 'type_label' => 'block' === $type && is_string( $content ) ? self::block_label( $content ) : self::type_label( $type ), + 'title' => null !== $title ? self::plain( $title ) : '', + 'action' => (string) ( $widget['action'] ?? '' ), + ]; + // A block widget has no title. The dashboard shows its first line of + // text to tell it apart; that is text of the widget, so it is not its + // title (the subject, search and the public API never get it). + if ( '' === $out['title'] && 'block' === $type && is_string( $content ) ) { + $lines = ContentDiff::text_lines( $content ); + $first = self::plain( (string) ( $lines[0] ?? '' ) ); + if ( '' !== $first ) { + $out['excerpt'] = function_exists( 'mb_substr' ) ? mb_substr( $first, 0, 80 ) : substr( $first, 0, 80 ); + } + } + foreach ( [ 'area', 'old_area' ] as $side ) { + if ( isset( $widget[ $side ] ) ) { + $out[ $side ] = self::area( (string) $widget[ $side ] ); + } + } + foreach ( [ 'changed', 'title_old', 'values' ] as $key ) { + if ( isset( $widget[ $key ] ) ) { + $out[ $key ] = 'title_old' === $key ? self::plain( (string) $widget[ $key ] ) : $widget[ $key ]; + } + } + if ( isset( $widget['_text'] ) && is_array( $widget['_text'] ) ) { + $out['content'] = ContentDiff::compare( (string) ( $widget['_text']['old'] ?? '' ), (string) ( $widget['_text']['new'] ?? '' ) ); + } + + return $out; + } + + /** + * The settings of a widget as stored now; null when it is gone. + * + * @param string $type The widget's ID base (`text`). + * @param string $id The widget ID (`text-3`). + * + * @return array|null + */ + private static function stored_instance( string $type, string $id ): ?array { + if ( '' === $type || 0 !== strpos( $id, $type . '-' ) || ! ctype_digit( substr( $id, strlen( $type ) + 1 ) ) ) { + return null; + } + $instances = get_option( 'widget_' . $type ); + $instance = is_array( $instances ) ? ( $instances[ (int) substr( $id, strlen( $type ) + 1 ) ] ?? null ) : null; + + return is_array( $instance ) ? $instance : null; + } + + /** + * The title of a block widget's first block, such as "Paragraph". + * + * @param string $content The widget's content. + * + * @return string + */ + private static function block_label( string $content ): string { + foreach ( parse_blocks( $content ) as $block ) { + $name = $block['blockName'] ?? null; + if ( ! is_string( $name ) || '' === $name ) { + continue; + } + $type = \WP_Block_Type_Registry::get_instance()->get_registered( $name ); + + return $type instanceof \WP_Block_Type && '' !== (string) $type->title ? (string) $type->title : $name; + } + + return __( 'Block', 'scanfully' ); + } + + /** + * A classic widget type's name, such as "Recent Posts"; its ID base when + * it isn't registered. + * + * @param string $type The widget's ID base. + * + * @return string + */ + private static function type_label( string $type ): string { + global $wp_widget_factory; + + if ( is_object( $wp_widget_factory ) && isset( $wp_widget_factory->widgets ) && is_array( $wp_widget_factory->widgets ) ) { + foreach ( $wp_widget_factory->widgets as $widget ) { + if ( is_object( $widget ) && isset( $widget->id_base, $widget->name ) && $type === $widget->id_base ) { + return self::plain( (string) $widget->name ); + } + } + } + + return $type; + } + + /** + * A widget area by ID and name. + * + * @param string $id The area ID. + * + * @return array{id: string, name: string} + */ + private static function area( string $id ): array { + global $wp_registered_sidebars; + + if ( Collector::INACTIVE === $id ) { + $name = __( 'Inactive widgets', 'scanfully' ); + } elseif ( is_array( $wp_registered_sidebars ) && isset( $wp_registered_sidebars[ $id ]['name'] ) ) { + $name = self::plain( (string) $wp_registered_sidebars[ $id ]['name'] ); + } else { + $name = $id; + } + + return [ + 'id' => $id, + 'name' => $name, + ]; + } + + /** + * Text as plain text, cut to MAX_LABEL characters. + * + * @param string $text The text, possibly with HTML and entities. + * + * @return string + */ + private static function plain( string $text ): string { + $text = trim( html_entity_decode( wp_strip_all_tags( $text ), ENT_QUOTES, 'UTF-8' ) ); + + return function_exists( 'mb_substr' ) ? mb_substr( $text, 0, self::MAX_LABEL ) : substr( $text, 0, self::MAX_LABEL ); + } +} diff --git a/src/Events/WidgetChanges/Collector.php b/src/Events/WidgetChanges/Collector.php new file mode 100644 index 0000000..b52b5ab --- /dev/null +++ b/src/Events/WidgetChanges/Collector.php @@ -0,0 +1,438 @@ + + */ + private static array $options = []; + + /** + * Hook into WordPress. + * + * @return void + */ + public static function setup(): void { + add_action( 'updated_option', [ self::class, 'note_updated' ], 10, 3 ); + add_action( 'added_option', [ self::class, 'note_added' ], 10, 2 ); + add_action( 'shutdown', [ self::class, 'flush' ], 1, 0 ); + } + + /** + * Forget what was noted (tests). + * + * @return void + */ + public static function reset(): void { + self::$options = []; + } + + /** + * Whether an option holds widgets. + * + * @param string $option The option name. + * + * @return bool + */ + private static function is_widget_option( string $option ): bool { + return self::AREAS_OPTION === $option || 0 === strpos( $option, 'widget_' ); + } + + /** + * Whether this request's widget changes are left out. + * + * @return bool + */ + private static function is_quiet(): bool { + return MenuCollector::is_quiet() || MenuCollector::is_read_request(); + } + + /** + * `updated_option`: widget settings or areas changed. + * + * @param mixed $option The option name. + * @param mixed $old_value The value before. + * @param mixed $value The value after. + * + * @return void + */ + public static function note_updated( $option, $old_value, $value ): void { + if ( ! is_string( $option ) || ! self::is_widget_option( $option ) || self::is_quiet() ) { + return; + } + + if ( ! isset( self::$options[ $option ] ) ) { + self::$options[ $option ] = [ + 'old' => $old_value, + 'new' => $value, + ]; + } + self::$options[ $option ]['new'] = $value; + } + + /** + * `added_option`: the first widget of a type. + * + * @param mixed $option The option name. + * @param mixed $value The value. + * + * @return void + */ + public static function note_added( $option, $value ): void { + if ( ! is_string( $option ) || ! self::is_widget_option( $option ) || self::is_quiet() ) { + return; + } + + self::$options[ $option ] = [ + 'old' => [], + 'new' => $value, + ]; + } + + /** + * The row's data for what this request changed (the job completes it), + * or [] when no widget changed. + * + * @return array + */ + public static function row(): array { + if ( [] === self::$options ) { + return []; + } + + $areas = self::$options[ self::AREAS_OPTION ] ?? null; + $current = null === $areas ? get_option( self::AREAS_OPTION ) : null; + $old_places = self::places( null === $areas ? $current : $areas['old'] ); + $new_places = self::places( null === $areas ? $current : $areas['new'] ); + + // Settings changes per widget ID. + $instances = []; + foreach ( self::$options as $option => $values ) { + if ( self::AREAS_OPTION === $option ) { + continue; + } + $type = substr( $option, strlen( 'widget_' ) ); + $before = is_array( $values['old'] ) ? $values['old'] : []; + $after = is_array( $values['new'] ) ? $values['new'] : []; + foreach ( array_unique( array_merge( array_keys( $before ), array_keys( $after ) ) ) as $number ) { + if ( ! is_int( $number ) && ! ctype_digit( (string) $number ) ) { + // `_multiwidget` and the like. + continue; + } + $old = isset( $before[ $number ] ) && is_array( $before[ $number ] ) ? $before[ $number ] : null; + $new = isset( $after[ $number ] ) && is_array( $after[ $number ] ) ? $after[ $number ] : null; + if ( $old === $new ) { + continue; + } + $instances[ $type . '-' . $number ] = [ + 'type' => $type, + 'old' => $old, + 'new' => $new, + ]; + } + } + + $widgets = []; + $ids = array_unique( array_merge( array_keys( $instances ), array_keys( $old_places ), array_keys( $new_places ) ) ); + foreach ( $ids as $id ) { + $widget = self::widget( (string) $id, $old_places[ $id ] ?? null, $new_places[ $id ] ?? null, $instances[ $id ] ?? null ); + if ( null !== $widget ) { + $widgets[] = $widget; + } + if ( count( $widgets ) >= self::MAX_WIDGETS ) { + break; + } + } + + $reordered = self::reordered( $old_places, $new_places, $widgets ); + if ( [] === $widgets && [] === $reordered ) { + return []; + } + + $data = [ 'widgets' => $widgets ]; + if ( [] !== $reordered ) { + $data['order_changed'] = $reordered; + } + + return $data; + } + + /** + * What happened to one widget, or null when nothing a visitor could see + * changed. + * + * @param string $id The widget ID (`text-3`). + * @param array{0: string, 1: int}|null $before Its area and place before. + * @param array{0: string, 1: int}|null $after Its area and place after. + * @param array|null $instance Its settings change. + * + * @return array|null + */ + private static function widget( string $id, ?array $before, ?array $after, ?array $instance ): ?array { + $was_active = null !== $before && self::is_active( $before[0] ); + $is_active = null !== $after && self::is_active( $after[0] ); + $exists = null === $instance || null !== $instance['new']; + + if ( ! $was_active && $is_active ) { + $action = 'added'; + } elseif ( $was_active && ! $is_active ) { + $action = $exists ? 'removed' : 'deleted'; + } elseif ( $was_active && $is_active && $before[0] !== $after[0] ) { + $action = 'moved'; + } elseif ( $was_active && null !== $instance && null !== $instance['old'] && null !== $instance['new'] ) { + $action = 'changed'; + } elseif ( ! $was_active && ! $is_active && null !== $instance && null !== $instance['old'] && null === $instance['new'] && null !== $before ) { + // Deleted from the inactive widgets. + $action = 'deleted'; + } else { + return null; + } + + $type = null !== $instance ? (string) $instance['type'] : (string) preg_replace( '/-\d+$/', '', $id ); + $values = null !== $instance ? ( $instance['new'] ?? $instance['old'] ) : null; + $widget = [ + 'id' => $id, + 'type' => $type, + 'action' => $action, + ]; + if ( is_array( $values ) && isset( $values['title'] ) && is_scalar( $values['title'] ) ) { + $widget['title'] = (string) $values['title']; + } + if ( in_array( $action, [ 'added', 'moved', 'changed' ], true ) && null !== $after ) { + $widget['area'] = $after[0]; + } + if ( in_array( $action, [ 'moved', 'removed', 'deleted' ], true ) && null !== $before ) { + $widget['old_area'] = $before[0]; + } + + if ( null !== $instance && is_array( $instance['old'] ) && is_array( $instance['new'] ) ) { + $widget += self::setting_changes( $instance['old'], $instance['new'] ); + if ( 'changed' === $action && ! isset( $widget['changed'] ) ) { + // Only the stored form of a value changed. + return null; + } + } + // For the job: a block widget has no title; its label comes from + // its content (read from the option when the request didn't touch + // its settings). + if ( 'block' === $type && is_array( $values ) && isset( $values['content'] ) && is_string( $values['content'] ) ) { + $widget['_content'] = $values['content']; + } + + return $widget; + } + + /** + * The settings that changed: their keys, the title before, short values + * before and after, and the text before and after for the job's diff. + * + * @param array $old_settings The settings before. + * @param array $new_settings The settings after. + * + * @return array + */ + public static function setting_changes( array $old_settings, array $new_settings ): array { + $out = []; + $changed = []; + foreach ( array_unique( array_merge( array_keys( $old_settings ), array_keys( $new_settings ) ) ) as $key ) { + $key = (string) $key; + $before = $old_settings[ $key ] ?? null; + $after = $new_settings[ $key ] ?? null; + if ( self::value_string( $before ) === self::value_string( $after ) ) { + continue; + } + $changed[] = $key; + + if ( 'title' === $key ) { + $out['title_old'] = self::value_string( $before ); + continue; + } + if ( in_array( $key, self::CONTENT_KEYS, true ) && ( is_string( $before ) || is_string( $after ) ) ) { + $out['_text'] = [ + 'old' => is_string( $before ) ? $before : '', + 'new' => is_string( $after ) ? $after : '', + ]; + continue; + } + + $old_text = self::value_string( $before ); + $new_text = self::value_string( $after ); + if ( strlen( $old_text ) <= self::MAX_VALUE && strlen( $new_text ) <= self::MAX_VALUE ) { + $out['values'][ $key ] = [ + 'old' => $old_text, + 'new' => $new_text, + ]; + } + } + + if ( [] !== $changed ) { + $out['changed'] = $changed; + } + + return $out; + } + + /** + * A setting's value as a string, so '1' and 1 or a reordered list of + * equal values aren't a change. + * + * @param mixed $value The value. + * + * @return string + */ + private static function value_string( $value ): string { + if ( is_bool( $value ) ) { + return $value ? '1' : '0'; + } + if ( is_scalar( $value ) ) { + return (string) $value; + } + if ( null === $value ) { + return ''; + } + + return (string) wp_json_encode( $value ); + } + + /** + * Every widget's area and place in it. + * + * @param mixed $sidebars The `sidebars_widgets` option. + * + * @return array + */ + private static function places( $sidebars ): array { + $places = []; + if ( ! is_array( $sidebars ) ) { + return $places; + } + foreach ( $sidebars as $area => $ids ) { + if ( 'array_version' === $area || ! is_array( $ids ) ) { + continue; + } + foreach ( array_values( $ids ) as $place => $id ) { + if ( is_string( $id ) && ! isset( $places[ $id ] ) ) { + $places[ $id ] = [ (string) $area, $place ]; + } + } + } + + return $places; + } + + /** + * Whether an area shows on the site (not the inactive or orphaned ones). + * + * @param string $area The area ID. + * + * @return bool + */ + private static function is_active( string $area ): bool { + return self::INACTIVE !== $area && 0 !== strpos( $area, 'orphaned_widgets' ); + } + + /** + * The areas whose widgets kept their area but changed order among + * themselves. + * + * @param array $before Places before. + * @param array $after Places after. + * @param array> $widgets The widgets reported. + * + * @return array + */ + private static function reordered( array $before, array $after, array $widgets ): array { + $listed = array_column( $widgets, 'action', 'id' ); + $orders = []; + foreach ( $after as $id => [ $area, $place ] ) { + if ( ! self::is_active( $area ) || ! isset( $before[ $id ] ) || $before[ $id ][0] !== $area || in_array( $listed[ $id ] ?? '', [ 'added', 'moved' ], true ) ) { + continue; + } + $orders[ $area ][ $place ] = $before[ $id ][1]; + } + + $areas = []; + foreach ( $orders as $area => $places ) { + ksort( $places ); + $values = array_values( $places ); + $sorted = $values; + sort( $sorted ); + if ( $values !== $sorted ) { + $areas[] = (string) $area; + } + } + + return $areas; + } + + /** + * Report what this request changed, once, at the end of the request. + * + * @return void + */ + public static function flush(): void { + $row = self::row(); + self::reset(); + if ( [] === $row || Limiter::take( Limiter::KIND_WIDGET, 1 ) < 1 ) { + return; + } + + do_action( ContentEvent::hook( 'WidgetsChanged' ), $row ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- The hooks start with scanfully_. + } +} diff --git a/src/Events/WidgetsChanged.php b/src/Events/WidgetsChanged.php new file mode 100644 index 0000000..3cedfac --- /dev/null +++ b/src/Events/WidgetsChanged.php @@ -0,0 +1,30 @@ + self::get_db_collate(), ], 'plugins' => self::get_plugins(), + // Must-use plugins, their folders and drop-ins, with content hashes. + 'mu_plugins' => MuPlugins::scan(), ]; // filter data. diff --git a/src/Health/MuPlugins.php b/src/Health/MuPlugins.php new file mode 100644 index 0000000..132cd30 --- /dev/null +++ b/src/Health/MuPlugins.php @@ -0,0 +1,403 @@ +> + */ + public static function scan(): array { + if ( ! function_exists( 'get_mu_plugins' ) ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + } + + $mu_dir = defined( 'WPMU_PLUGIN_DIR' ) ? (string) WPMU_PLUGIN_DIR : WP_CONTENT_DIR . '/mu-plugins'; + $mu_plugins = is_dir( $mu_dir ) ? get_mu_plugins() : []; + $dropins = get_dropins(); + $cache = get_option( self::HASH_OPTION, [] ); + $cache = is_array( $cache ) ? $cache : []; + $used = []; + $entries = self::entries( $mu_dir, $mu_plugins, WP_CONTENT_DIR, $dropins, $cache, $used ); + $stat = self::stat_fingerprint( $mu_dir, WP_CONTENT_DIR, array_keys( $dropins ) ); + + // Keep only the hashes of files that are still there. + update_option( self::HASH_OPTION, array_intersect_key( $cache, $used ), false ); + update_option( self::STAT_OPTION, $stat, false ); + + /** + * Filters the MU plugins and drop-ins sent to Scanfully. + * + * @param array $entries The entries. + */ + $entries = apply_filters( 'scanfully_mu_plugins_data', $entries ); + + return is_array( $entries ) ? array_values( $entries ) : []; + } + + /** + * Whether the MU plugins or drop-ins look different from what the last + * sync saw: a quick check of names, sizes and times, without reading any + * file. False when no sync has run yet. + * + * @return bool + */ + public static function changed_since_last_sync(): bool { + $last = get_option( self::STAT_OPTION, '' ); + if ( ! is_string( $last ) || '' === $last ) { + return false; + } + + if ( ! function_exists( 'get_dropins' ) ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + } + + $mu_dir = defined( 'WPMU_PLUGIN_DIR' ) ? (string) WPMU_PLUGIN_DIR : WP_CONTENT_DIR . '/mu-plugins'; + + return self::stat_fingerprint( $mu_dir, WP_CONTENT_DIR, array_keys( get_dropins() ) ) !== $last; + } + + /** + * The entries for the MU plugin files, the folders next to them and the + * drop-ins. + * + * @param string $mu_dir The MU plugins folder. + * @param array> $mu_plugins Header data of the MU plugin files, by file name. + * @param string $content_dir The `wp-content` folder. + * @param array> $dropins Header data of the drop-ins, by file name. + * @param array $cache Content hashes by path; updated. + * @param array $used Paths whose hash was used; updated. + * + * @return array> + */ + public static function entries( string $mu_dir, array $mu_plugins, string $content_dir, array $dropins, array &$cache, array &$used ): array { + $entries = []; + $mu_dir = rtrim( $mu_dir, '/\\' ); + + ksort( $mu_plugins, SORT_STRING ); + foreach ( $mu_plugins as $file => $header ) { + $entry = self::file_entry( 'mu', (string) $file, $mu_dir . '/' . $file, is_array( $header ) ? $header : [], $content_dir, $cache, $used ); + if ( null !== $entry ) { + $entries[] = $entry; + } + } + + foreach ( self::folders( $mu_dir ) as $folder ) { + $entries[] = self::folder_entry( $folder, $mu_dir . '/' . $folder, $content_dir, $cache, $used ); + } + + ksort( $dropins, SORT_STRING ); + foreach ( $dropins as $file => $header ) { + $entry = self::file_entry( 'dropin', (string) $file, rtrim( $content_dir, '/\\' ) . '/' . $file, is_array( $header ) ? $header : [], $content_dir, $cache, $used ); + if ( null !== $entry ) { + $entries[] = $entry; + } + } + + return $entries; + } + + /** + * A MU plugin file or drop-in: its header, size, time and hash. + * + * @param string $kind `mu` or `dropin`. + * @param string $file The file name. + * @param string $path The full path. + * @param array $header The plugin header. + * @param string $content_dir The `wp-content` folder. + * @param array $cache Content hashes by path; updated. + * @param array $used Paths whose hash was used; updated. + * + * @return array|null Null when the file is gone. + */ + private static function file_entry( string $kind, string $file, string $path, array $header, string $content_dir, array &$cache, array &$used ): ?array { + $stat = @stat( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A file can disappear between the listing and here. + if ( false === $stat || ! is_file( $path ) ) { + return null; + } + + $name = self::text( $header['Name'] ?? '' ); + + return [ + 'kind' => $kind, + 'file' => $file, + 'name' => '' !== $name ? $name : $file, + 'version' => self::text( $header['Version'] ?? '' ), + 'author' => self::text( $header['Author'] ?? '' ), + 'description' => self::text( $header['Description'] ?? '' ), + 'size' => (int) $stat['size'], + 'modified' => (int) $stat['mtime'], + 'hash' => self::hash( $path, (int) $stat['size'], (int) $stat['mtime'], $content_dir, $cache, $used ), + ]; + } + + /** + * A folder in `mu-plugins`: its file count, size, newest time and a + * fingerprint over the relative paths and content hashes of its files, + * in name order. Past the caps the fingerprint covers the first files + * only, and `partial` says so. + * + * @param string $folder The folder name. + * @param string $path The full path. + * @param string $content_dir The `wp-content` folder. + * @param array $cache Content hashes by path; updated. + * @param array $used Paths whose hash was used; updated. + * + * @return array + */ + private static function folder_entry( string $folder, string $path, string $content_dir, array &$cache, array &$used ): array { + $files = self::folder_files( $path ); + $partial = count( $files ) > self::MAX_FOLDER_LISTING; + if ( $partial ) { + $files = array_slice( $files, 0, self::MAX_FOLDER_LISTING ); + } + sort( $files, SORT_STRING ); + + $size = 0; + $modified = 0; + $read = 0; + $lines = []; + foreach ( $files as $index => $relative ) { + $stat = @stat( $path . '/' . $relative ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A file can disappear between the listing and here. + if ( false === $stat ) { + continue; + } + $size += (int) $stat['size']; + $modified = max( $modified, (int) $stat['mtime'] ); + + if ( $index >= self::MAX_FOLDER_FILES || $read + (int) $stat['size'] > self::MAX_FOLDER_BYTES ) { + $partial = true; + continue; + } + $read += (int) $stat['size']; + $lines[] = $relative . "\0" . self::hash( $path . '/' . $relative, (int) $stat['size'], (int) $stat['mtime'], $content_dir, $cache, $used ); + } + + return [ + 'kind' => 'mu_folder', + 'file' => $folder, + 'name' => $folder, + 'files' => count( $files ), + 'size' => $size, + 'modified' => $modified, + 'hash' => 'sha256:' . hash( 'sha256', implode( "\n", $lines ) ), + 'partial' => $partial, + ]; + } + + /** + * The folders in the root of the MU plugins folder, by name. + * + * @param string $mu_dir The MU plugins folder. + * + * @return string[] + */ + private static function folders( string $mu_dir ): array { + $names = @scandir( $mu_dir ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- The folder may not exist. + if ( false === $names ) { + return []; + } + + $folders = []; + foreach ( $names as $name ) { + if ( '.' !== $name[0] && is_dir( $mu_dir . '/' . $name ) ) { + $folders[] = $name; + } + } + sort( $folders, SORT_STRING ); + + return $folders; + } + + /** + * The files of a folder and its subfolders, relative to it. Symbolic + * links to folders are not followed. Stops one past the listing cap. + * + * @param string $path The folder. + * + * @return string[] + */ + private static function folder_files( string $path ): array { + $files = []; + try { + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator( $path, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS ), + \RecursiveIteratorIterator::LEAVES_ONLY, + \RecursiveIteratorIterator::CATCH_GET_CHILD + ); + $prefix = strlen( rtrim( str_replace( '\\', '/', $path ), '/' ) ) + 1; + foreach ( $iterator as $item ) { + if ( $item instanceof \SplFileInfo && $item->isFile() ) { + $files[] = substr( str_replace( '\\', '/', $item->getPathname() ), $prefix ); + if ( count( $files ) > self::MAX_FOLDER_LISTING ) { + break; + } + } + } + } catch ( \Throwable $e ) { + return $files; + } + + return $files; + } + + /** + * The content hash of a file, from the cache when its size and time are + * the same as when it was hashed. A file too large to read gets a + * fingerprint of its size and time instead. + * + * @param string $path The full path. + * @param int $size Its size. + * @param int $modified Its modification time. + * @param string $content_dir The `wp-content` folder. + * @param array $cache Content hashes by path; updated. + * @param array $used Paths whose hash was used; updated. + * + * @return string + */ + private static function hash( string $path, int $size, int $modified, string $content_dir, array &$cache, array &$used ): string { + if ( $size > self::MAX_HASH_BYTES ) { + return 'stat:' . $size . ':' . $modified; + } + + $key = self::cache_key( $path, $content_dir ); + $used[ $key ] = true; + $stamp = $size . ':' . $modified . ':'; + if ( isset( $cache[ $key ] ) && is_string( $cache[ $key ] ) && 0 === strpos( $cache[ $key ], $stamp ) ) { + return substr( $cache[ $key ], strlen( $stamp ) ); + } + + $hash = @hash_file( 'sha256', $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- An unreadable file gets no hash. + if ( false === $hash ) { + return ''; + } + + $cache[ $key ] = $stamp . 'sha256:' . $hash; + + return 'sha256:' . $hash; + } + + /** + * The key of a file in the hash cache: its path relative to `wp-content`. + * + * @param string $path The full path. + * @param string $content_dir The `wp-content` folder. + * + * @return string + */ + private static function cache_key( string $path, string $content_dir ): string { + $content_dir = rtrim( str_replace( '\\', '/', $content_dir ), '/' ) . '/'; + $path = str_replace( '\\', '/', $path ); + + return 0 === strpos( $path, $content_dir ) ? substr( $path, strlen( $content_dir ) ) : $path; + } + + /** + * A quick fingerprint of the MU plugins folder and the drop-ins: the + * names, sizes and times of the files and folders in the root of + * `mu-plugins`, and of the drop-ins. Reads no file. + * + * @param string $mu_dir The MU plugins folder. + * @param string $content_dir The `wp-content` folder. + * @param string[] $dropin_files The drop-in file names. + * + * @return string + */ + public static function stat_fingerprint( string $mu_dir, string $content_dir, array $dropin_files ): string { + $lines = []; + $names = @scandir( $mu_dir ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- The folder may not exist. + foreach ( false !== $names ? $names : [] as $name ) { + if ( '.' === $name[0] ) { + continue; + } + $stat = @stat( $mu_dir . '/' . $name ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A file can disappear between the listing and here. + if ( false !== $stat ) { + $lines[] = 'mu/' . $name . ':' . $stat['size'] . ':' . $stat['mtime']; + } + } + + sort( $dropin_files, SORT_STRING ); + foreach ( $dropin_files as $file ) { + $stat = @stat( rtrim( $content_dir, '/\\' ) . '/' . $file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A file can disappear between the listing and here. + if ( false !== $stat ) { + $lines[] = 'dropin/' . $file . ':' . $stat['size'] . ':' . $stat['mtime']; + } + } + sort( $lines, SORT_STRING ); + + return hash( 'sha256', implode( "\n", $lines ) ); + } + + /** + * Header text as plain text, cut to the longest kept. + * + * @param mixed $value The header value. + * + * @return string + */ + private static function text( $value ): string { + $text = trim( html_entity_decode( wp_strip_all_tags( (string) $value ), ENT_QUOTES, 'UTF-8' ) ); + + return mb_strlen( $text ) > self::MAX_TEXT ? mb_substr( $text, 0, self::MAX_TEXT ) : $text; + } +} diff --git a/src/Main.php b/src/Main.php index ecd407a..2e095c1 100644 --- a/src/Main.php +++ b/src/Main.php @@ -145,9 +145,62 @@ private function register_events(): void { Events\Controller::register( new Events\DeactivatedPlugin() ); // when a plugin is deactivated. Events\Controller::register( new Events\PluginUpdate() ); // when a plugin is updated. Events\Controller::register( new Events\ThemeUpdate() ); // when a plugin is updated. - Events\Controller::register( new Events\RewriteRules() ); // when new rewrite rules are saved. - Events\Controller::register( new Events\PostSaved() ); // when a post status is changed. + Events\Controller::register( new Events\PluginUpdateFailed() ); // when a plugin update fails. + Events\Controller::register( new Events\ThemeUpdateFailed() ); // when a theme update fails. + Events\Controller::register( new Events\PluginInstalled() ); // when a plugin is installed. + Events\Controller::register( new Events\PluginDeleted() ); // when a plugin is deleted. + Events\Controller::register( new Events\ThemeInstalled() ); // when a theme is installed. + Events\Controller::register( new Events\ThemeDeleted() ); // when a theme is deleted. + Events\Controller::register( new Events\ThemeSwitched() ); // when another theme is activated. + Events\Controller::register( new Events\PluginFileEdited() ); // when a plugin file is changed in the plugin file editor. + Events\Controller::register( new Events\ThemeFileEdited() ); // when a theme file is changed in the theme file editor. + Events\FileEdits\Collector::setup(); + Events\Controller::register( new Events\PermalinksChanged() ); // when the permalink structure is changed. + Events\Controller::register( new Events\PostSaved() ); // when a post is created or changed. + Events\Controller::register( new Events\PostDeleted() ); // when a post is deleted permanently. + Events\Controller::register( new Events\PostBulkAction() ); // when many posts get the same action in one request. + Events\Controller::register( new Events\TermCreated() ); // when a category, tag or other term is created. + Events\Controller::register( new Events\TermChanged() ); // when a term's name, slug, parent or description changes. + Events\Controller::register( new Events\TermDeleted() ); // when a term is deleted. + Events\Controller::register( new Events\TermBulkAction() ); // when many terms get the same action in one request. + Events\TermChanges\Collector::setup(); + Events\Controller::register( new Events\MediaUploaded() ); // when a file is added to the media library. + Events\Controller::register( new Events\MediaChanged() ); // when a file's details, file, image or post change. + Events\Controller::register( new Events\MediaDeleted() ); // when a file is deleted permanently. + Events\Controller::register( new Events\MediaBulkAction() ); // when many files get the same action within a minute. + Events\MediaChanges\Collector::setup(); Events\Controller::register( new Events\CoreUpdate() ); // when the core is updated. + Events\Controller::register( new Events\CoreUpdateFailed() ); // when an automatic core update fails. + Events\Controller::register( new Events\UserCreated() ); // when a user is created. + Events\Controller::register( new Events\UserDeleted() ); // when a user is deleted. + Events\Controller::register( new Events\UserRoleChanged() ); // when a user's role is changed. + Events\Controller::register( new Events\UserLogin() ); // when a user with elevated rights logs in. + Events\FailedLogins\Counter::setup(); // counts failed logins per hour, sent by the hourly job. + Events\Controller::register( new Events\AppPasswordCreated() ); // when an application password is created for a user with elevated rights. + Events\Controller::register( new Events\AppPasswordRevoked() ); // when an application password of a user with elevated rights is revoked. + Events\Controller::register( new Events\AppPasswordFirstUsed() ); // when an application password of a user with elevated rights is used for the first time. + Events\Controller::register( new Events\PasswordChanged() ); // when the password of a user with elevated rights is changed. + Events\Controller::register( new Events\EmailChanged() ); // when the email address of a user with elevated rights is changed. + Events\Controller::register( new Events\SuperAdminGranted() ); // when a user is made super admin (multisite). + Events\Controller::register( new Events\SuperAdminRevoked() ); // when a user is no longer super admin (multisite). + Events\Controller::register( new Events\SiteOptionChanged() ); // when a setting of the settings screens is changed. + Events\SettingsChanges\Collector::setup(); + Events\Controller::register( new Events\MenuCreated() ); // when a navigation menu is made. + Events\Controller::register( new Events\MenuChanged() ); // when a navigation menu or its items change. + Events\Controller::register( new Events\MenuDeleted() ); // when a navigation menu is deleted. + Events\MenuChanges\Collector::setup(); + Events\Controller::register( new Events\WidgetsChanged() ); // when widgets are added, changed, moved or removed. + Events\WidgetChanges\Collector::setup(); + Events\Controller::register( new Events\ThemeSettingsChanged() ); // when theme settings, the logo or Additional CSS change (the Customizer and other ways). + Events\ThemeSettings\Collector::setup(); + Events\Controller::register( new Events\StylesChanged() ); // when the global styles of a block theme are saved in the Site Editor. + Events\Controller::register( new Events\TemplateChanged() ); // when a template or template part is saved (also its first customization). + Events\Controller::register( new Events\TemplateCreated() ); // when a custom template or template part is made. + Events\Controller::register( new Events\TemplateReset() ); // when a template or template part is reset to the theme's version. + Events\Controller::register( new Events\TemplateDeleted() ); // when a custom template or template part is deleted. + Events\Controller::register( new Events\FontInstalled() ); // when a font, or variants of one, is installed in the Font Library. + Events\Controller::register( new Events\FontDeleted() ); // when a font, or variants of one, is removed from the Font Library. + Events\SiteEditor\Collector::setup(); // custom events. Events\Controller::setup_custom_events(); diff --git a/src/WooCheckout/Cleanup.php b/src/WooCheckout/Cleanup.php index 4b7f9ac..6266faa 100644 --- a/src/WooCheckout/Cleanup.php +++ b/src/WooCheckout/Cleanup.php @@ -82,11 +82,22 @@ private static function cancel_stale_pending_orders( string $type ): void { for ( $batch = 0; $batch < self::MAX_BATCHES; $batch++ ) { $orders = self::find_probe_orders( $type, 'pending', $cutoff ); + $cancelled = 0; foreach ( $orders as $order ) { - $order->update_status( 'cancelled', __( 'Scanfully probe order. Cancelled by the probe order cleanup.', 'scanfully' ) ); + try { + $order->update_status( 'cancelled', __( 'Scanfully probe order. Cancelled by the probe order cleanup.', 'scanfully' ) ); + ++$cancelled; + } catch ( \Throwable $e ) { + // One order the status change is refused for (WooCommerce + // Subscriptions throws for a transition its rules reject) + // must not end the run for all the others. + self::log_failure( 'cancel', $order, $e ); + } } - if ( count( $orders ) < self::BATCH_SIZE ) { + // A short batch means there is nothing more; a batch without a + // single change would only come back unchanged. + if ( count( $orders ) < self::BATCH_SIZE || 0 === $cancelled ) { break; } } @@ -110,16 +121,45 @@ private static function delete_old_cancelled_orders( string $type ): void { for ( $batch = 0; $batch < self::MAX_BATCHES; $batch++ ) { $orders = self::find_probe_orders( $type, 'cancelled', $cutoff ); + $deleted = 0; foreach ( $orders as $order ) { - $order->delete( true ); + try { + if ( false !== $order->delete( true ) ) { + ++$deleted; + } + } catch ( \Throwable $e ) { + self::log_failure( 'delete', $order, $e ); + } } - if ( count( $orders ) < self::BATCH_SIZE ) { + // A short batch means there is nothing more; a batch without a + // single deletion would only come back unchanged. + if ( count( $orders ) < self::BATCH_SIZE || 0 === $deleted ) { break; } } } + /** + * Record a probe order the cleanup could not change, in WooCommerce's + * log under the `scanfully` source, and carry on. + * + * @param string $action What was attempted: cancel or delete. + * @param \WC_Order $order The order. + * @param \Throwable $e What went wrong. + * + * @return void + */ + private static function log_failure( string $action, \WC_Order $order, \Throwable $e ): void { + if ( ! function_exists( 'wc_get_logger' ) ) { + return; + } + wc_get_logger()->warning( + sprintf( 'Scanfully: could not %1$s probe order #%2$d in the probe order cleanup: %3$s', $action, $order->get_id(), $e->getMessage() ), + [ 'source' => 'scanfully' ] + ); + } + /** * Find probe orders (or probe subscriptions) with a status, created * before a cutoff. diff --git a/src/WooCheckout/Controller.php b/src/WooCheckout/Controller.php index 04e3168..7c10a5b 100644 --- a/src/WooCheckout/Controller.php +++ b/src/WooCheckout/Controller.php @@ -177,9 +177,28 @@ public static function get_or_create_probe_secret(): string { public static function prime_probe_request_check(): void { if ( self::is_probe_request() ) { self::mark_response_uncacheable(); + self::keep_cron_out_of_probe_request(); } } + /** + * Stop WordPress from running cron jobs inside a probe request. + * + * With ALTERNATE_WP_CRON, wp-cron.php runs inside the page request that + * found a due job instead of in a request of its own. In a probe request + * the registered gateway list holds only the probe gateway, so a job that + * needs a real gateway, such as a WooCommerce Subscriptions renewal, would + * treat the subscription as manual. Reporting no due jobs leaves them for + * the next ordinary request, usually within a minute. + * + * Runs at `init` priority 1; wp_cron() looks for due jobs at priority 10. + * + * @return void + */ + private static function keep_cron_out_of_probe_request(): void { + add_filter( 'pre_get_ready_cron_jobs', '__return_empty_array' ); + } + /** * Keep page caches from storing a probe response. A probe sees the probe * gateway and a logged-in probe customer; a cached copy served to a real diff --git a/src/WooCheckout/ProbeGateway.php b/src/WooCheckout/ProbeGateway.php index 242f57a..6774343 100644 --- a/src/WooCheckout/ProbeGateway.php +++ b/src/WooCheckout/ProbeGateway.php @@ -31,7 +31,11 @@ public function __construct() { // drops any gateway that does not declare them when the cart has a // subscription and manual renewals are disabled. The probe never // charges a real PSP; it only needs to stay visible on checkout. - $this->supports = [ 'products', 'subscriptions', 'multiple_subscriptions' ]; + // subscription_cancellation: Subscriptions only moves a subscription + // to cancelled when its gateway declares this. Without it, the + // subscriptions a probe order creates stay pending, both here and in + // the cleanup. There is no PSP to notify, so cancelling is always fine. + $this->supports = [ 'products', 'subscriptions', 'multiple_subscriptions', 'subscription_cancellation' ]; // Always enabled at the gateway settings level; availability is // gated dynamically by ProbeGateway::filter_available_gateways(). @@ -184,8 +188,7 @@ public function process_payment( $order_id ) { } self::tag_probe_order( $order ); - $subscriptions = self::order_subscriptions( $order ); - foreach ( $subscriptions as $subscription ) { + foreach ( self::order_subscriptions( $order ) as $subscription ) { self::tag_probe_order( $subscription ); $subscription->save_meta_data(); } @@ -193,7 +196,10 @@ public function process_payment( $order_id ) { $order->set_status( 'cancelled', __( 'Scanfully probe order. Cancelled automatically at the end of the checkout check.', 'scanfully' ) ); $order->save(); - foreach ( $subscriptions as $subscription ) { + // Saving the cancelled order makes Subscriptions cancel the + // subscriptions as well. Load them again so that shows, instead of + // cancelling a stale copy a second time with a second note. + foreach ( self::order_subscriptions( $order ) as $subscription ) { self::cancel_subscription( $subscription ); } diff --git a/tests/Integration/AccountSecurityEventTest.php b/tests/Integration/AccountSecurityEventTest.php new file mode 100644 index 0000000..bc06906 --- /dev/null +++ b/tests/Integration/AccountSecurityEventTest.php @@ -0,0 +1,311 @@ + + */ + private array $users = []; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'as_get_scheduled_actions' ) || ! class_exists( \WP_Application_Passwords::class ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + require_once ABSPATH . 'wp-admin/includes/user.php'; + + update_option( 'scanfully_connect_is_connected', 'yes' ); + delete_transient( 'scanfully_user_events_rate' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + wp_set_current_user( 1 ); + } + + protected function tearDown(): void { + if ( function_exists( 'as_unschedule_all_actions' ) ) { + foreach ( $this->users as $id ) { + wp_delete_user( $id ); + } + wp_set_current_user( 0 ); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( 'scanfully_connect_is_connected' ); + } + parent::tearDown(); + } + + /** + * The events queued so far, oldest first, as [type, data] pairs. + * + * @return array}> + */ + private function queued(): array { + $actions = as_get_scheduled_actions( + [ + 'hook' => EventsController::ACTION_SEND_EVENT, + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + 'orderby' => 'action_id', + 'order' => 'ASC', + ] + ); + + $events = []; + foreach ( $actions as $action ) { + $args = $action->get_args(); + $events[] = [ (string) $args['type'], (array) $args['data'] ]; + } + + return $events; + } + + /** + * The types of the events queued so far. + * + * @return array + */ + private function queued_types(): array { + return array_column( $this->queued(), 0 ); + } + + /** + * Create a user and forget the events that queued. + * + * @param string $role The role. + * + * @return int + */ + private function create_user( string $role ): int { + $login = 'scanfully-' . strtolower( wp_generate_password( 8, false ) ); + $id = wp_insert_user( + [ + 'user_login' => $login, + 'user_email' => $login . '@scanfully.com', + 'user_pass' => wp_generate_password(), + 'display_name' => 'Scanfully Test', + 'role' => $role, + ] + ); + $this->assertIsInt( $id ); + $this->users[] = $id; + as_unschedule_all_actions( '', [], 'scanfully' ); + + return $id; + } + + /** + * Start what counts as a new request for the password events: the users + * created so far were created in an earlier request. + * + * @return void + */ + private function new_request(): void { + \Scanfully\Events\PasswordChanged::flush(); + as_unschedule_all_actions( '', [], 'scanfully' ); + $created = new \ReflectionProperty( \Scanfully\Events\PasswordChanged::class, 'created' ); + $created->setAccessible( true ); + $created->setValue( null, [] ); + } + + /** + * Create an application password. + * + * @param int $user_id The user ID. + * + * @return array{0: string, 1: array} The password and its record. + */ + private function create_app_password( int $user_id ): array { + $created = \WP_Application_Passwords::create_new_application_password( $user_id, [ 'name' => 'Zapier' ] ); + $this->assertIsArray( $created ); + + return $created; + } + + public function test_creating_an_application_password_is_reported_for_elevated_accounts_only(): void { + $subscriber = $this->create_user( 'subscriber' ); + $admin = $this->create_user( 'administrator' ); + + $this->create_app_password( $subscriber ); + [ $password, $item ] = $this->create_app_password( $admin ); + + $events = $this->queued(); + $this->assertSame( [ 'AppPasswordCreated' ], array_column( $events, 0 ) ); + $this->assertSame( $admin, $events[0][1]['id'] ); + $this->assertSame( 'Zapier', $events[0][1]['app_name'] ); + $this->assertSame( $item['uuid'], $events[0][1]['app_id'] ); + $this->assertStringNotContainsString( $password, (string) wp_json_encode( $events ), 'Never the password.' ); + } + + public function test_revoking_application_passwords_is_reported_once_per_password(): void { + $admin = $this->create_user( 'administrator' ); + $first = $this->create_app_password( $admin )[1]; + $this->create_app_password( $admin ); + as_unschedule_all_actions( '', [], 'scanfully' ); + + \WP_Application_Passwords::delete_application_password( $admin, $first['uuid'] ); + \WP_Application_Passwords::delete_all_application_passwords( $admin ); + + $events = $this->queued(); + $this->assertSame( [ 'AppPasswordRevoked', 'AppPasswordRevoked' ], array_column( $events, 0 ) ); + $this->assertSame( $first['uuid'], $events[0][1]['app_id'] ); + $this->assertNotSame( $first['uuid'], $events[1][1]['app_id'] ); + $this->assertSame( '', $events[0][1]['last_used'] ); + } + + /** + * Sign a request in with an application password through HTTP Basic + * authentication, as a REST request does. + * + * @param int $user_id The user ID. + * @param string $password The application password. + * + * @return int The authenticated user ID, or 0. + */ + private function sign_request_in( int $user_id, string $password ): int { + $api_request = '__return_true'; + add_filter( 'application_password_is_api_request', $api_request ); + add_filter( 'wp_is_application_passwords_available', $api_request ); + $_SERVER['PHP_AUTH_USER'] = get_userdata( $user_id )->user_login; + $_SERVER['PHP_AUTH_PW'] = $password; + $_SERVER['REMOTE_ADDR'] = '203.0.113.9'; + + $authenticated = apply_filters( 'determine_current_user', false ); + + unset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], $_SERVER['REMOTE_ADDR'] ); + remove_filter( 'application_password_is_api_request', $api_request ); + remove_filter( 'wp_is_application_passwords_available', $api_request ); + + return (int) $authenticated; + } + + public function test_the_first_use_of_an_application_password_is_reported_once(): void { + $admin = $this->create_user( 'administrator' ); + [ $password, $item ] = $this->create_app_password( $admin ); + $subscriber = $this->create_user( 'subscriber' ); + $other_password = $this->create_app_password( $subscriber )[0]; + as_unschedule_all_actions( '', [], 'scanfully' ); + + $this->assertSame( $admin, $this->sign_request_in( $admin, $password ) ); + $this->assertSame( $admin, $this->sign_request_in( $admin, $password ), 'A second request.' ); + $this->assertSame( $subscriber, $this->sign_request_in( $subscriber, $other_password ) ); + + $events = $this->queued(); + $this->assertSame( [ 'AppPasswordFirstUsed' ], array_column( $events, 0 ) ); + $this->assertSame( $item['uuid'], $events[0][1]['app_id'] ); + $this->assertSame( '203.0.113.9', $events[0][1]['ip'] ); + $this->assertStringNotContainsString( $password, (string) wp_json_encode( $events ), 'Never the password.' ); + } + + public function test_password_changes_are_reported_with_how_they_were_made(): void { + $profile = $this->create_user( 'administrator' ); + $reset = $this->create_user( 'administrator' ); + $direct = $this->create_user( 'editor' ); + $subscriber = $this->create_user( 'subscriber' ); + $this->new_request(); + + wp_update_user( + [ + 'ID' => $profile, + 'user_pass' => 'Profile-' . wp_generate_password(), + ] + ); + reset_password( get_userdata( $reset ), 'Reset-' . wp_generate_password() ); + wp_set_password( 'Direct-' . wp_generate_password(), $direct ); + wp_set_password( 'Direct-' . wp_generate_password(), $subscriber ); + $this->assertSame( [], $this->queued_types(), 'Nothing is sent before the end of the request.' ); + \Scanfully\Events\PasswordChanged::flush(); + + $events = $this->queued(); + $this->assertSame( [ 'PasswordChanged', 'PasswordChanged', 'PasswordChanged' ], array_column( $events, 0 ) ); + $this->assertSame( [ $profile, $reset, $direct ], array_column( array_column( $events, 1 ), 'id' ) ); + $this->assertSame( [ 'profile', 'reset', 'other' ], array_column( array_column( $events, 1 ), 'via' ) ); + $encoded = (string) wp_json_encode( $events ); + $this->assertStringNotContainsString( 'Profile-', $encoded, 'Never the password.' ); + $this->assertStringNotContainsString( '$', $encoded, 'Never the hash.' ); + } + + public function test_the_password_of_a_new_user_is_not_a_change(): void { + $this->new_request(); + as_unschedule_all_actions( '', [], 'scanfully' ); + $id = wp_insert_user( + [ + 'user_login' => 'scanfully-' . strtolower( wp_generate_password( 8, false ) ), + 'user_pass' => wp_generate_password(), + 'role' => 'administrator', + ] + ); + $this->assertIsInt( $id ); + $this->users[] = $id; + wp_set_password( wp_generate_password(), $id ); + \Scanfully\Events\PasswordChanged::flush(); + + $this->assertSame( [ 'UserCreated' ], $this->queued_types() ); + } + + public function test_logging_in_is_not_a_password_change(): void { + $admin = $this->create_user( 'administrator' ); + $password = 'Login-' . wp_generate_password(); + wp_set_password( $password, $admin ); + $this->new_request(); + // Store the password with an old hash, so logging in rehashes it. + global $wpdb; + $wpdb->update( $wpdb->users, [ 'user_pass' => md5( $password ) ], [ 'ID' => $admin ] ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Test setup. + clean_user_cache( $admin ); + + $user = wp_authenticate( get_userdata( $admin )->user_login, $password ); + \Scanfully\Events\PasswordChanged::flush(); + + $this->assertInstanceOf( \WP_User::class, $user ); + $this->assertNotSame( md5( $password ), get_userdata( $admin )->user_pass, 'WordPress stored a newer hash.' ); + $this->assertSame( [], $this->queued_types() ); + } + + public function test_an_email_change_is_reported_for_elevated_accounts_only(): void { + $admin = $this->create_user( 'administrator' ); + $subscriber = $this->create_user( 'subscriber' ); + $old_email = get_userdata( $admin )->user_email; + $new_email = "o'brien-" . strtolower( wp_generate_password( 6, false ) ) . '@scanfully.com'; + + wp_update_user( + [ + 'ID' => $admin, + 'user_email' => $new_email, + ] + ); + wp_update_user( + [ + 'ID' => $subscriber, + 'user_email' => 'new-' . get_userdata( $subscriber )->user_email, + ] + ); + wp_update_user( + [ + 'ID' => $admin, + 'display_name' => 'Renamed', + ] + ); + + $events = $this->queued(); + $this->assertSame( [ 'EmailChanged' ], array_column( $events, 0 ) ); + $this->assertSame( $new_email, $events[0][1]['email'] ); + $this->assertSame( $old_email, $events[0][1]['old_email'] ); + } +} diff --git a/tests/Integration/ActivityEventTest.php b/tests/Integration/ActivityEventTest.php new file mode 100644 index 0000000..c080694 --- /dev/null +++ b/tests/Integration/ActivityEventTest.php @@ -0,0 +1,422 @@ + + */ + private array $users = []; + + /** + * Options to restore after a test, with their value before it. + * + * @var array + */ + private array $options = []; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'as_get_scheduled_actions' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + require_once ABSPATH . 'wp-admin/includes/user.php'; + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + require_once ABSPATH . 'wp-admin/includes/file.php'; + require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; + + update_option( 'scanfully_connect_is_connected', 'yes' ); + delete_transient( 'scanfully_user_events_rate' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + wp_set_current_user( 1 ); + } + + protected function tearDown(): void { + if ( function_exists( 'as_unschedule_all_actions' ) ) { + foreach ( $this->users as $id ) { + wp_delete_user( $id ); + } + foreach ( $this->options as $option => $value ) { + update_option( $option, $value ); + } + wp_set_current_user( 0 ); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( 'scanfully_connect_is_connected' ); + } + parent::tearDown(); + } + + /** + * The events queued so far, oldest first, as [type, data] pairs. + * + * @return array}> + */ + private function queued(): array { + $actions = as_get_scheduled_actions( + [ + 'hook' => EventsController::ACTION_SEND_EVENT, + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + 'orderby' => 'action_id', + 'order' => 'ASC', + ] + ); + + $events = []; + foreach ( $actions as $action ) { + $args = $action->get_args(); + $events[] = [ (string) $args['type'], (array) $args['data'] ]; + } + + return $events; + } + + /** + * The types of the events queued so far. + * + * @return array + */ + private function queued_types(): array { + return array_column( $this->queued(), 0 ); + } + + /** + * Remember an option's value so tearDown restores it. + * + * @param string $option The option. + */ + private function restore_later( string $option ): void { + if ( ! array_key_exists( $option, $this->options ) ) { + $this->options[ $option ] = get_option( $option ); + } + } + + /** + * Create a user. + * + * @param string $role The role. + * + * @return int + */ + private function create_user( string $role ): int { + $login = 'scanfully-' . wp_generate_password( 8, false ); + $id = wp_insert_user( + [ + 'user_login' => $login, + 'user_email' => $login . '@scanfully.com', + 'user_pass' => wp_generate_password(), + 'display_name' => 'Scanfully Test', + 'role' => $role, + ] + ); + $this->assertIsInt( $id ); + $this->users[] = $id; + + return $id; + } + + public function test_creating_a_user_is_one_event_without_a_role_change(): void { + $id = $this->create_user( 'editor' ); + + $this->assertSame( + [ + [ + 'UserCreated', + [ + 'id' => $id, + 'name' => 'Scanfully Test', + 'email' => get_userdata( $id )->user_email, + 'roles' => [ 'editor' ], + ], + ], + ], + $this->queued() + ); + } + + public function test_a_visitor_signing_up_is_not_reported(): void { + wp_set_current_user( 0 ); + + $this->create_user( (string) get_option( 'default_role' ) ); + + $this->assertSame( [], $this->queued_types() ); + } + + public function test_a_sign_up_as_administrator_is_reported_when_that_is_the_default_role(): void { + $this->restore_later( 'default_role' ); + update_option( 'default_role', 'administrator' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + wp_set_current_user( 0 ); + + $this->create_user( 'administrator' ); + + $this->assertSame( [ 'UserCreated' ], $this->queued_types() ); + } + + public function test_a_role_another_plugin_sets_on_sign_up_is_not_a_role_change(): void { + wp_set_current_user( 0 ); + if ( ! get_role( 'customer' ) ) { + $this->markTestSkipped( 'Needs the WooCommerce customer role.' ); + } + $set_role = static function ( $user_id ) { + ( new \WP_User( $user_id ) )->set_role( 'customer' ); + }; + add_action( 'user_register', $set_role, 20 ); + + $this->create_user( 'subscriber' ); + remove_action( 'user_register', $set_role, 20 ); + + $this->assertSame( [], $this->queued_types() ); + } + + /** + * Sign a new user with this role in through wp_signon(), as the login + * form does. + * + * @param string $role The role. + * + * @return int The user ID. + */ + private function sign_in_new_user( string $role ): int { + $id = $this->create_user( $role ); + $password = wp_generate_password(); + wp_set_password( $password, $id ); + as_unschedule_all_actions( '', [], 'scanfully' ); + wp_set_current_user( 0 ); + + add_filter( 'send_auth_cookies', '__return_false' ); + $_SERVER['REMOTE_ADDR'] = '203.0.113.9'; + $user = wp_signon( + [ + 'user_login' => get_userdata( $id )->user_login, + 'user_password' => $password, + ] + ); + unset( $_SERVER['REMOTE_ADDR'] ); + remove_filter( 'send_auth_cookies', '__return_false' ); + + $this->assertInstanceOf( \WP_User::class, $user ); + + return $id; + } + + public function test_an_administrator_logging_in_is_reported(): void { + $id = $this->sign_in_new_user( 'administrator' ); + + $events = $this->queued(); + $this->assertSame( [ 'UserLogin' ], array_column( $events, 0 ) ); + $this->assertSame( $id, $events[0][1]['id'] ); + $this->assertSame( get_userdata( $id )->user_email, $events[0][1]['email'] ); + $this->assertSame( [ 'administrator' ], $events[0][1]['roles'] ); + $this->assertSame( '203.0.113.9', $events[0][1]['ip'] ); + } + + public function test_a_subscriber_logging_in_is_not_reported(): void { + $this->sign_in_new_user( 'subscriber' ); + + $this->assertSame( [], $this->queued_types() ); + } + + public function test_changing_and_deleting_a_user_is_reported(): void { + $id = $this->create_user( 'editor' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + + wp_update_user( + [ + 'ID' => $id, + 'role' => 'administrator', + ] + ); + wp_delete_user( $id ); + $this->users = []; + + $events = $this->queued(); + $this->assertSame( [ 'UserRoleChanged', 'UserDeleted' ], array_column( $events, 0 ) ); + $this->assertSame( [ 'administrator' ], $events[0][1]['roles'] ); + $this->assertSame( [ 'editor' ], $events[0][1]['old_roles'] ); + $this->assertSame( [ 'administrator' ], $events[1][1]['roles'] ); + + // An account with elevated rights carries its email address, and + // nothing else from the account beyond its name and roles. + $email = $events[0][1]['email']; + $this->assertStringEndsWith( '@scanfully.com', $email ); + $this->assertSame( $email, $events[1][1]['email'] ); + unset( $events[0][1]['email'], $events[1][1]['email'] ); + $this->assertStringNotContainsString( 'scanfully-', (string) wp_json_encode( $events ), 'Never the login.' ); + } + + public function test_a_permalink_change_is_reported_and_rewrite_flushes_are_not(): void { + $this->restore_later( 'permalink_structure' ); + $old = (string) get_option( 'permalink_structure' ); + $new = '/scanfully-test/%postname%/' === $old ? '/%postname%/' : '/scanfully-test/%postname%/'; + + update_option( 'permalink_structure', $new ); + flush_rewrite_rules(); + + $this->assertSame( + [ + [ + 'PermalinksChanged', + [ + 'old' => $old, + 'new' => $new, + ], + ], + ], + $this->queued() + ); + } + + public function test_switching_the_theme_is_reported(): void { + $old = wp_get_theme(); + $new = null; + foreach ( wp_get_themes() as $theme ) { + if ( $theme->get_stylesheet() !== $old->get_stylesheet() && ! $theme->parent() ) { + $new = $theme; + break; + } + } + if ( null === $new ) { + $this->markTestSkipped( 'Needs a second theme.' ); + } + + switch_theme( $new->get_stylesheet() ); + $events = $this->queued(); + switch_theme( $old->get_stylesheet() ); + + $this->assertSame( + [ + [ + 'ThemeSwitched', + [ + 'name' => $new->get( 'Name' ), + 'slug' => $new->get_stylesheet(), + 'old_name' => $old->get( 'Name' ), + 'old_slug' => $old->get_stylesheet(), + ], + ], + ], + $events + ); + } + + public function test_installing_and_deleting_a_plugin_is_reported(): void { + if ( ! class_exists( \ZipArchive::class ) || 'direct' !== get_filesystem_method() ) { + $this->markTestSkipped( 'Needs ZipArchive and direct file system access.' ); + } + + $slug = 'scanfully-test-' . strtolower( wp_generate_password( 6, false ) ); + $zip = get_temp_dir() . $slug . '.zip'; + $pack = new \ZipArchive(); + $pack->open( $zip, \ZipArchive::CREATE ); + $pack->addFromString( $slug . '/' . $slug . '.php', "close(); + + WP_Filesystem(); + $upgrader = new \Plugin_Upgrader( new \Automatic_Upgrader_Skin() ); + $this->assertTrue( $upgrader->install( $zip ) ); + wp_delete_file( $zip ); + + $plugin = $slug . '/' . $slug . '.php'; + $this->assertSame( [ true ], array_values( array_unique( (array) delete_plugins( [ $plugin ] ) ) ) ); + + $this->assertSame( + [ + [ + 'PluginInstalled', + [ + 'name' => 'Scanfully Test Plugin', + 'slug' => $plugin, + 'version' => '1.2.3', + 'author' => 'Scanfully', + ], + ], + [ + 'PluginDeleted', + [ + 'name' => 'Scanfully Test Plugin', + 'slug' => $plugin, + 'version' => '1.2.3', + ], + ], + ], + $this->queued() + ); + } + + public function test_a_failed_plugin_update_is_reported(): void { + global $wpdb; + // The same failure is reported once a day; forget earlier runs. + $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\\_transient\\_%scanfully\\_update\\_failed\\_%'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Test cleanup. + wp_cache_flush(); + + $slug = 'hello.php'; + $options = apply_filters( + 'upgrader_package_options', + [ 'hook_extra' => [ 'plugin' => $slug ] ] + ); + + $failed = new \WP_Error( 'incompatible_php_required_version', 'The package requires a newer PHP version.' ); + apply_filters( 'upgrader_install_package_result', $failed, $options['hook_extra'] ); + + $events = $this->queued(); + $this->assertSame( [ 'PluginUpdateFailed' ], array_column( $events, 0 ) ); + $this->assertSame( $slug, $events[0][1]['slug'] ); + $this->assertSame( 'Hello Dolly', $events[0][1]['name'] ); + $this->assertSame( 'The package requires a newer PHP version.', $events[0][1]['error'] ); + } + + public function test_a_failed_automatic_core_update_is_reported(): void { + $version = '99.' . wp_rand( 0, 9999 ); + + do_action( + 'automatic_updates_complete', + [ + 'core' => [ + (object) [ + 'item' => (object) [ + 'current' => $version, + 'version' => $version, + ], + 'result' => new \WP_Error( 'download_failed', 'Download failed.', 'Not Found' ), + 'name' => 'WordPress ' . $version, + 'messages' => [], + ], + ], + ] + ); + + $this->assertSame( + [ + [ + 'CoreUpdateFailed', + [ + 'version' => $version, + 'old_version' => get_bloginfo( 'version' ), + 'error' => 'Download failed. Not Found', + ], + ], + ], + $this->queued() + ); + } +} diff --git a/tests/Integration/ContentEventsTest.php b/tests/Integration/ContentEventsTest.php new file mode 100644 index 0000000..5dac87d --- /dev/null +++ b/tests/Integration/ContentEventsTest.php @@ -0,0 +1,538 @@ + + */ + private array $posts = []; + + /** + * Terms created by a test: term ID and taxonomy. + * + * @var array + */ + private array $terms = []; + + /** + * Event bodies sent to the API. + * + * @var array> + */ + private array $sent = []; + + /** + * The signed-in user before the test. + * + * @var int + */ + private int $user = 0; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'as_get_scheduled_actions' ) || ! function_exists( 'wp_insert_post' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + + update_option( 'scanfully_connect_is_connected', 'yes' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + Collector::reset(); + TermCollector::reset(); + $this->sent = []; + $this->user = get_current_user_id(); + wp_set_current_user( 1 ); + add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 3 ); + // No per-minute cap unless a test sets one: the suite changes more + // posts a minute than a site does. + add_filter( 'scanfully_post_saved_events_per_minute', '__return_zero' ); + add_filter( 'scanfully_term_events_per_minute', '__return_zero' ); + } + + protected function tearDown(): void { + if ( function_exists( 'wp_delete_post' ) ) { + remove_filter( 'pre_http_request', [ $this, 'capture_request' ], 10 ); + remove_all_filters( 'scanfully_post_saved_events_per_minute' ); + remove_all_filters( 'scanfully_term_events_per_minute' ); + foreach ( array_reverse( $this->posts ) as $id ) { + wp_delete_post( $id, true ); + } + foreach ( $this->terms as [ $id, $taxonomy ] ) { + wp_delete_term( $id, $taxonomy ); + } + Collector::reset(); + TermCollector::reset(); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( 'scanfully_connect_is_connected' ); + wp_set_current_user( $this->user ); + } + parent::tearDown(); + } + + /** + * `pre_http_request`: keep the event sent to the API and accept it. + * + * @param mixed $preempt Whether to preempt the request. + * @param array $args The request arguments. + * @param string $url The URL. + * + * @return mixed + */ + public function capture_request( $preempt, $args, $url ) { + if ( false === strpos( (string) $url, '/timeline' ) ) { + return $preempt; + } + + $this->sent[] = json_decode( (string) ( $args['body'] ?? '' ), true ); + + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 202, + 'message' => 'Accepted', + ], + 'cookies' => [], + ]; + } + + /** + * Posts made for a test, in an earlier "request". + * + * @param int $count How many. + * @param array $fields Fields of each post. + * + * @return array + */ + private function make_posts( int $count, array $fields = [] ): array { + $ids = []; + for ( $i = 1; $i <= $count; $i++ ) { + $id = wp_insert_post( + array_merge( + [ + 'post_title' => 'Bulk post ' . $i, + 'post_type' => 'post', + 'post_status' => 'publish', + ], + $fields + ) + ); + $ids[] = $id; + $this->posts[] = $id; + } + + $this->end_request(); + $this->sent = []; + as_unschedule_all_actions( '', [], 'scanfully' ); + + return $ids; + } + + /** + * A term made for a test, in an earlier "request". + * + * @param string $name The name. + * @param string $taxonomy The taxonomy. + * @param int $parent_id The parent. + * + * @return int The term ID. + */ + private function make_term( string $name, string $taxonomy = 'category', int $parent_id = 0 ): int { + $term = wp_insert_term( $name, $taxonomy, [ 'parent' => $parent_id ] ); + $this->assertIsArray( $term ); + $this->terms[] = [ (int) $term['term_id'], $taxonomy ]; + + $this->end_request(); + $this->sent = []; + as_unschedule_all_actions( '', [], 'scanfully' ); + + return (int) $term['term_id']; + } + + /** + * End the "request": report the changed posts, then the terms. + * + * @return void + */ + private function end_request(): void { + Collector::flush(); + TermCollector::flush(); + } + + /** + * Run the pending event jobs, as Action Scheduler would, until none is + * left, and return the events sent: type and data. + * + * @return array}> + */ + private function run_jobs(): array { + $hooks = [ EventsController::ACTION_BUILD_POST_EVENT, EventsController::ACTION_BUILD_CONTENT_EVENT, EventsController::ACTION_SEND_EVENT, EventsController::ACTION_SEND_OVERFLOW ]; + for ( $round = 0; $round < 5; $round++ ) { + $actions = as_get_scheduled_actions( + [ + 'hook__in' => $hooks, + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + 'orderby' => 'none', + ] + ); + if ( [] === $actions ) { + break; + } + foreach ( $actions as $id => $action ) { + \ActionScheduler::store()->mark_complete( $id ); + do_action_ref_array( $action->get_hook(), array_values( $action->get_args() ) ); + } + } + + return array_map( + static fn( array $body ): array => [ + 'type' => (string) $body['type'], + 'data' => (array) $body['data'], + ], + $this->sent + ); + } + + /** + * The types of the events sent. + * + * @param array}> $events The events. + * + * @return array + */ + private static function types( array $events ): array { + return array_column( $events, 'type' ); + } + + public function test_delete_permanently_reports_the_post(): void { + [ $id ] = $this->make_posts( 1, [ 'post_title' => 'Old news' ] ); + wp_trash_post( $id ); + $this->end_request(); + $this->sent = []; + as_unschedule_all_actions( '', [], 'scanfully' ); + + wp_delete_post( $id, true ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'PostDeleted' ], self::types( $events ) ); + $this->assertSame( + [ + 'id' => $id, + 'title' => 'Old news', + 'post_type' => 'post', + 'type_label' => 'Post', + 'post_status' => 'trash', + ], + $events[0]['data'] + ); + } + + public function test_a_force_delete_of_a_published_post_says_it_was_published(): void { + [ $id ] = $this->make_posts( 1 ); + + wp_delete_post( $id, true ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'PostDeleted' ], self::types( $events ) ); + $this->assertSame( 'publish', $events[0]['data']['post_status'] ); + } + + public function test_emptying_the_trash_is_one_row_with_every_post(): void { + $ids = $this->make_posts( 12, [ 'post_status' => 'trash' ] ); + + // What edit.php does for "Empty Trash". + foreach ( $ids as $id ) { + wp_delete_post( $id ); + } + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'PostBulkAction' ], self::types( $events ) ); + $data = $events[0]['data']; + $this->assertSame( [ 'deleted', 'post', 'Posts', 12 ], [ $data['action'], $data['post_type'], $data['type_label'], $data['count'] ] ); + $this->assertSame( $ids, array_column( $data['posts'], 'id' ) ); + $this->assertSame( 'Bulk post 12', $data['posts'][11]['title'] ); + } + + public function test_the_trash_wordpress_empties_itself_is_marked(): void { + $ids = $this->make_posts( 2 ); + foreach ( $ids as $id ) { + wp_trash_post( $id ); + update_post_meta( $id, '_wp_trash_meta_time', time() - 40 * DAY_IN_SECONDS ); + } + $this->end_request(); + $this->sent = []; + as_unschedule_all_actions( '', [], 'scanfully' ); + + do_action( 'wp_scheduled_delete' ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'PostDeleted', 'PostDeleted' ], self::types( $events ) ); + $this->assertTrue( $events[0]['data']['expired'] ); + $this->assertSame( EMPTY_TRASH_DAYS, $events[0]['data']['trash_days'] ); + } + + public function test_a_bulk_trash_of_thirty_posts_is_one_row(): void { + $ids = $this->make_posts( 30 ); + + foreach ( $ids as $id ) { + wp_trash_post( $id ); + } + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'PostBulkAction' ], self::types( $events ) ); + $this->assertSame( 'trashed', $events[0]['data']['action'] ); + $this->assertSame( 30, $events[0]['data']['count'] ); + $this->assertCount( 30, $events[0]['data']['posts'] ); + } + + public function test_a_bulk_edit_adding_a_category_says_which(): void { + require_once ABSPATH . 'wp-admin/includes/post.php'; + $ids = $this->make_posts( 30 ); + $category = $this->make_term( 'Bulk news' ); + + bulk_edit_posts( + [ + 'post_type' => 'post', + 'post' => $ids, + '_status' => '-1', + 'post_author' => '-1', + 'post_category' => [ $category ], + ] + ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'PostBulkAction' ], self::types( $events ) ); + $data = $events[0]['data']; + $this->assertSame( 'updated', $data['action'] ); + $this->assertSame( 30, $data['changed']['terms'] ?? null ); + $this->assertSame( + [ + [ + 'taxonomy' => 'category', + 'label' => 'Categories', + 'added' => [ 'Bulk news' ], + // Bulk Edit takes the default category off posts it gives a category. + 'removed' => [ 'Uncategorized' ], + ], + ], + $data['terms'] ?? null + ); + } + + public function test_a_few_posts_trashed_keep_rows_of_their_own(): void { + $ids = $this->make_posts( 3 ); + + foreach ( $ids as $id ) { + wp_trash_post( $id ); + } + $this->end_request(); + + $this->assertSame( [ 'PostSaved', 'PostSaved', 'PostSaved' ], self::types( $this->run_jobs() ) ); + } + + public function test_saves_over_the_per_minute_cap_arrive_as_one_row(): void { + $ids = $this->make_posts( 5 ); + remove_all_filters( 'scanfully_post_saved_events_per_minute' ); + delete_transient( 'scanfully_post_events_' . (int) floor( time() / MINUTE_IN_SECONDS ) ); + // An earlier run in this minute left the marker of a job setUp() unscheduled. + delete_transient( 'scanfully_minute_overflow_post_' . (int) floor( time() / MINUTE_IN_SECONDS ) . '_job' ); + add_filter( 'scanfully_post_saved_events_per_minute', static fn() => 2 ); + + // Five requests, each renaming one post. + foreach ( $ids as $index => $id ) { + wp_update_post( + [ + 'ID' => $id, + 'post_title' => 'Renamed ' . $index, + ] + ); + $this->end_request(); + } + $events = $this->run_jobs(); + + $this->assertSame( [ 'PostSaved', 'PostSaved', 'PostBulkAction' ], self::types( $events ) ); + $data = $events[2]['data']; + $this->assertTrue( $data['overflow'] ); + $this->assertSame( 'updated', $data['action'] ); + $this->assertSame( array_slice( $ids, 2 ), array_column( $data['posts'], 'id' ) ); + $this->assertSame( [ 'title' => 3 ], $data['changed'] ); + } + + public function test_a_new_term_is_reported_with_its_parent(): void { + $parent = $this->make_term( 'Company' ); + + $term = wp_insert_term( 'Team', 'category', [ 'parent' => $parent ] ); + $this->terms[] = [ (int) $term['term_id'], 'category' ]; + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'TermCreated' ], self::types( $events ) ); + $this->assertSame( + [ + 'id' => (int) $term['term_id'], + 'name' => 'Team', + 'slug' => 'team', + 'taxonomy' => 'category', + 'label' => 'Category', + 'parent' => [ + 'id' => $parent, + 'name' => 'Company', + ], + ], + $events[0]['data'] + ); + } + + public function test_renaming_and_moving_a_term_reports_both(): void { + $parent = $this->make_term( 'Company' ); + $term = $this->make_term( 'Updates' ); + + wp_update_term( + $term, + 'category', + [ + 'name' => 'News & updates', + 'slug' => 'news', + 'parent' => $parent, + 'description' => 'What is new.', + ] + ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'TermChanged' ], self::types( $events ) ); + $this->assertSame( + [ + 'name' => [ + 'old' => 'Updates', + 'new' => 'News & updates', + ], + 'slug' => [ + 'old' => 'updates', + 'new' => 'news', + ], + 'description' => [ + 'old' => '', + 'new' => 'What is new.', + ], + 'parent' => [ + 'old' => [ + 'id' => 0, + 'name' => '', + ], + 'new' => [ + 'id' => $parent, + 'name' => 'Company', + ], + ], + ], + $events[0]['data']['changes'] + ); + } + + public function test_saving_a_term_unchanged_sends_nothing(): void { + $term = $this->make_term( 'Updates' ); + + wp_update_term( $term, 'category', [ 'name' => 'Updates' ] ); + $this->end_request(); + + $this->assertSame( [], $this->run_jobs() ); + } + + public function test_a_deleted_term_says_how_many_posts_had_it(): void { + $term = $this->make_term( 'Old tag', 'post_tag' ); + $ids = $this->make_posts( 3, [ 'tags_input' => [ 'Old tag' ] ] ); + $this->assertCount( 3, $ids ); + + wp_delete_term( $term, 'post_tag' ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'TermDeleted' ], self::types( $events ) ); + $this->assertSame( 'Old tag', $events[0]['data']['name'] ); + $this->assertSame( 3, $events[0]['data']['posts'] ); + } + + public function test_deleting_many_tags_is_one_row_with_every_tag(): void { + $ids = []; + for ( $i = 1; $i <= 12; $i++ ) { + $ids[] = $this->make_term( 'Tag ' . $i, 'post_tag' ); + } + + foreach ( $ids as $id ) { + wp_delete_term( $id, 'post_tag' ); + } + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'TermBulkAction' ], self::types( $events ) ); + $this->assertSame( [ 'deleted', 'post_tag', 'Tags', 12 ], [ $events[0]['data']['action'], $events[0]['data']['taxonomy'], $events[0]['data']['label'], $events[0]['data']['count'] ] ); + $this->assertSame( 'Tag 12', $events[0]['data']['terms'][11]['name'] ); + } + + public function test_a_tag_typed_while_saving_a_post_is_only_on_the_posts_row(): void { + [ $id ] = $this->make_posts( 1 ); + + wp_update_post( + [ + 'ID' => $id, + 'tags_input' => [ 'Brand new tag' ], + ] + ); + $new = get_term_by( 'name', 'Brand new tag', 'post_tag' ); + $this->terms[] = [ (int) $new->term_id, 'post_tag' ]; + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'PostSaved' ], self::types( $events ) ); + $this->assertSame( [ 'Brand new tag' ], $events[0]['data']['changes']['terms'][0]['added'] ?? null ); + } + + public function test_a_post_type_without_a_screen_is_not_reported_when_deleted(): void { + register_post_type( 'scanfully_internal', [ 'show_ui' => false ] ); + $id = wp_insert_post( + [ + 'post_title' => 'Internal', + 'post_type' => 'scanfully_internal', + 'post_status' => 'publish', + ] + ); + $this->end_request(); + $this->sent = []; + as_unschedule_all_actions( '', [], 'scanfully' ); + + wp_delete_post( $id, true ); + $this->end_request(); + + $this->assertSame( [], $this->run_jobs() ); + unregister_post_type( 'scanfully_internal' ); + } +} diff --git a/tests/Integration/FailedLoginsTest.php b/tests/Integration/FailedLoginsTest.php new file mode 100644 index 0000000..d705c1d --- /dev/null +++ b/tests/Integration/FailedLoginsTest.php @@ -0,0 +1,245 @@ + + */ + private array $users = []; + + /** + * Bodies sent to the failed logins endpoint. + * + * @var array> + */ + private array $sent = []; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'wp_signon' ) || ! function_exists( 'as_get_scheduled_actions' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + + update_option( 'scanfully_connect_is_connected', 'yes' ); + Store::delete_all(); + Counter::reset(); + as_unschedule_all_actions( '', [], 'scanfully' ); + add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 3 ); + } + + protected function tearDown(): void { + if ( function_exists( 'wp_delete_user' ) ) { + require_once ABSPATH . 'wp-admin/includes/user.php'; + remove_filter( 'pre_http_request', [ $this, 'capture_request' ], 10 ); + remove_all_filters( 'application_password_is_api_request' ); + remove_filter( 'send_auth_cookies', '__return_false' ); + foreach ( $this->users as $id ) { + wp_delete_user( $id ); + } + Store::delete_all(); + Counter::reset(); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( 'scanfully_connect_is_connected' ); + } + parent::tearDown(); + } + + /** + * `pre_http_request`: keep what is sent to the failed logins endpoint and accept it. + * + * @param mixed $preempt Whether to preempt the request. + * @param array $args The request arguments. + * @param string $url The URL. + * + * @return mixed + */ + public function capture_request( $preempt, $args, $url ) { + if ( false === strpos( (string) $url, '/logins/failed' ) ) { + return $preempt; + } + $this->sent[] = json_decode( (string) ( $args['body'] ?? '' ), true ); + + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 204, + 'message' => 'No Content', + ], + 'cookies' => [], + ]; + } + + /** + * A user with a role. + * + * @param string $role The role. + * + * @return \WP_User + */ + private function user( string $role ): \WP_User { + $login = 'scanfully_lf_' . $role . '_' . wp_generate_password( 6, false ); + $id = wp_insert_user( + [ + 'user_login' => $login, + 'user_pass' => 'right-password-123', + 'user_email' => $login . '@scanfully.com', + 'display_name' => ucfirst( $role ) . ' Tester', + 'role' => $role, + ] + ); + $this->users[] = $id; + + return get_userdata( $id ); + } + + /** + * Fail a login, as a new request would. + * + * @param string $login The login. + * @param string $password The password. + * + * @return void + */ + private function fail_login( string $login, string $password = 'wrong' ): void { + Counter::reset(); + $result = wp_signon( + [ + 'user_login' => $login, + 'user_password' => $password, + ] + ); + $this->assertInstanceOf( \WP_Error::class, $result ); + } + + /** + * The counters of this hour. + * + * @return array + */ + private function counters(): array { + return Store::hours_before( Store::hour() + 1 )[ Store::hour() ] ?? []; + } + + public function test_wrong_passwords_and_unknown_accounts_are_counted_by_reason(): void { + $admin = $this->user( 'administrator' ); + $customer = $this->user( 'subscriber' ); + + $this->fail_login( $admin->user_login ); + $this->fail_login( $admin->user_email ); + $this->fail_login( $customer->user_login ); + $this->fail_login( 'nobody-' . wp_generate_password( 6, false ) ); + $this->fail_login( '' ); + + $counters = $this->counters(); + $this->assertSame( 4, $counters['total'], 'WordPress does not report an empty login as failed.' ); + $this->assertSame( 3, $counters['r_wrong_password'] ); + $this->assertSame( 1, $counters['r_unknown_account'] ); + $this->assertSame( 2, $counters[ 'u_' . $admin->ID ] ); + $this->assertArrayNotHasKey( 'u_' . $customer->ID, $counters, 'Only accounts with elevated rights are named.' ); + $this->assertSame( 4, $counters['c_other'], 'Not the login page, XML-RPC or an application password.' ); + } + + public function test_a_wrong_application_password_is_counted_once(): void { + $admin = $this->user( 'administrator' ); + add_filter( 'application_password_is_api_request', '__return_true' ); + + Counter::reset(); + $result = wp_authenticate( $admin->user_login, 'abcd efgh ijkl mnop qrst uvwx' ); + + $this->assertInstanceOf( \WP_Error::class, $result ); + $counters = $this->counters(); + $this->assertSame( 1, $counters['total'] ); + $this->assertSame( 1, $counters['c_app_password'] ); + $this->assertSame( 1, $counters[ 'u_' . $admin->ID ] ); + } + + public function test_the_hourly_job_sends_finished_hours_and_removes_them(): void { + $admin = $this->user( 'administrator' ); + $hour = Store::hour() - 1; + Store::increment( [ 'total', 'r_wrong_password', 'c_login_page', 'u_' . $admin->ID ], $hour ); + Store::increment( [ 'total', 'r_wrong_password', 'c_login_page', 'u_' . $admin->ID ], $hour ); + Store::increment( [ 'total', 'r_blocked', 'c_xmlrpc' ], $hour ); + Store::increment( [ 'total' ], Store::hour() ); + + Reporter::send(); + + $this->assertCount( 1, $this->sent ); + $sent = $this->sent[0]['hours'][0]; + $this->assertSame( 3, $sent['total'] ); + $this->assertSame( 2, $sent['reasons']['wrong_password'] ); + $this->assertSame( 1, $sent['reasons']['blocked'] ); + $this->assertSame( 1, $sent['channels']['xmlrpc'] ); + $this->assertSame( $admin->ID, $sent['accounts'][0]['id'] ); + $this->assertSame( 'Administrator Tester', $sent['accounts'][0]['name'] ); + $this->assertSame( 2, $sent['accounts'][0]['count'] ); + $this->assertArrayNotHasKey( 'email', $sent['accounts'][0] ); + $this->assertSame( [ Store::hour() ], array_keys( Store::hours_before( Store::hour() + 1 ) ), 'The finished hour is removed, the current one kept.' ); + } + + public function test_a_login_after_wrong_passwords_says_how_many(): void { + $admin = $this->user( 'administrator' ); + $this->fail_login( $admin->user_login ); + $this->fail_login( $admin->user_login ); + $this->fail_login( $admin->user_login ); + + add_filter( 'send_auth_cookies', '__return_false' ); + $user = wp_signon( + [ + 'user_login' => $admin->user_login, + 'user_password' => 'right-password-123', + ] + ); + $this->assertInstanceOf( \WP_User::class, $user ); + + $logins = array_values( + array_filter( + array_map( + static fn( $action ) => $action->get_args(), + as_get_scheduled_actions( + [ + 'hook' => EventsController::ACTION_SEND_EVENT, + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + ] + ) + ), + static fn( array $args ) => 'UserLogin' === ( $args['type'] ?? '' ) + ) + ); + $this->assertCount( 1, $logins ); + $this->assertSame( 3, $logins[0]['data']['failed_before'] ); + } + + public function test_counting_is_atomic_in_the_real_options_table(): void { + $hour = Store::hour() - 3; + for ( $i = 0; $i < 25; $i++ ) { + Store::increment( [ 'total' ], $hour ); + } + + $this->assertSame( 25, Store::count( 'total', $hour ) ); + $this->assertFalse( wp_load_alloptions()[ 'scanfully_lf_' . $hour . '_total' ] ?? false, 'Counters are never autoloaded.' ); + } +} diff --git a/tests/Integration/FileEditTest.php b/tests/Integration/FileEditTest.php new file mode 100644 index 0000000..8b30e9b --- /dev/null +++ b/tests/Integration/FileEditTest.php @@ -0,0 +1,311 @@ +> + */ + private array $sent = []; + + /** + * The signed-in user before the test. + * + * @var int + */ + private int $user = 0; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'as_get_scheduled_actions' ) || ! function_exists( 'wp_insert_post' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + if ( defined( 'DISALLOW_FILE_EDIT' ) && DISALLOW_FILE_EDIT ) { + $this->markTestSkipped( 'The file editors are turned off on this site.' ); + } + + require_once ABSPATH . 'wp-admin/includes/file.php'; + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + require_once ABSPATH . 'wp-admin/includes/theme.php'; + + update_option( 'scanfully_connect_is_connected', 'yes' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + Collector::reset(); + $this->sent = []; + $this->user = get_current_user_id(); + wp_set_current_user( 1 ); + add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 3 ); + + $this->write( WP_PLUGIN_DIR . '/' . self::PLUGIN . '/' . self::PLUGIN . '.php', "write( WP_PLUGIN_DIR . '/' . self::PLUGIN . '/readme.txt', "=== Scanfully File Edit Test ===\nFirst line\nSecond line\nThird line\n" ); + $this->write( get_theme_root() . '/' . self::THEME . '/style.css', "/*\nTheme Name: Scanfully File Edit Test Theme\n*/\nbody {\n\tcolor: black;\n}\n" ); + $this->write( get_theme_root() . '/' . self::THEME . '/index.php', "remove_folder( WP_PLUGIN_DIR . '/' . self::PLUGIN ); + $this->remove_folder( get_theme_root() . '/' . self::THEME ); + wp_clean_plugins_cache( false ); + wp_clean_themes_cache( false ); + Collector::reset(); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( 'scanfully_connect_is_connected' ); + wp_set_current_user( $this->user ); + } + parent::tearDown(); + } + + /** + * Write a test file. + * + * @param string $path The file. + * @param string $content The content. + * + * @return void + */ + private function write( string $path, string $content ): void { + if ( ! is_dir( dirname( $path ) ) ) { + mkdir( dirname( $path ), 0777, true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir -- A test plugin or theme. + } + file_put_contents( $path, $content ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- A test plugin or theme. + } + + /** + * Remove a test plugin or theme folder. + * + * @param string $folder The folder. + * + * @return void + */ + private function remove_folder( string $folder ): void { + foreach ( glob( $folder . '/*' ) ?: [] as $file ) { // phpcs:ignore Universal.Operators.DisallowShortTernary.Found -- glob() returns false on an error. + unlink( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- A test plugin or theme. + } + if ( is_dir( $folder ) ) { + rmdir( $folder ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- A test plugin or theme. + } + } + + /** + * `pre_http_request`: keep the event sent to the API and accept it. + * + * @param mixed $preempt Whether to preempt the request. + * @param array $args The request arguments. + * @param string $url The URL. + * + * @return mixed + */ + public function capture_request( $preempt, $args, $url ) { + if ( false === strpos( (string) $url, '/timeline' ) ) { + return $preempt; + } + + $this->sent[] = json_decode( (string) ( $args['body'] ?? '' ), true ); + + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 202, + 'message' => 'Accepted', + ], + 'cookies' => [], + ]; + } + + /** + * Save a file as the editor does: note it, let WordPress save it, end + * the request. + * + * @param array $args The posted fields. + * + * @return true|\WP_Error What WordPress returned. + */ + private function save( array $args ) { + Collector::note( $args ); + $result = wp_edit_theme_plugin_file( $args ); + Collector::flush(); + + return $result; + } + + /** + * Run the pending event jobs and return the events sent: type and data. + * + * @return array> + */ + private function run_jobs(): array { + $actions = as_get_scheduled_actions( + [ + 'hook' => EventsController::ACTION_BUILD_CONTENT_EVENT, + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + ] + ); + foreach ( $actions as $action ) { + do_action_ref_array( EventsController::ACTION_BUILD_CONTENT_EVENT, array_values( $action->get_args() ) ); + } + + return $this->sent; + } + + /** + * The fields the plugin editor posts for a file of the test plugin. + * + * @param string $file The file, relative to the plugin folder. + * @param string $content The new content. + * + * @return array + */ + private function plugin_save( string $file, string $content ): array { + $path = self::PLUGIN . '/' . $file; + + return [ + 'file' => $path, + 'plugin' => self::PLUGIN . '/' . self::PLUGIN . '.php', + 'newcontent' => $content, + 'nonce' => wp_create_nonce( 'edit-plugin_' . $path ), + ]; + } + + public function test_a_plugin_file_edit_is_sent_with_a_diff(): void { + $result = $this->save( $this->plugin_save( 'readme.txt', "=== Scanfully File Edit Test ===\nFirst line\nSecond line, edited\nThird line\n" ) ); + $this->assertTrue( $result ); + + $sent = $this->run_jobs(); + + $this->assertCount( 1, $sent ); + $this->assertSame( 'PluginFileEdited', $sent[0]['type'] ); + $this->assertSame( 'Scanfully File Edit Test', $sent[0]['data']['name'] ); + $this->assertSame( self::PLUGIN . '/' . self::PLUGIN . '.php', $sent[0]['data']['slug'] ); + $this->assertSame( self::PLUGIN . '/readme.txt', $sent[0]['data']['file'] ); + $content = $sent[0]['data']['changes']['content']; + $this->assertSame( 1, $content['added'] ); + $this->assertSame( 1, $content['removed'] ); + $this->assertContains( + [ + 'op' => '-', + 'text' => 'Second line', + ], + $content['lines'] + ); + $this->assertContains( + [ + 'op' => '+', + 'text' => 'Second line, edited', + ], + $content['lines'] + ); + } + + public function test_a_theme_file_edit_is_sent_with_a_diff(): void { + $file = 'style.css'; + $result = $this->save( + [ + 'file' => $file, + 'theme' => self::THEME, + 'newcontent' => "/*\nTheme Name: Scanfully File Edit Test Theme\n*/\nbody {\n\tcolor: red;\n}\n", + 'nonce' => wp_create_nonce( 'edit-theme_' . self::THEME . '_' . $file ), + ] + ); + $this->assertTrue( $result ); + + $sent = $this->run_jobs(); + + $this->assertCount( 1, $sent ); + $this->assertSame( 'ThemeFileEdited', $sent[0]['type'] ); + $this->assertSame( 'Scanfully File Edit Test Theme', $sent[0]['data']['name'] ); + $this->assertSame( self::THEME, $sent[0]['data']['slug'] ); + $this->assertSame( 'style.css', $sent[0]['data']['file'] ); + $this->assertContains( + [ + 'op' => '+', + 'text' => "\tcolor: red;", + ], + $sent[0]['data']['changes']['content']['lines'] + ); + } + + public function test_the_editor_ajax_save_is_followed_before_wordpress_saves(): void { + $this->assertSame( 0, has_action( 'wp_ajax_edit-theme-plugin-file', [ Collector::class, 'note_ajax_save' ] ), 'Before the handler WordPress runs at priority 1.' ); + + $args = $this->plugin_save( 'readme.txt', "=== Scanfully File Edit Test ===\nChanged through AJAX\n" ); + $_POST = wp_slash( $args ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- The request the editor sends. + Collector::note_ajax_save(); + $_POST = []; + $this->assertTrue( wp_edit_theme_plugin_file( $args ) ); + Collector::flush(); + + $sent = $this->run_jobs(); + + $this->assertCount( 1, $sent ); + $this->assertSame( 1, $sent[0]['data']['changes']['content']['added'] ); + $this->assertSame( 3, $sent[0]['data']['changes']['content']['removed'] ); + } + + public function test_a_save_wordpress_refuses_sends_nothing(): void { + $args = $this->plugin_save( 'readme.txt', 'Changed' ); + $args['nonce'] = 'not-a-nonce'; + + $this->assertInstanceOf( \WP_Error::class, $this->save( $args ) ); + $this->assertSame( [], $this->run_jobs() ); + } + + public function test_saving_the_same_content_sends_nothing(): void { + $this->assertTrue( $this->save( $this->plugin_save( 'readme.txt', "=== Scanfully File Edit Test ===\nFirst line\nSecond line\nThird line\n" ) ) ); + + $this->assertSame( [], $this->run_jobs() ); + } + + public function test_a_user_who_may_not_edit_plugins_is_not_followed(): void { + $subscriber = wp_insert_user( + [ + 'user_login' => 'scanfully_file_edit_subscriber', + 'user_pass' => wp_generate_password(), + 'user_email' => 'file-edit-subscriber@scanfully.com', + 'role' => 'subscriber', + ] + ); + $this->assertIsInt( $subscriber ); + wp_set_current_user( $subscriber ); + + Collector::note( $this->plugin_save( 'readme.txt', 'Changed' ) ); + // The file changes some other way during the request. + $this->write( WP_PLUGIN_DIR . '/' . self::PLUGIN . '/readme.txt', 'Changed' ); + Collector::flush(); + + wp_set_current_user( 1 ); + require_once ABSPATH . 'wp-admin/includes/user.php'; + wp_delete_user( $subscriber ); + + $this->assertSame( [], $this->run_jobs() ); + } +} diff --git a/tests/Integration/MediaEventsTest.php b/tests/Integration/MediaEventsTest.php new file mode 100644 index 0000000..aebe299 --- /dev/null +++ b/tests/Integration/MediaEventsTest.php @@ -0,0 +1,640 @@ + + */ + private array $posts = []; + + /** + * Event bodies sent to the API. + * + * @var array> + */ + private array $sent = []; + + /** + * The signed-in user before the test. + * + * @var int + */ + private int $user = 0; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'as_get_scheduled_actions' ) || ! function_exists( 'wp_insert_post' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + + require_once ABSPATH . 'wp-admin/includes/file.php'; + require_once ABSPATH . 'wp-admin/includes/media.php'; + require_once ABSPATH . 'wp-admin/includes/image.php'; + require_once ABSPATH . 'wp-admin/includes/image-edit.php'; + + update_option( 'scanfully_connect_is_connected', 'yes' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + self::clear_minute_store(); + Collector::reset(); + TermCollector::reset(); + MediaCollector::reset(); + $this->sent = []; + $this->user = get_current_user_id(); + wp_set_current_user( 1 ); + add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 3 ); + add_filter( 'scanfully_post_saved_events_per_minute', '__return_zero' ); + add_filter( 'scanfully_media_events_per_minute', '__return_zero' ); + } + + protected function tearDown(): void { + if ( function_exists( 'wp_delete_post' ) ) { + remove_filter( 'pre_http_request', [ $this, 'capture_request' ], 10 ); + remove_all_filters( 'scanfully_post_saved_events_per_minute' ); + remove_all_filters( 'scanfully_media_events_per_minute' ); + foreach ( array_reverse( $this->posts ) as $id ) { + wp_delete_post( $id, true ); + } + Collector::reset(); + TermCollector::reset(); + MediaCollector::reset(); + self::clear_minute_store(); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( 'scanfully_connect_is_connected' ); + wp_set_current_user( $this->user ); + $_REQUEST = []; + } + parent::tearDown(); + } + + /** + * Remove what earlier runs left in the minute store, with the markers + * that say a minute's job is scheduled (the tests unschedule the jobs). + * + * @return void + */ + private static function clear_minute_store(): void { + global $wpdb; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Test cleanup. + $names = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", $wpdb->esc_like( 'scanfully_minute_' ) . '%', $wpdb->esc_like( '_transient_scanfully_minute_' ) . '%' ) ); + foreach ( $names as $name ) { + if ( 0 === strpos( $name, '_transient_' ) ) { + delete_transient( substr( $name, strlen( '_transient_' ) ) ); + } else { + delete_option( $name ); + } + } + } + + /** + * Wait until the minute has at least 15 seconds left, so the requests of + * a test land in one minute, as they would when someone works quickly. + * + * @return void + */ + private static function start_of_minute(): void { + $second = (int) gmdate( 's' ); + if ( $second >= 45 ) { + sleep( 61 - $second ); + } + } + + /** + * `pre_http_request`: keep the event sent to the API and accept it. + * + * @param mixed $preempt Whether to preempt the request. + * @param array $args The request arguments. + * @param string $url The URL. + * + * @return mixed + */ + public function capture_request( $preempt, $args, $url ) { + if ( false === strpos( (string) $url, '/timeline' ) ) { + return $preempt; + } + + $this->sent[] = json_decode( (string) ( $args['body'] ?? '' ), true ); + + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 202, + 'message' => 'Accepted', + ], + 'cookies' => [], + ]; + } + + /** + * End the "request": what the collectors do at `shutdown`. + * + * @return void + */ + private function end_request(): void { + Collector::flush(); + TermCollector::flush(); + MediaCollector::flush(); + } + + /** + * Forget the events of the setup of a test. + * + * @return void + */ + private function forget(): void { + $this->end_request(); + self::clear_minute_store(); + as_unschedule_all_actions( '', [], 'scanfully' ); + $this->sent = []; + } + + /** + * Run the pending event jobs, as Action Scheduler would, until none is + * left, and return the events sent: type and data. + * + * @return array}> + */ + private function run_jobs(): array { + $hooks = [ EventsController::ACTION_BUILD_POST_EVENT, EventsController::ACTION_BUILD_CONTENT_EVENT, EventsController::ACTION_SEND_EVENT, EventsController::ACTION_SEND_OVERFLOW, EventsController::ACTION_SEND_MEDIA ]; + for ( $round = 0; $round < 5; $round++ ) { + $actions = as_get_scheduled_actions( + [ + 'hook__in' => $hooks, + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + 'orderby' => 'none', + ] + ); + if ( [] === $actions ) { + break; + } + foreach ( $actions as $id => $action ) { + \ActionScheduler::store()->mark_complete( $id ); + do_action_ref_array( $action->get_hook(), array_values( $action->get_args() ) ); + } + } + + return array_map( + static fn( array $body ): array => [ + 'type' => (string) $body['type'], + 'data' => (array) $body['data'], + ], + $this->sent + ); + } + + /** + * The types of the events sent. + * + * @param array}> $events The events. + * + * @return array + */ + private static function types( array $events ): array { + return array_column( $events, 'type' ); + } + + /** + * A post files can belong to, made in an earlier "request". + * + * @param string $title The title. + * + * @return int + */ + private function make_post( string $title = 'About us' ): int { + $id = wp_insert_post( + [ + 'post_title' => $title, + 'post_type' => 'page', + 'post_status' => 'publish', + ] + ); + + $this->posts[] = $id; + + return $id; + } + + /** + * Upload a JPEG the way the media library does, to the post given. + * + * @param string $name The file name. + * @param int $parent_id The post it is uploaded to. + * @param int $width The width. + * @param int $height The height. + * + * @return int The attachment ID. + */ + private function upload( string $name, int $parent_id = 0, int $width = 640, int $height = 480 ): int { + $tmp = wp_tempnam( $name ); + $image = imagecreatetruecolor( $width, $height ); + imagefill( $image, 0, 0, (int) imagecolorallocate( $image, 30, 120, 200 ) ); + imagejpeg( $image, $tmp ); + imagedestroy( $image ); + + $id = media_handle_sideload( + [ + 'name' => $name, + 'tmp_name' => $tmp, + ], + $parent_id + ); + $this->assertIsInt( $id, is_wp_error( $id ) ? $id->get_error_message() : '' ); + $this->posts[] = $id; + + return $id; + } + + public function test_an_upload_is_one_row_with_the_file_as_it_is_a_minute_later(): void { + self::start_of_minute(); + $page = $this->make_post(); + $this->forget(); + + $id = $this->upload( 'team-photo.jpg', $page ); + $this->end_request(); + // The alt text, saved in its own request right after. + update_post_meta( $id, '_wp_attachment_image_alt', 'The team' ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'MediaUploaded' ], self::types( $events ) ); + $data = $events[0]['data']; + $this->assertSame( $id, $data['id'] ); + $this->assertSame( 'team-photo.jpg', $data['name'] ); + $this->assertMatchesRegularExpression( '#^\d{4}/\d{2}/team-photo\.jpg$#', $data['file'] ); + $this->assertSame( 'team-photo', $data['title'] ); + $this->assertSame( 'image/jpeg', $data['mime_type'] ); + $this->assertSame( [ 640, 480 ], [ $data['width'], $data['height'] ] ); + $this->assertGreaterThan( 0, $data['filesize'] ); + $this->assertSame( + [ + 'id' => $page, + 'title' => 'About us', + 'type_label' => 'Page', + ], + $data['parent'] + ); + } + + public function test_a_big_image_wordpress_scales_is_still_one_upload(): void { + self::start_of_minute(); + + // WordPress scales images over 2560 pixels; a lower threshold takes + // the same path with less memory. + $threshold = static fn(): int => 1000; + add_filter( 'big_image_size_threshold', $threshold ); + + $id = $this->upload( 'poster.jpg', 0, 1200, 800 ); + remove_filter( 'big_image_size_threshold', $threshold ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'MediaUploaded' ], self::types( $events ) ); + $this->assertSame( 'poster-scaled.jpg', $events[0]['data']['name'] ); + $this->assertSame( $id, $events[0]['data']['id'] ); + } + + public function test_details_saved_field_by_field_are_one_change(): void { + self::start_of_minute(); + $id = $this->upload( 'photo.jpg' ); + $title = get_post( $id )->post_title; + $this->forget(); + + // The grid view saves each field in its own request. + wp_update_post( + [ + 'ID' => $id, + 'post_title' => 'Team photo', + ] + ); + $this->end_request(); + update_post_meta( $id, '_wp_attachment_image_alt', 'The team & friends' ); + $this->end_request(); + wp_update_post( + [ + 'ID' => $id, + 'post_excerpt' => 'Our team in 2026', + ] + ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'MediaChanged' ], self::types( $events ) ); + $this->assertSame( + [ + 'title' => [ + 'old' => $title, + 'new' => 'Team photo', + ], + 'alt' => [ + 'old' => '', + 'new' => 'The team & friends', + ], + 'caption' => [ + 'old' => '', + 'new' => 'Our team in 2026', + ], + ], + $events[0]['data']['changes'] + ); + } + + public function test_saving_the_details_unchanged_sends_nothing(): void { + $id = $this->upload( 'photo.jpg' ); + $this->forget(); + + wp_update_post( + [ + 'ID' => $id, + 'post_title' => get_post( $id )->post_title, + ] + ); + $this->end_request(); + + $this->assertSame( [], $this->run_jobs() ); + } + + public function test_an_image_editor_save_and_restore(): void { + self::start_of_minute(); + $id = $this->upload( 'photo.jpg' ); + $this->forget(); + + $_REQUEST = [ + 'action' => 'image-editor', + 'do' => 'save', + 'postid' => (string) $id, + 'history' => '[{"r":90},{"f":1}]', + 'target' => 'all', + 'context' => '', + ]; + MediaCollector::note_image_editor(); + $saved = wp_save_image( $id ); + $this->assertTrue( empty( $saved->error ), (string) ( $saved->error ?? '' ) ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'MediaChanged' ], self::types( $events ) ); + $this->assertSame( + [ + 'image' => [ + 'edits' => [ 'rotate', 'flip' ], + 'target' => 'all', + ], + ], + $events[0]['data']['changes'], + 'The editor\'s new file name is part of the edit, not a change of its own.' + ); + + $this->sent = []; + $_REQUEST = [ + 'action' => 'image-editor', + 'do' => 'restore', + 'postid' => (string) $id, + ]; + MediaCollector::note_image_editor(); + wp_restore_image( $id ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'MediaChanged' ], self::types( $events ) ); + $this->assertSame( [ 'image' => [ 'restored' => true ] ], $events[0]['data']['changes'] ); + } + + public function test_the_block_editors_edited_copy_names_the_original(): void { + self::start_of_minute(); + $id = $this->upload( 'photo.jpg' ); + $this->forget(); + + $request = new \WP_REST_Request( 'POST', '/wp/v2/media/' . $id . '/edit' ); + $request->set_param( 'src', wp_get_attachment_image_url( $id, 'full' ) ); + $request->set_param( + 'modifiers', + [ + [ + 'type' => 'rotate', + 'args' => [ 'angle' => 90 ], + ], + ] + ); + $response = rest_do_request( $request ); + $this->assertSame( 201, $response->get_status(), (string) wp_json_encode( $response->get_data() ) ); + $copy = (int) $response->get_data()['id']; + $this->posts[] = $copy; + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'MediaUploaded' ], self::types( $events ) ); + $this->assertSame( $copy, $events[0]['data']['id'] ); + $this->assertSame( + [ + 'id' => $id, + 'name' => wp_basename( (string) get_attached_file( $id ) ), + ], + $events[0]['data']['edited_from'] + ); + $this->assertSame( [ 'rotate' ], $events[0]['data']['edits'] ); + } + + public function test_a_file_swapped_by_the_browser_after_an_upload_is_no_change(): void { + $id = $this->upload( 'photo.jpg' ); + $this->forget(); + + // WordPress 7.0's client-side processing sends the scaled file later. + $request = new \WP_REST_Request( 'POST', '/wp/v2/media/' . $id . '/sideload' ); + apply_filters( 'rest_request_before_callbacks', null, [], $request ); + update_attached_file( $id, str_replace( 'photo.jpg', 'photo-big.jpg', (string) get_attached_file( $id ) ) ); + apply_filters( 'rest_request_after_callbacks', null, [], $request ); + $this->end_request(); + + $this->assertSame( [], $this->run_jobs() ); + } + + public function test_attaching_in_the_list_view(): void { + self::start_of_minute(); + $page = $this->make_post( 'Contact' ); + $id = $this->upload( 'map.jpg' ); + $this->forget(); + + // What wp_media_attach_action() does before it redirects. + global $wpdb; + get_post( $id ); + $wpdb->update( $wpdb->posts, [ 'post_parent' => $page ], [ 'ID' => $id ] ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- As WordPress does it. + do_action( 'wp_media_attach_action', 'attach', $id, $page ); + clean_attachment_cache( $id ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'MediaChanged' ], self::types( $events ) ); + $this->assertSame( + [ + 'old' => [ + 'id' => 0, + 'title' => '', + ], + 'new' => [ + 'id' => $page, + 'title' => 'Contact', + 'type_label' => 'Page', + ], + ], + $events[0]['data']['changes']['parent'] + ); + } + + public function test_trash_and_restore(): void { + self::start_of_minute(); + $id = $this->upload( 'photo.jpg' ); + $this->forget(); + + wp_trash_post( $id ); + $this->end_request(); + $events = $this->run_jobs(); + $this->assertSame( [ 'MediaChanged' ], self::types( $events ) ); + $this->assertSame( + [ + 'status' => [ + 'old' => 'inherit', + 'new' => 'trash', + ], + ], + $events[0]['data']['changes'] + ); + + $this->sent = []; + wp_untrash_post( $id ); + $this->end_request(); + $events = $this->run_jobs(); + $this->assertSame( [ 'status' ], array_keys( $events[0]['data']['changes'] ?? [] ) ); + $this->assertSame( 'trash', $events[0]['data']['changes']['status']['old'] ?? null ); + } + + public function test_a_file_trashed_and_deleted_by_someone_else_before_the_job_keeps_its_name(): void { + self::start_of_minute(); + $id = $this->upload( 'brochure.jpg' ); + $this->forget(); + + wp_trash_post( $id ); + $this->end_request(); + // Someone else deletes it before the minute's job runs. + wp_set_current_user( 0 ); + wp_delete_attachment( $id, true ); + $this->end_request(); + wp_set_current_user( 1 ); + $events = array_column( $this->run_jobs(), 'data', 'type' ); + + $this->assertSame( [ 'MediaChanged', 'MediaDeleted' ], array_keys( $events ) ); + $trashed = $events['MediaChanged']; + $this->assertSame( [ 'brochure.jpg', 'brochure', 'image/jpeg' ], [ $trashed['name'], $trashed['title'], $trashed['mime_type'] ] ); + $this->assertSame( 'trash', $trashed['changes']['status']['new'] ); + } + + public function test_deleting_a_featured_image_says_how_many_posts_had_it(): void { + self::start_of_minute(); + $id = $this->upload( 'header.jpg' ); + $posts = [ $this->make_post( 'A' ), $this->make_post( 'B' ), $this->make_post( 'C' ) ]; + foreach ( $posts as $post ) { + set_post_thumbnail( $post, $id ); + } + $this->forget(); + + wp_delete_attachment( $id, true ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'MediaDeleted' ], self::types( $events ) ); + $data = $events[0]['data']; + $this->assertSame( [ 'header.jpg', 'header', 'image/jpeg', 'inherit', 3 ], [ $data['name'], $data['title'], $data['mime_type'], $data['post_status'], $data['featured_on'] ] ); + $this->assertSame( [ 640, 480 ], [ $data['width'], $data['height'] ] ); + $this->assertArrayNotHasKey( 'expired', $data ); + } + + public function test_the_media_trash_wordpress_empties_itself_is_marked(): void { + $id = $this->upload( 'old.jpg' ); + wp_trash_post( $id ); + update_post_meta( $id, '_wp_trash_meta_time', time() - 40 * DAY_IN_SECONDS ); + $this->forget(); + + do_action( 'wp_scheduled_delete' ); + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( [ 'MediaDeleted' ], self::types( $events ) ); + $this->assertTrue( $events[0]['data']['expired'] ); + $this->assertSame( 'trash', $events[0]['data']['post_status'] ); + } + + public function test_a_grid_delete_of_twelve_files_one_request_each_is_one_row(): void { + self::start_of_minute(); + $ids = []; + for ( $i = 1; $i <= 12; $i++ ) { + $ids[] = $this->upload( 'bulk-' . $i . '.jpg', 0, 64, 64 ); + } + $this->forget(); + + foreach ( $ids as $id ) { + wp_delete_attachment( $id, true ); + $this->end_request(); + } + $events = $this->run_jobs(); + + $this->assertSame( [ 'MediaBulkAction' ], self::types( $events ) ); + $data = $events[0]['data']; + $this->assertSame( [ 'deleted', 12 ], [ $data['action'], $data['count'] ] ); + $this->assertSame( $ids, array_column( $data['files'], 'id' ) ); + $this->assertSame( 'bulk-12.jpg', $data['files'][11]['name'] ); + } + + public function test_an_upload_deleted_within_the_minute_is_nothing(): void { + self::start_of_minute(); + + $id = $this->upload( 'oops.jpg' ); + $this->end_request(); + wp_delete_attachment( $id, true ); + $this->end_request(); + + $this->assertSame( [], $this->run_jobs() ); + } + + public function test_a_replace_through_enable_media_replace(): void { + // Enable Media Replace is not installed here; it fires this hook + // once it replaced the file, under the same name by default. + $id = $this->upload( 'logo.jpg' ); + $this->forget(); + do_action( 'enable-media-replace-upload-done', 'https://scanfully.com/wp-content/uploads/logo.jpg', 'https://scanfully.com/wp-content/uploads/logo.jpg', $id ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- Enable Media Replace's hook. + $this->end_request(); + $events = $this->run_jobs(); + + $this->assertSame( + [ + 'old' => 'logo.jpg', + 'new' => 'logo.jpg', + 'replaced' => true, + ], + $events[0]['data']['changes']['file'] ?? null + ); + } +} diff --git a/tests/Integration/MenuEventsTest.php b/tests/Integration/MenuEventsTest.php new file mode 100644 index 0000000..9f2c627 --- /dev/null +++ b/tests/Integration/MenuEventsTest.php @@ -0,0 +1,724 @@ + + */ + private array $menus = []; + + /** + * Posts created by a test. + * + * @var array + */ + private array $posts = []; + + /** + * Event bodies sent to the API. + * + * @var array> + */ + private array $sent = []; + + /** + * The menu locations before the test. + * + * @var mixed + */ + private $locations; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'as_get_scheduled_actions' ) || ! function_exists( 'wp_create_nav_menu' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + // A theme switched by an earlier test of this run counts for the + // whole process; in a site it is a request of its own. + unset( $GLOBALS['wp_actions']['switch_theme'] ); + require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; + + update_option( 'scanfully_connect_is_connected', 'yes' ); + register_nav_menus( + [ + 'scanfully-primary' => 'Primary', + 'scanfully-footer' => 'Footer', + ] + ); + $this->locations = get_theme_mod( 'nav_menu_locations' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + $this->reset_collectors(); + $this->sent = []; + wp_set_current_user( 1 ); + add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 3 ); + add_filter( 'scanfully_menu_events_per_minute', '__return_zero' ); + add_filter( 'scanfully_post_saved_events_per_minute', '__return_zero' ); + unset( $_SERVER['REQUEST_METHOD'] ); + } + + protected function tearDown(): void { + if ( function_exists( 'wp_delete_nav_menu' ) ) { + foreach ( $this->menus as $id ) { + wp_delete_nav_menu( $id ); + } + foreach ( $this->posts as $id ) { + wp_delete_post( $id, true ); + } + set_theme_mod( 'nav_menu_locations', $this->locations ); + unregister_nav_menu( 'scanfully-primary' ); + unregister_nav_menu( 'scanfully-footer' ); + remove_filter( 'pre_http_request', [ $this, 'capture_request' ], 10 ); + remove_all_filters( 'scanfully_menu_events_per_minute' ); + remove_all_filters( 'scanfully_post_saved_events_per_minute' ); + $_POST = []; + unset( $_SERVER['REQUEST_METHOD'] ); + $this->reset_collectors(); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( 'scanfully_connect_is_connected' ); + wp_set_current_user( 0 ); + } + parent::tearDown(); + } + + /** + * Forget what every collector noted. + * + * @return void + */ + private function reset_collectors(): void { + Collector::reset(); + PostCollector::reset(); + TermCollector::reset(); + SettingsCollector::reset(); + } + + /** + * `pre_http_request`: keep the event sent to the API and accept it. + * + * @param mixed $preempt Whether to preempt the request. + * @param array $args The request arguments. + * @param string $url The URL. + * + * @return mixed + */ + public function capture_request( $preempt, $args, $url ) { + if ( false === strpos( (string) $url, '/timeline' ) ) { + return $preempt; + } + + $this->sent[] = json_decode( (string) ( $args['body'] ?? '' ), true ); + + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 202, + 'message' => 'Accepted', + ], + 'cookies' => [], + ]; + } + + /** + * End the "request", run the jobs as Action Scheduler would, and return + * the menu events sent: type and data. + * + * @return array}> + */ + private function sent_menu_events(): array { + Collector::flush(); + PostCollector::flush(); + TermCollector::flush(); + SettingsCollector::flush(); + + $actions = as_get_scheduled_actions( + [ + 'hook__in' => [ EventsController::ACTION_BUILD_CONTENT_EVENT, EventsController::ACTION_BUILD_POST_EVENT, EventsController::ACTION_SEND_EVENT ], + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + 'orderby' => 'action_id', + 'order' => 'ASC', + ] + ); + foreach ( $actions as $id => $action ) { + \ActionScheduler::store()->mark_complete( $id ); + do_action_ref_array( $action->get_hook(), array_values( $action->get_args() ) ); + } + + $events = []; + foreach ( $this->sent as $body ) { + if ( 0 === strpos( (string) $body['type'], 'Menu' ) || 'PostSaved' === $body['type'] ) { + $events[] = [ + 'type' => (string) $body['type'], + 'data' => (array) $body['data'], + ]; + } + } + $this->sent = []; + + return $events; + } + + /** + * A classic menu with items made in an earlier "request". + * + * @param string $name The menu name. + * @param array $labels The labels of its custom link items. + * + * @return array{0: int, 1: array} The menu ID and the item IDs. + */ + private function make_menu( string $name, array $labels ): array { + $menu_id = wp_create_nav_menu( $name ); + $this->menus[] = $menu_id; + $items = []; + foreach ( $labels as $position => $label ) { + $items[] = wp_update_nav_menu_item( + $menu_id, + 0, + [ + 'menu-item-title' => $label, + 'menu-item-url' => 'https://scanfully.com/' . strtolower( $label ) . '/', + 'menu-item-type' => 'custom', + 'menu-item-status' => 'publish', + 'menu-item-position' => $position + 1, + ] + ); + } + $this->sent_menu_events(); + + return [ $menu_id, $items ]; + } + + /** + * Save a menu the way the Menus screen does: every item posted, the + * ones left out deleted. + * + * @param int $menu_id The menu ID. + * @param array> $items Per item ID, in the new order: the fields to change. + * + * @return void + */ + private function save_menu_screen( int $menu_id, array $items ): void { + $current = []; + foreach ( wp_get_nav_menu_items( $menu_id, [ 'post_status' => 'draft,publish' ] ) as $item ) { + $current[ (int) $item->db_id ] = $item; + } + + $_POST = []; + $position = 0; + foreach ( $items as $item_id => $fields ) { + $item = $current[ $item_id ]; + ++$position; + $posted = [ + 'menu-item-db-id' => $item_id, + 'menu-item-object-id' => $item->object_id, + 'menu-item-object' => $item->object, + 'menu-item-parent-id' => $item->menu_item_parent, + 'menu-item-position' => $position, + 'menu-item-type' => $item->type, + 'menu-item-title' => $item->post_title, + 'menu-item-url' => $item->url, + 'menu-item-description' => $item->description, + 'menu-item-attr-title' => $item->attr_title, + 'menu-item-target' => $item->target, + 'menu-item-classes' => implode( ' ', (array) $item->classes ), + 'menu-item-xfn' => $item->xfn, + ]; + foreach ( array_merge( $posted, $fields ) as $field => $value ) { + $_POST[ $field ][ $item_id ] = $value; + } + } + + wp_nav_menu_update_menu_items( $menu_id, 'Main menu' ); + $_POST = []; + } + + public function test_creating_a_menu_is_reported(): void { + $menu_id = wp_create_nav_menu( 'Main menu' ); + $this->menus[] = $menu_id; + + $this->assertSame( + [ + [ + 'type' => 'MenuCreated', + 'data' => [ + 'id' => $menu_id, + 'kind' => 'classic', + 'name' => 'Main menu', + 'items' => 0, + ], + ], + ], + $this->sent_menu_events() + ); + } + + public function test_renaming_a_menu_is_reported(): void { + [ $menu_id ] = $this->make_menu( 'Main menu', [] ); + + wp_update_nav_menu_object( $menu_id, [ 'menu-name' => 'Header menu' ] ); + + $events = $this->sent_menu_events(); + $this->assertSame( [ 'MenuChanged' ], array_column( $events, 'type' ) ); + $this->assertSame( + [ + 'old' => 'Main menu', + 'new' => 'Header menu', + ], + $events[0]['data']['changes']['name'] + ); + } + + public function test_the_first_auto_add_pages_setting_on_a_site_is_reported(): void { + [ $menu_id ] = $this->make_menu( 'Main menu', [] ); + $before = get_option( 'nav_menu_options' ); + // A site whose Menus screen was never saved has no such option yet: + // update_option() adds it. + delete_option( 'nav_menu_options' ); + + update_option( 'nav_menu_options', [ 'auto_add' => [ $menu_id ] ], false ); + $events = $this->sent_menu_events(); + + if ( false === $before ) { + delete_option( 'nav_menu_options' ); + } else { + update_option( 'nav_menu_options', $before, false ); + } + Collector::reset(); + + $this->assertSame( [ 'MenuChanged' ], array_column( $events, 'type' ) ); + $this->assertSame( $menu_id, $events[0]['data']['id'] ); + $this->assertSame( + [ + 'old' => false, + 'new' => true, + ], + $events[0]['data']['changes']['auto_add'] + ); + } + + public function test_a_menus_screen_save_reports_each_item_change_and_only_the_real_move(): void { + [ $menu_id, $items ] = $this->make_menu( 'Main menu', [ 'Home', 'Blog', 'Shop', 'About', 'Old' ] ); + [ $home, $blog, $shop, $about, $old ] = $items; + + // "Add to Menu" makes a draft item over admin-ajax first. + $contact = wp_update_nav_menu_item( + $menu_id, + 0, + [ + 'menu-item-title' => 'Contact', + 'menu-item-url' => 'https://scanfully.com/contact/', + 'menu-item-type' => 'custom', + 'menu-item-status' => 'draft', + ] + ); + $this->assertSame( [], $this->sent_menu_events(), 'A draft item is not on the menu yet.' ); + + // Save Menu: About moved to the top, Blog renamed, Shop under Home, + // Old removed, Contact saved. + $this->save_menu_screen( + $menu_id, + [ + $about => [], + $home => [], + $blog => [ 'menu-item-title' => 'News' ], + $shop => [ 'menu-item-parent-id' => $home ], + $contact => [], + ] + ); + + $events = $this->sent_menu_events(); + $this->assertSame( [ 'MenuChanged' ], array_column( $events, 'type' ) ); + $data = $events[0]['data']; + $changes = $data['changes']; + $this->assertSame( 'Main menu', $data['name'] ); + $this->assertSame( 5, $data['items'] ); + $this->assertSame( [ 'Contact' ], array_column( $changes['added'], 'label' ) ); + $this->assertSame( [ 'Old' ], array_column( $changes['removed'], 'label' ) ); + $this->assertSame( + [ + 'old' => 'Blog', + 'new' => 'News', + ], + array_intersect_key( $changes['renamed'][0], array_flip( [ 'old', 'new' ] ) ) + ); + $moved = array_column( $changes['moved'], 'parent', 'label' ); + ksort( $moved ); + $this->assertSame( + [ + 'About' => '', + 'Shop' => 'Home', + ], + $moved + ); + $this->assertSame( 'Custom Link', $changes['added'][0]['type'] ); + } + + public function test_saving_a_menu_without_changes_sends_nothing(): void { + [ $menu_id, $items ] = $this->make_menu( 'Main menu', [ 'Home', 'Blog' ] ); + + $this->save_menu_screen( $menu_id, array_fill_keys( $items, [] ) ); + + $this->assertSame( [], $this->sent_menu_events() ); + } + + public function test_deleting_a_menu_is_one_row_with_its_items_and_locations(): void { + [ $menu_id ] = $this->make_menu( 'Old menu', [ 'Home', 'Blog', 'Shop' ] ); + $this->menus = []; + $locations = (array) get_theme_mod( 'nav_menu_locations' ); + $locations['scanfully-primary'] = $menu_id; + set_theme_mod( 'nav_menu_locations', $locations ); + $this->sent_menu_events(); + + wp_delete_nav_menu( $menu_id ); + + $this->assertSame( + [ + [ + 'type' => 'MenuDeleted', + 'data' => [ + 'id' => $menu_id, + 'kind' => 'classic', + 'name' => 'Old menu', + 'items' => 3, + 'locations' => [ + [ + 'slug' => 'scanfully-primary', + 'name' => 'Primary', + ], + ], + ], + ], + ], + $this->sent_menu_events() + ); + } + + public function test_showing_another_menu_in_a_location_is_on_both_menus(): void { + [ $main ] = $this->make_menu( 'Main menu', [ 'Home' ] ); + [ $other ] = $this->make_menu( 'Other menu', [ 'Shop' ] ); + $locations = (array) get_theme_mod( 'nav_menu_locations' ); + $locations['scanfully-primary'] = $other; + set_theme_mod( 'nav_menu_locations', $locations ); + $this->sent_menu_events(); + + $locations['scanfully-primary'] = $main; + set_theme_mod( 'nav_menu_locations', $locations ); + + $events = $this->sent_menu_events(); + $by_id = array_column( array_column( $events, 'data' ), 'changes', 'id' ); + $this->assertSame( [ 'Primary' ], array_column( $by_id[ $main ]['locations']['added'], 'name' ) ); + $this->assertSame( [ 'Primary' ], array_column( $by_id[ $other ]['locations']['removed'], 'name' ) ); + } + + public function test_an_item_whose_page_was_deleted_is_removed_with_that_reason(): void { + [ $menu_id ] = $this->make_menu( 'Main menu', [ 'Home' ] ); + $page = wp_insert_post( + [ + 'post_type' => 'page', + 'post_title' => 'Pricing', + 'post_status' => 'publish', + ] + ); + wp_update_nav_menu_item( + $menu_id, + 0, + [ + 'menu-item-object-id' => $page, + 'menu-item-object' => 'page', + 'menu-item-type' => 'post_type', + 'menu-item-status' => 'publish', + ] + ); + $this->sent_menu_events(); + + wp_delete_post( $page, true ); + + $events = array_values( array_filter( $this->sent_menu_events(), static fn( array $event ): bool => 'MenuChanged' === $event['type'] ) ); + $this->assertCount( 1, $events ); + $this->assertSame( 'object_deleted', $events[0]['data']['changes']['removed'][0]['reason'] ); + $this->assertSame( 'Page', $events[0]['data']['changes']['removed'][0]['type'] ); + $this->assertSame( 'Pricing', $events[0]['data']['changes']['removed'][0]['label'], 'The item showed the page title.' ); + $this->assertSame( $menu_id, $events[0]['data']['id'] ); + $this->assertSame( 'Main menu', $events[0]['data']['name'] ); + } + + public function test_an_item_added_over_rest_is_reported(): void { + [ $menu_id ] = $this->make_menu( 'Main menu', [ 'Home' ] ); + + $request = new \WP_REST_Request( 'POST', '/wp/v2/menu-items' ); + $request->set_body_params( + [ + 'title' => 'Docs', + 'url' => 'https://scanfully.com/docs/', + 'menus' => $menu_id, + 'status' => 'publish', + ] + ); + $this->assertSame( 201, rest_do_request( $request )->get_status() ); + + $events = $this->sent_menu_events(); + $this->assertSame( [ 'MenuChanged' ], array_column( $events, 'type' ) ); + $this->assertSame( [ 'Docs' ], array_column( $events[0]['data']['changes']['added'], 'label' ) ); + } + + public function test_a_theme_switch_remapping_locations_is_not_reported(): void { + [ $menu_id ] = $this->make_menu( 'Main menu', [ 'Home' ] ); + $remap = static function () use ( $menu_id ): void { + set_theme_mod( 'nav_menu_locations', [ 'scanfully-footer' => $menu_id ] ); + }; + // Only this remap runs (WooCommerce's handlers expect a real switch). + global $wp_filter; + $handlers = $wp_filter['after_switch_theme'] ?? null; + remove_all_actions( 'after_switch_theme' ); + add_action( 'after_switch_theme', $remap ); + + do_action( 'after_switch_theme', 'twentytwentyfour', null ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core's hook. + remove_all_actions( 'after_switch_theme' ); + if ( null !== $handlers ) { + $wp_filter['after_switch_theme'] = $handlers; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Restoring what the test took away. + } + + $this->assertSame( [], $this->sent_menu_events() ); + } + + /** + * Navigation link blocks. + * + * @param array $labels The labels. + * + * @return string + */ + private static function links( array $labels ): string { + $blocks = ''; + foreach ( $labels as $label ) { + $blocks .= ''; + } + + return $blocks; + } + + public function test_a_block_menu_reads_like_a_classic_one_and_is_no_content_row(): void { + $id = wp_insert_post( + [ + 'post_type' => 'wp_navigation', + 'post_title' => 'Header navigation', + 'post_status' => 'publish', + 'post_content' => self::links( [ 'Home', 'Blog', 'Shop' ] ), + ] + ); + $this->posts[] = $id; + $this->assertSame( + [ + [ + 'type' => 'MenuCreated', + 'data' => [ + 'id' => $id, + 'kind' => 'block', + 'name' => 'Header navigation', + 'items' => 3, + ], + ], + ], + $this->sent_menu_events() + ); + + wp_update_post( + [ + 'ID' => $id, + 'post_content' => self::links( [ 'Shop', 'Home', 'News', 'Contact' ] ), + ] + ); + + $events = $this->sent_menu_events(); + $this->assertSame( [ 'MenuChanged' ], array_column( $events, 'type' ), 'No PostSaved row.' ); + $changes = $events[0]['data']['changes']; + $this->assertSame( [ 'News', 'Contact' ], array_column( $changes['added'], 'label' ) ); + $this->assertSame( [ 'Blog' ], array_column( $changes['removed'], 'label' ) ); + $this->assertSame( [ 'Shop' ], array_column( $changes['moved'], 'label' ) ); + $this->assertSame( 4, $events[0]['data']['items'] ); + } + + public function test_the_fallback_menu_the_editor_makes_is_not_reported(): void { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $id = wp_insert_post( + [ + 'post_type' => 'wp_navigation', + 'post_title' => 'Navigation', + 'post_status' => 'publish', + 'post_content' => '', + ] + ); + $this->posts[] = $id; + + $this->assertSame( [], $this->sent_menu_events() ); + } + + public function test_deleting_a_block_menu_is_reported(): void { + $id = wp_insert_post( + [ + 'post_type' => 'wp_navigation', + 'post_title' => 'Footer navigation', + 'post_status' => 'publish', + 'post_content' => self::links( [ 'Privacy', 'Terms' ] ), + ] + ); + $this->sent_menu_events(); + + wp_delete_post( $id, true ); + + $this->assertSame( + [ + [ + 'type' => 'MenuDeleted', + 'data' => [ + 'id' => $id, + 'kind' => 'block', + 'name' => 'Footer navigation', + 'items' => 2, + ], + ], + ], + $this->sent_menu_events() + ); + } + + /** + * A custom link item with its own place, as the Customizer or REST number them. + * + * @param int $menu_id The menu. + * @param string $label The label. + * @param int $position Its menu_order. + * @param int $parent The item it is under. + * + * @return int + */ + private function add_item( int $menu_id, string $label, int $position, int $parent = 0 ): int { + return (int) wp_update_nav_menu_item( + $menu_id, + 0, + [ + 'menu-item-title' => $label, + 'menu-item-url' => 'https://scanfully.com/' . strtolower( $label ) . '/', + 'menu-item-type' => 'custom', + 'menu-item-status' => 'publish', + 'menu-item-position' => $position, + 'menu-item-parent-id' => $parent, + ] + ); + } + + public function test_items_numbered_per_parent_are_not_moves(): void { + // The Customizer numbers the items under each parent from 1. + $menu_id = wp_create_nav_menu( 'Customizer menu' ); + $this->menus[] = $menu_id; + $this->add_item( $menu_id, 'Home', 1 ); + $about = $this->add_item( $menu_id, 'About', 2 ); + $contact = $this->add_item( $menu_id, 'Contact', 3 ); + $this->add_item( $menu_id, 'Team', 1, $about ); + $this->add_item( $menu_id, 'Jobs', 2, $about ); + $this->sent_menu_events(); + + wp_update_post( + [ + 'ID' => $contact, + 'post_title' => 'Get in touch', + ] + ); + + $events = $this->sent_menu_events(); + $this->assertSame( [ 'MenuChanged' ], array_column( $events, 'type' ) ); + $this->assertSame( [ 'renamed' ], array_keys( $events[0]['data']['changes'] ) ); + } + + public function test_a_menu_whose_items_all_have_the_same_number_has_no_moves(): void { + // REST gives new items menu_order 1. + $menu_id = wp_create_nav_menu( 'REST menu' ); + $this->menus[] = $menu_id; + $items = [ $this->add_item( $menu_id, 'Home', 1 ), $this->add_item( $menu_id, 'Blog', 1 ), $this->add_item( $menu_id, 'Shop', 1 ) ]; + $this->sent_menu_events(); + + // Save Menu without edits renumbers them 1, 2, 3 in the order shown. + $this->save_menu_screen( $menu_id, array_fill_keys( $items, [] ) ); + $this->assertSame( [], $this->sent_menu_events() ); + + $locations = (array) get_theme_mod( 'nav_menu_locations' ); + $locations['scanfully-primary'] = $menu_id; + set_theme_mod( 'nav_menu_locations', $locations ); + $events = $this->sent_menu_events(); + $this->assertSame( [ 'locations' ], array_keys( $events[0]['data']['changes'] ) ); + } + + public function test_an_item_set_back_to_draft_is_removed(): void { + [ $menu_id, $items ] = $this->make_menu( 'Main menu', [ 'Home', 'Blog' ] ); + + wp_update_post( + [ + 'ID' => $items[1], + 'post_status' => 'draft', + ] + ); + + $events = $this->sent_menu_events(); + $this->assertSame( [ 'Blog' ], array_column( $events[0]['data']['changes']['removed'], 'label' ) ); + $this->assertSame( $menu_id, $events[0]['data']['id'] ); + } + + public function test_a_block_menu_link_that_goes_elsewhere_is_relinked(): void { + $id = wp_insert_post( + [ + 'post_type' => 'wp_navigation', + 'post_title' => 'Header navigation', + 'post_status' => 'publish', + 'post_content' => self::links( [ 'Home', 'Shop' ] ), + ] + ); + $this->posts[] = $id; + $this->sent_menu_events(); + + wp_update_post( + [ + 'ID' => $id, + 'post_content' => str_replace( 'https://scanfully.com/shop/', 'https://shop.scanfully.com/', self::links( [ 'Home', 'Shop' ] ) ), + ] + ); + + $changes = $this->sent_menu_events()[0]['data']['changes']; + $this->assertSame( [ 'relinked' ], array_keys( $changes ) ); + $this->assertSame( 'https://shop.scanfully.com/', $changes['relinked'][0]['new'] ); + } + + public function test_a_menu_name_with_an_apostrophe_reads_as_typed(): void { + // The Menus screen passes the name slashed and escaped. + $menu_id = wp_create_nav_menu( wp_slash( esc_html( "Barry's menu" ) ) ); + $this->menus[] = $menu_id; + + $this->assertSame( "Barry's menu", $this->sent_menu_events()[0]['data']['name'] ); + } +} diff --git a/tests/Integration/MuPluginsTest.php b/tests/Integration/MuPluginsTest.php new file mode 100644 index 0000000..c72a100 --- /dev/null +++ b/tests/Integration/MuPluginsTest.php @@ -0,0 +1,168 @@ +markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + if ( file_exists( WP_CONTENT_DIR . '/' . self::DROPIN ) ) { + $this->markTestSkipped( 'The site has a db-error.php drop-in of its own.' ); + } + + $this->had_mu_dir = is_dir( WPMU_PLUGIN_DIR ); + if ( ! $this->had_mu_dir ) { + mkdir( WPMU_PLUGIN_DIR, 0777, true ); + } + update_option( 'scanfully_connect_is_connected', 'yes' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( MuPlugins::HASH_OPTION ); + delete_option( MuPlugins::STAT_OPTION ); + } + + protected function tearDown(): void { + if ( defined( 'WPMU_PLUGIN_DIR' ) ) { + foreach ( [ WPMU_PLUGIN_DIR . '/' . self::FILE, WPMU_PLUGIN_DIR . '/' . self::FOLDER . '/includes/admin.php', WPMU_PLUGIN_DIR . '/' . self::FOLDER . '/main.php', WP_CONTENT_DIR . '/' . self::DROPIN ] as $file ) { + if ( file_exists( $file ) ) { + unlink( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- Test cleanup. + } + } + foreach ( [ WPMU_PLUGIN_DIR . '/' . self::FOLDER . '/includes', WPMU_PLUGIN_DIR . '/' . self::FOLDER ] as $dir ) { + if ( is_dir( $dir ) ) { + rmdir( $dir ); + } + } + if ( ! $this->had_mu_dir && is_dir( WPMU_PLUGIN_DIR ) ) { + rmdir( WPMU_PLUGIN_DIR ); + } + delete_option( MuPlugins::HASH_OPTION ); + delete_option( MuPlugins::STAT_OPTION ); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( 'scanfully_connect_is_connected' ); + } + parent::tearDown(); + } + + /** + * Write a file, creating its folder. + * + * @param string $path The full path. + * @param string $content The content. + * + * @return void + */ + private function write( string $path, string $content ): void { + if ( ! is_dir( dirname( $path ) ) ) { + mkdir( dirname( $path ), 0777, true ); + } + file_put_contents( $path, $content ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test fixture. + clearstatcache(); + } + + /** + * The MU plugin entries of the site data, by kind and file. + * + * @return array> + */ + private function sent(): array { + $out = []; + foreach ( HealthController::get_site_data()['mu_plugins'] as $entry ) { + $out[ $entry['kind'] . ':' . $entry['file'] ] = $entry; + } + + return $out; + } + + public function test_the_site_data_has_the_mu_plugins_their_folders_and_drop_ins(): void { + $plugin = "write( WPMU_PLUGIN_DIR . '/' . self::FILE, $plugin ); + $this->write( WPMU_PLUGIN_DIR . '/' . self::FOLDER . '/main.php', 'write( WPMU_PLUGIN_DIR . '/' . self::FOLDER . '/includes/admin.php', 'write( WP_CONTENT_DIR . '/' . self::DROPIN, "sent(); + + $file = $sent[ 'mu:' . self::FILE ] ?? []; + $this->assertSame( 'Scanfully Test MU', $file['name'] ?? null ); + $this->assertSame( '1.4.0', $file['version'] ?? null ); + $this->assertSame( 'sha256:' . hash( 'sha256', $plugin ), $file['hash'] ?? null ); + + $folder = $sent[ 'mu_folder:' . self::FOLDER ] ?? []; + $this->assertSame( 2, $folder['files'] ?? null ); + $this->assertFalse( $folder['partial'] ?? true ); + + $this->assertSame( 'Test DB Error', $sent[ 'dropin:' . self::DROPIN ]['name'] ?? null ); + } + + public function test_the_hourly_check_syncs_only_when_something_changed(): void { + $this->write( WPMU_PLUGIN_DIR . '/' . self::FILE, 'sent(); + + CronController::check_mu_plugins(); + $this->assertSame( [], $this->debounced_syncs(), 'Nothing changed since the sync.' ); + + $this->write( WPMU_PLUGIN_DIR . '/' . self::FOLDER . '/main.php', 'assertCount( 1, $this->debounced_syncs() ); + } + + public function test_the_hourly_check_does_nothing_before_the_first_sync(): void { + $this->write( WPMU_PLUGIN_DIR . '/' . self::FILE, 'assertSame( [], $this->debounced_syncs() ); + } + + /** + * The pending debounced site data syncs. + * + * @return array + */ + private function debounced_syncs(): array { + return as_get_scheduled_actions( + [ + 'hook' => CronController::ACTION_SYNC_SITE_HEALTH, + 'args' => [ 'trigger' => 'debounced' ], + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + ], + 'ids' + ); + } +} diff --git a/tests/Integration/PostChangesTest.php b/tests/Integration/PostChangesTest.php new file mode 100644 index 0000000..c6dcb51 --- /dev/null +++ b/tests/Integration/PostChangesTest.php @@ -0,0 +1,446 @@ + + */ + private array $posts = []; + + /** + * Event bodies sent to the API. + * + * @var array> + */ + private array $sent = []; + + /** + * The permalink structure before the test. + * + * @var string + */ + private string $permalinks = ''; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'as_get_scheduled_actions' ) || ! function_exists( 'wp_insert_post' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + + update_option( 'scanfully_connect_is_connected', 'yes' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + Collector::reset(); + $this->sent = []; + add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 3 ); + // No per-minute cap: the suite saves more posts a minute than a site does. + add_filter( 'scanfully_post_saved_events_per_minute', '__return_zero' ); + + global $wp_rewrite; + $this->permalinks = (string) get_option( 'permalink_structure' ); + $wp_rewrite->set_permalink_structure( '/%postname%/' ); + } + + protected function tearDown(): void { + if ( function_exists( 'wp_delete_post' ) ) { + remove_filter( 'pre_http_request', [ $this, 'capture_request' ], 10 ); + remove_filter( 'wp_revisions_to_keep', '__return_zero' ); + remove_filter( 'scanfully_post_saved_events_per_minute', '__return_zero' ); + foreach ( array_reverse( $this->posts ) as $id ) { + wp_delete_post( $id, true ); + } + global $wp_rewrite; + $wp_rewrite->set_permalink_structure( $this->permalinks ); + Collector::reset(); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( 'scanfully_connect_is_connected' ); + } + parent::tearDown(); + } + + /** + * `pre_http_request`: keep the event sent to the API and accept it. + * + * @param mixed $preempt Whether to preempt the request. + * @param array $args The request arguments. + * @param string $url The URL. + * + * @return mixed + */ + public function capture_request( $preempt, $args, $url ) { + if ( false === strpos( (string) $url, '/timeline' ) ) { + return $preempt; + } + + $this->sent[] = json_decode( (string) ( $args['body'] ?? '' ), true ); + + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 202, + 'message' => 'Accepted', + ], + 'cookies' => [], + ]; + } + + /** + * A published page with two paragraphs; its own "created" event is + * already sent and forgotten. + * + * @param array $fields Fields that differ from the defaults. + * + * @return int + */ + private function publish( array $fields = [] ): int { + $id = wp_insert_post( + array_merge( + [ + 'post_title' => 'About', + 'post_name' => 'about-scanfully-test', + 'post_type' => 'page', + 'post_status' => 'publish', + 'post_content' => "\n

One

\n\n\n\n

Two

\n", + ], + $fields + ) + ); + $this->posts[] = $id; + + Collector::flush(); + as_unschedule_all_actions( '', [], 'scanfully' ); + + return $id; + } + + /** + * End the "request": report the changed posts. + * + * @return void + */ + private function end_request(): void { + Collector::flush(); + } + + /** + * The arguments of the pending post event jobs. + * + * @return array> + */ + private function jobs(): array { + $actions = as_get_scheduled_actions( + [ + 'hook' => EventsController::ACTION_BUILD_POST_EVENT, + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + ] + ); + + return array_values( array_map( static fn( $action ) => $action->get_args(), $actions ) ); + } + + /** + * Run the pending post event jobs and return the changes each sent. + * + * @return array> + */ + private function run_jobs(): array { + foreach ( $this->jobs() as $args ) { + do_action_ref_array( EventsController::ACTION_BUILD_POST_EVENT, array_values( $args ) ); + } + + return array_map( static fn( array $body ): array => $body['data']['changes'] ?? [], $this->sent ); + } + + public function test_a_save_that_changes_nothing_queues_nothing(): void { + $id = $this->publish(); + + wp_update_post( [ 'ID' => $id ] ); + $this->end_request(); + + $this->assertSame( [], $this->jobs() ); + } + + public function test_a_new_post_queues_one_event_without_changes(): void { + $this->posts[] = wp_insert_post( + [ + 'post_title' => 'New', + 'post_status' => 'publish', + ] + ); + $this->end_request(); + + $this->assertCount( 1, $this->jobs() ); + $this->assertSame( [ [] ], $this->run_jobs() ); + } + + public function test_a_renamed_page_reports_its_title_slug_and_url(): void { + $id = $this->publish(); + + wp_update_post( + [ + 'ID' => $id, + 'post_title' => 'About us', + 'post_name' => 'about-us-scanfully-test', + ] + ); + $this->end_request(); + $changes = $this->run_jobs()[0]; + + $this->assertSame( + [ + 'old' => 'About', + 'new' => 'About us', + ], + $changes['title'] + ); + $this->assertSame( 'about-us-scanfully-test', $changes['slug']['new'] ); + $this->assertStringEndsWith( '/about-scanfully-test/', $changes['url']['old'] ); + $this->assertStringEndsWith( '/about-us-scanfully-test/', $changes['url']['new'] ); + } + + public function test_a_content_change_is_sent_as_a_short_diff(): void { + $id = $this->publish(); + + wp_update_post( + [ + 'ID' => $id, + 'post_content' => "\n

One

\n\n\n\n

Two and a half

\n", + ] + ); + $this->end_request(); + $content = $this->run_jobs()[0]['content']; + + $this->assertSame( 1, $content['added'] ); + $this->assertSame( 1, $content['removed'] ); + $this->assertContains( + [ + 'op' => '-', + 'text' => 'Two', + ], + $content['lines'] + ); + $this->assertContains( + [ + 'op' => '+', + 'text' => 'Two and a half', + ], + $content['lines'] + ); + } + + public function test_a_later_edit_is_compared_with_the_revision_before_it(): void { + $id = $this->publish(); + wp_update_post( + [ + 'ID' => $id, + 'post_content' => '

One

Two

Three

', + ] + ); + $this->end_request(); + as_unschedule_all_actions( '', [], 'scanfully' ); + + wp_update_post( + [ + 'ID' => $id, + 'post_content' => '

One

2

Three

', + ] + ); + $this->end_request(); + $this->assertArrayHasKey( 'revisions', $this->jobs()[0]['data']['changes']['content'], 'Compared from revisions, nothing stored.' ); + $this->assertSame( '', $this->jobs()[0]['stash'] ); + + $content = $this->run_jobs()[0]['content']; + + $this->assertSame( + [ + [ + 'op' => '=', + 'text' => 'One', + ], + [ + 'op' => '-', + 'text' => 'Two', + ], + [ + 'op' => '+', + 'text' => '2', + ], + [ + 'op' => '=', + 'text' => 'Three', + ], + ], + $content['lines'] + ); + } + + public function test_content_is_compared_without_revisions_and_the_copy_is_removed(): void { + add_filter( 'wp_revisions_to_keep', '__return_zero' ); + $id = $this->publish(); + + wp_update_post( + [ + 'ID' => $id, + 'post_content' => '

Something else

', + ] + ); + $this->end_request(); + $stash = $this->jobs()[0]['stash']; + $this->assertNotSame( '', $stash ); + + $content = $this->run_jobs()[0]['content']; + + $this->assertSame( 1, $content['added'] ); + $this->assertSame( 2, $content['removed'] ); + $this->assertFalse( get_transient( 'scanfully_post_change_' . $stash ) ); + } + + public function test_custom_fields_and_the_featured_image_are_reported(): void { + $id = $this->publish(); + update_post_meta( $id, 'subtitle', 'Old' ); + update_post_meta( $id, '_edit_last', '1' ); + $this->posts[] = $image = wp_insert_attachment( // phpcs:ignore Squiz.PHP.DisallowMultipleAssignments.Found -- Created and cleaned up. + [ + 'post_mime_type' => 'image/jpeg', + 'post_title' => 'Team', + 'post_status' => 'inherit', + ], + 'team-photo.jpg' + ); + Collector::reset(); + + // What a save does: the fields first, then the post. + update_post_meta( $id, 'subtitle', 'New' ); + update_post_meta( $id, '_edit_last', '2' ); + set_post_thumbnail( $id, $image ); + wp_update_post( [ 'ID' => $id ] ); + $this->end_request(); + $fields = array_column( $this->run_jobs()[0]['fields'], null, 'key' ); + + $this->assertSame( + [ + 'key' => 'subtitle', + 'change' => 'changed', + 'old' => 'Old', + 'new' => 'New', + ], + $fields['subtitle'] + ); + $this->assertSame( 'added', $fields['_thumbnail_id']['change'] ); + $this->assertSame( 'team-photo.jpg', $fields['_thumbnail_id']['new'] ); + $this->assertArrayNotHasKey( '_edit_last', $fields ); + } + + public function test_categories_added_and_removed_are_reported_by_name(): void { + $name = 'News ' . wp_generate_password( 8, false ); + $news = wp_insert_term( $name, 'category' ); + $news_id = (int) $news['term_id']; + $id = $this->publish( [ 'post_type' => 'post' ] ); + + wp_update_post( + [ + 'ID' => $id, + 'post_category' => [ $news_id ], + ] + ); + $this->end_request(); + $terms = $this->run_jobs()[0]['terms']; + wp_delete_term( $news_id, 'category' ); + + $this->assertSame( 'category', $terms[0]['taxonomy'] ); + $this->assertSame( [ $name ], $terms[0]['added'] ); + $this->assertSame( [ get_cat_name( (int) get_option( 'default_category' ) ) ], $terms[0]['removed'] ); + } + + public function test_a_new_parent_is_reported_by_title(): void { + $parent = $this->publish( + [ + 'post_title' => 'Company', + 'post_name' => 'company-scanfully-test', + ] + ); + $id = $this->publish(); + + wp_update_post( + [ + 'ID' => $id, + 'post_parent' => $parent, + ] + ); + $this->end_request(); + $changes = $this->run_jobs()[0]; + + $this->assertSame( + [ + 'id' => $parent, + 'title' => 'Company', + ], + $changes['parent']['new'] + ); + $this->assertStringEndsWith( '/company-scanfully-test/about-scanfully-test/', $changes['url']['new'] ); + } + + public function test_two_quick_edits_are_both_reported(): void { + $id = $this->publish(); + + wp_update_post( + [ + 'ID' => $id, + 'post_title' => 'First edit', + ] + ); + $this->end_request(); + wp_update_post( + [ + 'ID' => $id, + 'post_title' => 'Second edit', + ] + ); + $this->end_request(); + + $this->assertCount( 2, $this->jobs() ); + } + + public function test_the_password_itself_is_never_sent(): void { + $id = $this->publish(); + + wp_update_post( + [ + 'ID' => $id, + 'post_password' => 'scanfully-secret', + ] + ); + $this->end_request(); + $changes = $this->run_jobs()[0]; + + $this->assertSame( + [ + 'old' => false, + 'new' => true, + ], + $changes['password'] + ); + $this->assertStringNotContainsString( 'scanfully-secret', (string) wp_json_encode( $this->sent ) ); + } +} diff --git a/tests/Integration/PostEventTest.php b/tests/Integration/PostEventTest.php index d598730..7dcdfe6 100644 --- a/tests/Integration/PostEventTest.php +++ b/tests/Integration/PostEventTest.php @@ -11,6 +11,7 @@ use PHPUnit\Framework\TestCase; use Scanfully\Events\Controller as EventsController; +use Scanfully\Events\PostChanges\Collector; /** * Verifies which post saves queue a timeline event. @@ -32,6 +33,7 @@ protected function setUp(): void { } update_option( 'scanfully_connect_is_connected', 'yes' ); as_unschedule_all_actions( '', [], 'scanfully' ); + Collector::reset(); } protected function tearDown(): void { @@ -41,6 +43,9 @@ protected function tearDown(): void { } as_unschedule_all_actions( '', [], 'scanfully' ); delete_option( 'scanfully_connect_is_connected' ); + remove_filter( 'scanfully_post_saved_events_per_minute', '__return_zero' ); + unregister_post_type( 'seopress_404' ); + unregister_post_type( 'scanfully_test_type' ); } parent::tearDown(); } @@ -61,11 +66,13 @@ private function events_queued_for( string $type, string $status ): int { 'post_status' => $status, ] ); + // The post is reported at the end of the request. + Collector::flush(); return count( as_get_scheduled_actions( [ - 'hook' => EventsController::ACTION_SEND_EVENT, + 'hook' => EventsController::ACTION_BUILD_POST_EVENT, 'group' => 'scanfully', 'status' => \ActionScheduler_Store::STATUS_PENDING, 'per_page' => -1, @@ -86,4 +93,103 @@ public function test_an_hpos_order_placeholder_queues_nothing(): void { public function test_an_order_backup_post_queues_nothing(): void { $this->assertSame( 0, $this->events_queued_for( 'shop_order', 'draft' ) ); } + + public function test_a_seopress_404_record_queues_nothing_from_creation_to_deletion(): void { + // SEOPress registers the type with an admin screen and saves a + // published record for every request to a missing URL. + register_post_type( 'seopress_404', [ 'show_ui' => true ] ); + + $this->assertSame( + [ + 'created' => 0, + 'updated' => 0, + 'status changed' => 0, + 'trashed' => 0, + 'deleted' => 0, + ], + $this->jobs_queued_per_step( 'seopress_404' ) + ); + } + + public function test_a_custom_post_type_with_an_admin_screen_is_still_reported(): void { + register_post_type( 'scanfully_test_type', [ 'show_ui' => true ] ); + + $queued = $this->jobs_queued_per_step( 'scanfully_test_type' ); + + $this->assertSame( 1, $queued['created'] ); + $this->assertSame( 1, $queued['updated'] ); + $this->assertSame( 1, $queued['status changed'] ); + $this->assertSame( 1, $queued['trashed'] ); + } + + /** + * Create, update, unpublish, trash and delete a post, each as its own + * request, and return how many Scanfully jobs each step queued. + * + * @param string $type Post type. + * + * @return array + */ + private function jobs_queued_per_step( string $type ): array { + // Other tests' saves this minute must not cap these. + add_filter( 'scanfully_post_saved_events_per_minute', '__return_zero' ); + + $id = 0; + $steps = [ + 'created' => function () use ( $type, &$id ): void { + $id = (int) wp_insert_post( + [ + 'post_title' => '"/.env" not found', + 'post_type' => $type, + 'post_status' => 'publish', + ] + ); + $this->posts[] = $id; + }, + 'updated' => static function () use ( &$id ): void { + wp_update_post( + [ + 'ID' => $id, + 'post_title' => '"/.git/config" not found', + ] + ); + }, + 'status changed' => static function () use ( &$id ): void { + wp_update_post( + [ + 'ID' => $id, + 'post_status' => 'draft', + ] + ); + }, + 'trashed' => static function () use ( &$id ): void { + wp_trash_post( $id ); + }, + 'deleted' => static function () use ( &$id ): void { + wp_delete_post( $id, true ); + }, + ]; + + $queued = []; + foreach ( $steps as $step => $run ) { + as_unschedule_all_actions( '', [], 'scanfully' ); + Collector::reset(); + $run(); + // The post is reported at the end of the request. + Collector::flush(); + + $queued[ $step ] = count( + as_get_scheduled_actions( + [ + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + ], + 'ids' + ) + ); + } + + return $queued; + } } diff --git a/tests/Integration/SettingsEventsTest.php b/tests/Integration/SettingsEventsTest.php new file mode 100644 index 0000000..989149b --- /dev/null +++ b/tests/Integration/SettingsEventsTest.php @@ -0,0 +1,546 @@ + + */ + private array $options = []; + + /** + * Posts created by a test. + * + * @var array + */ + private array $posts = []; + + /** + * Event bodies sent to the API. + * + * @var array> + */ + private array $sent = []; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'as_get_scheduled_actions' ) || ! function_exists( 'update_option' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + + update_option( 'scanfully_connect_is_connected', 'yes' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + Collector::reset(); + $this->sent = []; + wp_set_current_user( 1 ); + add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 3 ); + // Never send mail (the admin email request mails a confirmation link). + add_filter( 'pre_wp_mail', '__return_true' ); + add_filter( 'scanfully_settings_events_per_minute', '__return_zero' ); + + // The admin email request is handled by a hook wp-admin adds + // (admin-filters.php), which a CLI run doesn't load. + require_once ABSPATH . 'wp-admin/includes/misc.php'; + if ( ! has_action( 'update_option_new_admin_email', 'update_option_new_admin_email' ) ) { + add_action( 'update_option_new_admin_email', 'update_option_new_admin_email', 10, 2 ); + add_action( 'add_option_new_admin_email', 'update_option_new_admin_email', 10, 2 ); + } + } + + protected function tearDown(): void { + if ( function_exists( 'update_option' ) ) { + foreach ( $this->options as $option => $value ) { + if ( null === $value ) { + delete_option( $option ); + } else { + update_option( $option, $value ); + } + } + foreach ( $this->posts as $id ) { + wp_delete_post( $id, true ); + } + remove_filter( 'pre_http_request', [ $this, 'capture_request' ], 10 ); + remove_filter( 'pre_wp_mail', '__return_true' ); + remove_all_filters( 'scanfully_settings_events_per_minute' ); + Collector::reset(); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( 'scanfully_connect_is_connected' ); + wp_set_current_user( 0 ); + } + parent::tearDown(); + } + + /** + * `pre_http_request`: keep the event sent to the API and accept it. + * + * @param mixed $preempt Whether to preempt the request. + * @param array $args The request arguments. + * @param string $url The URL. + * + * @return mixed + */ + public function capture_request( $preempt, $args, $url ) { + if ( false === strpos( (string) $url, '/timeline' ) ) { + return $preempt; + } + + $this->sent[] = json_decode( (string) ( $args['body'] ?? '' ), true ); + + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 202, + 'message' => 'Accepted', + ], + 'cookies' => [], + ]; + } + + /** + * Remember options' values so tearDown restores them. + * + * @param string ...$options The options. + */ + private function restore_later( string ...$options ): void { + foreach ( $options as $option ) { + if ( ! array_key_exists( $option, $this->options ) ) { + $value = get_option( $option, null ); + $this->options[ $option ] = $value; + } + } + } + + /** + * Set options before the test's "request", without reporting them. + * + * @param array $values The options and their values. + */ + private function given( array $values ): void { + $this->restore_later( ...array_keys( $values ) ); + foreach ( $values as $option => $value ) { + update_option( $option, $value ); + } + Collector::reset(); + } + + /** + * Save fields the way wp-admin/options.php does: update_option() for + * every field of the screen, a missing one as null. + * + * @param array $fields The fields and their posted values. + */ + private function save_screen( array $fields ): void { + $this->restore_later( ...array_keys( $fields ) ); + foreach ( $fields as $option => $value ) { + update_option( $option, is_string( $value ) ? trim( $value ) : $value ); + } + } + + /** + * End the "request" and run the jobs, as Action Scheduler would; return + * the events sent: type and data. + * + * @return array}> + */ + private function sent_events(): array { + Collector::flush(); + + $actions = as_get_scheduled_actions( + [ + 'hook__in' => [ EventsController::ACTION_BUILD_CONTENT_EVENT, EventsController::ACTION_SEND_EVENT ], + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + 'orderby' => 'action_id', + 'order' => 'ASC', + ] + ); + foreach ( $actions as $id => $action ) { + \ActionScheduler::store()->mark_complete( $id ); + do_action_ref_array( $action->get_hook(), array_values( $action->get_args() ) ); + } + + return array_map( + static fn( array $body ): array => [ + 'type' => (string) $body['type'], + 'data' => (array) $body['data'], + ], + $this->sent + ); + } + + /** + * The data of the SiteOptionChanged events sent. + * + * @return array> + */ + private function sent_settings(): array { + $events = $this->sent_events(); + $this->assertSame( array_fill( 0, count( $events ), 'SiteOptionChanged' ), array_column( $events, 'type' ) ); + + return array_column( $events, 'data' ); + } + + public function test_a_general_settings_save_reports_each_changed_field(): void { + $this->given( + [ + 'blogdescription' => 'Just another site', + 'date_format' => 'F j, Y', + 'start_of_week' => '1', + ] + ); + + $this->save_screen( + [ + 'blogdescription' => 'Shop & more', + 'date_format' => 'd/m/Y', + 'time_format' => get_option( 'time_format' ), + 'start_of_week' => '1', + ] + ); + + $this->assertSame( + [ + [ + 'option' => 'blogdescription', + 'old' => 'Just another site', + 'new' => 'Shop & more', + ], + [ + 'option' => 'date_format', + 'old' => 'F j, Y', + 'new' => 'd/m/Y', + 'old_example' => 'January 31, 2026', + 'new_example' => '31/01/2026', + ], + ], + $this->sent_settings() + ); + } + + public function test_a_save_without_changes_sends_nothing(): void { + $this->given( + [ + 'comment_moderation' => '1', + 'show_avatars' => '1', + 'users_can_register' => '0', + 'close_comments_days_old' => '14', + ] + ); + + // Unchecked boxes are posted as null; numbers come back as strings. + $this->save_screen( + [ + 'comment_moderation' => '1', + 'show_avatars' => '1', + 'users_can_register' => null, + 'close_comments_days_old' => 14, + ] + ); + + $this->assertSame( [], $this->sent_events() ); + } + + public function test_discussion_changes_are_a_row_each_and_word_lists_only_counts(): void { + $this->given( + [ + 'default_comment_status' => 'open', + 'comment_moderation' => '', + 'disallowed_keys' => "spam\n203.0.113.9", + ] + ); + + $this->save_screen( + [ + 'default_comment_status' => null, + 'comment_moderation' => '1', + 'disallowed_keys' => "spam\nbad@scanfully.com\ncasino", + ] + ); + + $sent = $this->sent_settings(); + $this->assertSame( [ 'default_comment_status', 'comment_moderation', 'disallowed_keys' ], array_column( $sent, 'option' ) ); + $this->assertSame( + [ + 'option' => 'disallowed_keys', + 'added' => 2, + 'removed' => 1, + ], + $sent[2] + ); + $this->assertStringNotContainsString( 'scanfully.com', (string) wp_json_encode( $sent ) ); + } + + public function test_update_services_saved_while_search_engines_are_discouraged_list_only_the_real_change(): void { + $this->given( + [ + 'ping_sites' => 'http://rpc.pingomatic.com/', + // WordPress now reads the update services as empty. + 'blog_public' => '0', + ] + ); + // A later request reads `blog_public` from the database as '0' (the + // request that saves it holds the int 0, which the filter ignores). + wp_cache_delete( 'alloptions', 'options' ); + $this->assertSame( '', get_option( 'ping_sites' ) ); + + // Only code, REST or WP-CLI can: the Writing screen hides the field. + $this->save_screen( [ 'ping_sites' => "http://rpc.pingomatic.com/\nhttps://ping.scanfully.com/" ] ); + + $this->assertSame( + [ + [ + 'option' => 'ping_sites', + 'added' => [ 'https://ping.scanfully.com/' ], + 'removed' => [], + ], + ], + $this->sent_settings() + ); + } + + public function test_the_post_via_email_password_is_never_sent(): void { + $this->given( [ 'mailserver_pass' => 'old-password' ] ); + + $this->save_screen( [ 'mailserver_pass' => 'new-password' ] ); + + $sent = $this->sent_settings(); + $this->assertSame( + [ + [ + 'option' => 'mailserver_pass', + 'secret' => true, + ], + ], + $sent + ); + } + + public function test_a_static_front_page_comes_with_the_page_titles(): void { + $home = wp_insert_post( + [ + 'post_type' => 'page', + 'post_title' => 'Home & away', + 'post_status' => 'publish', + ] + ); + $this->posts[] = $home; + $this->given( + [ + 'show_on_front' => 'posts', + 'page_on_front' => '0', + ] + ); + + $this->save_screen( + [ + 'show_on_front' => 'page', + 'page_on_front' => (string) $home, + ] + ); + + $this->assertSame( + [ + [ + 'option' => 'show_on_front', + 'old' => 'posts', + 'new' => 'page', + ], + [ + 'option' => 'page_on_front', + 'old' => '0', + 'new' => (string) $home, + 'new_name' => 'Home & away', + ], + ], + $this->sent_settings() + ); + } + + public function test_choosing_a_utc_offset_instead_of_a_city_is_one_timezone_row(): void { + $this->given( + [ + 'timezone_string' => 'Europe/Amsterdam', + 'gmt_offset' => '', + ] + ); + + // What options.php saves for "UTC+2". + $this->save_screen( + [ + 'gmt_offset' => '2', + 'timezone_string' => '', + ] + ); + + $this->assertSame( + [ + [ + 'option' => 'timezone', + 'old' => 'Europe/Amsterdam', + 'new' => 'UTC+2', + ], + ], + $this->sent_settings() + ); + } + + public function test_an_admin_email_change_is_reported_when_asked_for_and_when_confirmed(): void { + $this->restore_later( 'admin_email', 'new_admin_email', 'adminhash' ); + $admin = (string) get_option( 'admin_email' ); + + // Settings, General: WordPress stores the request and mails a link. + $this->save_screen( [ 'new_admin_email' => 'owner@scanfully.com' ] ); + $this->assertSame( + [ + [ + 'option' => 'new_admin_email', + 'old' => $admin, + 'new' => 'owner@scanfully.com', + ], + ], + $this->sent_settings() + ); + $hash = get_option( 'adminhash' ); + $this->assertIsArray( $hash ); + $this->assertStringNotContainsString( (string) $hash['hash'], (string) wp_json_encode( $this->sent ) ); + + // The link: what options.php does with ?adminhash=. + $this->sent = []; + update_option( 'admin_email', 'owner@scanfully.com' ); + delete_option( 'adminhash' ); + delete_option( 'new_admin_email' ); + $this->assertSame( + [ + [ + 'option' => 'admin_email', + 'old' => $admin, + 'new' => 'owner@scanfully.com', + ], + ], + $this->sent_settings() + ); + } + + public function test_a_withdrawn_admin_email_request_is_reported_as_cancelled(): void { + $this->restore_later( 'admin_email', 'new_admin_email', 'adminhash' ); + update_option( 'new_admin_email', 'owner@scanfully.com' ); + Collector::reset(); + + // The Cancel link: what options.php does with ?dismiss=new_admin_email. + delete_option( 'adminhash' ); + delete_option( 'new_admin_email' ); + + $sent = $this->sent_settings(); + $this->assertCount( 1, $sent ); + $this->assertSame( 'new_admin_email', $sent[0]['option'] ); + $this->assertSame( 'owner@scanfully.com', $sent[0]['new'] ); + $this->assertTrue( $sent[0]['cancelled'] ); + } + + public function test_saving_the_current_admin_email_asks_for_nothing(): void { + $this->restore_later( 'new_admin_email', 'adminhash' ); + + $this->save_screen( [ 'new_admin_email' => (string) get_option( 'admin_email' ) ] ); + + $this->assertSame( [], $this->sent_events() ); + } + + public function test_the_category_base_is_reported_from_the_permalinks_screen(): void { + global $wp_rewrite; + $this->restore_later( 'category_base' ); + $this->given( [ 'category_base' => '' ] ); + + $wp_rewrite->set_category_base( 'topics' ); + + $this->assertSame( + [ + [ + 'option' => 'category_base', + 'old' => '', + 'new' => 'topics', + ], + ], + $this->sent_settings() + ); + } + + public function test_the_rest_settings_endpoint_is_reported_too(): void { + $this->given( + [ + 'blogdescription' => 'Before', + 'posts_per_page' => '10', + ] + ); + + $request = new \WP_REST_Request( 'POST', '/wp/v2/settings' ); + $request->set_body_params( + [ + 'description' => 'After', + 'posts_per_page' => 12, + ] + ); + $response = rest_do_request( $request ); + $this->assertSame( 200, $response->get_status() ); + + $this->assertSame( [ 'blogdescription', 'posts_per_page' ], array_column( $this->sent_settings(), 'option' ) ); + } + + public function test_the_customizer_site_identity_is_reported(): void { + require_once ABSPATH . WPINC . '/class-wp-customize-manager.php'; + $this->given( [ 'blogdescription' => 'Before' ] ); + + $manager = new \WP_Customize_Manager(); + $manager->register_controls(); + $result = $manager->save_changeset_post( + [ + 'data' => [ 'blogdescription' => [ 'value' => 'From the Customizer' ] ], + 'status' => 'publish', + ] + ); + $this->assertIsArray( $result ); + + $this->assertSame( + [ + [ + 'option' => 'blogdescription', + 'old' => 'Before', + 'new' => 'From the Customizer', + ], + ], + $this->sent_settings() + ); + } + + public function test_database_upgrades_are_not_reported(): void { + $this->given( [ 'posts_per_rss' => '10' ] ); + + wp_installing( true ); + update_option( 'posts_per_rss', '20' ); + wp_installing( false ); + + $this->assertSame( [], $this->sent_events() ); + } +} diff --git a/tests/Integration/SiteDataTest.php b/tests/Integration/SiteDataTest.php index 1526a85..23f22dc 100644 --- a/tests/Integration/SiteDataTest.php +++ b/tests/Integration/SiteDataTest.php @@ -75,7 +75,9 @@ public function test_plugin_slugs_use_the_folder_or_the_single_file_name(): void public function test_the_memory_limit_is_reported_as_it_was_before_being_raised(): void { $original = (string) ini_get( 'memory_limit' ); - ini_set( 'memory_limit', '96M' ); // phpcs:ignore WordPress.PHP.IniSet.memory_limit_Disallowed -- Simulates the site's normal limit. + // PHP refuses a limit under the memory in use, which grows with the suite. + $normal = max( 96, (int) ceil( memory_get_usage() / MB_IN_BYTES ) + 32 ) . 'M'; + ini_set( 'memory_limit', $normal ); // phpcs:ignore WordPress.PHP.IniSet.memory_limit_Disallowed -- Simulates the site's normal limit. Controller::record_boot_memory_limit(); // Action Scheduler raises the limit before running the health sync. @@ -85,7 +87,7 @@ public function test_the_memory_limit_is_reported_as_it_was_before_being_raised( ini_set( 'memory_limit', $original ); // phpcs:ignore WordPress.PHP.IniSet.memory_limit_Disallowed -- Restore. Controller::record_boot_memory_limit(); - $this->assertSame( '96M', $reported, 'A low normal limit must not be hidden by the raised one.' ); + $this->assertSame( $normal, $reported, 'A low normal limit must not be hidden by the raised one.' ); } /** diff --git a/tests/Integration/SiteEditorEventsTest.php b/tests/Integration/SiteEditorEventsTest.php new file mode 100644 index 0000000..90cbb92 --- /dev/null +++ b/tests/Integration/SiteEditorEventsTest.php @@ -0,0 +1,549 @@ + + */ + private array $existing = []; + + /** + * Event bodies sent to the API. + * + * @var array> + */ + private array $sent = []; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'rest_do_request' ) || ! function_exists( 'as_get_scheduled_actions' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + if ( self::THEME !== get_stylesheet() ) { + $this->markTestSkipped( 'Twenty Twenty-Five is not the active theme.' ); + } + + update_option( 'scanfully_connect_is_connected', 'yes' ); + wp_set_current_user( 1 ); + add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 3 ); + add_filter( 'scanfully_site_editor_events_per_minute', '__return_zero' ); + $this->existing = $this->site_editor_posts(); + $this->forget(); + } + + protected function tearDown(): void { + if ( function_exists( 'wp_delete_post' ) ) { + remove_filter( 'pre_http_request', [ $this, 'capture_request' ], 10 ); + remove_filter( 'scanfully_site_editor_events_per_minute', '__return_zero' ); + foreach ( array_diff( $this->site_editor_posts(), $this->existing ) as $id ) { + wp_delete_post( $id, true ); + } + \WP_Theme_JSON_Resolver::clean_cached_data(); + $this->forget(); + delete_option( 'scanfully_connect_is_connected' ); + wp_set_current_user( 0 ); + } + parent::tearDown(); + } + + /** + * The IDs of the posts of the Site Editor's post types. + * + * @return array + */ + private function site_editor_posts(): array { + return array_map( + 'intval', + get_posts( + [ + 'post_type' => self::POST_TYPES, + 'post_status' => 'any', + 'numberposts' => -1, + 'fields' => 'ids', + ] + ) + ); + } + + /** + * `pre_http_request`: keep the event sent to the API and accept it. + * + * @param mixed $preempt Whether to preempt the request. + * @param array $args The request arguments. + * @param string $url The URL. + * + * @return mixed + */ + public function capture_request( $preempt, $args, $url ) { + if ( false === strpos( (string) $url, '/timeline' ) ) { + return $preempt; + } + + $this->sent[] = json_decode( (string) ( $args['body'] ?? '' ), true ); + + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 202, + 'message' => 'Accepted', + ], + 'cookies' => [], + ]; + } + + /** + * Forget what the setup of a test noted and sent. + * + * @return void + */ + private function forget(): void { + Collector::reset(); + PostCollector::reset(); + self::clear_minute_store(); + as_unschedule_all_actions( '', [], 'scanfully' ); + $this->sent = []; + } + + /** + * Remove what earlier runs left in the minute store. + * + * @return void + */ + private static function clear_minute_store(): void { + global $wpdb; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Test cleanup. + $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", $wpdb->esc_like( 'scanfully_minute_' ) . '%', $wpdb->esc_like( '_transient_scanfully_minute_' ) . '%' ) ); + wp_cache_delete( 'alloptions', 'options' ); + } + + /** + * A REST request, as the Site Editor makes it; fails the test on an + * error. + * + * @param string $method The method. + * @param string $route The route. + * @param array $params The parameters. + * + * @return array + */ + private function rest( string $method, string $route, array $params = [] ): array { + $request = new \WP_REST_Request( $method, $route ); + foreach ( $params as $key => $value ) { + $request->set_param( $key, $value ); + } + $response = rest_do_request( $request ); + $this->assertFalse( $response->is_error(), $method . ' ' . $route . ': ' . wp_json_encode( $response->get_data() ) ); + + return (array) $response->get_data(); + } + + /** + * End the request (the collector's `shutdown`) and run the jobs it + * scheduled, as Action Scheduler would; return the events sent. + * + * @return array}> + */ + private function end_request(): array { + Collector::flush(); + PostCollector::flush(); + + $hooks = [ EventsController::ACTION_BUILD_CONTENT_EVENT, EventsController::ACTION_BUILD_POST_EVENT, EventsController::ACTION_SEND_FONTS ]; + for ( $round = 0; $round < 3; $round++ ) { + $actions = as_get_scheduled_actions( + [ + 'hook__in' => $hooks, + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + 'orderby' => 'none', + ] + ); + if ( [] === $actions ) { + break; + } + foreach ( $actions as $id => $action ) { + \ActionScheduler::store()->mark_complete( $id ); + do_action_ref_array( $action->get_hook(), array_values( $action->get_args() ) ); + } + } + + $sent = $this->sent; + $this->sent = []; + + return array_values( + array_map( + static fn( array $body ): array => [ + 'type' => (string) $body['type'], + 'data' => (array) $body['data'], + ], + array_filter( $sent, static fn( array $body ): bool => 'PostSaved' !== ( $body['type'] ?? '' ) ) + ) + ); + } + + /** + * The global styles post of the theme, made the way the Site Editor + * makes it, with what that sent forgotten. + * + * @return int + */ + private function styles_post(): int { + // Core keeps the post's ID for the request; an earlier test removed it. + \WP_Theme_JSON_Resolver::clean_cached_data(); + $id = \WP_Theme_JSON_Resolver::get_user_global_styles_post_id(); + $this->end_request(); + + return $id; + } + + /** + * The lines of a diff with a given op. + * + * @param array $diff The diff. + * @param string $op `+`, `-` or `=`. + * + * @return array + */ + private static function lines( array $diff, string $op ): array { + $lines = []; + foreach ( (array) ( $diff['lines'] ?? [] ) as $line ) { + if ( $op === ( $line['op'] ?? '' ) ) { + $lines[] = trim( (string) $line['text'] ); + } + } + + return $lines; + } + + public function test_the_styles_post_core_makes_when_the_site_editor_opens_is_not_reported(): void { + foreach ( get_posts( + [ + 'post_type' => 'wp_global_styles', + 'post_status' => 'any', + 'numberposts' => -1, + 'fields' => 'ids', + ] + ) as $id ) { + wp_delete_post( (int) $id, true ); + } + \WP_Theme_JSON_Resolver::clean_cached_data(); + + $this->assertGreaterThan( 0, \WP_Theme_JSON_Resolver::get_user_global_styles_post_id() ); + $this->assertSame( [], $this->end_request() ); + } + + public function test_a_styles_change_lists_each_setting_and_the_css(): void { + $id = $this->styles_post(); + + $this->rest( + 'POST', + '/wp/v2/global-styles/' . $id, + [ + 'styles' => [ + 'color' => [ 'background' => '#ffeedd' ], + 'elements' => [ 'link' => [ 'color' => [ 'text' => '#1e73be' ] ] ], + 'css' => 'body { margin: 0; }', + ], + 'settings' => new \stdClass(), + ] + ); + $events = $this->end_request(); + + $this->assertCount( 1, $events ); + $this->assertSame( 'StylesChanged', $events[0]['type'] ); + $this->assertSame( 'Twenty Twenty-Five', $events[0]['data']['name'] ); + $styles = array_column( (array) $events[0]['data']['changes']['styles'], null, 'path' ); + $this->assertSame( + [ + 'path' => 'styles.color.background', + 'change' => 'added', + 'new' => '#ffeedd', + ], + $styles['styles.color.background'] + ); + $this->assertSame( '#1e73be', $styles['styles.elements.link.color.text']['new'] ); + $this->assertSame( [ 'body { margin: 0; }' ], self::lines( $events[0]['data']['changes']['css'], '+' ) ); + + $this->rest( + 'POST', + '/wp/v2/global-styles/' . $id, + [ + 'styles' => [ 'color' => [ 'background' => '#000000' ] ], + 'settings' => new \stdClass(), + ] + ); + $changes = $this->end_request()[0]['data']['changes']; + $styles = array_column( (array) $changes['styles'], null, 'path' ); + + $this->assertSame( + [ + 'path' => 'styles.color.background', + 'change' => 'changed', + 'old' => '#ffeedd', + 'new' => '#000000', + ], + $styles['styles.color.background'] + ); + $this->assertSame( 'removed', $styles['styles.elements.link.color.text']['change'] ); + $this->assertSame( [ 'body { margin: 0; }' ], self::lines( $changes['css'], '-' ) ); + } + + public function test_a_style_variation_is_named_and_a_reset_is_one_change(): void { + $id = $this->styles_post(); + $variations = $this->rest( 'GET', '/wp/v2/global-styles/themes/' . self::THEME . '/variations' ); + $variation = (array) ( $variations[1] ?? $variations[0] ); + + $this->rest( + 'POST', + '/wp/v2/global-styles/' . $id, + [ + 'styles' => $variation['styles'] ?? new \stdClass(), + 'settings' => $variation['settings'] ?? new \stdClass(), + 'title' => $variation['title'], + ] + ); + $events = $this->end_request(); + + $this->assertSame( $variation['title'], $events[0]['data']['changes']['variation']['new'] ); + + // The Site Editor itself saves only the variation's styles and + // settings, without its title. + $other = (array) ( $variations[2] ?? $variations[0] ); + $this->rest( + 'POST', + '/wp/v2/global-styles/' . $id, + [ + 'styles' => $other['styles'] ?? new \stdClass(), + 'settings' => $other['settings'] ?? new \stdClass(), + ] + ); + $events = $this->end_request(); + + $this->assertSame( $other['title'], $events[0]['data']['changes']['variation']['new'] ); + + $this->rest( + 'POST', + '/wp/v2/global-styles/' . $id, + [ + 'styles' => new \stdClass(), + 'settings' => new \stdClass(), + ] + ); + + $this->assertSame( [ 'reset' => true ], $this->end_request()[0]['data']['changes'] ); + } + + public function test_a_first_customization_is_compared_with_the_theme_file_and_a_reset_back(): void { + $template = $this->rest( + 'GET', + '/wp/v2/templates/' . self::THEME . '//page', + [ 'context' => 'edit' ] + ); + $content = (string) $template['content']['raw']; + + $this->rest( 'POST', '/wp/v2/templates/' . self::THEME . '//page', [ 'content' => '

Opening hours

' . $content ] ); + $events = $this->end_request(); + + $this->assertSame( 'TemplateChanged', $events[0]['type'] ); + $data = $events[0]['data']; + $this->assertTrue( $data['first_customization'] ); + $this->assertSame( 'template', $data['kind'] ); + $this->assertSame( 'page', $data['slug'] ); + $this->assertSame( 'theme', $data['source'] ); + $this->assertSame( [ 'paragraph: Opening hours' ], self::lines( $data['changes']['blocks'], '+' ) ); + $this->assertSame( [], self::lines( $data['changes']['blocks'], '-' ), 'The theme file and the editor agree on the rest, patterns included.' ); + + $this->rest( 'POST', '/wp/v2/templates/' . self::THEME . '//page', [ 'source' => 'theme' ] ); + $events = $this->end_request(); + + $this->assertSame( 'TemplateReset', $events[0]['type'] ); + $this->assertSame( [ 'paragraph: Opening hours' ], self::lines( $events[0]['data']['changes']['blocks'], '-' ) ); + } + + public function test_a_later_edit_reports_the_title_and_blocks_and_an_unchanged_save_nothing(): void { + $template = $this->rest( 'GET', '/wp/v2/templates/' . self::THEME . '//page', [ 'context' => 'edit' ] ); + $content = (string) $template['content']['raw']; + $this->rest( 'POST', '/wp/v2/templates/' . self::THEME . '//page', [ 'content' => $content ] ); + $this->end_request(); + + $this->rest( + 'POST', + '/wp/v2/templates/' . self::THEME . '//page', + [ + 'title' => 'Pages (shop)', + 'content' => $content . '

Visit us

', + ] + ); + $events = $this->end_request(); + + $this->assertSame( 'TemplateChanged', $events[0]['type'] ); + $this->assertArrayNotHasKey( 'first_customization', $events[0]['data'] ); + $this->assertSame( 'Pages (shop)', $events[0]['data']['name'] ); + $this->assertSame( 'Pages (shop)', $events[0]['data']['changes']['title']['new'] ); + $this->assertSame( [ 'heading: Visit us' ], self::lines( $events[0]['data']['changes']['blocks'], '+' ) ); + + $current = $this->rest( 'GET', '/wp/v2/templates/' . self::THEME . '//page', [ 'context' => 'edit' ] ); + $this->rest( 'POST', '/wp/v2/templates/' . self::THEME . '//page', [ 'content' => (string) $current['content']['raw'] ] ); + + $this->assertSame( [], $this->end_request() ); + } + + public function test_a_custom_template_is_created_and_deleted_or_trashed(): void { + $created = $this->rest( + 'POST', + '/wp/v2/templates', + [ + 'slug' => 'page-opening-hours', + 'title' => 'Page: Opening hours', + 'content' => '', + ] + ); + $events = $this->end_request(); + + $this->assertSame( 'TemplateCreated', $events[0]['type'] ); + $this->assertSame( 'Page: Opening hours', $events[0]['data']['name'] ); + $this->assertSame( 'custom', $events[0]['data']['source'] ); + $this->assertSame( 2, $events[0]['data']['blocks'] ); + + $this->rest( 'DELETE', '/wp/v2/templates/' . $created['id'], [ 'force' => true ] ); + $events = $this->end_request(); + + $this->assertSame( 'TemplateDeleted', $events[0]['type'] ); + $this->assertSame( 'page-opening-hours', $events[0]['data']['slug'] ); + + $trashed = $this->rest( + 'POST', + '/wp/v2/templates', + [ + 'slug' => 'page-contact', + 'title' => 'Page: Contact', + ] + ); + $this->end_request(); + $this->rest( 'DELETE', '/wp/v2/templates/' . $trashed['id'] ); + + $this->assertSame( [ 'TemplateDeleted' ], array_column( $this->end_request(), 'type' ) ); + } + + public function test_a_template_part_has_its_area(): void { + $part = $this->rest( 'GET', '/wp/v2/template-parts/' . self::THEME . '//footer', [ 'context' => 'edit' ] ); + + $this->rest( 'POST', '/wp/v2/template-parts/' . self::THEME . '//footer', [ 'content' => (string) $part['content']['raw'] . '

Closed on Sundays

' ] ); + $events = $this->end_request(); + + $this->assertSame( 'TemplateChanged', $events[0]['type'] ); + $this->assertSame( 'template_part', $events[0]['data']['kind'] ); + $this->assertSame( 'footer', $events[0]['data']['area'] ); + $this->assertSame( [ 'paragraph: Closed on Sundays' ], self::lines( $events[0]['data']['changes']['blocks'], '+' ) ); + } + + public function test_a_font_installed_in_several_requests_is_one_row_and_removals_are_reported(): void { + $family = $this->rest( + 'POST', + '/wp/v2/font-families', + [ + 'font_family_settings' => wp_json_encode( + [ + 'name' => 'Scanfully Sans', + 'slug' => 'scanfully-sans', + 'fontFamily' => 'Scanfully Sans, sans-serif', + ] + ), + ] + ); + Collector::flush(); + $faces = []; + foreach ( [ [ 'normal', '400' ], [ 'italic', '400' ], [ 'normal', '700' ] ] as [ $style, $weight ] ) { + $faces[] = $this->rest( + 'POST', + '/wp/v2/font-families/' . $family['id'] . '/font-faces', + [ + 'font_face_settings' => wp_json_encode( + [ + 'fontFamily' => 'Scanfully Sans', + 'fontStyle' => $style, + 'fontWeight' => $weight, + 'src' => 'https://scanfully.com/fonts/scanfully-sans-' . $weight . $style . '.woff2', + ] + ), + ] + ); + Collector::flush(); + } + $events = $this->end_request(); + + $this->assertCount( 1, $events ); + $this->assertSame( 'FontInstalled', $events[0]['type'] ); + $this->assertSame( + [ + 'name' => 'Scanfully Sans', + 'slug' => 'scanfully-sans', + 'family' => true, + 'variants' => [ + [ + 'style' => 'normal', + 'weight' => '400', + ], + [ + 'style' => 'italic', + 'weight' => '400', + ], + [ + 'style' => 'normal', + 'weight' => '700', + ], + ], + ], + $events[0]['data'] + ); + + $this->rest( 'DELETE', '/wp/v2/font-families/' . $family['id'] . '/font-faces/' . $faces[2]['id'], [ 'force' => true ] ); + $events = $this->end_request(); + + $this->assertSame( 'FontDeleted', $events[0]['type'] ); + $this->assertFalse( $events[0]['data']['family'] ); + $this->assertSame( '700', $events[0]['data']['variants'][0]['weight'] ); + + $this->rest( 'DELETE', '/wp/v2/font-families/' . $family['id'], [ 'force' => true ] ); + $events = $this->end_request(); + + $this->assertSame( 'FontDeleted', $events[0]['type'] ); + $this->assertTrue( $events[0]['data']['family'] ); + $this->assertCount( 2, $events[0]['data']['variants'] ); + } +} diff --git a/tests/Integration/ThemeSettingsEventsTest.php b/tests/Integration/ThemeSettingsEventsTest.php new file mode 100644 index 0000000..488b60f --- /dev/null +++ b/tests/Integration/ThemeSettingsEventsTest.php @@ -0,0 +1,429 @@ + + */ + private array $options = []; + + /** + * Posts created by a test. + * + * @var array + */ + private array $posts = []; + + /** + * Event bodies sent to the API. + * + * @var array> + */ + private array $sent = []; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'as_get_scheduled_actions' ) || ! function_exists( 'update_option' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + if ( ! wp_get_theme( self::THEME )->exists() ) { + $this->markTestSkipped( 'Twenty Seventeen is not installed.' ); + } + require_once ABSPATH . WPINC . '/class-wp-customize-manager.php'; + + // The classic theme, set without switch_theme(): a theme switch makes + // the rest of the request quiet, and nothing resets that. + $this->restore_later( 'template', 'stylesheet', 'theme_mods_' . self::THEME, Collector::LOGO_OPTION ); + update_option( 'template', self::THEME ); + update_option( 'stylesheet', self::THEME ); + delete_option( 'theme_mods_' . self::THEME ); + delete_option( Collector::LOGO_OPTION ); + // Twenty Seventeen's features. Core fills in their defaults while + // the page loads, which has passed, so they are given in full; they + // stay for the rest of the run (core can't remove a custom + // background it never set up). + if ( ! current_theme_supports( 'custom-header' ) ) { + add_theme_support( 'custom-logo' ); + add_theme_support( + 'custom-header', + [ + 'video' => true, + 'header-text' => true, + 'uploads' => true, + 'default-text-color' => '', + 'width' => 2000, + 'height' => 1200, + ] + ); + add_theme_support( 'custom-background', [ 'default-color' => '' ] ); + } + + update_option( 'scanfully_connect_is_connected', 'yes' ); + wp_set_current_user( 1 ); + add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 3 ); + add_filter( 'scanfully_theme_settings_events_per_minute', '__return_zero' ); + unset( $GLOBALS['wp_customize'] ); + $this->forget(); + } + + protected function tearDown(): void { + if ( function_exists( 'update_option' ) ) { + foreach ( $this->posts as $id ) { + wp_delete_post( $id, true ); + } + foreach ( $this->options as $option => $value ) { + if ( null === $value ) { + delete_option( $option ); + } else { + update_option( $option, $value ); + } + } + remove_filter( 'pre_http_request', [ $this, 'capture_request' ], 10 ); + remove_filter( 'scanfully_theme_settings_events_per_minute', '__return_zero' ); + remove_filter( 'wp_doing_cron', '__return_true' ); + unset( $GLOBALS['wp_customize'], $_SERVER['REQUEST_METHOD'] ); + $this->forget(); + delete_option( 'scanfully_connect_is_connected' ); + wp_set_current_user( 0 ); + } + parent::tearDown(); + } + + /** + * Forget what the collectors noted and the jobs they queued. + */ + private function forget(): void { + Collector::reset(); + SettingsCollector::reset(); + PostCollector::reset(); + as_unschedule_all_actions( '', [], 'scanfully' ); + $this->sent = []; + } + + /** + * `pre_http_request`: keep the event sent to the API and accept it. + * + * @param mixed $preempt Whether to preempt the request. + * @param array $args The request arguments. + * @param string $url The URL. + * + * @return mixed + */ + public function capture_request( $preempt, $args, $url ) { + if ( false === strpos( (string) $url, '/timeline' ) ) { + return $preempt; + } + + $this->sent[] = json_decode( (string) ( $args['body'] ?? '' ), true ); + + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 202, + 'message' => 'Accepted', + ], + 'cookies' => [], + ]; + } + + /** + * Remember options' values so tearDown restores them. + * + * @param string ...$options The options. + */ + private function restore_later( string ...$options ): void { + foreach ( $options as $option ) { + if ( ! array_key_exists( $option, $this->options ) ) { + $this->options[ $option ] = get_option( $option, null ); + } + } + } + + /** + * An image attachment with a file name. + * + * @param string $file The file name. + * + * @return int + */ + private function image( string $file ): int { + $id = wp_insert_attachment( + [ + 'post_mime_type' => 'image/png', + 'post_title' => $file, + 'post_status' => 'inherit', + ], + $file + ); + $this->posts[] = $id; + + return $id; + } + + /** + * A Customizer for the classic theme, with core's settings and + * controls, as the publish request has it. + * + * @param string $uuid The changeset UUID, or '' for a new one. + * + * @return \WP_Customize_Manager + */ + private function customizer( string $uuid = '' ): \WP_Customize_Manager { + $args = [ 'settings_previewed' => false ]; + if ( '' !== $uuid ) { + $args['changeset_uuid'] = $uuid; + } + $manager = new \WP_Customize_Manager( $args ); + $manager->register_controls(); + $GLOBALS['wp_customize'] = $manager; + + return $manager; + } + + /** + * Publish settings in the Customizer. + * + * @param array $values Setting ID to value. + * + * @return void + */ + private function publish( array $values ): void { + $data = []; + foreach ( $values as $id => $value ) { + $data[ $id ] = [ 'value' => $value ]; + } + $result = $this->customizer()->save_changeset_post( + [ + 'data' => $data, + 'status' => 'publish', + ] + ); + $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' ); + } + + /** + * End the "request" and run the jobs, as Action Scheduler would; return + * the ThemeSettingsChanged events sent: user and data. + * + * @return array, data: array}> + */ + private function sent_events(): array { + Collector::flush(); + + $actions = as_get_scheduled_actions( + [ + 'hook__in' => [ EventsController::ACTION_BUILD_CONTENT_EVENT ], + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + 'orderby' => 'action_id', + 'order' => 'ASC', + ] + ); + foreach ( $actions as $id => $action ) { + \ActionScheduler::store()->mark_complete( $id ); + do_action_ref_array( $action->get_hook(), array_values( $action->get_args() ) ); + } + + $events = []; + foreach ( $this->sent as $body ) { + if ( 'ThemeSettingsChanged' === ( $body['type'] ?? '' ) ) { + $events[] = [ + 'user' => (array) $body['user'], + 'data' => (array) $body['data'], + ]; + } + } + + return $events; + } + + /** + * The settings of an event by ID. + * + * @param array $data The event data. + * + * @return array> + */ + private static function settings( array $data ): array { + return array_column( (array) ( $data['settings'] ?? [] ), null, 'id' ); + } + + public function test_a_customizer_publish_reports_colours_with_their_labels(): void { + set_theme_mod( 'background_color', 'ffffff' ); + $this->forget(); + + $this->publish( + [ + 'background_color' => '#1e73be', + 'header_textcolor' => 'blank', + 'blogdescription' => 'Reported as a setting', + ] + ); + $events = $this->sent_events(); + + $this->assertCount( 1, $events ); + $data = $events[0]['data']; + $this->assertSame( 'customizer', $data['source'] ); + $this->assertSame( 'Twenty Seventeen', $data['name'] ); + $settings = self::settings( $data ); + $this->assertSame( [ 'background_color', 'header_textcolor' ], array_keys( $settings ) ); + $this->assertSame( 'Background Color', $settings['background_color']['label'] ); + $this->assertSame( 'color', $settings['background_color']['kind'] ); + $this->assertSame( 'ffffff', $settings['background_color']['old'] ); + $this->assertSame( '1e73be', $settings['background_color']['new'] ); + $this->assertSame( 'blank', $settings['header_textcolor']['new'] ); + $this->assertSame( 1, (int) $events[0]['user']['id'] ); + } + + public function test_the_header_image_from_the_customizer_is_one_change_with_its_file(): void { + $image = $this->image( 'header-new.jpg' ); + $url = 'http://localhost:8889/wp-content/uploads/header-new.jpg'; + + $this->publish( + [ + 'header_image' => $url, + 'header_image_data' => [ + 'url' => $url, + 'thumbnail_url' => $url, + 'attachment_id' => $image, + 'width' => 2000, + 'height' => 1200, + ], + ] + ); + $settings = self::settings( $this->sent_events()[0]['data'] ); + + $this->assertSame( [ 'header_image' ], array_keys( $settings ) ); + $this->assertSame( 'media', $settings['header_image']['kind'] ); + $this->assertSame( $url, $settings['header_image']['new'] ); + $this->assertSame( 'header-new.jpg', $settings['header_image']['new_file'] ); + } + + public function test_the_logo_from_the_customizer_names_its_file(): void { + $logo = $this->image( 'logo-new.png' ); + + $this->publish( [ 'custom_logo' => $logo ] ); + $data = $this->sent_events()[0]['data']; + + $this->assertSame( + [ + 'id' => (string) $logo, + 'file' => 'logo-new.png', + ], + $data['logo']['new'] + ); + $this->assertArrayNotHasKey( 'settings', $data ); + } + + public function test_additional_css_from_the_customizer_is_sent_as_lines(): void { + $this->posts[] = wp_update_custom_css_post( ".site-header {\n\tpadding: 20px;\n}" )->ID; + $this->forget(); + + $this->publish( [ 'custom_css[' . self::THEME . ']' => ".site-header {\n\tpadding: 32px;\n}" ] ); + $data = $this->sent_events()[0]['data']; + + $this->assertSame( 1, $data['css']['added'] ); + $this->assertSame( 1, $data['css']['removed'] ); + $this->assertContains( 'padding: 32px;', array_map( 'trim', array_column( $data['css']['lines'], 'text' ) ) ); + $this->assertArrayNotHasKey( 'settings', $data, 'The CSS setting is the css field, not a setting.' ); + } + + public function test_a_scheduled_change_is_reported_when_cron_publishes_it_by_its_author(): void { + set_theme_mod( 'background_color', 'ffffff' ); + $this->forget(); + + $manager = $this->customizer(); + $result = $manager->save_changeset_post( + [ + 'data' => [ 'background_color' => [ 'value' => '#000000' ] ], + 'status' => 'future', + 'date_gmt' => gmdate( 'Y-m-d H:i:s', time() + HOUR_IN_SECONDS ), + ] + ); + $this->assertIsArray( $result ); + $this->assertSame( [], $this->sent_events(), 'Nothing changed yet.' ); + + // Later, cron publishes it, signed out. + wp_set_current_user( 0 ); + add_filter( 'wp_doing_cron', '__return_true' ); + $this->customizer( $manager->changeset_uuid() ); + wp_publish_post( $manager->changeset_post_id() ); + $events = $this->sent_events(); + + $this->assertCount( 1, $events ); + $this->assertTrue( $events[0]['data']['scheduled'] ); + $this->assertArrayNotHasKey( '_actor', $events[0]['data'] ); + $this->assertSame( 1, (int) $events[0]['user']['id'] ); + $this->assertSame( '000000', self::settings( $events[0]['data'] )['background_color']['new'] ); + } + + public function test_theme_mods_changed_by_code_are_reported(): void { + set_theme_mod( 'background_color', 'abcdef' ); + set_theme_mod( 'nav_menu_locations', [ 'top' => 3 ] ); + $events = $this->sent_events(); + + $this->assertCount( 1, $events ); + $this->assertSame( 'other', $events[0]['data']['source'] ); + $this->assertSame( [ 'background_color' ], array_keys( self::settings( $events[0]['data'] ) ) ); + } + + public function test_the_logo_set_over_rest_is_reported(): void { + $logo = $this->image( 'block-logo.png' ); + $request = new \WP_REST_Request( 'POST', '/wp/v2/settings' ); + $request->set_body_params( [ 'site_logo' => $logo ] ); + $response = rest_do_request( $request ); + $this->assertSame( 200, $response->get_status() ); + + $data = $this->sent_events()[0]['data']; + + $this->assertSame( 'other', $data['source'] ); + $this->assertSame( 'block-logo.png', $data['logo']['new']['file'] ); + } + + public function test_additional_css_saved_by_a_plugin_is_reported(): void { + $this->posts[] = wp_update_custom_css_post( 'body { color: red; }' )->ID; + $data = $this->sent_events()[0]['data']; + + $this->assertSame( 1, $data['css']['added'] ); + $this->assertSame( 0, $data['css']['removed'] ); + } + + public function test_theme_mods_written_on_a_page_view_are_not_reported(): void { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + set_theme_mod( 'background_color', '123456' ); + + $this->assertSame( [], $this->sent_events() ); + } +} diff --git a/tests/Integration/WidgetEventsTest.php b/tests/Integration/WidgetEventsTest.php new file mode 100644 index 0000000..a408ccb --- /dev/null +++ b/tests/Integration/WidgetEventsTest.php @@ -0,0 +1,343 @@ + + */ + private array $options = []; + + /** + * Event bodies sent to the API. + * + * @var array> + */ + private array $sent = []; + + protected function setUp(): void { + parent::setUp(); + + if ( ! function_exists( 'as_get_scheduled_actions' ) || ! function_exists( 'register_sidebar' ) ) { + $this->markTestSkipped( 'WordPress not available. Run this suite under wp-env.' ); + } + + // A theme switched by an earlier test of this run counts for the + // whole process; in a site it is a request of its own. + unset( $GLOBALS['wp_actions']['switch_theme'] ); + foreach ( [ 'sidebars_widgets', 'widget_block', 'widget_text', 'widget_search' ] as $option ) { + $this->options[ $option ] = get_option( $option ); + } + register_sidebar( + [ + 'id' => 'scanfully-sidebar', + 'name' => 'Test sidebar', + ] + ); + register_sidebar( + [ + 'id' => 'scanfully-footer', + 'name' => 'Test footer', + ] + ); + + update_option( 'scanfully_connect_is_connected', 'yes' ); + as_unschedule_all_actions( '', [], 'scanfully' ); + Collector::reset(); + $this->sent = []; + wp_set_current_user( 1 ); + add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 3 ); + add_filter( 'scanfully_widget_events_per_minute', '__return_zero' ); + unset( $_SERVER['REQUEST_METHOD'] ); + } + + protected function tearDown(): void { + if ( function_exists( 'unregister_sidebar' ) ) { + foreach ( $this->options as $option => $value ) { + update_option( $option, $value ); + } + unregister_sidebar( 'scanfully-sidebar' ); + unregister_sidebar( 'scanfully-footer' ); + remove_filter( 'pre_http_request', [ $this, 'capture_request' ], 10 ); + remove_all_filters( 'scanfully_widget_events_per_minute' ); + unset( $_SERVER['REQUEST_METHOD'] ); + Collector::reset(); + as_unschedule_all_actions( '', [], 'scanfully' ); + delete_option( 'scanfully_connect_is_connected' ); + wp_set_current_user( 0 ); + } + parent::tearDown(); + } + + /** + * `pre_http_request`: keep the event sent to the API and accept it. + * + * @param mixed $preempt Whether to preempt the request. + * @param array $args The request arguments. + * @param string $url The URL. + * + * @return mixed + */ + public function capture_request( $preempt, $args, $url ) { + if ( false === strpos( (string) $url, '/timeline' ) ) { + return $preempt; + } + + $this->sent[] = json_decode( (string) ( $args['body'] ?? '' ), true ); + + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 202, + 'message' => 'Accepted', + ], + 'cookies' => [], + ]; + } + + /** + * End the "request", run the jobs as Action Scheduler would, and return + * the WidgetsChanged events sent: their data. + * + * @return array> + */ + private function sent_widget_events(): array { + Collector::flush(); + + $actions = as_get_scheduled_actions( + [ + 'hook__in' => [ EventsController::ACTION_BUILD_CONTENT_EVENT, EventsController::ACTION_SEND_EVENT ], + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'per_page' => -1, + 'orderby' => 'action_id', + 'order' => 'ASC', + ] + ); + foreach ( $actions as $id => $action ) { + \ActionScheduler::store()->mark_complete( $id ); + do_action_ref_array( $action->get_hook(), array_values( $action->get_args() ) ); + } + + $events = []; + foreach ( $this->sent as $body ) { + if ( 'WidgetsChanged' === $body['type'] ) { + $events[] = (array) $body['data']; + } + } + $this->sent = []; + + return $events; + } + + /** + * Widgets in the test areas, set in an earlier "request". + * + * @param array> $areas Area ID to widget IDs. + * @param array> $instances Option to instances. + * + * @return void + */ + private function given( array $areas, array $instances ): void { + foreach ( $instances as $option => $value ) { + update_option( $option, $value + [ '_multiwidget' => 1 ] ); + } + $sidebars = wp_get_sidebars_widgets(); + foreach ( $areas as $area => $ids ) { + $sidebars[ $area ] = $ids; + } + wp_set_sidebars_widgets( $sidebars ); + Collector::reset(); + } + + public function test_a_block_widget_added_in_the_block_widget_editor(): void { + $this->given( [ 'scanfully-sidebar' => [] ], [] ); + + $request = new \WP_REST_Request( 'POST', '/wp/v2/widgets' ); + $request->set_body_params( + [ + 'id_base' => 'block', + 'sidebar' => 'scanfully-sidebar', + 'instance' => [ 'raw' => [ 'content' => '

Opening hours: 9 to 5

' ] ], + ] + ); + $this->assertSame( 201, rest_do_request( $request )->get_status() ); + + $events = $this->sent_widget_events(); + $this->assertCount( 1, $events ); + $widget = $events[0]['widgets'][0]; + $this->assertSame( 'added', $widget['action'] ); + $this->assertSame( 'block', $widget['type'] ); + $this->assertSame( 'Paragraph', $widget['type_label'] ); + $this->assertSame( '', $widget['title'], 'A block widget has no title; its text is not one.' ); + $this->assertSame( 'Opening hours: 9 to 5', $widget['excerpt'] ); + $this->assertSame( + [ + 'id' => 'scanfully-sidebar', + 'name' => 'Test sidebar', + ], + $widget['area'] + ); + $this->assertSame( 'Paragraph', $events[0]['name'] ); + } + + public function test_a_text_widget_edit_reports_the_title_and_the_lines(): void { + $this->given( + [ 'scanfully-sidebar' => [ 'text-91' ] ], + [ + 'widget_text' => [ + 91 => [ + 'title' => 'Hours', + 'text' => "Monday 9 to 5\nTuesday 9 to 5", + ], + ], + ] + ); + + $instances = get_option( 'widget_text' ); + $instances[91] = [ + 'title' => 'Opening hours', + 'text' => "Monday 9 to 5\nTuesday 10 to 4", + ]; + update_option( 'widget_text', $instances ); + + $events = $this->sent_widget_events(); + $this->assertCount( 1, $events ); + $widget = $events[0]['widgets'][0]; + $this->assertSame( 'changed', $widget['action'] ); + $this->assertSame( 'Text', $widget['type_label'] ); + $this->assertSame( 'Opening hours', $widget['title'] ); + $this->assertSame( 'Hours', $widget['title_old'] ); + $this->assertSame( 1, $widget['content']['added'] ); + $this->assertSame( 1, $widget['content']['removed'] ); + } + + public function test_moving_and_removing_widgets_in_one_save_is_one_row(): void { + $this->given( + [ + 'scanfully-sidebar' => [ 'search-91', 'text-92' ], + 'scanfully-footer' => [], + ], + [ + 'widget_search' => [ 91 => [ 'title' => 'Find' ] ], + 'widget_text' => [ + 92 => [ + 'title' => 'Promo', + 'text' => 'Sale', + ], + ], + ] + ); + + $sidebars = wp_get_sidebars_widgets(); + $sidebars['scanfully-sidebar'] = []; + $sidebars['scanfully-footer'] = [ 'search-91' ]; + $sidebars['wp_inactive_widgets'] = array_merge( (array) ( $sidebars['wp_inactive_widgets'] ?? [] ), [ 'text-92' ] ); + wp_set_sidebars_widgets( $sidebars ); + + $events = $this->sent_widget_events(); + $this->assertCount( 1, $events ); + $actions = array_column( $events[0]['widgets'], 'action', 'id' ); + ksort( $actions ); + $this->assertSame( + [ + 'search-91' => 'moved', + 'text-92' => 'removed', + ], + $actions + ); + $moved = array_column( $events[0]['widgets'], null, 'id' )['search-91']; + $this->assertSame( 'Test sidebar', $moved['old_area']['name'] ); + $this->assertSame( 'Test footer', $moved['area']['name'] ); + // Their settings didn't change: the job reads the titles. + $this->assertSame( + [ + 'search-91' => 'Find', + 'text-92' => 'Promo', + ], + array_column( $events[0]['widgets'], 'title', 'id' ) + ); + } + + public function test_a_widget_removed_without_a_settings_change_is_named_by_its_title(): void { + $this->given( + [ 'scanfully-sidebar' => [ 'text-95' ] ], + [ + 'widget_text' => [ + 95 => [ + 'title' => 'Opening hours', + 'text' => 'Mon', + ], + ], + ] + ); + + // What WP-CLI's `widget deactivate` and the classic Widgets screen's + // drag do: only the areas change. + $sidebars = wp_get_sidebars_widgets(); + $sidebars['scanfully-sidebar'] = []; + $sidebars['wp_inactive_widgets'] = array_merge( (array) ( $sidebars['wp_inactive_widgets'] ?? [] ), [ 'text-95' ] ); + wp_set_sidebars_widgets( $sidebars ); + + $events = $this->sent_widget_events(); + $this->assertCount( 1, $events ); + $this->assertSame( 'removed', $events[0]['widgets'][0]['action'] ); + $this->assertSame( 'Opening hours', $events[0]['widgets'][0]['title'] ); + $this->assertSame( 'Opening hours', $events[0]['name'] ); + } + + public function test_loading_the_widgets_screen_reports_nothing(): void { + $this->given( + [ 'scanfully-sidebar' => [ 'text-93' ] ], + [ 'widget_text' => [ 93 => [ 'title' => 'Hours' ] ] ] + ); + $_SERVER['REQUEST_METHOD'] = 'GET'; + + // What retrieve_widgets() does with a lost widget on a page load. + $sidebars = wp_get_sidebars_widgets(); + $sidebars['scanfully-sidebar'] = []; + $sidebars['wp_inactive_widgets'] = array_merge( (array) ( $sidebars['wp_inactive_widgets'] ?? [] ), [ 'text-93' ] ); + wp_set_sidebars_widgets( $sidebars ); + + $this->assertSame( [], $this->sent_widget_events() ); + } + + public function test_saving_without_changes_reports_nothing(): void { + $this->given( + [ 'scanfully-sidebar' => [ 'text-94' ] ], + [ + 'widget_text' => [ + 94 => [ + 'title' => 'Hours', + 'text' => 'Mon', + ], + ], + ] + ); + + update_option( 'widget_text', get_option( 'widget_text' ) ); + wp_set_sidebars_widgets( wp_get_sidebars_widgets() ); + + $this->assertSame( [], $this->sent_widget_events() ); + } +} diff --git a/tests/Unit/Cron/ScheduleEventsTest.php b/tests/Unit/Cron/ScheduleEventsTest.php index 9d8ec36..9143143 100644 --- a/tests/Unit/Cron/ScheduleEventsTest.php +++ b/tests/Unit/Cron/ScheduleEventsTest.php @@ -56,7 +56,7 @@ static function ( $timestamp, $hook, $args, $group, $unique = false ) use ( &$un Controller::schedule_events(); - $this->assertCount( 5, $unique_flags ); + $this->assertCount( 7, $unique_flags ); $this->assertSame( [ true ], array_values( array_unique( $unique_flags ) ), 'Every job must be scheduled as unique.' ); } diff --git a/tests/Unit/Events/AccountChangeEventsTest.php b/tests/Unit/Events/AccountChangeEventsTest.php new file mode 100644 index 0000000..f1e991f --- /dev/null +++ b/tests/Unit/Events/AccountChangeEventsTest.php @@ -0,0 +1,373 @@ + + */ + private array $users = []; + + /** + * In-memory transient store. + * + * @var array + */ + private array $transients = []; + + /** + * Arguments of scheduled jobs. + * + * @var array> + */ + private array $scheduled = []; + + /** + * The callbacks events added, by hook: [callback, accepted args]. + * + * @var array + */ + private array $listeners = []; + + protected function setUp(): void { + parent::setUp(); + + $defaults = [ + 'pending' => [], + 'resetting' => [], + 'created' => [], + 'authenticating' => false, + ]; + foreach ( $defaults as $property => $value ) { + $reset = new ReflectionProperty( PasswordChanged::class, $property ); + $reset->setAccessible( true ); + $reset->setValue( null, $value ); + } + + $this->add_user( 4, 'Bob', [ 'administrator' ] ); + $this->add_user( 5, 'Sue', [ 'subscriber' ] ); + + Functions\when( 'get_userdata' )->alias( fn( int $id ) => $this->users[ $id ] ?? false ); + Functions\when( 'user_can' )->alias( static fn( $user ) => in_array( 'administrator', (array) $user->roles, true ) ); + Functions\when( 'is_email' )->alias( static fn( $email ) => false !== filter_var( $email, FILTER_VALIDATE_EMAIL ) ); + Functions\when( 'get_transient' )->alias( fn( string $key ) => array_key_exists( $key, $this->transients ) ? $this->transients[ $key ] : false ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value ) { + $this->transients[ $key ] = $value; + return true; + } + ); + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'wp_unslash' )->alias( 'stripslashes' ); + Functions\when( 'wp_get_current_user' )->justReturn( + (object) [ + 'ID' => 1, + 'display_name' => 'Admin', + ] + ); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'as_schedule_single_action' )->alias( + function ( $timestamp, $hook, $args ) { + $this->scheduled[] = $args; + return 1; + } + ); + Functions\when( 'add_action' )->alias( + function ( $hook, $callback, $priority = 10, $accepted_args = 1 ) { + $this->listeners[ $hook ] = [ $callback, $accepted_args ]; + return true; + } + ); + Actions\expectDone( PasswordChanged::ACTION )->zeroOrMoreTimes()->whenHappen( + function ( ...$args ) { + $this->fire( PasswordChanged::ACTION, ...$args ); + } + ); + Functions\when( 'add_filter' )->alias( + function ( $hook, $callback, $priority = 10, $accepted_args = 1 ) { + $this->listeners[ $hook ] = [ $callback, $accepted_args ]; + return true; + } + ); + } + + /** + * Add a user. + * + * @param int $id User ID. + * @param string $name Display name. + * @param array $roles Roles. + * + * @return \WP_User + */ + private function add_user( int $id, string $name, array $roles ) { + $user = Mockery::mock( 'WP_User' ); + $user->ID = $id; + $user->display_name = $name; + $user->first_name = ''; + $user->last_name = ''; + $user->roles = $roles; + $user->user_login = strtolower( $name ); + $user->user_email = strtolower( $name ) . '@scanfully.com'; + $user->user_pass = '$wp$2y$10$new-hash'; + + $this->users[ $id ] = $user; + + return $user; + } + + /** + * Run a hook the way WordPress would, with the arguments its listener + * accepts. + * + * @param string $hook The hook. + * @param mixed ...$args The hook arguments. + * + * @return void + */ + private function fire( string $hook, ...$args ): void { + $this->assertArrayHasKey( $hook, $this->listeners, "Nothing listens to $hook." ); + [ $callback, $accepted ] = $this->listeners[ $hook ]; + $callback( ...array_slice( $args, 0, $accepted ) ); + } + + /** + * The user as it was before a profile update. + * + * @param int $id User ID. + * @param array $fields Fields that were different. + * + * @return object + */ + private function before( int $id, array $fields ): object { + $before = clone $this->users[ $id ]; + foreach ( $fields as $field => $value ) { + $before->$field = $value; + } + + return $before; + } + + /** + * The types of the queued events. + * + * @return array + */ + private function types(): array { + return array_column( $this->scheduled, 'type' ); + } + + /** + * End the request: noted password changes are sent. + * + * @return void + */ + private function end_request(): void { + $this->fire( 'shutdown' ); + } + + public function test_a_password_changed_through_a_profile_update_is_reported(): void { + new PasswordChanged(); + + $this->fire( 'profile_update', 4, $this->before( 4, [ 'user_pass' => '$wp$2y$10$old-hash' ] ), [] ); + $this->assertSame( [], $this->scheduled, 'Nothing is sent before the end of the request.' ); + $this->end_request(); + + $this->assertSame( [ 'PasswordChanged' ], $this->types() ); + $this->assertSame( + [ + 'id' => 4, + 'name' => 'Bob', + 'email' => 'bob@scanfully.com', + 'roles' => [ 'administrator' ], + 'via' => 'profile', + ], + $this->scheduled[0]['data'] + ); + $this->assertStringNotContainsString( 'hash', (string) json_encode( $this->scheduled ), 'Never the hash.' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + } + + public function test_a_profile_update_on_newer_wordpress_is_reported_as_profile(): void { + new PasswordChanged(); + + // wp_update_user() fires wp_set_password before profile_update. + $this->fire( 'wp_set_password', 'new-plain-password', 4, $this->users[4] ); + $this->fire( 'profile_update', 4, $this->before( 4, [ 'user_pass' => '$wp$2y$10$old-hash' ] ), [] ); + $this->end_request(); + + $this->assertSame( [ 'PasswordChanged' ], $this->types() ); + $this->assertSame( 'profile', $this->scheduled[0]['data']['via'] ); + } + + public function test_a_profile_update_that_keeps_the_password_is_not_reported(): void { + new PasswordChanged(); + + $this->fire( 'profile_update', 4, $this->before( 4, [ 'display_name' => 'Robert' ] ), [] ); + $this->end_request(); + + $this->assertSame( [], $this->scheduled ); + } + + public function test_a_reset_with_a_reset_link_is_reported_once_as_reset(): void { + new PasswordChanged(); + + $this->fire( 'password_reset', $this->users[4], 'new-plain-password' ); + $this->fire( 'wp_set_password', 'new-plain-password', 4, $this->users[4] ); + $this->fire( 'after_password_reset', $this->users[4], 'new-plain-password' ); + $this->end_request(); + + $this->assertSame( [ 'PasswordChanged' ], $this->types() ); + $this->assertSame( 'reset', $this->scheduled[0]['data']['via'] ); + $this->assertStringNotContainsString( 'new-plain-password', (string) json_encode( $this->scheduled ), 'Never the password.' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + } + + public function test_a_reset_on_a_site_whose_wp_set_password_has_no_action_is_still_reported_as_reset(): void { + new PasswordChanged(); + + $this->fire( 'password_reset', $this->users[4], 'new-plain-password' ); + $this->fire( 'after_password_reset', $this->users[4], 'new-plain-password' ); + $this->end_request(); + + $this->assertSame( 'reset', $this->scheduled[0]['data']['via'] ); + } + + public function test_setting_a_password_directly_is_reported_as_other(): void { + new PasswordChanged(); + + $this->fire( 'wp_set_password', 'new-plain-password', 4, $this->users[4] ); + $this->end_request(); + + $this->assertSame( [ 'PasswordChanged' ], $this->types() ); + $this->assertSame( 'other', $this->scheduled[0]['data']['via'] ); + } + + public function test_a_newer_hash_stored_while_logging_in_is_not_a_change(): void { + new PasswordChanged(); + + PasswordChanged::note_authentication_started( null ); + $this->fire( 'wp_set_password', 'same-plain-password', 4, $this->users[4] ); + PasswordChanged::note_authentication_done( $this->users[4] ); + $this->end_request(); + + $this->assertSame( [], $this->scheduled ); + } + + public function test_the_first_password_of_a_new_user_is_not_reported(): void { + new PasswordChanged(); + + // Newer WordPress fires wp_set_password for a new user before user_register. + $this->fire( 'wp_set_password', 'new-plain-password', 4, $this->users[4] ); + $this->fire( 'user_register', 4, [] ); + $this->end_request(); + + $this->assertSame( [], $this->scheduled ); + } + + public function test_a_password_change_of_an_account_without_elevated_rights_is_not_reported(): void { + new PasswordChanged(); + + $this->fire( 'wp_set_password', 'new-plain-password', 5, $this->users[5] ); + $this->fire( 'profile_update', 5, $this->before( 5, [ 'user_pass' => '$wp$2y$10$old-hash' ] ), [] ); + $this->end_request(); + + $this->assertSame( [], $this->scheduled ); + } + + public function test_a_changed_email_address_is_reported_with_the_old_and_new_address(): void { + new EmailChanged(); + + // WordPress slashes the old address before profile_update. + $this->fire( 'profile_update', 4, $this->before( 4, [ 'user_email' => "o\\'brien@scanfully.com" ] ), [] ); + + $this->assertSame( [ 'EmailChanged' ], $this->types() ); + $this->assertSame( 'Admin', $this->scheduled[0]['user']['name'], 'The actor is who made the change.' ); + $this->assertSame( + [ + 'id' => 4, + 'name' => 'Bob', + 'email' => 'bob@scanfully.com', + 'roles' => [ 'administrator' ], + 'old_email' => "o'brien@scanfully.com", + ], + $this->scheduled[0]['data'] + ); + } + + public function test_a_profile_update_that_keeps_the_email_address_is_not_reported(): void { + new EmailChanged(); + + $this->fire( 'profile_update', 4, $this->before( 4, [ 'display_name' => 'Robert' ] ), [] ); + + $this->assertSame( [], $this->scheduled ); + } + + public function test_a_changed_email_address_of_an_account_without_elevated_rights_is_not_reported(): void { + new EmailChanged(); + + $this->fire( 'profile_update', 5, $this->before( 5, [ 'user_email' => 'old@scanfully.com' ] ), [] ); + + $this->assertSame( [], $this->scheduled ); + } + + public function test_granting_and_revoking_super_admin_is_reported_with_the_account(): void { + new SuperAdminGranted(); + new SuperAdminRevoked(); + + $this->fire( 'granted_super_admin', 4 ); + $this->fire( 'revoked_super_admin', 4 ); + + $this->assertSame( [ 'SuperAdminGranted', 'SuperAdminRevoked' ], $this->types() ); + $expected = [ + 'id' => 4, + 'name' => 'Bob', + 'email' => 'bob@scanfully.com', + 'roles' => [ 'administrator' ], + ]; + $this->assertSame( $expected, $this->scheduled[0]['data'] ); + $this->assertSame( $expected, $this->scheduled[1]['data'] ); + $this->assertSame( 'Admin', $this->scheduled[0]['user']['name'], 'The actor is who made the change.' ); + } + + public function test_a_revoke_is_reported_even_when_the_account_has_no_role_on_the_site(): void { + new SuperAdminRevoked(); + + // Without super admin rights the account has nothing left on this site. + $this->fire( 'revoked_super_admin', 5 ); + + $this->assertSame( [ 'SuperAdminRevoked' ], $this->types() ); + $this->assertSame( 'sue@scanfully.com', $this->scheduled[0]['data']['email'] ); + } + + public function test_an_unknown_user_is_not_reported(): void { + new SuperAdminGranted(); + + $this->fire( 'granted_super_admin', 999 ); + + $this->assertSame( [], $this->scheduled ); + } +} diff --git a/tests/Unit/Events/AppPasswordEventsTest.php b/tests/Unit/Events/AppPasswordEventsTest.php new file mode 100644 index 0000000..6178bf6 --- /dev/null +++ b/tests/Unit/Events/AppPasswordEventsTest.php @@ -0,0 +1,290 @@ + + */ + private array $users = []; + + /** + * In-memory transient store. + * + * @var array + */ + private array $transients = []; + + /** + * Arguments of scheduled jobs. + * + * @var array> + */ + private array $scheduled = []; + + /** + * $_SERVER before the test. + * + * @var array + */ + private array $server = []; + + protected function setUp(): void { + parent::setUp(); + $this->server = $_SERVER; + unset( $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'], $_SERVER['HTTP_CF_CONNECTING_IP'], $_SERVER['HTTP_X_REAL_IP'], $_SERVER['HTTP_X_FORWARDED_FOR'] ); + Functions\when( 'wp_unslash' )->returnArg(); + Functions\when( 'sanitize_text_field' )->alias( static fn( $value ) => trim( (string) $value ) ); + + $this->add_user( 4, 'Bob', [ 'administrator' ] ); + $this->add_user( 5, 'Sue', [ 'subscriber' ] ); + + Functions\when( 'get_userdata' )->alias( fn( int $id ) => $this->users[ $id ] ?? false ); + Functions\when( 'user_can' )->alias( static fn( $user ) => in_array( 'administrator', (array) $user->roles, true ) ); + Functions\when( 'is_email' )->alias( static fn( $email ) => false !== filter_var( $email, FILTER_VALIDATE_EMAIL ) ); + Functions\when( 'get_transient' )->alias( fn( string $key ) => array_key_exists( $key, $this->transients ) ? $this->transients[ $key ] : false ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value ) { + $this->transients[ $key ] = $value; + return true; + } + ); + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'wp_get_current_user' )->justReturn( + (object) [ + 'ID' => 1, + 'display_name' => 'Admin', + ] + ); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'as_schedule_single_action' )->alias( + function ( $timestamp, $hook, $args ) { + $this->scheduled[] = $args; + return 1; + } + ); + } + + protected function tearDown(): void { + $_SERVER = $this->server; + parent::tearDown(); + } + + /** + * Add a user. + * + * @param int $id User ID. + * @param string $name Display name. + * @param array $roles Roles. + * + * @return void + */ + private function add_user( int $id, string $name, array $roles ): void { + $user = Mockery::mock( 'WP_User' ); + $user->ID = $id; + $user->display_name = $name; + $user->first_name = ''; + $user->last_name = ''; + $user->roles = $roles; + $user->user_login = strtolower( $name ); + $user->user_email = strtolower( $name ) . '@scanfully.com'; + + $this->users[ $id ] = $user; + } + + /** + * An application password record as WordPress stores it. + * + * @param array $fields Fields to change. + * + * @return array + */ + private function item( array $fields = [] ): array { + return array_merge( + [ + 'uuid' => '6f8f1c2e-7a5b-4c3d-9e1f-2a3b4c5d6e7f', + 'app_id' => '', + 'name' => 'Zapier', + 'password' => '$generic$hashed-password', + 'created' => 1760000000, + 'last_used' => null, + 'last_ip' => null, + ], + $fields + ); + } + + /** + * Run a hook's callbacks the way WordPress would, with the arguments the + * listener accepts. + * + * @param string $hook The hook. + * @param mixed ...$args The hook arguments. + * + * @return void + */ + private function run_listener( string $hook, ...$args ): void { + $listener = null; + $accepted = 1; + Actions\expectAdded( $hook )->whenHappen( + static function ( $callback, $priority, $accepted_args ) use ( &$listener, &$accepted ) { + $listener = $callback; + $accepted = $accepted_args; + } + ); + + $this->event_for( $hook ); + $this->assertIsCallable( $listener ); + $listener( ...array_slice( $args, 0, $accepted ) ); + } + + /** + * Create the event that listens to a hook. + * + * @param string $hook The hook. + * + * @return object + */ + private function event_for( string $hook ): object { + $events = [ + 'wp_create_application_password' => AppPasswordCreated::class, + 'wp_delete_application_password' => AppPasswordRevoked::class, + 'application_password_did_authenticate' => AppPasswordFirstUsed::class, + ]; + + return new $events[ $hook ](); + } + + public function test_a_new_application_password_of_an_elevated_account_is_reported(): void { + $this->run_listener( 'wp_create_application_password', 4, $this->item(), 'abcd efgh ijkl mnop qrst uvwx', [ 'name' => 'Zapier' ] ); + + $this->assertCount( 1, $this->scheduled ); + $this->assertSame( 'AppPasswordCreated', $this->scheduled[0]['type'] ); + $this->assertSame( 'Admin', $this->scheduled[0]['user']['name'], 'The actor is whoever created it.' ); + $this->assertSame( + [ + 'id' => 4, + 'name' => 'Bob', + 'email' => 'bob@scanfully.com', + 'roles' => [ 'administrator' ], + 'app_name' => 'Zapier', + 'app_id' => '6f8f1c2e-7a5b-4c3d-9e1f-2a3b4c5d6e7f', + ], + $this->scheduled[0]['data'] + ); + + $encoded = (string) json_encode( $this->scheduled ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + $this->assertStringNotContainsString( 'abcd efgh', $encoded, 'Never the password.' ); + $this->assertStringNotContainsString( 'hashed-password', $encoded, 'Never the hash.' ); + } + + public function test_a_new_application_password_of_another_account_is_not_reported(): void { + $this->run_listener( 'wp_create_application_password', 5, $this->item(), 'abcd efgh ijkl mnop qrst uvwx', [] ); + $this->run_listener( 'wp_create_application_password', 999, $this->item(), 'abcd efgh ijkl mnop qrst uvwx', [] ); + + $this->assertSame( [], $this->scheduled ); + } + + public function test_a_revoked_application_password_is_reported_with_when_it_was_last_used(): void { + $this->run_listener( 'wp_delete_application_password', 4, $this->item( [ 'last_used' => 1759492800 ] ) ); + + $this->assertSame( 'AppPasswordRevoked', $this->scheduled[0]['type'] ); + $this->assertSame( + [ + 'id' => 4, + 'name' => 'Bob', + 'email' => 'bob@scanfully.com', + 'roles' => [ 'administrator' ], + 'app_name' => 'Zapier', + 'app_id' => '6f8f1c2e-7a5b-4c3d-9e1f-2a3b4c5d6e7f', + 'last_used' => '2025-10-03T12:00:00Z', + ], + $this->scheduled[0]['data'] + ); + $this->assertStringNotContainsString( 'hashed-password', (string) json_encode( $this->scheduled ), 'Never the hash.' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + } + + public function test_a_never_used_application_password_has_an_empty_last_used(): void { + $this->run_listener( 'wp_delete_application_password', 4, $this->item() ); + + $this->assertSame( '', $this->scheduled[0]['data']['last_used'] ); + } + + public function test_a_revoked_application_password_of_another_account_is_not_reported(): void { + $this->run_listener( 'wp_delete_application_password', 5, $this->item() ); + + $this->assertSame( [], $this->scheduled ); + } + + public function test_the_first_use_of_an_application_password_is_reported_with_where_it_came_from(): void { + $_SERVER['REMOTE_ADDR'] = '203.0.113.9'; + $_SERVER['HTTP_X_FORWARDED_FOR'] = '198.51.100.7'; + $_SERVER['HTTP_USER_AGENT'] = 'Zapier'; + Functions\expect( 'wp_get_current_user' )->never(); + + $this->run_listener( 'application_password_did_authenticate', $this->users[4], $this->item() ); + + $this->assertSame( 'AppPasswordFirstUsed', $this->scheduled[0]['type'] ); + $this->assertSame( + [ + 'id' => 4, + 'name' => 'Bob', + ], + $this->scheduled[0]['user'], + 'The actor is the authenticated user.' + ); + $this->assertSame( + [ + 'id' => 4, + 'name' => 'Bob', + 'email' => 'bob@scanfully.com', + 'roles' => [ 'administrator' ], + 'app_name' => 'Zapier', + 'app_id' => '6f8f1c2e-7a5b-4c3d-9e1f-2a3b4c5d6e7f', + 'ip' => '203.0.113.9', + 'forwarded_for' => '198.51.100.7', + 'user_agent' => 'Zapier', + ], + $this->scheduled[0]['data'] + ); + } + + public function test_a_later_use_returns_before_any_other_work(): void { + Functions\expect( 'get_option' )->never(); + Functions\expect( 'user_can' )->never(); + + $this->run_listener( 'application_password_did_authenticate', $this->users[4], $this->item( [ 'last_used' => 1759492800 ] ) ); + + $this->assertSame( [], $this->scheduled ); + } + + public function test_the_first_use_by_another_account_is_not_reported(): void { + $this->run_listener( 'application_password_did_authenticate', $this->users[5], $this->item() ); + + $this->assertSame( [], $this->scheduled ); + $this->assertFalse( ( new AppPasswordFirstUsed() )->should_fire( [ null, $this->item() ] ) ); + } +} diff --git a/tests/Unit/Events/Content/BuilderTest.php b/tests/Unit/Events/Content/BuilderTest.php new file mode 100644 index 0000000..9f5699e --- /dev/null +++ b/tests/Unit/Events/Content/BuilderTest.php @@ -0,0 +1,180 @@ +> + */ + private array $sent = []; + + /** + * Stored transients. + * + * @var array + */ + private array $transients = []; + + protected function setUp(): void { + parent::setUp(); + + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'esc_html' )->returnArg(); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'is_wp_error' )->alias( static fn( $thing ) => null === $thing ); + Functions\when( 'wp_remote_post' )->alias( + function ( $url, $args ) { + $this->sent[] = json_decode( $args['body'], true ); + return [ 202 ]; + } + ); + Functions\when( 'wp_remote_retrieve_response_code' )->alias( static fn( $response ) => $response[0] ); + Functions\when( 'update_option' )->justReturn( true ); + Functions\when( 'get_transient' )->alias( fn( $key ) => $this->transients[ $key ] ?? false ); + Functions\when( 'delete_transient' )->alias( + function ( $key ) { + unset( $this->transients[ $key ] ); + return true; + } + ); + Functions\when( 'get_term' )->alias( + static function ( $id ) { + $names = [ + 4 => 'Company', + 5 => 'News & updates', + ]; + if ( ! isset( $names[ $id ] ) ) { + return null; + } + $term = new \WP_Term( (object) [] ); + $term->name = $names[ $id ]; + return $term; + } + ); + Functions\when( 'get_term_by' )->alias( + static function ( $field, $id ) { + $term = new \WP_Term( (object) [] ); + $term->name = 12 === $id ? 'News' : 'Sports'; + return $term; + } + ); + Functions\when( 'get_taxonomy' )->justReturn( (object) [ 'labels' => (object) [ 'name' => 'Categories' ] ] ); + } + + public function test_a_new_terms_parent_is_named(): void { + $data = Builder::resolve( + 'TermCreated', + [ + 'id' => 9, + 'taxonomy' => 'category', + 'parent' => [ 'id' => 4 ], + ] + ); + + $this->assertSame( + [ + 'id' => 4, + 'name' => 'Company', + ], + $data['parent'] + ); + } + + public function test_a_moved_terms_parents_are_named_and_a_gone_one_keeps_its_id(): void { + $data = Builder::resolve( + 'TermChanged', + [ + 'taxonomy' => 'category', + 'changes' => [ + 'parent' => [ + 'old' => [ 'id' => 99 ], + 'new' => [ 'id' => 5 ], + ], + ], + ] + ); + + $this->assertSame( + [ + 'old' => [ + 'id' => 99, + 'name' => '', + ], + 'new' => [ + 'id' => 5, + 'name' => 'News & updates', + ], + ], + $data['changes']['parent'] + ); + } + + public function test_the_terms_of_a_bulk_edit_are_named(): void { + $data = Builder::resolve( + 'PostBulkAction', + [ + 'terms' => [ + 'category' => [ + 'added' => [ 12 ], + 'removed' => [ 13 ], + ], + ], + ] + ); + + $this->assertSame( + [ + [ + 'taxonomy' => 'category', + 'label' => 'Categories', + 'added' => [ 'News' ], + 'removed' => [ 'Sports' ], + ], + ], + $data['terms'] + ); + } + + public function test_stored_data_is_sent_and_removed(): void { + $key = str_repeat( 'a', 32 ); + $this->transients[ 'scanfully_post_change_' . $key ] = [ + 'data' => [ + 'action' => 'trashed', + 'count' => 1, + 'posts' => [ + [ + 'id' => 1, + 'title' => 'About', + ], + ], + ], + ]; + + Builder::build( 'PostBulkAction', [ 'id' => 1 ], [ 'stashed' => true ], $key ); + + $this->assertSame( 'PostBulkAction', $this->sent[0]['type'] ); + $this->assertSame( 'About', $this->sent[0]['data']['posts'][0]['title'] ); + $this->assertSame( [], $this->transients ); + } + + public function test_stored_data_that_expired_sends_nothing(): void { + Builder::build( 'PostBulkAction', [ 'id' => 1 ], [ 'stashed' => true ], str_repeat( 'b', 32 ) ); + + $this->assertSame( [], $this->sent ); + } +} diff --git a/tests/Unit/Events/Content/FakeOptionsTable.php b/tests/Unit/Events/Content/FakeOptionsTable.php new file mode 100644 index 0000000..ff368cf --- /dev/null +++ b/tests/Unit/Events/Content/FakeOptionsTable.php @@ -0,0 +1,119 @@ +options`. + * + * @var string + */ + public string $options = 'wp_options'; + + /** + * The stored options, in insertion order. + * + * @var array + */ + public array $rows = []; + + /** + * Install it: `$wpdb` and the options functions. + * + * @return self + */ + public static function install(): self { + $table = new self(); + $GLOBALS['wpdb'] = $table; + + Functions\when( 'add_option' )->alias( + static function ( string $name, $value ) use ( $table ): bool { + if ( array_key_exists( $name, $table->rows ) ) { + return false; + } + $table->rows[ $name ] = $value; + return true; + } + ); + Functions\when( 'delete_option' )->alias( + static function ( string $name ) use ( $table ): bool { + if ( ! array_key_exists( $name, $table->rows ) ) { + return false; + } + unset( $table->rows[ $name ] ); + return true; + } + ); + Functions\when( 'maybe_unserialize' )->returnArg(); + + return $table; + } + + /** + * Names of the stored options that start with a prefix. + * + * @param string $prefix The prefix. + * + * @return array + */ + public function names( string $prefix ): array { + return array_values( array_filter( array_keys( $this->rows ), static fn( string $name ): bool => 0 === strpos( $name, $prefix ) ) ); + } + + /** + * `$wpdb->esc_like()`. + * + * @param string $text The text. + * + * @return string + */ + public function esc_like( string $text ): string { + return addcslashes( $text, '_%\\' ); + } + + /** + * `$wpdb->prepare()` for the one LIKE query: keeps the pattern. + * + * @param string $query The query. + * @param mixed ...$args The arguments. + * + * @return string + */ + public function prepare( string $query, ...$args ): string { + return (string) ( $args[0] ?? '' ); + } + + /** + * `$wpdb->get_results()` for the LIKE query: the options whose name + * matches the pattern, in insertion order. + * + * @param string $pattern The LIKE pattern prepare() kept. + * + * @return array + */ + public function get_results( string $pattern ): array { + $prefix = stripcslashes( substr( $pattern, 0, -1 ) ); + $rows = []; + foreach ( $this->names( $prefix ) as $name ) { + $rows[] = (object) [ + 'option_name' => $name, + 'option_value' => $this->rows[ $name ], + ]; + } + + return $rows; + } +} diff --git a/tests/Unit/Events/Content/LimiterTest.php b/tests/Unit/Events/Content/LimiterTest.php new file mode 100644 index 0000000..24fbf9c --- /dev/null +++ b/tests/Unit/Events/Content/LimiterTest.php @@ -0,0 +1,85 @@ + + */ + private array $transients = []; + + /** + * How many transients were written. + * + * @var int + */ + private int $writes = 0; + + protected function setUp(): void { + parent::setUp(); + + Functions\when( 'get_transient' )->alias( fn( string $key ) => $this->transients[ $key ] ?? false ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value ) { + ++$this->writes; + $this->transients[ $key ] = $value; + return true; + } + ); + } + + public function test_a_request_takes_room_for_all_its_events_in_one_write(): void { + $this->assertSame( 12, Limiter::take( Report::KIND_POST, 12 ) ); + $this->assertSame( 1, $this->writes ); + } + + public function test_events_over_the_cap_get_no_room(): void { + Filters\expectApplied( 'scanfully_post_saved_events_per_minute' )->andReturn( 5 ); + + $this->assertSame( 3, Limiter::take( Report::KIND_POST, 3 ) ); + $this->assertSame( 2, Limiter::take( Report::KIND_POST, 4 ) ); + $this->assertSame( 0, Limiter::take( Report::KIND_POST, 1 ) ); + } + + public function test_terms_have_a_cap_of_their_own(): void { + Filters\expectApplied( 'scanfully_post_saved_events_per_minute' )->andReturn( 1 ); + Filters\expectApplied( 'scanfully_term_events_per_minute' )->andReturn( 2 ); + + $this->assertSame( 1, Limiter::take( Report::KIND_POST, 3 ) ); + $this->assertSame( 2, Limiter::take( Report::KIND_TERM, 3 ) ); + } + + public function test_settings_menus_and_widgets_have_caps_of_their_own(): void { + Filters\expectApplied( 'scanfully_settings_events_per_minute' )->andReturn( 1 ); + Filters\expectApplied( 'scanfully_menu_events_per_minute' )->andReturn( 2 ); + Filters\expectApplied( 'scanfully_widget_events_per_minute' )->andReturn( 3 ); + + $this->assertSame( 1, Limiter::take( Limiter::KIND_SETTING, 5 ) ); + $this->assertSame( 2, Limiter::take( Limiter::KIND_MENU, 5 ) ); + $this->assertSame( 3, Limiter::take( Limiter::KIND_WIDGET, 5 ) ); + } + + public function test_no_cap_lets_everything_through_without_a_write(): void { + Filters\expectApplied( 'scanfully_post_saved_events_per_minute' )->andReturn( 0 ); + + $this->assertSame( 500, Limiter::take( Report::KIND_POST, 500 ) ); + $this->assertSame( 0, $this->writes ); + } +} diff --git a/tests/Unit/Events/Content/MinuteStoreTest.php b/tests/Unit/Events/Content/MinuteStoreTest.php new file mode 100644 index 0000000..5a14319 --- /dev/null +++ b/tests/Unit/Events/Content/MinuteStoreTest.php @@ -0,0 +1,129 @@ + + */ + private array $transients = []; + + /** + * Scheduled jobs: time, hook and arguments. + * + * @var array}> + */ + private array $scheduled = []; + + /** + * Keys made so far. + * + * @var int + */ + private int $uuids = 0; + + protected function setUp(): void { + parent::setUp(); + + $this->table = FakeOptionsTable::install(); + Functions\when( 'wp_generate_uuid4' )->alias( fn() => sprintf( '%08x-0000-4000-8000-000000000000', ++$this->uuids ) ); + Functions\when( 'get_transient' )->alias( fn( string $key ) => $this->transients[ $key ] ?? false ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value ) { + $this->transients[ $key ] = $value; + return true; + } + ); + Functions\when( 'delete_transient' )->alias( + function ( string $key ) { + unset( $this->transients[ $key ] ); + return true; + } + ); + Functions\when( 'as_schedule_single_action' )->alias( + function ( $timestamp, $hook, $args ) { + $this->scheduled[] = [ + 'time' => $timestamp, + 'hook' => $hook, + 'args' => $args, + ]; + return 1; + } + ); + } + + public function test_each_request_keeps_its_entry_and_the_minute_gets_one_job(): void { + $this->assertTrue( MinuteStore::add( 'media', [ 'n' => 1 ], 'scanfully_job' ) ); + $this->assertTrue( MinuteStore::add( 'media', [ 'n' => 2 ], 'scanfully_job' ) ); + + $bucket = MinuteStore::bucket(); + $this->assertCount( 2, $this->table->names( 'scanfully_minute_media_' . $bucket . '_' ) ); + $this->assertCount( 1, $this->scheduled ); + $this->assertSame( 'scanfully_job', $this->scheduled[0]['hook'] ); + $this->assertSame( [ $bucket ], $this->scheduled[0]['args'] ); + $this->assertSame( ( $bucket + 1 ) * 60 + MinuteStore::DELAY, $this->scheduled[0]['time'] ); + } + + public function test_the_jobs_arguments_come_before_the_minute(): void { + MinuteStore::add( 'overflow_term', [ 'n' => 1 ], 'scanfully_job', [ 'term' ] ); + + $this->assertSame( [ 'term', MinuteStore::bucket() ], $this->scheduled[0]['args'] ); + } + + public function test_take_returns_the_entries_oldest_first_and_removes_them(): void { + MinuteStore::add( 'media', [ 'n' => 1 ], 'scanfully_job' ); + MinuteStore::add( 'media', [ 'n' => 2 ], 'scanfully_job' ); + $bucket = MinuteStore::bucket(); + + $this->assertSame( [ [ 'n' => 1 ], [ 'n' => 2 ] ], MinuteStore::take( 'media', $bucket ) ); + $this->assertSame( [], $this->table->rows ); + $this->assertSame( [], $this->transients, 'The minute\'s job marker is gone too.' ); + $this->assertSame( [], MinuteStore::take( 'media', $bucket ), 'A second run of the job finds nothing.' ); + } + + public function test_take_leaves_later_minutes_and_other_kinds_and_sweeps_earlier_ones(): void { + $bucket = MinuteStore::bucket(); + $key = str_repeat( 'a', 32 ); + + $this->table->rows[ 'scanfully_minute_media_' . ( $bucket - 5 ) . '_' . $key ] = [ 'n' => 'missed' ]; + $this->table->rows[ 'scanfully_minute_media_' . $bucket . '_' . $key ] = [ 'n' => 'now' ]; + $this->table->rows[ 'scanfully_minute_media_' . ( $bucket + 1 ) . '_' . $key ] = [ 'n' => 'next' ]; + $this->table->rows[ 'scanfully_minute_mediax_' . $bucket . '_' . $key ] = [ 'n' => 'other kind' ]; + $this->table->rows[ 'scanfully_minute_overflow_post_' . $bucket . '_' . $key ] = [ 'n' => 'overflow' ]; + + $this->assertSame( [ [ 'n' => 'missed' ], [ 'n' => 'now' ] ], MinuteStore::take( 'media', $bucket ) ); + $this->assertCount( 3, $this->table->rows ); + } + + public function test_an_entry_another_job_took_first_is_skipped(): void { + MinuteStore::add( 'media', [ 'n' => 1 ], 'scanfully_job' ); + $bucket = MinuteStore::bucket(); + + // Another run deletes it between the read and the claim. + Functions\when( 'delete_option' )->justReturn( false ); + + $this->assertSame( [], MinuteStore::take( 'media', $bucket ) ); + } +} diff --git a/tests/Unit/Events/Content/ReportTest.php b/tests/Unit/Events/Content/ReportTest.php new file mode 100644 index 0000000..dd53c92 --- /dev/null +++ b/tests/Unit/Events/Content/ReportTest.php @@ -0,0 +1,238 @@ + + */ + private array $transients = []; + + /** + * Scheduled jobs: hook and arguments. + * + * @var array}> + */ + private array $scheduled = []; + + /** + * Fired actions: hook and arguments. + * + * @var array}> + */ + private array $fired = []; + + /** + * Whether the site is connected. + * + * @var string + */ + private string $connected = 'yes'; + + /** + * Stash keys made so far. + * + * @var int + */ + private int $uuids = 0; + + /** + * The options table the minute store writes to. + * + * @var FakeOptionsTable + */ + private FakeOptionsTable $table; + + protected function setUp(): void { + parent::setUp(); + + Functions\when( 'get_option' )->alias( fn() => $this->connected ); + $this->table = FakeOptionsTable::install(); + Functions\when( 'get_post_type_object' )->justReturn( (object) [ 'labels' => (object) [ 'name' => 'Posts' ] ] ); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'wp_generate_uuid4' )->alias( fn() => sprintf( '%08x-0000-4000-8000-000000000000', ++$this->uuids ) ); + Functions\when( 'get_transient' )->alias( fn( string $key ) => $this->transients[ $key ] ?? false ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value ) { + $this->transients[ $key ] = $value; + return true; + } + ); + Functions\when( 'delete_transient' )->alias( + function ( string $key ) { + unset( $this->transients[ $key ] ); + return true; + } + ); + Functions\when( 'as_schedule_single_action' )->alias( + function ( $timestamp, $hook, $args ) { + $this->scheduled[] = [ + 'hook' => $hook, + 'args' => $args, + ]; + return 1; + } + ); + Functions\when( 'wp_get_current_user' )->justReturn( + (object) [ + 'ID' => 3, + 'display_name' => 'Editor', + ] + ); + + foreach ( [ ContentEvent::hook( 'PostBulkAction' ), ContentEvent::hook( 'PostDeleted' ) ] as $hook ) { + Actions\expectDone( $hook )->zeroOrMoreTimes()->whenHappen( + function ( ...$args ) use ( $hook ) { + $this->fired[] = [ + 'hook' => $hook, + 'args' => $args, + ]; + } + ); + } + } + + /** + * Deleted post items, each with its own event. + * + * @param int $count How many. + * @param int $from The first ID. + * + * @return array> + */ + private function deletes( int $count, int $from = 1 ): array { + $items = []; + for ( $id = $from; $id < $from + $count; $id++ ) { + $items[] = [ + 'action' => 'deleted', + 'group' => 'post', + 'id' => $id, + 'title' => 'Post ' . $id, + 'event' => [ + 'hook' => ContentEvent::hook( 'PostDeleted' ), + 'args' => [ [ 'id' => $id ] ], + ], + ]; + } + + return $items; + } + + /** + * The hooks fired, in order. + * + * @return array + */ + private function fired_hooks(): array { + return array_column( $this->fired, 'hook' ); + } + + public function test_a_few_posts_get_rows_of_their_own(): void { + Report::send( Report::KIND_POST, $this->deletes( 10 ) ); + + $this->assertSame( array_fill( 0, 10, ContentEvent::hook( 'PostDeleted' ) ), $this->fired_hooks() ); + } + + public function test_more_than_the_threshold_become_one_row_with_every_post(): void { + Report::send( Report::KIND_POST, $this->deletes( 11 ) ); + + $this->assertSame( [ ContentEvent::hook( 'PostBulkAction' ) ], $this->fired_hooks() ); + $data = $this->fired[0]['args'][0]; + $this->assertSame( 11, $data['count'] ); + $this->assertSame( range( 1, 11 ), array_column( $data['posts'], 'id' ) ); + } + + public function test_the_threshold_is_filterable(): void { + Filters\expectApplied( 'scanfully_activity_bulk_threshold' )->with( 10, 'post' )->andReturn( 2 ); + + Report::send( Report::KIND_POST, $this->deletes( 3 ) ); + + $this->assertSame( [ ContentEvent::hook( 'PostBulkAction' ) ], $this->fired_hooks() ); + } + + public function test_posts_only_counted_always_go_in_a_summary_row(): void { + $items = $this->deletes( 2 ); + unset( $items[1]['event'] ); + + Report::send( Report::KIND_POST, $items ); + + $this->assertSame( [ ContentEvent::hook( 'PostBulkAction' ) ], $this->fired_hooks() ); + } + + public function test_nothing_is_reported_while_the_site_is_not_connected(): void { + $this->connected = ''; + + Report::send( Report::KIND_POST, $this->deletes( 3 ) ); + + $this->assertSame( [], $this->fired ); + $this->assertSame( [], $this->transients ); + } + + public function test_events_over_the_cap_are_kept_for_the_minutes_job(): void { + Filters\expectApplied( 'scanfully_post_saved_events_per_minute' )->andReturn( 2 ); + + Report::send( Report::KIND_POST, $this->deletes( 3 ) ); + Report::send( Report::KIND_POST, $this->deletes( 2, 10 ) ); + + $this->assertCount( 2, $this->fired ); + $jobs = array_values( array_filter( $this->scheduled, static fn( array $job ): bool => Controller::ACTION_SEND_OVERFLOW === $job['hook'] ) ); + $this->assertCount( 1, $jobs, 'The minute\'s job is scheduled once.' ); + + [ $kind, $bucket ] = $jobs[0]['args']; + $this->assertSame( Report::KIND_POST, $kind ); + $this->assertCount( 2, $this->table->names( 'scanfully_minute_overflow_post_' . $bucket . '_' ), 'Both requests kept what they could not send, each in an option of its own.' ); + + Overflow::send( $kind, $bucket ); + + $builds = array_values( array_filter( $this->scheduled, static fn( array $job ): bool => Controller::ACTION_BUILD_CONTENT_EVENT === $job['hook'] ) ); + $this->assertCount( 1, $builds ); + $this->assertSame( 'PostBulkAction', $builds[0]['args']['type'] ); + $this->assertSame( + [ + 'id' => 3, + 'name' => 'Editor', + ], + $builds[0]['args']['user'] + ); + $data = $builds[0]['args']['data']; + $this->assertTrue( $data['overflow'] ); + $this->assertSame( [ 3, 10, 11 ], array_column( $data['posts'], 'id' ) ); + $this->assertSame( [], $this->table->rows ); + $this->assertArrayNotHasKey( 'scanfully_minute_overflow_post_' . $bucket . '_job', $this->transients ); + } + + public function test_a_summary_row_too_long_for_the_job_is_stored_for_it(): void { + $items = $this->deletes( 300 ); + + Report::send( Report::KIND_POST, $items ); + ( new \Scanfully\Events\PostBulkAction() )->listener_callback( $this->fired[0]['args'][0] ); + + $job = end( $this->scheduled ); + $this->assertSame( Controller::ACTION_BUILD_CONTENT_EVENT, $job['hook'] ); + $this->assertSame( [ 'stashed' => true ], $job['args']['data'] ); + $this->assertCount( 300, $this->transients[ 'scanfully_post_change_' . $job['args']['stash'] ]['data']['posts'] ); + } +} diff --git a/tests/Unit/Events/Content/SummaryTest.php b/tests/Unit/Events/Content/SummaryTest.php new file mode 100644 index 0000000..83bdd3d --- /dev/null +++ b/tests/Unit/Events/Content/SummaryTest.php @@ -0,0 +1,198 @@ +justReturn( (object) [ 'labels' => (object) [ 'name' => 'Pages' ] ] ); + Functions\when( 'get_taxonomy' )->justReturn( (object) [ 'labels' => (object) [ 'name' => 'Tags' ] ] ); + } + + /** + * Post items. + * + * @param int $count How many. + * @param array $fields Fields every item has. + * + * @return array> + */ + private function items( int $count, array $fields = [] ): array { + $items = []; + for ( $i = 1; $i <= $count; $i++ ) { + $items[] = array_merge( + [ + 'action' => 'trashed', + 'group' => 'page', + 'id' => $i, + 'title' => 'Page ' . $i, + ], + $fields + ); + } + + return $items; + } + + public function test_a_row_lists_every_post(): void { + $rows = Summary::rows( Report::KIND_POST, $this->items( 25 ) ); + + $this->assertCount( 1, $rows ); + $this->assertSame( 'PostBulkAction', $rows[0]['type'] ); + $this->assertSame( 'trashed', $rows[0]['data']['action'] ); + $this->assertSame( 'page', $rows[0]['data']['post_type'] ); + $this->assertSame( 'Pages', $rows[0]['data']['type_label'] ); + $this->assertSame( 25, $rows[0]['data']['count'] ); + $this->assertCount( 25, $rows[0]['data']['posts'] ); + $this->assertSame( + [ + 'id' => 25, + 'title' => 'Page 25', + ], + $rows[0]['data']['posts'][24] + ); + $this->assertArrayNotHasKey( 'part', $rows[0]['data'] ); + } + + public function test_more_posts_than_a_row_holds_make_numbered_parts(): void { + $rows = Summary::rows( Report::KIND_POST, $this->items( Summary::MAX_ITEMS_PER_ROW + 5 ) ); + + $this->assertCount( 2, $rows ); + $this->assertSame( Summary::MAX_ITEMS_PER_ROW, $rows[0]['data']['count'] ); + $this->assertSame( 5, $rows[1]['data']['count'] ); + $this->assertSame( [ 2, 2, Summary::MAX_ITEMS_PER_ROW + 5 ], [ $rows[1]['data']['part'], $rows[1]['data']['parts'], $rows[1]['data']['total'] ] ); + } + + public function test_a_bulk_edit_row_counts_the_changes_and_joins_the_terms(): void { + $items = $this->items( + 3, + [ + 'action' => 'updated', + 'changed' => [ 'terms', 'author' ], + 'terms' => [ + 'category' => [ + 'added' => [ 12 ], + 'removed' => [], + ], + ], + ] + ); + $items[2]['terms']['category']['added'][] = 14; + + $data = Summary::rows( Report::KIND_POST, $items )[0]['data']; + + $this->assertSame( + [ + 'terms' => 3, + 'author' => 3, + ], + $data['changed'] + ); + $this->assertSame( + [ + 'category' => [ + 'added' => [ 12, 14 ], + 'removed' => [], + ], + ], + $data['terms'] + ); + } + + public function test_the_trash_wordpress_emptied_itself_is_marked(): void { + $data = Summary::rows( + Report::KIND_POST, + $this->items( + 2, + [ + 'action' => 'deleted', + 'expired' => true, + ] + ) + )[0]['data']; + + $this->assertTrue( $data['expired'] ); + $this->assertSame( 30, $data['trash_days'] ); + } + + public function test_a_term_row_lists_every_term_and_adds_up_the_posts(): void { + $items = [ + [ + 'action' => 'deleted', + 'group' => 'post_tag', + 'id' => 3, + 'title' => 'News', + 'posts' => 4, + ], + [ + 'action' => 'deleted', + 'group' => 'post_tag', + 'id' => 5, + 'title' => 'Sports', + 'posts' => 2, + ], + ]; + + $rows = Summary::rows( Report::KIND_TERM, $items, true ); + + $this->assertSame( 'TermBulkAction', $rows[0]['type'] ); + $this->assertSame( + [ + 'action' => 'deleted', + 'taxonomy' => 'post_tag', + 'label' => 'Tags', + 'count' => 2, + 'terms' => [ + [ + 'id' => 3, + 'name' => 'News', + ], + [ + 'id' => 5, + 'name' => 'Sports', + ], + ], + 'posts' => 6, + 'overflow' => true, + ], + $rows[0]['data'] + ); + } + + public function test_items_are_grouped_by_action_type_and_expiry(): void { + $items = array_merge( + $this->items( 2 ), + $this->items( 1, [ 'group' => 'post' ] ), + $this->items( 1, [ 'action' => 'deleted' ] ), + $this->items( + 1, + [ + 'action' => 'deleted', + 'expired' => true, + ] + ) + ); + + $this->assertSame( [ 'trashed|page', 'trashed|post', 'deleted|page', 'deleted|page|expired' ], array_keys( Summary::group( $items ) ) ); + } + + public function test_titles_are_plain_text_and_cut(): void { + $this->assertSame( 'Bread & butter', Summary::title( 'Bread & butter' ) ); + $this->assertSame( Summary::MAX_TITLE, mb_strlen( Summary::title( str_repeat( 'é', 300 ) ) ) ); + } +} diff --git a/tests/Unit/Events/EventPayloadTest.php b/tests/Unit/Events/EventPayloadTest.php index 0a51012..574e5a1 100644 --- a/tests/Unit/Events/EventPayloadTest.php +++ b/tests/Unit/Events/EventPayloadTest.php @@ -78,6 +78,46 @@ public function test_a_normal_payload_is_scheduled_unchanged(): void { $this->assertSame( $payload, $this->scheduled[0]['data'] ); } + /** + * @dataProvider provide_actor_names + * + * @param array $actor The signed-in user's fields. + * @param string $expected The name sent. + */ + public function test_the_actor_name_is_never_an_email_address( array $actor, string $expected ): void { + Functions\when( 'is_email' )->alias( static fn( $email ) => false !== filter_var( $email, FILTER_VALIDATE_EMAIL ) ); + Functions\when( 'wp_get_current_user' )->justReturn( (object) array_merge( [ 'ID' => 3 ], $actor ) ); + + ( new PluginUpdate() )->listener_callback( [ 'name' => 'Akismet' ] ); + + $this->assertSame( + [ + 'id' => 3, + 'name' => $expected, + ], + $this->scheduled[0]['user'] + ); + } + + /** + * @return array, string}> + */ + public function provide_actor_names(): array { + return [ + 'a normal display name' => [ [ 'display_name' => 'Jane Doe' ], 'Jane Doe' ], + 'email, with a first and last name' => [ + [ + 'display_name' => 'jane@scanfully.com', + 'first_name' => 'Jane', + 'last_name' => 'Doe', + ], + 'Jane Doe', + ], + 'email, without a name' => [ [ 'display_name' => 'jane@scanfully.com' ], '' ], + 'an @ that is not an email' => [ [ 'display_name' => '@jane' ], '@jane' ], + ]; + } + public function test_an_oversized_payload_is_shortened_to_fit_action_scheduler(): void { ( new PluginUpdate() )->listener_callback( [ diff --git a/tests/Unit/Events/FailedLogins/CounterTest.php b/tests/Unit/Events/FailedLogins/CounterTest.php new file mode 100644 index 0000000..7910423 --- /dev/null +++ b/tests/Unit/Events/FailedLogins/CounterTest.php @@ -0,0 +1,216 @@ + + */ + private array $users = []; + + protected function setUp(): void { + parent::setUp(); + Counter::reset(); + $this->table = FakeCounterTable::install(); + unset( $GLOBALS['pagenow'] ); + + $admin = Mockery::mock( 'WP_User' ); + $admin->ID = 7; + $admin->roles = [ 'administrator' ]; + $customer = Mockery::mock( 'WP_User' ); + $customer->ID = 8; + $customer->roles = [ 'customer' ]; + $this->users = [ + 'login:bob' => $admin, + 'email:bob@scanfully.com' => $admin, + 'login:carol' => $customer, + ]; + + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'is_email' )->alias( static fn( $text ) => false !== filter_var( $text, FILTER_VALIDATE_EMAIL ) ); + Functions\when( 'get_user_by' )->alias( fn( $field, $value ) => $this->users[ $field . ':' . $value ] ?? false ); + Functions\when( 'user_can' )->alias( static fn( $user ) => in_array( 'administrator', (array) $user->roles, true ) ); + } + + protected function tearDown(): void { + Counter::reset(); + unset( $GLOBALS['pagenow'] ); + parent::tearDown(); + } + + /** + * A login error. + * + * @param string $code The error code. + * @param mixed $data The error data. + * + * @return \WP_Error + */ + private function error( string $code, $data = null ) { + $error = Mockery::mock( 'WP_Error' ); + $error->shouldReceive( 'get_error_code' )->andReturn( $code ); + $error->shouldReceive( 'get_error_data' )->andReturn( $data ); + + return $error; + } + + /** + * The counters of this hour, without the prefix. + * + * @return array + */ + private function counted(): array { + $prefix = 'scanfully_lf_' . Store::hour() . '_'; + $counted = []; + foreach ( $this->table->rows as $name => $count ) { + $counted[ substr( $name, strlen( $prefix ) ) ] = $count; + } + ksort( $counted ); + + return $counted; + } + + public function test_a_wrong_password_on_an_admin_counts_the_account(): void { + $GLOBALS['pagenow'] = 'wp-login.php'; + + Counter::note_failure( 'bob', $this->error( 'incorrect_password' ) ); + + $this->assertSame( + [ + 'c_login_page' => 1, + 'r_wrong_password' => 1, + 'total' => 1, + 'u_7' => 1, + ], + $this->counted() + ); + $this->assertCount( 1, $this->table->queries, 'One query per failed login.' ); + } + + public function test_a_wrong_password_with_an_email_address_finds_the_account(): void { + Counter::note_failure( 'bob@scanfully.com', $this->error( 'incorrect_password' ) ); + + $this->assertArrayHasKey( 'u_7', $this->counted() ); + } + + public function test_a_wrong_password_on_a_customer_names_no_account(): void { + Counter::note_failure( 'carol', $this->error( 'incorrect_password' ) ); + + $this->assertSame( + [ + 'c_other' => 1, + 'r_wrong_password' => 1, + 'total' => 1, + ], + $this->counted() + ); + } + + /** + * @dataProvider provide_reasons + * + * @param string $code The error code. + * @param string $reason The reason counted. + */ + public function test_the_reason_comes_from_the_error_code( string $code, string $reason ): void { + Counter::note_failure( 'nobody', $this->error( $code ) ); + + $this->assertArrayHasKey( 'r_' . $reason, $this->counted() ); + $this->assertArrayNotHasKey( 'u_7', $this->counted() ); + } + + /** + * @return array + */ + public function provide_reasons(): array { + return [ + 'unknown username' => [ 'invalid_username', 'unknown_account' ], + 'unknown email address' => [ 'invalid_email', 'unknown_account' ], + 'a security plugin blocks' => [ 'too_many_retries', 'blocked' ], + ]; + } + + public function test_an_unknown_username_is_never_kept(): void { + Counter::note_failure( 'admin-attacker-guess', $this->error( 'invalid_username' ) ); + + foreach ( array_merge( array_keys( $this->table->rows ), $this->table->queries ) as $text ) { + $this->assertStringNotContainsString( 'attacker', $text ); + } + } + + public function test_a_wrong_application_password_counts_as_its_own_way_in(): void { + Counter::note_attempt( null, 'bob' ); + Counter::note_application_password_failure( $this->error( 'incorrect_password' ) ); + + $this->assertSame( + [ + 'c_app_password' => 1, + 'r_wrong_password' => 1, + 'total' => 1, + 'u_7' => 1, + ], + $this->counted() + ); + } + + public function test_a_wrong_application_password_over_the_rest_api_finds_the_account_from_the_header(): void { + $_SERVER['PHP_AUTH_USER'] = 'bob'; + Functions\when( 'wp_unslash' )->returnArg(); + + Counter::note_application_password_failure( $this->error( 'incorrect_password' ) ); + unset( $_SERVER['PHP_AUTH_USER'] ); + + $this->assertArrayHasKey( 'u_7', $this->counted() ); + } + + public function test_one_login_attempt_counts_once_when_two_hooks_report_it(): void { + Counter::note_attempt( null, 'bob' ); + Counter::note_application_password_failure( $this->error( 'incorrect_password' ) ); + Counter::note_failure( 'bob', $this->error( 'incorrect_password' ) ); + + $this->assertSame( 1, $this->counted()['total'] ); + } + + public function test_nothing_is_counted_while_the_site_is_not_connected(): void { + Functions\when( 'get_option' )->justReturn( '' ); + + Counter::note_failure( 'bob', $this->error( 'incorrect_password' ) ); + + $this->assertSame( [], $this->table->rows ); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function test_xml_rpc_is_its_own_way_in(): void { + define( 'XMLRPC_REQUEST', true ); + + $this->assertSame( 'xmlrpc', Counter::channel() ); + } +} diff --git a/tests/Unit/Events/FailedLogins/FakeCounterTable.php b/tests/Unit/Events/FailedLogins/FakeCounterTable.php new file mode 100644 index 0000000..df593bb --- /dev/null +++ b/tests/Unit/Events/FailedLogins/FakeCounterTable.php @@ -0,0 +1,171 @@ +options`. + * + * @var string + */ + public string $options = 'wp_options'; + + /** + * The stored counters by option name. + * + * @var array + */ + public array $rows = []; + + /** + * The queries run, in order. + * + * @var array + */ + public array $queries = []; + + /** + * Install it as `$wpdb`. + * + * @return self + */ + public static function install(): self { + $table = new self(); + $GLOBALS['wpdb'] = $table; + + return $table; + } + + /** + * `$wpdb->prepare()`, for %s and %d. + * + * @param string $query The query. + * @param mixed ...$args The values, or one array of them. + * + * @return string + */ + public function prepare( string $query, ...$args ): string { + if ( 1 === count( $args ) && is_array( $args[0] ) ) { + $args = $args[0]; + } + $index = 0; + + return (string) preg_replace_callback( + '/%[sd]/', + static function ( array $match ) use ( &$index, $args ): string { + $value = $args[ $index++ ] ?? ''; + return '%d' === $match[0] ? (string) (int) $value : "'" . addslashes( (string) $value ) . "'"; + }, + $query + ); + } + + /** + * `$wpdb->esc_like()`. + * + * @param string $text The text. + * + * @return string + */ + public function esc_like( string $text ): string { + return addcslashes( $text, '_%\\' ); + } + + /** + * `$wpdb->query()`: the increment and the deletes. + * + * @param string $sql The query. + * + * @return int|false + */ + public function query( string $sql ) { + $this->queries[] = $sql; + + if ( 0 === strpos( $sql, 'INSERT INTO wp_options' ) ) { + preg_match_all( "/\('([^']+)', '1', 'no'\)/", $sql, $matches ); + foreach ( $matches[1] as $name ) { + $this->rows[ $name ] = ( $this->rows[ $name ] ?? 0 ) + 1; + } + return count( $matches[1] ); + } + + if ( 1 === preg_match( "/^DELETE FROM wp_options WHERE option_name LIKE '(.*)'$/", $sql, $match ) ) { + $prefix = self::like_prefix( $match[1] ); + $deleted = 0; + foreach ( array_keys( $this->rows ) as $name ) { + if ( 0 === strpos( $name, $prefix ) ) { + unset( $this->rows[ $name ] ); + ++$deleted; + } + } + return $deleted; + } + + return false; + } + + /** + * The prefix a quoted `LIKE 'prefix%'` pattern matches: the SQL quoting + * undone, then the LIKE escapes. + * + * @param string $quoted The pattern as it is in the query, without its quotes. + * + * @return string + */ + private static function like_prefix( string $quoted ): string { + $pattern = stripslashes( substr( $quoted, 0, -1 ) ); + + return str_replace( [ '\\_', '\\%', '\\\\' ], [ '_', '%', '\\' ], $pattern ); + } + + /** + * `$wpdb->get_var()`: one counter. + * + * @param string $sql The query. + * + * @return string|null + */ + public function get_var( string $sql ): ?string { + $this->queries[] = $sql; + + return 1 === preg_match( "/option_name = '([^']+)'/", $sql, $match ) && isset( $this->rows[ $match[1] ] ) ? (string) $this->rows[ $match[1] ] : null; + } + + /** + * `$wpdb->get_results()`: the counters by name prefix. + * + * @param string $sql The query. + * + * @return array + */ + public function get_results( string $sql ): array { + $this->queries[] = $sql; + if ( 1 !== preg_match( "/option_name LIKE '(.*)'$/", $sql, $match ) ) { + return []; + } + $prefix = self::like_prefix( $match[1] ); + + $rows = []; + foreach ( $this->rows as $name => $value ) { + if ( 0 === strpos( $name, $prefix ) ) { + $rows[] = (object) [ + 'option_name' => $name, + 'option_value' => (string) $value, + ]; + } + } + + return $rows; + } +} diff --git a/tests/Unit/Events/FailedLogins/ReporterTest.php b/tests/Unit/Events/FailedLogins/ReporterTest.php new file mode 100644 index 0000000..f184e84 --- /dev/null +++ b/tests/Unit/Events/FailedLogins/ReporterTest.php @@ -0,0 +1,225 @@ +> + */ + private array $sent = []; + + /** + * The fake API status, or null for no answer. + * + * @var int|null + */ + private ?int $status = 204; + + protected function setUp(): void { + parent::setUp(); + $this->table = FakeCounterTable::install(); + + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'is_wp_error' )->alias( static fn( $thing ) => null === $thing ); + Functions\when( 'wp_remote_post' )->alias( + function ( $url, $args ) { + $this->sent[] = json_decode( $args['body'], true ); + return null === $this->status ? null : [ $this->status ]; + } + ); + Functions\when( 'wp_remote_retrieve_response_code' )->alias( static fn( $response ) => $response[0] ); + Functions\when( 'update_option' )->justReturn( true ); + Functions\when( 'delete_transient' )->justReturn( true ); + Functions\when( 'user_can' )->justReturn( true ); + Functions\when( 'get_userdata' )->alias( + static function ( $id ) { + if ( 7 !== $id && 9 !== $id ) { + return false; + } + $user = Mockery::mock( 'WP_User' ); + $user->ID = $id; + $user->display_name = 7 === $id ? 'Bob' : 'bob@scanfully.com'; + $user->first_name = ''; + $user->last_name = 7 === $id ? '' : 'Smith'; + $user->roles = [ 'administrator' ]; + return $user; + } + ); + Functions\when( 'is_email' )->alias( static fn( $text ) => false !== filter_var( $text, FILTER_VALIDATE_EMAIL ) ); + } + + /** + * Put counters in an hour. + * + * @param int $hour The hour. + * @param array $counters The counters. + * + * @return void + */ + private function counters( int $hour, array $counters ): void { + foreach ( $counters as $counter => $count ) { + $this->table->rows[ 'scanfully_lf_' . $hour . '_' . $counter ] = $count; + } + } + + public function test_the_hours_that_are_over_are_sent_in_one_request_and_removed(): void { + $now = Store::hour(); + $this->counters( + $now - 2, + [ + 'total' => 12, + 'r_wrong_password' => 10, + 'r_unknown_account' => 2, + 'c_login_page' => 12, + 'u_7' => 4, + 'u_9' => 6, + 'u_3' => 1, + ] + ); + $this->counters( + $now - 1, + [ + 'total' => 1, + 'r_blocked' => 1, + 'c_xmlrpc' => 1, + ] + ); + $this->counters( $now, [ 'total' => 5 ] ); + + Reporter::send(); + + $this->assertCount( 1, $this->sent ); + $hours = $this->sent[0]['hours']; + $this->assertSame( gmdate( 'Y-m-d\TH:00:00\Z', ( $now - 2 ) * 3600 ), $hours[0]['hour'] ); + $this->assertSame( 12, $hours[0]['total'] ); + $this->assertSame( + [ + 'wrong_password' => 10, + 'unknown_account' => 2, + 'blocked' => 0, + ], + $hours[0]['reasons'] + ); + $this->assertSame( + [ + 'login_page' => 12, + 'xmlrpc' => 0, + 'app_password' => 0, + 'other' => 0, + ], + $hours[0]['channels'] + ); + $this->assertSame( + [ + [ + 'id' => 9, + 'name' => 'Smith', + 'roles' => [ 'administrator' ], + 'count' => 6, + ], + [ + 'id' => 7, + 'name' => 'Bob', + 'roles' => [ 'administrator' ], + 'count' => 4, + ], + ], + $hours[0]['accounts'], + 'The most targeted first, never an email address, accounts that no longer exist left out.' + ); + $this->assertSame( 1, $hours[1]['total'] ); + $this->assertCount( 2, $hours, 'The current hour is not over.' ); + + $this->assertSame( [ 'scanfully_lf_' . $now . '_total' ], array_keys( $this->table->rows ) ); + } + + /** + * @dataProvider provide_retried_answers + * + * @param int|null $status The API's answer. + */ + public function test_counts_the_api_did_not_take_are_kept_for_the_next_run( ?int $status ): void { + $this->status = $status; + $this->counters( Store::hour() - 1, [ 'total' => 3 ] ); + + Reporter::send(); + + $this->assertCount( 1, $this->table->rows ); + } + + /** + * @return array + */ + public function provide_retried_answers(): array { + return [ + 'no answer' => [ null ], + 'token being refreshed' => [ 401 ], + 'an API without the endpoint' => [ 404 ], + 'too many requests' => [ 429 ], + 'server error' => [ 503 ], + ]; + } + + public function test_counts_the_api_refuses_as_bad_data_are_dropped(): void { + $this->status = 400; + $this->counters( Store::hour() - 1, [ 'total' => 3 ] ); + + Reporter::send(); + + $this->assertSame( [], $this->table->rows ); + } + + public function test_hours_older_than_a_week_are_dropped_unsent(): void { + $this->counters( Store::hour() - 7 * 24 - 1, [ 'total' => 3 ] ); + + Reporter::send(); + + $this->assertSame( [], $this->sent ); + $this->assertSame( [], $this->table->rows ); + } + + public function test_nothing_is_sent_while_the_site_is_not_connected(): void { + Functions\when( 'get_option' )->justReturn( '' ); + $this->counters( Store::hour() - 1, [ 'total' => 3 ] ); + + Reporter::send(); + + $this->assertSame( [], $this->sent ); + } + + public function test_deleting_an_hour_leaves_hours_that_start_with_the_same_digits(): void { + $this->counters( 493000, [ 'total' => 1 ] ); + $this->counters( 4930001, [ 'total' => 1 ] ); + + Store::delete_hour( 493000 ); + + $this->assertSame( [ 'scanfully_lf_4930001_total' ], array_keys( $this->table->rows ) ); + } +} diff --git a/tests/Unit/Events/FileEdits/CollectorTest.php b/tests/Unit/Events/FileEdits/CollectorTest.php new file mode 100644 index 0000000..fca80fa --- /dev/null +++ b/tests/Unit/Events/FileEdits/CollectorTest.php @@ -0,0 +1,207 @@ + + */ + private array $files = []; + + protected function setUp(): void { + parent::setUp(); + Collector::reset(); + } + + protected function tearDown(): void { + foreach ( $this->files as $file ) { + if ( is_file( $file ) ) { + unlink( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- A temporary test file. + } + } + Collector::reset(); + parent::tearDown(); + } + + /** + * A temporary file with the given content. + * + * @param string $content The content. + * + * @return string + */ + private function file( string $content ): string { + $path = (string) tempnam( sys_get_temp_dir(), 'scanfully-file-edit-' ); + $this->files[] = $path; + file_put_contents( $path, $content ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- A temporary test file. + + return $path; + } + + public function test_a_small_file_is_read_with_its_content(): void { + $state = Collector::read( $this->file( "assertSame( "assertSame( md5( "file( $content ) ); + + $this->assertArrayNotHasKey( 'content', $state ); + $this->assertSame( md5( $content ), $state['hash'] ); + } + + public function test_a_missing_file_has_no_hash(): void { + $this->assertSame( [ 'hash' => '' ], Collector::read( sys_get_temp_dir() . '/scanfully-no-such-file-' . uniqid() ) ); + } + + public function test_an_unchanged_or_restored_file_is_no_change(): void { + $state = [ + 'content' => 'a', + 'hash' => md5( 'a' ), + ]; + + $this->assertNull( Collector::change( $state, $state ) ); + $this->assertNull( Collector::change( [ 'hash' => '' ], $state ), 'The file could not be read before.' ); + $this->assertNull( Collector::change( $state, [ 'hash' => '' ] ), 'The file is gone.' ); + } + + public function test_a_changed_file_is_kept_for_the_job(): void { + $change = Collector::change( + [ + 'content' => 'a', + 'hash' => md5( 'a' ), + ], + [ + 'content' => 'b', + 'hash' => md5( 'b' ), + ] + ); + + $this->assertSame( + [ + 'stash' => [ + 'old' => 'a', + 'new' => 'b', + ], + ], + $change + ); + } + + public function test_a_changed_large_file_is_reported_without_content(): void { + $this->assertSame( [ 'too_large' => true ], Collector::change( [ 'hash' => 'x' ], [ 'hash' => 'y' ] ) ); + } + + public function test_nothing_is_noted_without_a_file_or_a_plugin_or_theme(): void { + Functions\when( 'validate_file' )->justReturn( 0 ); + Functions\expect( 'current_user_can' )->never(); + + Collector::note( [ 'file' => 'akismet/akismet.php' ] ); + Collector::note( [ 'plugin' => 'akismet/akismet.php' ] ); + Collector::note( 'nonsense' ); + + Actions\expectDone( 'scanfully_content_event_PluginFileEdited' )->never(); + Collector::flush(); + } + + public function test_nothing_is_noted_for_a_user_who_may_not_edit_plugins(): void { + Functions\when( 'validate_file' )->justReturn( 0 ); + Functions\expect( 'current_user_can' )->once()->with( 'edit_plugins' )->andReturn( false ); + + Collector::note( + [ + 'file' => 'akismet/akismet.php', + 'plugin' => 'akismet/akismet.php', + ] + ); + + Actions\expectDone( 'scanfully_content_event_PluginFileEdited' )->never(); + Collector::flush(); + } + + public function test_a_path_that_climbs_out_is_not_noted(): void { + Functions\when( 'validate_file' )->alias( static fn( $file ) => false !== strpos( (string) $file, '..' ) ? 1 : 0 ); + Functions\expect( 'current_user_can' )->never(); + + Collector::note( + [ + 'file' => '../wp-config.php', + 'plugin' => 'akismet/akismet.php', + ] + ); + } + + public function test_code_lines_keep_indentation_and_drop_line_endings(): void { + $this->assertSame( [ 'assertSame( [], ContentDiff::code_lines( '' ) ); + } + + public function test_only_whitespace_at_line_ends_is_no_diff(): void { + $this->assertSame( + [ + 'changed' => true, + 'reason' => 'whitespace', + ], + ContentDiff::compare_code( "a\nb\n", "a \r\nb\r\n", [ ContentDiffTest::class, 'naive_diff' ] ) + ); + } + + public function test_a_code_change_is_a_diff_of_the_lines_as_written(): void { + $diff = ContentDiff::compare_code( "assertSame( 1, $diff['added'] ); + $this->assertSame( 1, $diff['removed'] ); + $this->assertContains( + [ + 'op' => '+', + 'text' => "\tbar();", + ], + $diff['lines'] + ); + } + + public function test_a_large_file_edit_is_reported_as_too_large_by_the_job(): void { + $data = Builder::resolve( + 'ThemeFileEdited', + [ + 'name' => 'Astra', + 'file' => 'functions.php', + 'changes' => [ 'content' => [ 'too_large' => true ] ], + ] + ); + + $this->assertSame( + [ + 'content' => [ + 'changed' => true, + 'reason' => 'too_large', + ], + ], + $data['changes'] + ); + } +} diff --git a/tests/Unit/Events/MediaChanges/BatchTest.php b/tests/Unit/Events/MediaChanges/BatchTest.php new file mode 100644 index 0000000..e410bd9 --- /dev/null +++ b/tests/Unit/Events/MediaChanges/BatchTest.php @@ -0,0 +1,612 @@ + + */ + private array $posts = []; + + /** + * Files of the attachments, by ID. + * + * @var array + */ + private array $files = []; + + /** + * Events queued: type, user and data. + * + * @var array, data: array}> + */ + private array $queued = []; + + /** + * Keys made so far. + * + * @var int + */ + private int $uuids = 0; + + protected function setUp(): void { + parent::setUp(); + + $this->table = FakeOptionsTable::install(); + Functions\when( 'wp_generate_uuid4' )->alias( fn() => sprintf( '%08x-0000-4000-8000-000000000000', ++$this->uuids ) ); + Functions\when( 'get_transient' )->justReturn( false ); + Functions\when( 'set_transient' )->justReturn( true ); + Functions\when( 'delete_transient' )->justReturn( true ); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'as_schedule_single_action' )->alias( + function ( $timestamp, $hook, $args ) { + if ( Controller::ACTION_BUILD_CONTENT_EVENT === $hook ) { + $this->queued[] = [ + 'type' => $args['type'], + 'user' => $args['user'], + 'data' => $args['data'], + ]; + } + return 1; + } + ); + Functions\when( '_prime_post_caches' )->justReturn( null ); + Functions\when( 'get_post' )->alias( fn( $id ) => $this->posts[ $id ] ?? null ); + Functions\when( 'get_post_meta' )->alias( fn( $id, $key ) => '_wp_attached_file' === $key ? ( $this->files[ $id ] ?? '' ) : '' ); + Functions\when( 'wp_get_attachment_metadata' )->justReturn( + [ + 'width' => 800, + 'height' => 600, + 'filesize' => 5000, + ] + ); + Functions\when( 'wp_get_post_parent_id' )->alias( fn( $id ) => isset( $this->posts[ $id ] ) ? $this->posts[ $id ]->post_parent : false ); + Functions\when( 'get_post_type_object' )->justReturn( (object) [ 'labels' => (object) [ 'singular_name' => 'Page' ] ] ); + Functions\when( 'wp_basename' )->alias( static fn( $path ) => basename( (string) $path ) ); + Functions\when( 'wp_parse_url' )->alias( static fn( $url, $component = -1 ) => parse_url( $url, $component ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- WordPress is not loaded in unit tests. + + $this->page( 4, 'About us' ); + } + + /** + * A page files can belong to. + * + * @param int $id The ID. + * @param string $title The title. + * + * @return void + */ + private function page( int $id, string $title ): void { + $this->posts[ $id ] = new \WP_Post( + (object) [ + 'ID' => $id, + 'post_type' => 'page', + 'post_title' => $title, + 'post_parent' => 0, + ] + ); + } + + /** + * A file in the media library. + * + * @param int $id The ID. + * @param string $file The file in the uploads folder. + * @param int $parent_id The post it is attached to. + * + * @return void + */ + private function attachment( int $id, string $file, int $parent_id = 0 ): void { + $this->posts[ $id ] = new \WP_Post( + (object) [ + 'ID' => $id, + 'post_type' => 'attachment', + 'post_title' => pathinfo( $file, PATHINFO_FILENAME ), + 'post_mime_type' => 'image/jpeg', + 'post_parent' => $parent_id, + 'guid' => 'https://scanfully.com/wp-content/uploads/' . $file, + ] + ); + $this->files[ $id ] = $file; + } + + /** + * Store a request's notes for this minute. + * + * @param array> $items The notes. + * @param int $user The user ID. + * + * @return void + */ + private function request( array $items, int $user = 3 ): void { + MinuteStore::add( + 'media', + [ + 'user' => [ + 'id' => $user, + 'name' => 'User ' . $user, + ], + 'items' => $items, + ], + Controller::ACTION_SEND_MEDIA + ); + } + + /** + * Run the minute's job and return the events it queued. + * + * @return array, data: array}> + */ + private function run_job(): array { + Batch::send( MinuteStore::bucket() ); + + return $this->queued; + } + + public function test_an_upload_is_reported_with_the_file_as_it_is_now(): void { + $this->attachment( 7, '2026/10/team-photo.jpg', 4 ); + $this->request( + [ + [ + 'id' => 7, + 'uploaded' => true, + 'file' => '2026/10/team-photo.jpg', + ], + ] + ); + $this->request( + [ + [ + 'id' => 7, + 'old' => [ 'alt' => '' ], + 'new' => [ 'alt' => 'The team' ], + ], + ] + ); + + $events = $this->run_job(); + + $this->assertSame( [ 'MediaUploaded' ], array_column( $events, 'type' ) ); + $this->assertSame( + [ + 'id' => 7, + 'name' => 'team-photo.jpg', + 'file' => '2026/10/team-photo.jpg', + 'title' => 'team-photo', + 'mime_type' => 'image/jpeg', + 'filesize' => 5000, + 'width' => 800, + 'height' => 600, + 'parent' => [ + 'id' => 4, + 'title' => 'About us', + 'type_label' => 'Page', + ], + ], + $events[0]['data'] + ); + $this->assertSame( 3, $events[0]['user']['id'] ); + $this->assertSame( [], $this->table->rows ); + } + + public function test_an_edited_copy_names_the_original(): void { + $this->attachment( 7, '2026/10/photo.jpg' ); + $this->attachment( 8, '2026/10/photo-edited.jpg' ); + $this->request( + [ + [ + 'id' => 8, + 'uploaded' => true, + 'edited_from' => 7, + 'edits' => [ 'crop' ], + ], + ] + ); + + $data = $this->run_job()[0]['data']; + + $this->assertSame( + [ + 'id' => 7, + 'name' => 'photo.jpg', + ], + $data['edited_from'] + ); + $this->assertSame( [ 'crop' ], $data['edits'] ); + } + + public function test_details_saved_one_by_one_are_one_change(): void { + $this->attachment( 7, '2026/10/photo.jpg' ); + $this->request( + [ + [ + 'id' => 7, + 'old' => [ 'title' => 'photo' ], + 'new' => [ 'title' => 'Photo' ], + ], + ] + ); + $this->request( + [ + [ + 'id' => 7, + 'old' => [ + 'title' => 'Photo', + 'alt' => '', + ], + 'new' => [ + 'title' => 'Team photo', + 'alt' => 'The team', + ], + ], + ] + ); + + $events = $this->run_job(); + + $this->assertSame( [ 'MediaChanged' ], array_column( $events, 'type' ) ); + $this->assertSame( + [ + 'title' => [ + 'old' => 'photo', + 'new' => 'Team photo', + ], + 'alt' => [ + 'old' => '', + 'new' => 'The team', + ], + ], + $events[0]['data']['changes'] + ); + } + + public function test_a_change_undone_within_the_minute_is_nothing(): void { + $this->attachment( 7, '2026/10/photo.jpg' ); + $this->request( + [ + [ + 'id' => 7, + 'old' => [ 'title' => 'photo' ], + 'new' => [ 'title' => 'Oops' ], + ], + ] + ); + $this->request( + [ + [ + 'id' => 7, + 'old' => [ 'title' => 'Oops' ], + 'new' => [ 'title' => 'photo' ], + ], + ] + ); + + $this->assertSame( [], $this->run_job() ); + } + + public function test_uploaded_and_deleted_within_the_minute_is_nothing(): void { + $this->request( + [ + [ + 'id' => 7, + 'uploaded' => true, + ], + ] + ); + $this->request( + [ + [ + 'id' => 7, + 'deleted' => [ 'file' => '2026/10/photo.jpg' ], + ], + ] + ); + + $this->assertSame( [], $this->run_job() ); + } + + public function test_a_delete_after_changes_is_only_the_delete(): void { + $this->request( + [ + [ + 'id' => 7, + 'old' => [ 'title' => 'a' ], + 'new' => [ 'title' => 'b' ], + ], + ] + ); + $this->request( + [ + [ + 'id' => 7, + 'deleted' => [ + 'title' => 'b', + 'file' => '2026/10/photo.jpg', + 'mime_type' => 'image/jpeg', + 'post_status' => 'trash', + 'facts' => [ 'filesize' => 5000 ], + 'featured_on' => 2, + 'expired' => true, + ], + ], + ] + ); + + $events = $this->run_job(); + + $this->assertSame( [ 'MediaDeleted' ], array_column( $events, 'type' ) ); + $this->assertSame( + [ + 'id' => 7, + 'name' => 'photo.jpg', + 'file' => '2026/10/photo.jpg', + 'title' => 'b', + 'mime_type' => 'image/jpeg', + 'filesize' => 5000, + 'post_status' => 'trash', + 'featured_on' => 2, + 'expired' => true, + 'trash_days' => 30, + ], + $events[0]['data'] + ); + } + + public function test_attach_trash_and_image_edits_get_their_own_actions_and_data(): void { + $this->attachment( 7, '2026/10/a.jpg', 4 ); + $this->attachment( 8, '2026/10/b.jpg' ); + $this->attachment( 9, '2026/10/c.jpg' ); + $this->request( + [ + [ + 'id' => 7, + 'old' => [ 'parent' => 0 ], + 'new' => [ 'parent' => 4 ], + ], + [ + 'id' => 8, + 'old' => [ 'status' => 'inherit' ], + 'new' => [ 'status' => 'trash' ], + ], + [ + 'id' => 9, + 'image' => [ + 'edits' => [ 'crop' ], + 'target' => 'all', + ], + ], + ] + ); + $this->request( + [ + [ + 'id' => 9, + 'image' => [ + 'edits' => [ 'rotate' ], + 'target' => 'thumbnail', + ], + ], + ] + ); + + $events = $this->run_job(); + + $this->assertSame( [ 'MediaChanged', 'MediaChanged', 'MediaChanged' ], array_column( $events, 'type' ) ); + $this->assertSame( + [ + 'old' => [ + 'id' => 0, + 'title' => '', + ], + 'new' => [ + 'id' => 4, + 'title' => 'About us', + 'type_label' => 'Page', + ], + ], + $events[0]['data']['changes']['parent'] + ); + $this->assertSame( + [ + 'old' => 'inherit', + 'new' => 'trash', + ], + $events[1]['data']['changes']['status'] + ); + $this->assertSame( + [ + 'edits' => [ 'crop', 'rotate' ], + 'target' => 'thumbnail', + ], + $events[2]['data']['changes']['image'] + ); + } + + public function test_a_change_to_a_file_deleted_since_says_what_the_request_knew(): void { + // No attachment 7: someone else deleted it before the job ran. + $this->request( + [ + [ + 'id' => 7, + 'old' => [ 'status' => 'inherit' ], + 'new' => [ 'status' => 'trash' ], + 'known' => [ + 'name' => 'brochure.pdf', + 'file' => '', + 'title' => 'Brochure', + 'mime_type' => 'application/pdf', + ], + ], + ] + ); + + $events = $this->run_job(); + + $this->assertSame( [ 'MediaChanged' ], array_column( $events, 'type' ) ); + $data = $events[0]['data']; + $this->assertSame( [ 'brochure.pdf', '', 'Brochure', 'application/pdf' ], [ $data['name'], $data['file'], $data['title'], $data['mime_type'] ] ); + $this->assertSame( 'trash', $data['changes']['status']['new'] ); + } + + public function test_a_rename_and_a_replace_say_what_happened_to_the_file(): void { + $this->attachment( 7, '2026/10/a.webp' ); + $this->attachment( 8, '2026/10/logo.png' ); + $this->request( + [ + [ + 'id' => 7, + 'old' => [ 'file' => '2026/10/a.png' ], + 'new' => [ 'file' => '2026/10/a.webp' ], + ], + [ + 'id' => 8, + 'replaced' => [ + 'old' => 'logo.png', + 'new' => 'logo.png', + ], + ], + ] + ); + + $events = $this->run_job(); + + $this->assertSame( + [ + 'old' => 'a.png', + 'new' => 'a.webp', + ], + $events[0]['data']['changes']['file'] + ); + $this->assertSame( + [ + 'old' => 'logo.png', + 'new' => 'logo.png', + 'replaced' => true, + ], + $events[1]['data']['changes']['file'] + ); + } + + public function test_many_uploads_by_one_person_are_one_row_with_every_file(): void { + $items = []; + for ( $id = 101; $id <= 112; $id++ ) { + $this->attachment( $id, '2026/10/photo-' . $id . '.jpg' ); + $items[] = [ + 'id' => $id, + 'uploaded' => true, + ]; + } + // One request per file, as the media library uploads. + foreach ( $items as $item ) { + $this->request( [ $item ] ); + } + // Someone else's upload in the same minute keeps its own row. + $this->attachment( 200, '2026/10/logo.png' ); + $this->request( + [ + [ + 'id' => 200, + 'uploaded' => true, + ], + ], + 5 + ); + + $events = $this->run_job(); + + $this->assertSame( [ 'MediaBulkAction', 'MediaUploaded' ], array_column( $events, 'type' ) ); + $data = $events[0]['data']; + $this->assertSame( [ 'uploaded', 12 ], [ $data['action'], $data['count'] ] ); + $this->assertSame( + [ + 'id' => 112, + 'name' => 'photo-112.jpg', + 'title' => 'photo-112', + ], + $data['files'][11] + ); + $this->assertSame( 5, $events[1]['user']['id'] ); + } + + public function test_files_attached_to_one_post_at_once_name_it(): void { + $items = []; + for ( $id = 101; $id <= 111; $id++ ) { + $this->attachment( $id, '2026/10/photo-' . $id . '.jpg', 4 ); + $items[] = [ + 'id' => $id, + 'old' => [ 'parent' => 0 ], + 'new' => [ 'parent' => 4 ], + ]; + } + $this->request( $items ); + + $data = $this->run_job()[0]['data']; + + $this->assertSame( [ 'attached', 11 ], [ $data['action'], $data['count'] ] ); + $this->assertSame( 'About us', $data['parent']['title'] ); + } + + public function test_past_the_per_minute_cap_the_rest_is_one_row(): void { + Filters\expectApplied( 'scanfully_media_events_per_minute' )->andReturn( 2 ); + $items = []; + for ( $id = 101; $id <= 105; $id++ ) { + $this->attachment( $id, '2026/10/photo-' . $id . '.jpg' ); + $items[] = [ + 'id' => $id, + 'old' => [ 'title' => 'a' ], + 'new' => [ 'title' => 'b' ], + ]; + } + $this->request( $items ); + + $events = $this->run_job(); + + $this->assertSame( [ 'MediaChanged', 'MediaChanged', 'MediaBulkAction' ], array_column( $events, 'type' ) ); + $this->assertTrue( $events[2]['data']['overflow'] ); + $this->assertSame( [ 103, 104, 105 ], array_column( $events[2]['data']['files'], 'id' ) ); + $this->assertSame( [ 'title' => 3 ], $events[2]['data']['changed'] ); + } + + public function test_a_filter_can_leave_a_change_out(): void { + $this->attachment( 7, '2026/10/photo.jpg' ); + Filters\expectApplied( 'scanfully_media_should_fire' )->andReturn( false ); + $this->request( + [ + [ + 'id' => 7, + 'uploaded' => true, + ], + ] + ); + + $this->assertSame( [], $this->run_job() ); + } +} diff --git a/tests/Unit/Events/MediaChanges/CollectorTest.php b/tests/Unit/Events/MediaChanges/CollectorTest.php new file mode 100644 index 0000000..ecec443 --- /dev/null +++ b/tests/Unit/Events/MediaChanges/CollectorTest.php @@ -0,0 +1,415 @@ + [ serialized value ]. + * + * @var array>> + */ + private array $meta = []; + + /** + * The post cache, per post ID. + * + * @var array + */ + private array $posts = []; + + /** + * Whether the site is connected. + * + * @var string + */ + private string $connected = 'yes'; + + /** + * Scheduled jobs: hook and arguments. + * + * @var array}> + */ + private array $scheduled = []; + + /** + * Keys made so far. + * + * @var int + */ + private int $uuids = 0; + + protected function setUp(): void { + parent::setUp(); + Collector::reset(); + + $this->table = FakeOptionsTable::install(); + Functions\when( 'get_option' )->alias( fn() => $this->connected ); + Functions\when( 'wp_cache_get' )->alias( + function ( $id, $group ) { + if ( 'post_meta' === $group ) { + return $this->meta[ $id ] ?? false; + } + return 'posts' === $group ? ( $this->posts[ $id ] ?? false ) : false; + } + ); + Functions\when( 'wp_get_current_user' )->justReturn( + (object) [ + 'ID' => 3, + 'display_name' => 'Editor', + ] + ); + Functions\when( 'wp_generate_uuid4' )->alias( fn() => sprintf( '%08x-0000-4000-8000-000000000000', ++$this->uuids ) ); + Functions\when( 'get_transient' )->justReturn( false ); + Functions\when( 'set_transient' )->justReturn( true ); + Functions\when( 'as_schedule_single_action' )->alias( + function ( $timestamp, $hook, $args ) { + $this->scheduled[] = [ + 'hook' => $hook, + 'args' => $args, + ]; + return 1; + } + ); + Functions\when( 'sanitize_key' )->alias( static fn( $key ) => strtolower( (string) preg_replace( '/[^a-z0-9_\-]/i', '', (string) $key ) ) ); + Functions\when( 'wp_unslash' )->returnArg(); + Functions\when( 'wp_parse_url' )->alias( static fn( $url, $component = -1 ) => parse_url( $url, $component ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- WordPress is not loaded in unit tests. + Functions\when( 'wp_basename' )->alias( static fn( $path ) => basename( (string) $path ) ); + } + + protected function tearDown(): void { + Collector::reset(); + $_REQUEST = []; + parent::tearDown(); + } + + /** + * End the "request" and return the items it stored for the minute. + * + * @return array> + */ + private function end_request(): array { + $before = $this->table->rows; + Collector::flush(); + $new = array_diff_key( $this->table->rows, $before ); + if ( [] === $new ) { + return []; + } + + $entry = array_values( $new )[0]; + $this->assertSame( + [ + 'id' => 3, + 'name' => 'Editor', + ], + $entry['user'] + ); + + return $entry['items']; + } + + /** + * An attachment post. + * + * @param array $fields Fields that differ from the default. + * + * @return object + */ + private static function post( array $fields = [] ): object { + return (object) array_merge( + [ + 'post_title' => 'Team photo', + 'post_excerpt' => '', + 'post_content' => '', + 'post_name' => 'team-photo', + 'post_parent' => 0, + 'post_status' => 'inherit', + 'post_mime_type' => 'image/jpeg', + ], + $fields + ); + } + + public function test_a_details_save_notes_old_and_new(): void { + $this->meta[7] = [ '_wp_attached_file' => [ '2026/10/team-photo.jpg' ] ]; + + Collector::note_updated( 7, self::post( [ 'post_title' => 'Team & friends' ] ), self::post() ); + + $this->assertSame( + [ + [ + 'id' => 7, + 'old' => [ 'title' => 'Team photo' ], + 'new' => [ 'title' => 'Team & friends' ], + // For the job, should the file be deleted before it runs. + 'known' => [ + 'name' => 'team-photo.jpg', + 'file' => '2026/10/team-photo.jpg', + 'title' => 'Team & friends', + 'mime_type' => 'image/jpeg', + ], + ], + ], + $this->end_request() + ); + $this->assertSame( Controller::ACTION_SEND_MEDIA, $this->scheduled[0]['hook'] ); + } + + public function test_alt_text_takes_the_old_value_from_the_meta_cache(): void { + $this->meta[7] = [ '_wp_attachment_image_alt' => [ 'Old alt' ] ]; + + Collector::note_meta_updating( 1, 7, '_wp_attachment_image_alt', 'New alt' ); + + $this->assertSame( + [ + [ + 'id' => 7, + 'old' => [ 'alt' => 'Old alt' ], + 'new' => [ 'alt' => 'New alt' ], + ], + ], + $this->end_request() + ); + } + + public function test_alt_text_added_and_removed(): void { + Collector::note_meta_added( 1, 7, '_wp_attachment_image_alt', 'First alt' ); + $this->assertSame( [ 'alt' => '' ], $this->end_request()[0]['old'] ); + + $this->meta[7] = [ '_wp_attachment_image_alt' => [ 'First alt' ] ]; + Collector::note_meta_deleting( [ 1 ], 7, '_wp_attachment_image_alt', '' ); + $this->assertSame( [ 'alt' => '' ], $this->end_request()[0]['new'] ); + } + + public function test_a_save_that_changes_nothing_stores_nothing(): void { + Collector::note_updated( 7, self::post(), self::post() ); + Collector::note_updated( 8, self::post( [ 'post_title' => 'B' ] ), self::post() ); + Collector::note_updated( 8, self::post(), self::post( [ 'post_title' => 'B' ] ) ); + + $this->assertSame( [], $this->end_request() ); + $this->assertSame( [], $this->scheduled ); + } + + public function test_an_upload_keeps_its_file_and_takes_in_later_changes(): void { + Collector::note_meta_added( 1, 7, '_wp_attached_file', '2026/10/team-photo.jpg' ); + Collector::note_added( 7 ); + Collector::note_updated( 7, self::post( [ 'post_title' => 'Team' ] ), self::post() ); + Collector::note_meta_added( 2, 7, '_wp_attachment_image_alt', 'The team' ); + Collector::note_meta_updating( 3, 7, '_wp_attached_file', '2026/10/team-photo-scaled.jpg' ); + + $this->assertSame( + [ + [ + 'id' => 7, + 'uploaded' => true, + 'file' => '2026/10/team-photo.jpg', + ], + ], + $this->end_request() + ); + } + + public function test_wordpress_own_follow_up_files_are_no_change(): void { + $this->meta[7] = [ '_wp_attached_file' => [ '2026/10/photo.jpg' ] ]; + + Collector::note_meta_updating( 1, 7, '_wp_attached_file', '2026/10/photo-scaled.jpg' ); + + $this->assertSame( [], $this->end_request() ); + } + + public function test_a_converted_or_renamed_file_is_a_change(): void { + $this->meta[7] = [ '_wp_attached_file' => [ '2026/10/photo.jpg' ] ]; + + Collector::note_meta_updating( 1, 7, '_wp_attached_file', '2026/10/photo.webp' ); + + $items = $this->end_request(); + $this->assertCount( 1, $items ); + $this->assertSame( [ 'file' => '2026/10/photo.jpg' ], $items[0]['old'] ?? null ); + $this->assertSame( [ 'file' => '2026/10/photo.webp' ], $items[0]['new'] ?? null ); + } + + public function test_same_file(): void { + $this->assertTrue( Collector::same_file( '2026/10/a.jpg', '2026/10/a-scaled.jpg' ) ); + $this->assertTrue( Collector::same_file( '2026/10/a.jpg', '2026/10/a-rotated.jpg' ) ); + $this->assertTrue( Collector::same_file( '2026/10/a-scaled.jpg', '2026/10/a.jpg' ) ); + $this->assertFalse( Collector::same_file( '2026/10/a.jpg', '2026/10/b.jpg' ) ); + $this->assertFalse( Collector::same_file( '2026/10/a.png', '2026/10/a.webp' ) ); + $this->assertFalse( Collector::same_file( '2026/10/a.jpg', '2026/11/a.jpg' ) ); + } + + public function test_a_permanent_delete_keeps_what_the_row_says(): void { + $this->meta[7] = [ + '_wp_attached_file' => [ '2026/10/team-photo.jpg' ], + '_wp_attachment_metadata' => [ + [ + 'width' => 2400, + 'height' => 1600, + 'filesize' => 1200000, + 'sizes' => [], + ], + ], + ]; + Functions\when( 'maybe_unserialize' )->returnArg(); + + Collector::note_deleting( 7, self::post() ); + Collector::note_meta_deleting( [ 11, 12, 13 ], 0, '_thumbnail_id', 7 ); + Collector::note_meta_deleting( [ 14 ], 7, '_wp_attachment_image_alt', '' ); + Collector::note_deleted( 7 ); + + $this->assertSame( + [ + [ + 'id' => 7, + 'deleted' => [ + 'title' => 'Team photo', + 'file' => '2026/10/team-photo.jpg', + 'mime_type' => 'image/jpeg', + 'post_status' => 'inherit', + 'parent' => 0, + 'facts' => [ + 'filesize' => 1200000, + 'width' => 2400, + 'height' => 1600, + ], + 'featured_on' => 3, + 'expired' => false, + ], + ], + ], + $this->end_request() + ); + } + + public function test_a_delete_that_did_not_go_through_is_not_stored(): void { + Collector::note_deleting( 7, self::post() ); + + $this->assertSame( [], $this->end_request() ); + } + + public function test_a_file_uploaded_and_deleted_in_one_request_is_nothing(): void { + Collector::note_added( 7 ); + Collector::note_deleting( 7, self::post() ); + Collector::note_deleted( 7 ); + + $this->assertSame( [], $this->end_request() ); + } + + public function test_an_image_editor_save_is_noted_once_wordpress_wrote_the_image(): void { + $_REQUEST = [ + 'do' => 'save', + 'postid' => '7', + 'history' => '[{"c":{"x":0,"y":0,"w":10,"h":10}},{"r":90},{"r":90}]', + 'target' => 'all', + ]; + $this->meta[7] = [ '_wp_attached_file' => [ '2026/10/photo.jpg' ] ]; + + Collector::note_image_editor(); + $this->assertSame( [], $this->end_request(), 'Refused or failed: nothing written, nothing noted.' ); + + Collector::note_image_editor(); + Collector::note_meta_updating( 1, 7, '_wp_attached_file', '2026/10/photo-e1697651234567.jpg' ); + Collector::note_meta_updating( 2, 7, '_wp_attachment_metadata', [] ); + + $this->assertSame( + [ + [ + 'id' => 7, + 'image' => [ + 'edits' => [ 'crop', 'rotate' ], + 'target' => 'all', + ], + ], + ], + $this->end_request() + ); + } + + public function test_restoring_the_original_image(): void { + $_REQUEST = [ + 'do' => 'restore', + 'postid' => '7', + ]; + + Collector::note_image_editor(); + Collector::note_meta_updating( 1, 7, '_wp_attachment_backup_sizes', [] ); + + $this->assertSame( [ 'restored' => true ], $this->end_request()[0]['image'] ); + } + + public function test_history_edits(): void { + $this->assertSame( [ 'flip', 'rotate' ], Collector::history_edits( [ [ 'f' => 1 ], [ 'r' => 90 ], 'junk' ] ) ); + $this->assertSame( [], Collector::history_edits( [] ) ); + } + + public function test_a_replace_through_enable_media_replace(): void { + $this->meta[7] = [ '_wp_attached_file' => [ '2026/10/logo.png' ] ]; + + Collector::note_meta_updating( 1, 7, '_wp_attached_file', '2026/10/logo-new.png' ); + Collector::note_replaced( 'https://scanfully.com/wp-content/uploads/2026/10/logo-new.png', 'https://scanfully.com/wp-content/uploads/2026/10/logo.png', 7 ); + + $this->assertSame( + [ + [ + 'id' => 7, + 'replaced' => [ + 'old' => 'logo.png', + 'new' => 'logo-new.png', + ], + ], + ], + $this->end_request() + ); + } + + public function test_attach_in_list_view_takes_the_old_parent_from_the_post_cache(): void { + $this->posts[7] = (object) [ 'post_parent' => 4 ]; + + Collector::note_attach( 'attach', 7, 12 ); + Collector::note_attach( 'detach', 8, 5 ); + + $this->assertSame( + [ + [ + 'id' => 7, + 'old' => [ 'parent' => 4 ], + 'new' => [ 'parent' => 12 ], + ], + [ + 'id' => 8, + 'old' => [ 'parent' => 5 ], + 'new' => [ 'parent' => 0 ], + ], + ], + $this->end_request() + ); + } + + public function test_nothing_is_stored_while_the_site_is_not_connected(): void { + $this->connected = 'no'; + Collector::note_updated( 7, self::post( [ 'post_title' => 'New' ] ), self::post() ); + + $this->assertSame( [], $this->end_request() ); + $this->assertSame( [], $this->scheduled ); + } +} diff --git a/tests/Unit/Events/MenuChanges/BuilderTest.php b/tests/Unit/Events/MenuChanges/BuilderTest.php new file mode 100644 index 0000000..6baa2e6 --- /dev/null +++ b/tests/Unit/Events/MenuChanges/BuilderTest.php @@ -0,0 +1,165 @@ +alias( static fn( $text ) => strip_tags( (string) $text ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- WordPress is not loaded in unit tests. + Functions\when( '__' )->returnArg(); + Functions\when( 'post_type_exists' )->alias( static fn( $type ) => in_array( $type, [ 'page', 'post' ], true ) ); + Functions\when( 'get_post_type_object' )->alias( + static fn( $type ) => (object) [ + 'labels' => (object) [ 'singular_name' => ucfirst( (string) $type ) ], + ] + ); + Functions\when( 'get_taxonomy' )->justReturn( false ); + } + + public function test_one_item_moved_up_is_the_only_move(): void { + // Places before, in today's order: item 5 moved from last to second. + $this->assertSame( + [ 5 ], + Builder::out_of_order( + [ + 1 => 1, + 5 => 5, + 2 => 2, + 3 => 3, + 4 => 4, + ] + ) + ); + } + + public function test_renumbering_after_a_removal_is_no_move(): void { + // Item 2 was removed; the ones below kept their order. + $this->assertSame( + [], + Builder::out_of_order( + [ + 1 => 1, + 3 => 3, + 4 => 4, + 6 => 6, + ] + ) + ); + } + + public function test_two_items_swapped_is_one_move(): void { + $this->assertCount( + 1, + Builder::out_of_order( + [ + 2 => 2, + 1 => 1, + 3 => 3, + ] + ) + ); + } + + public function test_a_single_item_never_moves(): void { + $this->assertSame( [], Builder::out_of_order( [ 9 => 4 ] ) ); + } + + /** + * A navigation link block. + * + * @param string $label The label. + * @param string $url The URL. + * @param array $extra More attributes. + * + * @return array + */ + private static function link( string $label, string $url, array $extra = [] ): array { + return [ + 'key' => isset( $extra['id'] ) ? 'page:' . $extra['id'] : 'url:' . $url, + 'id' => (int) ( $extra['id'] ?? 0 ), + 'label' => $label, + 'url' => $url, + 'type' => isset( $extra['id'] ) ? 'page' : 'custom', + 'parent' => (string) ( $extra['parent'] ?? '' ), + 'attrs' => (array) ( $extra['attrs'] ?? [] ), + ]; + } + + public function test_block_menu_items_added_removed_renamed_and_moved(): void { + $before = [ + self::link( 'Home', 'https://scanfully.com/' ), + self::link( 'Blog', 'https://scanfully.com/blog/', [ 'id' => 7 ] ), + self::link( 'Old', 'https://scanfully.com/old/' ), + self::link( 'Shop', 'https://scanfully.com/shop/' ), + ]; + $after = [ + self::link( 'Shop', 'https://scanfully.com/shop/' ), + self::link( 'Home', 'https://scanfully.com/' ), + self::link( 'News', 'https://scanfully.com/news/', [ 'id' => 7 ] ), + self::link( 'Contact', 'https://scanfully.com/contact/' ), + ]; + + $changes = Builder::block_changes( $before, $after ); + + $this->assertSame( [ 'Contact' ], array_column( $changes['added'], 'label' ) ); + $this->assertSame( [ 'Old' ], array_column( $changes['removed'], 'label' ) ); + $this->assertSame( 'Blog', $changes['renamed'][0]['old'] ); + $this->assertSame( 'News', $changes['renamed'][0]['new'] ); + $this->assertSame( 'https://scanfully.com/news/', $changes['relinked'][0]['new'] ); + $this->assertSame( [ 'Shop' ], array_column( $changes['moved'], 'label' ) ); + } + + public function test_a_link_moved_into_a_submenu_says_under_which(): void { + $before = [ + self::link( 'About', 'https://scanfully.com/about/' ), + self::link( 'Team', 'https://scanfully.com/team/' ), + ]; + $after = [ + self::link( 'About', 'https://scanfully.com/about/' ), + self::link( 'Team', 'https://scanfully.com/team/', [ 'parent' => 'About' ] ), + ]; + + $changes = Builder::block_changes( $before, $after ); + + $this->assertSame( + [ + [ + 'id' => 0, + 'label' => 'Team', + 'type' => 'Custom Link', + 'parent' => 'About', + ], + ], + $changes['moved'] + ); + $this->assertArrayNotHasKey( 'added', $changes ); + } + + public function test_a_link_opening_in_a_new_tab_is_a_detail(): void { + $changes = Builder::block_changes( + [ self::link( 'Shop', 'https://scanfully.com/shop/' ) ], + [ self::link( 'Shop', 'https://scanfully.com/shop/', [ 'attrs' => [ 'opensInNewTab' => true ] ] ) ] + ); + + $this->assertSame( [ 'opensInNewTab' ], $changes['details'][0]['changed'] ); + } + + public function test_the_same_menu_is_no_change(): void { + $items = [ self::link( 'Home', 'https://scanfully.com/' ), self::link( 'Shop', 'https://scanfully.com/shop/' ) ]; + + $this->assertSame( [], Builder::block_changes( $items, $items ) ); + } +} diff --git a/tests/Unit/Events/PermalinksChangedTest.php b/tests/Unit/Events/PermalinksChangedTest.php new file mode 100644 index 0000000..f046e36 --- /dev/null +++ b/tests/Unit/Events/PermalinksChangedTest.php @@ -0,0 +1,98 @@ +> + */ + private array $scheduled = []; + + protected function setUp(): void { + parent::setUp(); + $this->scheduled = []; + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'wp_get_current_user' )->justReturn( + (object) [ + 'ID' => 0, + 'display_name' => '', + ] + ); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'as_schedule_single_action' )->alias( + function ( $timestamp, $hook, $args ) { + $this->scheduled[] = $args; + return 1; + } + ); + } + + public function test_a_new_structure_is_reported_with_the_old_and_new_value(): void { + ( new PermalinksChanged() )->listener_callback( '/%year%/%postname%/', '/%postname%/', 'permalink_structure' ); + + $this->assertCount( 1, $this->scheduled ); + $this->assertSame( 'PermalinksChanged', $this->scheduled[0]['type'] ); + $this->assertSame( + [ + 'old' => '/%year%/%postname%/', + 'new' => '/%postname%/', + ], + $this->scheduled[0]['data'] + ); + } + + public function test_plain_permalinks_are_an_empty_string(): void { + $body = ( new PermalinksChanged() )->get_post_body( [ '/%postname%/', null ] ); + + $this->assertSame( '', $body['new'] ); + } + + public function test_an_unchanged_structure_is_not_reported(): void { + $this->assertFalse( ( new PermalinksChanged() )->should_fire( [ '/%postname%/', '/%postname%/' ] ) ); + $this->assertFalse( ( new PermalinksChanged() )->should_fire( [ false, '' ] ), 'A missing option and an empty one are both plain permalinks.' ); + } + + public function test_adding_the_option_is_reported_as_a_change_from_plain_permalinks(): void { + $add_listener = null; + Actions\expectAdded( 'add_option_permalink_structure' )->whenHappen( + static function ( $callback ) use ( &$add_listener ) { + $add_listener = $callback; + } + ); + + new PermalinksChanged(); + $this->assertIsCallable( $add_listener ); + $add_listener( 'permalink_structure', '/%postname%/' ); + + $this->assertSame( + [ + 'old' => '', + 'new' => '/%postname%/', + ], + $this->scheduled[0]['data'] + ); + } + + public function test_nothing_is_queued_while_the_site_is_not_connected(): void { + Functions\when( 'get_option' )->justReturn( '' ); + Functions\expect( 'as_schedule_single_action' )->never(); + + ( new PermalinksChanged() )->listener_callback( '', '/%postname%/' ); + } +} diff --git a/tests/Unit/Events/PluginThemeChangeTest.php b/tests/Unit/Events/PluginThemeChangeTest.php new file mode 100644 index 0000000..90ed123 --- /dev/null +++ b/tests/Unit/Events/PluginThemeChangeTest.php @@ -0,0 +1,323 @@ +setAccessible( true ); + $pending->setValue( null, [] ); + } + } + + /** + * A WP_Theme double. + * + * @param string $stylesheet The theme directory. + * @param string $name The theme name. + * @param string $version The theme version. + * @param bool $exists Whether the theme exists. + * + * @return \WP_Theme + */ + private function theme( string $stylesheet, string $name, string $version = '1.0', bool $exists = true ) { + $theme = Mockery::mock( 'WP_Theme' ); + $theme->shouldReceive( 'get_stylesheet' )->andReturn( $stylesheet ); + $theme->shouldReceive( 'exists' )->andReturn( $exists ); + $theme->shouldReceive( 'get' )->andReturnUsing( + static function ( string $header ) use ( $name, $version ) { + return [ + 'Name' => $name, + 'Version' => $version, + 'Author' => 'the WordPress team', + ][ $header ] ?? false; + } + ); + + return $theme; + } + + /** + * An upgrader double after an install. + * + * @param mixed $result The install result. + * @param mixed $info What plugin_info() or theme_info() returns. + * + * @return object + */ + private function upgrader( $result, $info ): object { + return new class( $result, $info ) { + /** + * The install result. + * + * @var mixed + */ + public $result; + + /** + * The installed item. + * + * @var mixed + */ + private $info; + + /** + * Constructor. + * + * @param mixed $result The install result. + * @param mixed $info The installed item. + */ + public function __construct( $result, $info ) { + $this->result = $result; + $this->info = $info; + } + + /** + * The installed plugin. + * + * @return mixed + */ + public function plugin_info() { + return $this->info; + } + + /** + * The installed theme. + * + * @return mixed + */ + public function theme_info() { + return $this->info; + } + }; + } + + public function test_an_installed_plugin_is_reported_with_its_details(): void { + Functions\when( 'get_file_data' )->justReturn( + [ + 'Name' => 'Akismet Anti-spam', + 'Version' => '5.4', + 'Author' => 'Automattic', + ] + ); + $data = [ + $this->upgrader( [ 'destination_name' => 'akismet' ], 'akismet/akismet.php' ), + [ + 'type' => 'plugin', + 'action' => 'install', + ], + ]; + + $event = new PluginInstalled(); + + $this->assertTrue( $event->should_fire( $data ) ); + $this->assertSame( + [ + 'name' => 'Akismet Anti-spam', + 'slug' => 'akismet/akismet.php', + 'version' => '5.4', + 'author' => 'Automattic', + ], + $event->get_post_body( $data ) + ); + } + + /** + * @dataProvider provide_no_plugin_install + * + * @param mixed $result The upgrader result. + * @param mixed $hook_extra The hook extras. + */ + public function test_other_upgrader_runs_are_not_plugin_installs( $result, $hook_extra ): void { + $this->assertFalse( ( new PluginInstalled() )->should_fire( [ $this->upgrader( $result, 'akismet/akismet.php' ), $hook_extra ] ) ); + } + + /** + * @return array + */ + public function provide_no_plugin_install(): array { + $install = [ + 'type' => 'plugin', + 'action' => 'install', + ]; + + return [ + 'failed install' => [ null, $install ], + 'update' => [ + [ 'destination_name' => 'akismet' ], + [ + 'type' => 'plugin', + 'action' => 'update', + 'plugins' => [ 'akismet/akismet.php' ], + ], + ], + 'theme install' => [ + [ 'destination_name' => 'akismet' ], + [ + 'type' => 'theme', + 'action' => 'install', + ], + ], + 'translation update' => [ + [ 'destination_name' => 'nl_NL' ], + [ + 'type' => 'translation', + 'action' => 'update', + ], + ], + ]; + } + + public function test_an_installed_theme_is_reported_with_its_details(): void { + $data = [ + $this->upgrader( [ 'destination_name' => 'twentytwentyfive' ], $this->theme( 'twentytwentyfive', 'Twenty Twenty-Five', '1.2' ) ), + [ + 'type' => 'theme', + 'action' => 'install', + ], + ]; + $event = new ThemeInstalled(); + + $this->assertTrue( $event->should_fire( $data ) ); + $this->assertSame( + [ + 'name' => 'Twenty Twenty-Five', + 'slug' => 'twentytwentyfive', + 'version' => '1.2', + 'author' => 'the WordPress team', + ], + $event->get_post_body( $data ) + ); + } + + public function test_a_failed_theme_install_is_not_reported(): void { + $data = [ + $this->upgrader( new \stdClass(), $this->theme( 'broken', 'Broken' ) ), + [ + 'type' => 'theme', + 'action' => 'install', + ], + ]; + + $this->assertFalse( ( new ThemeInstalled() )->should_fire( $data ) ); + } + + public function test_a_deleted_plugin_is_reported_with_the_details_read_before_deletion(): void { + Functions\when( 'get_file_data' )->justReturn( + [ + 'Name' => 'Hello Dolly', + 'Version' => '1.7.2', + ] + ); + $event = new PluginDeleted(); + + PluginDeleted::remember( 'hello.php' ); + + $this->assertTrue( $event->should_fire( [ 'hello.php', true ] ) ); + $this->assertSame( + [ + 'name' => 'Hello Dolly', + 'slug' => 'hello.php', + 'version' => '1.7.2', + ], + $event->get_post_body( [ 'hello.php', true ] ) + ); + } + + public function test_a_plugin_whose_files_could_not_be_deleted_is_not_reported(): void { + $this->assertFalse( ( new PluginDeleted() )->should_fire( [ 'hello.php', false ] ) ); + } + + public function test_a_deleted_theme_is_reported_with_the_details_read_before_deletion(): void { + Functions\when( 'wp_get_theme' )->justReturn( $this->theme( 'twentytwentythree', 'Twenty Twenty-Three', '1.6' ) ); + $event = new ThemeDeleted(); + + ThemeDeleted::remember( 'twentytwentythree' ); + + $this->assertTrue( $event->should_fire( [ 'twentytwentythree', true ] ) ); + $this->assertFalse( $event->should_fire( [ 'twentytwentythree', false ] ) ); + $this->assertSame( + [ + 'name' => 'Twenty Twenty-Three', + 'slug' => 'twentytwentythree', + 'version' => '1.6', + ], + $event->get_post_body( [ 'twentytwentythree', true ] ) + ); + } + + public function test_a_theme_switch_has_the_new_and_old_theme(): void { + $data = [ + 'Twenty Twenty-Five', + $this->theme( 'twentytwentyfive', 'Twenty Twenty-Five' ), + $this->theme( 'twentytwentyfour', 'Twenty Twenty-Four' ), + ]; + $event = new ThemeSwitched(); + + $this->assertTrue( $event->should_fire( $data ) ); + $this->assertSame( + [ + 'name' => 'Twenty Twenty-Five', + 'slug' => 'twentytwentyfive', + 'old_name' => 'Twenty Twenty-Four', + 'old_slug' => 'twentytwentyfour', + ], + $event->get_post_body( $data ) + ); + } + + public function test_theme_names_are_sent_as_plain_text(): void { + $new = $this->theme( 'tom-jerry', 'Tom & Jerry' ); + $old = $this->theme( 'barrys', 'Barry's Theme' ); + $body = ( new ThemeSwitched() )->get_post_body( [ 'Tom & Jerry', $new, $old ] ); + + $this->assertSame( 'Tom & Jerry', $body['name'] ); + $this->assertSame( "Barry's Theme", $body['old_name'] ); + + Functions\when( 'wp_get_theme' )->justReturn( $new ); + ThemeDeleted::remember( 'tom-jerry' ); + $this->assertSame( 'Tom & Jerry', ( new ThemeDeleted() )->get_post_body( [ 'tom-jerry', true ] )['name'] ); + + $installed = [ + $this->upgrader( [ 'destination_name' => 'tom-jerry' ], $new ), + [ + 'type' => 'theme', + 'action' => 'install', + ], + ]; + $this->assertSame( 'Tom & Jerry', ( new ThemeInstalled() )->get_post_body( $installed )['name'] ); + } + + public function test_switching_to_the_same_theme_is_not_reported(): void { + $theme = $this->theme( 'twentytwentyfive', 'Twenty Twenty-Five' ); + + $this->assertFalse( ( new ThemeSwitched() )->should_fire( [ 'Twenty Twenty-Five', $theme, $theme ] ) ); + $this->assertFalse( ( new ThemeSwitched() )->should_fire( [ 'Twenty Twenty-Five', null, $theme ] ) ); + } +} diff --git a/tests/Unit/Events/PostChanges/BuilderTest.php b/tests/Unit/Events/PostChanges/BuilderTest.php new file mode 100644 index 0000000..56d909e --- /dev/null +++ b/tests/Unit/Events/PostChanges/BuilderTest.php @@ -0,0 +1,210 @@ +> + */ + private array $sent = []; + + /** + * Retries scheduled: hook and arguments. + * + * @var array}> + */ + private array $retries = []; + + /** + * Stored transients. + * + * @var array + */ + private array $transients = []; + + protected function setUp(): void { + parent::setUp(); + + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'esc_html' )->returnArg(); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'is_wp_error' )->alias( static fn( $thing ) => null === $thing ); + Functions\when( 'wp_remote_post' )->alias( + function ( $url, $args ) { + $this->sent[] = json_decode( $args['body'], true ); + return [ $this->status ]; + } + ); + Functions\when( 'wp_remote_retrieve_response_code' )->alias( static fn( $response ) => $response[0] ); + Functions\when( 'update_option' )->justReturn( true ); + Functions\when( 'get_transient' )->alias( fn( $key ) => $this->transients[ $key ] ?? false ); + Functions\when( 'delete_transient' )->alias( + function ( $key ) { + unset( $this->transients[ $key ] ); + return true; + } + ); + Functions\when( 'as_schedule_single_action' )->alias( + function ( $timestamp, $hook, $args ) { + $this->retries[] = [ + 'hook' => $hook, + 'args' => $args, + ]; + return 1; + } + ); + } + + /** + * Event data for post 7 with the given changes. + * + * @param array $changes The changes as noted. + * + * @return array + */ + private function data( array $changes ): array { + return [ + 'id' => 7, + 'title' => 'About', + 'post_status' => 'publish', + 'post_before' => [ 'post_status' => 'publish' ], + 'post' => [ + 'post_status' => 'publish', + 'post_type' => 'page', + ], + 'changes' => $changes, + ]; + } + + /** + * Run the job and return the exception message, or '' when accepted. + * + * @param array $data The event data. + * @param string $stash The stash key. + * + * @return string + */ + private function build( array $data, string $stash = '' ): string { + try { + Builder::build( 'PostSaved', [ 'id' => 1 ], $data, $stash ); + } catch ( RuntimeException $e ) { + return $e->getMessage(); + } + + return ''; + } + + public function test_title_password_and_order_changes_are_sent_as_noted(): void { + $changes = [ + 'title' => [ + 'old' => 'A', + 'new' => 'About', + ], + 'password' => [ + 'old' => false, + 'new' => true, + ], + 'menu_order' => [ + 'old' => 0, + 'new' => 2, + ], + ]; + $this->build( $this->data( $changes ) ); + + $this->assertSame( $changes['title'], $this->sent[0]['data']['changes']['title'] ); + $this->assertSame( $changes['password'], $this->sent[0]['data']['changes']['password'] ); + $this->assertSame( $changes['menu_order'], $this->sent[0]['data']['changes']['menu_order'] ); + } + + public function test_a_save_without_changes_is_sent_without_a_changes_key(): void { + $this->build( $this->data( [] ) ); + + $this->assertArrayNotHasKey( 'changes', $this->sent[0]['data'] ); + } + + public function test_content_that_was_too_large_is_reported_as_changed(): void { + $this->build( $this->data( [ 'content' => [ 'too_large' => true ] ] ) ); + + $this->assertSame( + [ + 'changed' => true, + 'reason' => 'too_large', + ], + $this->sent[0]['data']['changes']['content'] + ); + } + + public function test_stashed_changes_that_expired_are_left_out(): void { + $this->build( $this->data( [ 'stashed' => true ] ), '0f8fad5bd9cb469fa16570867728950e' ); + + $this->assertArrayNotHasKey( 'changes', $this->sent[0]['data'] ); + } + + public function test_stashed_changes_are_used_and_removed_once_sent(): void { + $key = '0f8fad5bd9cb469fa16570867728950e'; + $this->transients[ 'scanfully_post_change_' . $key ] = [ + 'changes' => [ + 'title' => [ + 'old' => 'A', + 'new' => 'B', + ], + ], + ]; + + $this->build( $this->data( [ 'stashed' => true ] ), $key ); + + $this->assertSame( 'B', $this->sent[0]['data']['changes']['title']['new'] ); + $this->assertSame( [], $this->transients ); + } + + public function test_a_temporary_failure_retries_the_build_and_keeps_the_stash(): void { + $key = '0f8fad5bd9cb469fa16570867728950e'; + $this->transients[ 'scanfully_post_change_' . $key ] = [ 'changes' => [] ]; + $this->status = 503; + + $message = $this->build( $this->data( [ 'stashed' => true ] ), $key ); + + $this->assertStringContainsString( 'HTTP 503', $message ); + $this->assertSame( Controller::ACTION_BUILD_POST_EVENT, $this->retries[0]['hook'] ); + $this->assertSame( [ 'stashed' => true ], $this->retries[0]['args'][2]['changes'], 'The retry builds again from what was noted.' ); + $this->assertSame( $key, $this->retries[0]['args'][3] ); + $this->assertSame( 1, $this->retries[0]['args'][4] ); + $this->assertCount( 1, $this->transients ); + } + + public function test_a_refused_event_removes_the_stash(): void { + $key = '0f8fad5bd9cb469fa16570867728950e'; + $this->transients[ 'scanfully_post_change_' . $key ] = [ 'changes' => [] ]; + $this->status = 400; + + $this->build( $this->data( [ 'stashed' => true ] ), $key ); + + $this->assertSame( [], $this->retries ); + $this->assertSame( [], $this->transients ); + } +} diff --git a/tests/Unit/Events/PostChanges/CollectorTest.php b/tests/Unit/Events/PostChanges/CollectorTest.php new file mode 100644 index 0000000..033eb1f --- /dev/null +++ b/tests/Unit/Events/PostChanges/CollectorTest.php @@ -0,0 +1,745 @@ +>> + */ + private array $meta_cache = []; + + /** + * What the collector reported: the action's arguments. + * + * @var array> + */ + private array $reported = []; + + /** + * Content events reported: type and data. + * + * @var array}> + */ + private array $content = []; + + /** + * How many revisions WordPress keeps. + * + * @var int + */ + private int $revisions_to_keep = -1; + + protected function setUp(): void { + parent::setUp(); + Collector::reset(); + + Functions\when( 'wp_cache_get' )->alias( fn( $id, $group ) => 'post_meta' === $group ? ( $this->meta_cache[ $id ] ?? false ) : false ); + Functions\when( 'maybe_unserialize' )->alias( static fn( $value ) => is_string( $value ) && 0 === strpos( $value, 'a:' ) ? unserialize( $value ) : $value ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Test double of maybe_unserialize(). + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'get_taxonomy' )->alias( static fn( $name ) => in_array( $name, [ 'category', 'post_tag' ], true ) ? (object) [ 'show_ui' => true ] : (object) [ 'show_ui' => false ] ); + Functions\when( 'wp_revisions_to_keep' )->alias( fn() => $this->revisions_to_keep ); + // What the report needs: a connected site, post types with a screen, room in the per-minute cap. + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'wp_doing_ajax' )->justReturn( false ); + Functions\when( 'get_post_type_object' )->alias( + static fn( string $type ) => (object) [ + 'show_ui' => in_array( $type, [ 'post', 'page' ], true ), + 'labels' => (object) [ + 'name' => 'page' === $type ? 'Pages' : 'Posts', + 'singular_name' => 'page' === $type ? 'Page' : 'Post', + ], + ] + ); + Functions\when( 'get_transient' )->justReturn( false ); + Functions\when( 'set_transient' )->justReturn( true ); + Actions\expectDone( Collector::ACTION )->zeroOrMoreTimes()->whenHappen( + function ( ...$args ) { + $this->reported[] = $args; + } + ); + $this->content = []; + foreach ( [ 'PostDeleted', 'PostBulkAction' ] as $type ) { + Actions\expectDone( ContentEvent::hook( $type ) )->zeroOrMoreTimes()->whenHappen( + function ( $data ) use ( $type ) { + $this->content[] = [ + 'type' => $type, + 'data' => $data, + ]; + } + ); + } + } + + protected function tearDown(): void { + Collector::reset(); + parent::tearDown(); + } + + /** + * A post. + * + * @param array $fields Fields that differ from the defaults. + * + * @return \WP_Post + */ + private function post( array $fields = [] ): \WP_Post { + return new \WP_Post( + (object) array_merge( + [ + 'ID' => 7, + 'post_title' => 'About', + 'post_name' => 'about', + 'post_status' => 'publish', + 'post_type' => 'page', + 'post_content' => '

Hello

', + 'post_excerpt' => '', + 'post_parent' => 0, + 'post_author' => 1, + 'menu_order' => 0, + 'post_date' => '2026-10-01 10:00:00', + 'post_password' => '', + 'comment_status' => 'closed', + ], + $fields + ) + ); + } + + /** + * The changes between two posts, with no fields, terms or revisions. + * + * @param array $before Fields of the post before. + * @param array $after Fields of the post after. + * + * @return array|null + */ + private function changes( array $before, array $after ): ?array { + return Collector::changes( $this->post( $before ), $this->post( $after ), [], [], null ); + } + + public function test_a_save_that_changes_nothing_has_no_changes(): void { + $this->assertNull( $this->changes( [], [] ) ); + } + + public function test_a_status_change_alone_is_a_change_without_details(): void { + $this->assertSame( [], $this->changes( [ 'post_status' => 'draft' ], [] ) ); + } + + public function test_a_title_change_keeps_both_titles(): void { + $this->assertSame( + [ + 'title' => [ + 'old' => 'About', + 'new' => 'About us', + ], + ], + $this->changes( [], [ 'post_title' => 'About us' ] ) + ); + } + + public function test_a_draft_getting_its_first_slug_is_not_a_slug_change(): void { + $this->assertSame( + [], + $this->changes( + [ + 'post_status' => 'draft', + 'post_name' => '', + ], + [] + ) + ); + } + + public function test_the_trashed_slug_is_not_a_slug_change(): void { + $this->assertSame( + [], + $this->changes( + [], + [ + 'post_status' => 'trash', + 'post_name' => 'about__trashed', + ] + ) + ); + $this->assertSame( + [], + $this->changes( + [ + 'post_status' => 'trash', + 'post_name' => 'about__trashed', + ], + [ 'post_status' => 'draft' ] + ) + ); + } + + public function test_a_slug_change_keeps_both_slugs(): void { + $changes = $this->changes( [], [ 'post_name' => 'about-us' ] ); + + $this->assertSame( + [ + 'old' => 'about', + 'new' => 'about-us', + ], + $changes['slug'] ?? null + ); + } + + public function test_a_drafts_moving_date_is_not_a_change(): void { + $this->assertNull( + $this->changes( + [ 'post_status' => 'draft' ], + [ + 'post_status' => 'draft', + 'post_date' => '2026-10-02 09:00:00', + ] + ) + ); + } + + public function test_a_published_posts_date_change_is_a_change(): void { + $changes = $this->changes( [], [ 'post_date' => '2026-09-01 10:00:00' ] ); + + $this->assertSame( '2026-09-01 10:00:00', $changes['date']['new'] ?? null ); + } + + public function test_a_password_is_never_kept_only_whether_there_is_one(): void { + $changes = $this->changes( [ 'post_password' => 'old-secret' ], [ 'post_password' => 'new-secret' ] ); + + $this->assertSame( + [ + 'old' => true, + 'new' => true, + ], + $changes['password'] ?? null + ); + $this->assertStringNotContainsString( 'secret', (string) json_encode( $changes ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + } + + public function test_parent_author_and_menu_order_changes_keep_ids(): void { + $changes = $this->changes( + [], + [ + 'post_parent' => 12, + 'post_author' => 3, + 'menu_order' => 2, + ] + ); + + $this->assertSame( + [ + 'old' => 0, + 'new' => 12, + ], + $changes['parent'] ?? null + ); + $this->assertSame( + [ + 'old' => 1, + 'new' => 3, + ], + $changes['author'] ?? null + ); + $this->assertSame( + [ + 'old' => 0, + 'new' => 2, + ], + $changes['menu_order'] ?? null + ); + } + + public function test_changed_content_is_compared_from_revisions_when_wordpress_keeps_them(): void { + $changes = Collector::changes( + $this->post(), + $this->post( [ 'post_content' => '

Hi

' ] ), + [], + [], + [ + 'first' => 20, + 'last' => 21, + 'earlier' => true, + ] + ); + + $this->assertSame( + [ + 'revisions' => [ + 'first' => 20, + 'last' => 21, + ], + ], + $changes['content'] ?? null + ); + } + + public function test_changed_content_is_kept_for_the_job_without_revisions(): void { + $this->revisions_to_keep = 0; + + $changes = Collector::changes( + $this->post(), + $this->post( [ 'post_content' => '

Hi

' ] ), + [], + [], + [ + 'first' => 20, + 'last' => 20, + 'earlier' => true, + ] + ); + + $this->assertSame( + [ + 'stash' => [ + 'old' => '

Hello

', + 'new' => '

Hi

', + ], + ], + $changes['content'] ?? null + ); + } + + public function test_a_single_kept_revision_is_not_enough_to_compare(): void { + $this->revisions_to_keep = 1; + + $changes = Collector::changes( + $this->post(), + $this->post( [ 'post_content' => '

Hi

' ] ), + [], + [], + [ + 'first' => 20, + 'last' => 20, + 'earlier' => true, + ] + ); + + $this->assertArrayHasKey( 'stash', $changes['content'] ?? [] ); + } + + public function test_a_posts_first_revision_has_no_content_before_it_so_the_content_is_kept(): void { + $changes = Collector::changes( + $this->post(), + $this->post( [ 'post_content' => '

Hi

' ] ), + [], + [], + [ + 'first' => 20, + 'last' => 20, + 'earlier' => false, + ] + ); + + $this->assertArrayHasKey( 'stash', $changes['content'] ?? [] ); + } + + public function test_very_large_content_without_revisions_is_not_kept(): void { + $changes = $this->changes( [], [ 'post_content' => str_repeat( 'a', Collector::MAX_CONTENT + 1 ) ] ); + + $this->assertSame( [ 'too_large' => true ], $changes['content'] ?? null ); + } + + /** + * Save post 7 with the given fields before and after, then flush. + * + * @param array $before Fields of the post before. + * @param array $after Fields of the post after. + * @param bool $update Whether an existing post was updated. + * + * @return void + */ + private function save_and_flush( array $before = [], array $after = [], bool $update = true ): void { + Collector::note_saved( 7, $this->post( $after ), $update, $this->post( $before ) ); + Collector::flush(); + } + + public function test_a_custom_field_change_is_reported_with_both_values(): void { + $this->meta_cache[7] = [ 'subtitle' => [ 'Old' ] ]; + Collector::note_meta_updated( 1, 7, 'subtitle', 'New' ); + $this->save_and_flush(); + + $this->assertCount( 1, $this->reported ); + $this->assertSame( + [ + 'subtitle' => [ + 'change' => 'changed', + 'old' => 'Old', + 'new' => 'New', + ], + ], + $this->reported[0][4]['fields'] ?? null + ); + } + + public function test_setting_a_field_to_the_same_value_is_not_a_change(): void { + $this->meta_cache[7] = [ 'colors' => [ serialize( [ 'red' ] ) ] ]; // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Stored meta is serialized. + Collector::note_meta_updated( 1, 7, 'colors', [ 'red' ] ); + $this->save_and_flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_added_and_removed_fields_are_reported(): void { + $this->meta_cache[7] = [ 'gone' => [ 'Bye' ] ]; + Collector::note_meta_added( 1, 7, 'fresh', 'Hi' ); + Collector::note_meta_deleted( [ 2 ], 7, 'gone', '' ); + $this->save_and_flush(); + + $fields = $this->reported[0][4]['fields'] ?? []; + $this->assertSame( + [ + 'change' => 'added', + 'new' => 'Hi', + ], + $fields['fresh'] ?? null + ); + $this->assertSame( + [ + 'change' => 'removed', + 'old' => 'Bye', + ], + $fields['gone'] ?? null + ); + } + + public function test_a_field_added_and_removed_in_one_request_is_not_reported(): void { + Collector::note_meta_added( 1, 7, 'temp', 'x' ); + Collector::note_meta_deleted( [ 1 ], 7, 'temp', '' ); + $this->save_and_flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_large_field_value_is_only_marked_large(): void { + $this->meta_cache[7] = [ '_elementor_data' => [ str_repeat( 'x', 300 ) ] ]; + Collector::note_meta_updated( 1, 7, '_elementor_data', str_repeat( 'y', 300 ) ); + $this->save_and_flush(); + + $this->assertSame( + [ + 'change' => 'changed', + 'large' => true, + ], + $this->reported[0][4]['fields']['_elementor_data'] ?? null + ); + } + + public function test_bookkeeping_fields_are_not_changes(): void { + $this->meta_cache[7] = [ '_edit_lock' => [ '1:1' ] ]; + Collector::note_meta_updated( 1, 7, '_edit_lock', '2:1' ); + Collector::note_meta_updated( 1, 7, '_yoast_wpseo_content_score', '60' ); + $this->save_and_flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_field_changed_without_a_save_is_not_reported(): void { + Collector::note_meta_updated( 1, 7, 'views', '12' ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_terms_added_and_removed_are_reported(): void { + Collector::note_terms( 7, [], [ 3, 5 ], 'category', false, [ 1, 3 ] ); + $this->save_and_flush(); + + $this->assertSame( + [ + 'category' => [ + 'added' => [ 5 ], + 'removed' => [ 1 ], + ], + ], + $this->reported[0][4]['terms'] ?? null + ); + } + + public function test_appended_terms_keep_the_existing_ones(): void { + Collector::note_terms( 7, [], [ 5 ], 'post_tag', true, [ 1 ] ); + $this->save_and_flush(); + + $this->assertSame( + [ + 'added' => [ 5 ], + 'removed' => [], + ], + $this->reported[0][4]['terms']['post_tag'] ?? null + ); + } + + public function test_terms_of_internal_taxonomies_are_not_changes(): void { + Collector::note_terms( 7, [], [ 9 ], 'internal_tax', false, [] ); + $this->save_and_flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_new_post_is_reported_without_changes(): void { + Collector::note_saved( 7, $this->post(), false, null ); + Collector::flush(); + + $this->assertCount( 1, $this->reported ); + $this->assertSame( [], $this->reported[0][4] ); + } + + public function test_a_post_opened_as_auto_draft_and_saved_is_new(): void { + $this->save_and_flush( + [ + 'post_status' => 'auto-draft', + 'post_title' => '', + ], + [ 'post_status' => 'draft' ] + ); + + $this->assertSame( [], $this->reported[0][4] ); + } + + public function test_several_saves_in_one_request_are_reported_once_from_first_to_last(): void { + Collector::note_saved( 7, $this->post( [ 'post_title' => 'B' ] ), true, $this->post( [ 'post_title' => 'A' ] ) ); + Collector::note_saved( 7, $this->post( [ 'post_title' => 'C' ] ), true, $this->post( [ 'post_title' => 'B' ] ) ); + Collector::flush(); + + $this->assertCount( 1, $this->reported ); + $this->assertSame( + [ + 'old' => 'A', + 'new' => 'C', + ], + $this->reported[0][4]['title'] ?? null + ); + } + + public function test_a_flush_forgets_what_it_reported(): void { + $this->save_and_flush( [], [ 'post_title' => 'New' ] ); + Collector::flush(); + + $this->assertCount( 1, $this->reported ); + } + + public function test_a_revision_is_noted_for_its_post(): void { + $this->assertTrue( Collector::note_earlier_revision( true, (object) [ 'ID' => 19 ], (object) [ 'ID' => 7 ] ) ); + Collector::note_revision( 20, 7 ); + Collector::note_revision( 21, 7 ); + $this->save_and_flush( [], [ 'post_content' => '

Changed

' ] ); + + $this->assertSame( + [ + 'revisions' => [ + 'first' => 20, + 'last' => 21, + ], + ], + $this->reported[0][4]['content'] ?? null + ); + } + + /** + * Delete post 7 (or another) the way wp_delete_post() calls the hooks. + * + * @param array $fields The post's fields. + * @param bool $done Whether the delete went through. + * + * @return void + */ + private function delete( array $fields = [], bool $done = true ): void { + $post = $this->post( $fields ); + Collector::note_deleting( $post->ID, $post ); + if ( $done ) { + Collector::note_deleted( $post->ID ); + } + } + + public function test_a_permanent_delete_is_reported_with_its_title_type_and_status(): void { + $this->delete( [ 'post_status' => 'trash' ] ); + Collector::flush(); + + $this->assertSame( + [ + [ + 'type' => 'PostDeleted', + 'data' => [ + 'id' => 7, + 'title' => 'About', + 'post_type' => 'page', + 'type_label' => 'Page', + 'post_status' => 'trash', + ], + ], + ], + $this->content + ); + } + + public function test_a_delete_that_did_not_go_through_is_not_reported(): void { + $this->delete( [], false ); + Collector::flush(); + + $this->assertSame( [], $this->content ); + } + + public function test_the_trash_wordpress_empties_itself_is_marked_as_expired(): void { + Actions\expectDone( 'wp_scheduled_delete' )->once()->whenHappen( + function () { + $this->delete( [ 'post_status' => 'trash' ] ); + } + ); + do_action( 'wp_scheduled_delete' ); + Collector::flush(); + + $this->assertTrue( $this->content[0]['data']['expired'] ?? null ); + $this->assertSame( 30, $this->content[0]['data']['trash_days'] ?? null ); + } + + public function test_auto_drafts_and_types_without_a_screen_are_not_reported_when_deleted(): void { + $this->delete( [ 'post_status' => 'auto-draft' ] ); + $this->delete( + [ + 'ID' => 8, + 'post_type' => 'revision', + ] + ); + Collector::flush(); + + $this->assertSame( [], $this->content ); + } + + public function test_a_post_trashed_and_deleted_in_one_request_is_only_reported_as_deleted(): void { + Collector::note_saved( 7, $this->post( [ 'post_status' => 'trash' ] ), true, $this->post() ); + $this->delete( [ 'post_status' => 'trash' ] ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + $this->assertSame( [ 'PostDeleted' ], array_column( $this->content, 'type' ) ); + } + + public function test_a_post_made_and_deleted_in_one_request_is_not_reported(): void { + Collector::note_saved( 7, $this->post( [ 'post_status' => 'draft' ] ), false, null ); + $this->delete( [ 'post_status' => 'draft' ] ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + $this->assertSame( [], $this->content ); + } + + public function test_fields_removed_while_a_post_is_deleted_are_not_noted(): void { + $this->meta_cache[7] = [ 'subtitle' => [ 'Old' ] ]; + Collector::note_deleting( 7, $this->post() ); + Collector::note_meta_deleted( [ 1 ], 7, 'subtitle', 'Old' ); + Collector::note_saved( 7, $this->post(), true, $this->post() ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_many_posts_moved_to_the_trash_are_one_row_with_every_post(): void { + for ( $id = 1; $id <= 11; $id++ ) { + Collector::note_saved( + $id, + $this->post( + [ + 'ID' => $id, + 'post_title' => 'Page ' . $id, + 'post_status' => 'trash', + ] + ), + true, + $this->post( [ 'ID' => $id ] ) + ); + } + Collector::flush(); + + $this->assertSame( [], $this->reported ); + $this->assertSame( [ 'PostBulkAction' ], array_column( $this->content, 'type' ) ); + $data = $this->content[0]['data']; + $this->assertSame( [ 'trashed', 'page', 'Pages', 11 ], [ $data['action'], $data['post_type'], $data['type_label'], $data['count'] ] ); + $this->assertSame( 'Page 11', $data['posts'][10]['title'] ); + } + + public function test_a_few_posts_keep_rows_of_their_own(): void { + for ( $id = 1; $id <= 3; $id++ ) { + Collector::note_saved( $id, $this->post( [ 'post_status' => 'trash' ] ), true, $this->post() ); + } + Collector::flush(); + + $this->assertCount( 3, $this->reported ); + $this->assertSame( [], $this->content ); + } + + public function test_a_bulk_edit_row_says_which_terms_were_added(): void { + for ( $id = 1; $id <= 12; $id++ ) { + Collector::note_terms( $id, [ 'news' ], [ 12 ], 'category', true, [ 1 ] ); + Collector::note_saved( $id, $this->post( [ 'ID' => $id ] ), true, $this->post( [ 'ID' => $id ] ) ); + } + Collector::flush(); + + $data = $this->content[0]['data'] ?? []; + $this->assertSame( 'updated', $data['action'] ?? null ); + $this->assertSame( [ 'terms' => 12 ], $data['changed'] ?? null ); + $this->assertSame( + [ + 'category' => [ + 'added' => [ 12 ], + 'removed' => [], + ], + ], + $data['terms'] ?? null + ); + $this->assertSame( [ 12 => true ], Collector::added_terms() ); + } + + public function test_posts_past_the_first_hundred_are_counted_into_the_row(): void { + for ( $id = 1; $id <= 150; $id++ ) { + Collector::note_saved( $id, $this->post( [ 'post_title' => 'Renamed ' . $id ] ), true, $this->post() ); + } + // The same post saved again past the cap is counted once. + Collector::note_saved( 150, $this->post( [ 'post_title' => 'Again' ] ), true, $this->post() ); + Collector::flush(); + + $data = $this->content[0]['data'] ?? []; + $this->assertSame( 150, $data['count'] ?? null ); + $this->assertSame( [ 'title' => 150 ], $data['changed'] ?? null ); + $this->assertSame( 'Renamed 150', $data['posts'][149]['title'] ?? null ); + } + + public function test_posts_past_the_first_hundred_that_changed_nothing_are_not_counted(): void { + for ( $id = 1; $id <= 120; $id++ ) { + Collector::note_saved( $id, $this->post(), true, $this->post() ); + } + Collector::flush(); + + $this->assertSame( [], $this->content ); + $this->assertSame( [], $this->reported ); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function test_nothing_is_noted_during_an_import(): void { + define( 'WP_IMPORTING', true ); + + $this->save_and_flush( [], [ 'post_title' => 'Imported' ] ); + + $this->assertSame( [], $this->reported ); + } +} diff --git a/tests/Unit/Events/PostChanges/ContentDiffTest.php b/tests/Unit/Events/PostChanges/ContentDiffTest.php new file mode 100644 index 0000000..5e084d8 --- /dev/null +++ b/tests/Unit/Events/PostChanges/ContentDiffTest.php @@ -0,0 +1,163 @@ +alias( static fn( $text ) => strip_tags( (string) $text ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- WordPress is not loaded in unit tests. + Functions\when( 'wp_parse_url' )->alias( static fn( $url, $component = -1 ) => parse_url( $url, $component ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- WordPress is not loaded in unit tests. + } + + /** + * A line diff that only finds lines removed or added at the same place, + * with runs of the same operation merged, as Text_Diff returns them. + * + * @param string[] $before The lines before. + * @param string[] $after The lines after. + * + * @return array + */ + public static function naive_diff( array $before, array $after ): array { + $operations = []; + $add = static function ( string $op, string $line ) use ( &$operations ): void { + $last = count( $operations ) - 1; + if ( $last >= 0 && $operations[ $last ][0] === $op ) { + $operations[ $last ][1][] = $line; + return; + } + $operations[] = [ $op, [ $line ] ]; + }; + + $count = max( count( $before ), count( $after ) ); + for ( $i = 0; $i < $count; $i++ ) { + $a = $before[ $i ] ?? null; + $b = $after[ $i ] ?? null; + if ( $a === $b ) { + $add( '=', (string) $a ); + continue; + } + if ( null !== $a ) { + $add( '-', $a ); + } + if ( null !== $b ) { + $add( '+', $b ); + } + } + + return $operations; + } + + public function test_block_markup_becomes_one_line_per_block(): void { + $content = "\n

Our team

\n\n\n" + . "\n

We are five people & a dog.

\n\n\n" + . "\n
  • Alice
  • Bob
\n"; + + $this->assertSame( [ 'Our team', 'We are five people & a dog.', 'Alice', 'Bob' ], ContentDiff::text_lines( $content ) ); + } + + public function test_images_are_named_by_their_file(): void { + $this->assertSame( + [ 'Before', '[image: team-photo.jpg]', 'After' ], + ContentDiff::text_lines( '

Before

x

After

' ) + ); + } + + public function test_scripts_and_styles_are_left_out(): void { + $this->assertSame( [ 'Text' ], ContentDiff::text_lines( '

Text

' ) ); + } + + public function test_a_markup_only_change_has_no_lines(): void { + $this->assertSame( + [ + 'changed' => true, + 'reason' => 'markup', + ], + ContentDiff::compare( '

Same

', '

Same

', [ self::class, 'naive_diff' ] ) + ); + } + + public function test_very_large_content_is_not_compared(): void { + $this->assertSame( 'too_large', ContentDiff::compare( str_repeat( 'a', ContentDiff::MAX_CONTENT + 1 ), 'b', [ self::class, 'naive_diff' ] )['reason'] ?? null ); + } + + public function test_a_change_keeps_one_line_of_context_and_counts_the_rest(): void { + $old = '

One

Two

Three

Four

Five

Six

'; + $new = '

One

Two

Three

4

Five

Six

'; + + $this->assertSame( + [ + 'added' => 1, + 'removed' => 1, + 'lines' => [ + [ + 'op' => 'skip', + 'count' => 2, + ], + [ + 'op' => '=', + 'text' => 'Three', + ], + [ + 'op' => '-', + 'text' => 'Four', + ], + [ + 'op' => '+', + 'text' => '4', + ], + [ + 'op' => '=', + 'text' => 'Five', + ], + [ + 'op' => 'skip', + 'count' => 1, + ], + ], + 'truncated' => false, + ], + ContentDiff::compare( $old, $new, [ self::class, 'naive_diff' ] ) + ); + } + + public function test_short_unchanged_runs_between_changes_are_kept_whole(): void { + $summary = ContentDiff::summarize( + [ + [ '-', [ 'a' ] ], + [ '=', [ 'b', 'c' ] ], + [ '+', [ 'd' ] ], + ] + ); + + $this->assertSame( [ '-', '=', '=', '+' ], array_column( $summary['lines'], 'op' ) ); + } + + public function test_long_lines_are_cut(): void { + $summary = ContentDiff::summarize( [ [ '+', [ str_repeat( 'é', ContentDiff::MAX_LINE + 10 ) ] ] ] ); + + $this->assertSame( ContentDiff::MAX_LINE + 1, mb_strlen( $summary['lines'][0]['text'] ) ); + } + + public function test_a_long_diff_is_truncated_but_still_counted(): void { + $added = array_fill( 0, 100, str_repeat( 'x', 200 ) ); + $summary = ContentDiff::summarize( [ [ '+', $added ] ] ); + + $this->assertTrue( $summary['truncated'] ); + $this->assertSame( 100, $summary['added'] ); + $this->assertLessThanOrEqual( ContentDiff::MAX_DIFF, array_sum( array_map( 'strlen', array_column( $summary['lines'], 'text' ) ) ) ); + } +} diff --git a/tests/Unit/Events/PostChanges/PostSavedScheduleTest.php b/tests/Unit/Events/PostChanges/PostSavedScheduleTest.php new file mode 100644 index 0000000..388380f --- /dev/null +++ b/tests/Unit/Events/PostChanges/PostSavedScheduleTest.php @@ -0,0 +1,169 @@ +}> + */ + private array $scheduled = []; + + /** + * Stored transients. + * + * @var array + */ + private array $transients = []; + + /** + * Whether storing a transient works. + * + * @var bool + */ + private bool $can_store = true; + + protected function setUp(): void { + parent::setUp(); + $this->scheduled = []; + $this->transients = []; + $this->can_store = true; + + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'wp_doing_ajax' )->justReturn( false ); + Functions\when( 'get_post_type_object' )->justReturn( (object) [ 'show_ui' => true ] ); + // No per-minute cap, so the only transients are the stored changes. + Filters\expectApplied( 'scanfully_post_saved_events_per_minute' )->zeroOrMoreTimes()->andReturn( 0 ); + Functions\when( 'wp_get_current_user' )->justReturn( + (object) [ + 'ID' => 1, + 'display_name' => 'Admin', + ] + ); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'wp_generate_uuid4' )->justReturn( '0f8fad5b-d9cb-469f-a165-70867728950e' ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value ) { + if ( ! $this->can_store ) { + return false; + } + $this->transients[ $key ] = $value; + return true; + } + ); + Functions\when( 'as_schedule_single_action' )->alias( + function ( $timestamp, $hook, $args ) { + $this->scheduled[] = [ + 'hook' => $hook, + 'args' => $args, + ]; + return 1; + } + ); + } + + /** + * Report a saved post with the given changes. + * + * @param array $changes The changes. + * + * @return void + */ + private function report( array $changes ): void { + $post = (object) [ + 'ID' => 7, + 'post_title' => 'About', + 'post_status' => 'publish', + 'post_type' => 'page', + ]; + + ( new PostSaved() )->listener_callback( 7, $post, true, $post, $changes ); + } + + public function test_the_build_job_gets_the_changes_in_its_arguments(): void { + $changes = [ + 'title' => [ + 'old' => 'A', + 'new' => 'About', + ], + ]; + $this->report( $changes ); + + $this->assertSame( Controller::ACTION_BUILD_POST_EVENT, $this->scheduled[0]['hook'] ); + $this->assertSame( $changes, $this->scheduled[0]['args']['data']['changes'] ); + $this->assertSame( '', $this->scheduled[0]['args']['stash'] ); + $this->assertSame( [], $this->transients ); + } + + public function test_a_save_without_changes_sends_no_changes_key(): void { + $this->report( [] ); + + $this->assertArrayNotHasKey( 'changes', $this->scheduled[0]['args']['data'] ); + } + + public function test_content_without_revisions_is_stored_for_the_job(): void { + $changes = [ + 'content' => [ + 'stash' => [ + 'old' => '

Hello

', + 'new' => '

Hi

', + ], + ], + ]; + $this->report( $changes ); + + $args = $this->scheduled[0]['args']; + $this->assertSame( [ 'stashed' => true ], $args['data']['changes'] ); + $this->assertSame( '0f8fad5bd9cb469fa16570867728950e', $args['stash'] ); + $this->assertSame( [ 'changes' => $changes ], $this->transients[ 'scanfully_post_change_' . $args['stash'] ] ); + } + + public function test_changes_too_large_for_the_job_arguments_are_stored(): void { + $fields = []; + for ( $i = 0; $i < 30; $i++ ) { + $fields[ 'field_' . $i ] = [ + 'change' => 'changed', + 'old' => str_repeat( 'a', 200 ), + 'new' => str_repeat( 'b', 200 ), + ]; + } + $this->report( [ 'fields' => $fields ] ); + + $this->assertSame( [ 'stashed' => true ], $this->scheduled[0]['args']['data']['changes'] ); + $this->assertCount( 1, $this->transients ); + } + + public function test_content_that_could_not_be_stored_is_only_reported_as_changed(): void { + $this->can_store = false; + $this->report( + [ + 'content' => [ + 'stash' => [ + 'old' => 'a', + 'new' => 'b', + ], + ], + ] + ); + + $this->assertSame( [ 'content' => [ 'unavailable' => true ] ], $this->scheduled[0]['args']['data']['changes'] ); + $this->assertSame( '', $this->scheduled[0]['args']['stash'] ); + } +} diff --git a/tests/Unit/Events/PostSavedFilterTest.php b/tests/Unit/Events/PostSavedFilterTest.php index 4642740..719c814 100644 --- a/tests/Unit/Events/PostSavedFilterTest.php +++ b/tests/Unit/Events/PostSavedFilterTest.php @@ -1,6 +1,6 @@ */ - private array $ui_types = [ 'post', 'page', 'product', 'shop_order' ]; + private array $ui_types = [ 'post', 'page', 'product', 'shop_order', 'seopress_404' ]; protected function setUp(): void { parent::setUp(); $this->transients = []; - $fired = new ReflectionProperty( PostSaved::class, 'fired_ids' ); - $fired->setAccessible( true ); - $fired->setValue( null, [] ); - Functions\when( 'wp_doing_ajax' )->justReturn( false ); Functions\when( 'wc_get_order_types' )->justReturn( [ 'shop_order', 'shop_order_refund' ] ); Functions\when( 'get_post_type_object' )->alias( @@ -99,33 +94,25 @@ public function provide_ignored_saves(): array { 'refund' => [ 'shop_order_refund', 'draft' ], 'ACF field' => [ 'acf-field', 'publish' ], 'oEmbed cache' => [ 'oembed_cache', 'publish' ], + 'SEOPress 404 record' => [ 'seopress_404', 'publish' ], + 'SEOPress 404 record as a draft' => [ 'seopress_404', 'draft' ], + 'trashed SEOPress 404 record' => [ 'seopress_404', 'trash' ], 'custom type without an admin screen' => [ 'my_internal_type', 'publish' ], 'pending review status' => [ 'post', 'pending' ], ]; } - /** - * Forget saves made earlier in this "request" (the per-request list). - */ - private function new_request(): void { - $fired = new ReflectionProperty( PostSaved::class, 'fired_ids' ); - $fired->setAccessible( true ); - $fired->setValue( null, [] ); - } - public function test_publishing_right_after_saving_a_draft_is_reported(): void { $this->assertTrue( $this->fires( 'post', 'draft', 5 ) ); - $this->new_request(); - $this->assertTrue( $this->fires( 'post', 'publish', 5 ), 'The publish event must not be dropped as a duplicate of the draft save.' ); } - public function test_repeated_saves_with_the_same_status_are_reported_once(): void { + public function test_saves_seconds_apart_are_not_deduplicated_by_time(): void { + // The Collector reports a post once per request and only when it + // changed; there is no time window that drops a real change. $this->assertTrue( $this->fires( 'post', 'publish', 6 ) ); - $this->assertFalse( $this->fires( 'post', 'publish', 6 ), 'Same request.' ); - - $this->new_request(); - $this->assertFalse( $this->fires( 'post', 'publish', 6 ), 'Next request within seconds (block editor double save).' ); + $this->assertTrue( $this->fires( 'post', 'publish', 6 ) ); + $this->assertSame( [], array_filter( array_keys( $this->transients ), static fn( string $key ): bool => 0 === strpos( $key, 'scanfully_post_event_' ) ) ); } /** @@ -170,14 +157,6 @@ public function test_sites_can_exclude_saves_with_a_filter(): void { $this->assertFalse( $this->fires( 'post' ) ); } - public function test_saves_are_capped_per_minute(): void { - Filters\expectApplied( 'scanfully_post_saved_events_per_minute' )->andReturn( 2 ); - - $this->assertTrue( $this->fires( 'post', 'publish', 1 ) ); - $this->assertTrue( $this->fires( 'post', 'publish', 2 ) ); - $this->assertFalse( $this->fires( 'post', 'publish', 3 ) ); - } - /** * @runInSeparateProcess * @preserveGlobalState disabled diff --git a/tests/Unit/Events/RewriteRulesTest.php b/tests/Unit/Events/RewriteRulesTest.php deleted file mode 100644 index 0637dee..0000000 --- a/tests/Unit/Events/RewriteRulesTest.php +++ /dev/null @@ -1,83 +0,0 @@ - - */ - private array $transients = []; - - protected function setUp(): void { - parent::setUp(); - $this->transients = []; - $this->new_request(); - - Functions\when( 'get_transient' )->alias( fn( string $key ) => array_key_exists( $key, $this->transients ) ? $this->transients[ $key ] : false ); - Functions\when( 'set_transient' )->alias( - function ( string $key, $value ) { - $this->transients[ $key ] = $value; - return true; - } - ); - } - - /** - * Reset the per-request state. - */ - private function new_request(): void { - $fired = new ReflectionProperty( RewriteRules::class, 'fired' ); - $fired->setAccessible( true ); - $fired->setValue( null, false ); - } - - /** - * Whether an update of the option from $old to $new fires. - * - * @param mixed $old Old value. - * @param mixed $new New value. - * - * @return bool - */ - private function fires( $old, $new ): bool { - return ( new RewriteRules() )->should_fire( [ $old, $new, 'rewrite_rules' ] ); - } - - public function test_a_flush_on_old_wordpress_versions_is_reported_once(): void { - $rules = [ '^foo/?$' => 'index.php?foo=1' ]; - - // Before 6.4 a flush empties the option, then saves the rules. - $this->assertFalse( $this->fires( $rules, '' ) ); - $this->assertTrue( $this->fires( '', $rules ) ); - } - - public function test_repeated_flushes_are_throttled(): void { - $rules = [ '^foo/?$' => 'index.php?foo=1' ]; - - $this->assertTrue( $this->fires( [], $rules ) ); - $this->assertFalse( $this->fires( [], $rules ), 'Same request.' ); - - $this->new_request(); - $this->assertFalse( $this->fires( [], $rules ), 'A flush on the next page load within 5 minutes.' ); - - $this->transients = []; - $this->new_request(); - $this->assertTrue( $this->fires( [], $rules ), 'After the throttle window.' ); - } -} diff --git a/tests/Unit/Events/SettingsChanges/CollectorTest.php b/tests/Unit/Events/SettingsChanges/CollectorTest.php new file mode 100644 index 0000000..53b1808 --- /dev/null +++ b/tests/Unit/Events/SettingsChanges/CollectorTest.php @@ -0,0 +1,359 @@ + + */ + private array $options = []; + + /** + * The rows reported. + * + * @var array> + */ + private array $reported = []; + + /** + * Whether WordPress is installing or upgrading. + * + * @var bool + */ + private bool $installing = false; + + /** + * The signed-in user. + * + * @var int + */ + private int $user = 1; + + /** + * The current site (multisite). + * + * @var int + */ + private int $blog = 1; + + /** + * The site each row was reported on. + * + * @var array + */ + private array $reported_on = []; + + protected function setUp(): void { + parent::setUp(); + Collector::reset(); + $this->options = [ + 'admin_email' => 'admin@scanfully.com', + 'timezone_string' => 'Europe/Amsterdam', + 'gmt_offset' => '0', + 'scanfully_connect_is_connected' => 'yes', + ]; + $this->reported = []; + + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'get_option' )->alias( fn( $name, $fallback = false ) => $this->options[ $name ] ?? $fallback ); + Functions\when( 'wp_installing' )->alias( fn() => $this->installing ); + Functions\when( 'get_transient' )->justReturn( false ); + Functions\when( 'set_transient' )->justReturn( true ); + Functions\when( 'get_current_blog_id' )->alias( fn() => $this->blog ); + Functions\when( 'get_current_user_id' )->alias( fn() => $this->user ); + + Actions\expectDone( ContentEvent::hook( 'SiteOptionChanged' ) )->zeroOrMoreTimes()->whenHappen( + function ( $data ) { + $this->reported[] = $data; + $this->reported_on[] = $this->blog; + } + ); + } + + protected function tearDown(): void { + Collector::reset(); + parent::tearDown(); + } + + public function test_a_save_of_several_settings_is_a_row_each_in_screen_order(): void { + Collector::note_updated( 'show_avatars', '1', '' ); + Collector::note_updated( 'default_comment_status', 'open', 'closed' ); + Collector::note_updated( 'comment_moderation', '', '1' ); + Collector::flush(); + + $this->assertSame( [ 'default_comment_status', 'comment_moderation', 'show_avatars' ], array_column( $this->reported, 'option' ) ); + } + + public function test_an_option_that_is_no_setting_is_ignored(): void { + Collector::note_updated( 'active_plugins', [], [ 'akismet/akismet.php' ] ); + Collector::note_updated( '_transient_doing_cron', '1', '2' ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_setting_changed_twice_keeps_the_first_old_and_the_last_new_value(): void { + Collector::note_updated( 'posts_per_page', '10', '20' ); + Collector::note_updated( 'posts_per_page', '20', '12' ); + Collector::flush(); + + $this->assertSame( + [ + [ + 'option' => 'posts_per_page', + 'old' => '10', + 'new' => '12', + ], + ], + $this->reported + ); + } + + public function test_a_setting_changed_and_changed_back_is_nothing(): void { + Collector::note_updated( 'posts_per_page', '10', '20' ); + Collector::note_updated( 'posts_per_page', '20', '10' ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_setting_saved_for_the_first_time_changed_from_nothing(): void { + Collector::note_added( 'WPLANG', 'nl_NL' ); + Collector::flush(); + + $this->assertSame( + [ + [ + 'option' => 'WPLANG', + 'old' => '', + 'new' => 'nl_NL', + ], + ], + $this->reported + ); + } + + public function test_installs_and_database_upgrades_are_left_out(): void { + $this->installing = true; + Collector::note_updated( 'blogdescription', 'Old', 'New' ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_the_two_timezone_options_are_one_row(): void { + // Choosing UTC+2 instead of a city: the offset is set and the zone emptied. + Collector::note_updated( 'timezone_string', 'Europe/Amsterdam', '' ); + Collector::note_updated( 'gmt_offset', '0', '2' ); + Collector::flush(); + + $this->assertSame( + [ + [ + 'option' => 'timezone', + 'old' => 'Europe/Amsterdam', + 'new' => 'UTC+2', + ], + ], + $this->reported + ); + } + + public function test_an_offset_saved_next_to_a_city_zone_is_no_change(): void { + // Saving a city zone sends an empty offset; the shown zone stays the same. + Collector::note_updated( 'gmt_offset', '2', '' ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_an_admin_email_change_request_is_reported_without_the_hash(): void { + Collector::note_added( + 'adminhash', + [ + 'hash' => 'secret-hash', + 'newemail' => 'new@scanfully.com', + ] + ); + Collector::flush(); + + $this->assertSame( + [ + [ + 'option' => 'new_admin_email', + 'old' => 'admin@scanfully.com', + 'new' => 'new@scanfully.com', + ], + ], + $this->reported + ); + $this->assertStringNotContainsString( 'secret-hash', (string) json_encode( $this->reported ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + } + + public function test_a_withdrawn_request_is_reported_as_cancelled(): void { + $this->options['adminhash'] = [ + 'hash' => 'secret-hash', + 'newemail' => 'new@scanfully.com', + ]; + Collector::note_deleting( 'adminhash' ); + Collector::flush(); + + $this->assertSame( + [ + [ + 'option' => 'new_admin_email', + 'old' => 'admin@scanfully.com', + 'new' => 'new@scanfully.com', + 'cancelled' => true, + ], + ], + $this->reported + ); + } + + public function test_a_confirmed_request_is_only_the_admin_email_changing(): void { + $this->options['adminhash'] = [ + 'hash' => 'secret-hash', + 'newemail' => 'new@scanfully.com', + ]; + Collector::note_updated( 'admin_email', 'admin@scanfully.com', 'new@scanfully.com' ); + Collector::note_deleting( 'adminhash' ); + Collector::flush(); + + $this->assertSame( + [ + [ + 'option' => 'admin_email', + 'old' => 'admin@scanfully.com', + 'new' => 'new@scanfully.com', + ], + ], + $this->reported + ); + } + + public function test_rows_over_the_per_minute_cap_are_dropped_but_key_settings_never(): void { + Functions\when( 'get_transient' )->justReturn( 29 ); + Collector::note_updated( 'posts_per_page', '10', '12' ); + Collector::note_updated( 'posts_per_rss', '10', '12' ); + Collector::note_updated( 'default_role', 'subscriber', 'administrator' ); + Collector::note_updated( 'users_can_register', '0', '1' ); + Collector::flush(); + + $this->assertSame( [ 'users_can_register', 'default_role', 'posts_per_page' ], array_column( $this->reported, 'option' ) ); + } + + public function test_nothing_is_reported_for_a_site_that_is_not_connected(): void { + $this->options['scanfully_connect_is_connected'] = 'no'; + Collector::note_updated( 'posts_per_page', '10', '12' ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_deleted_setting_changed_to_empty(): void { + // Deleting the site icon's file deletes the option. + $this->options['site_icon'] = '42'; + Collector::note_deleting( 'site_icon' ); + Collector::flush(); + + $this->assertSame( + [ + [ + 'option' => 'site_icon', + 'old' => '42', + 'new' => '0', + ], + ], + $this->reported + ); + } + + public function test_a_change_published_by_cron_names_who_made_it(): void { + // A scheduled Customizer change: WordPress acts as its author, then + // signs out again before the request ends. + $this->user = 7; + Collector::note_updated( 'blogdescription', 'Old', 'New' ); + $this->user = 0; + Collector::flush(); + + $this->assertSame( 7, $this->reported[0]['_actor'] ); + } + + public function test_a_change_by_the_signed_in_user_names_no_one_else(): void { + Collector::note_updated( 'blogdescription', 'Old', 'New' ); + Collector::flush(); + + $this->assertArrayNotHasKey( '_actor', $this->reported[0] ); + } + + public function test_open_or_closed_settings_saved_empty_are_no_change(): void { + // An unticked box is saved as ''; REST saves 'closed'. + Collector::note_updated( 'default_comment_status', 'closed', '' ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_another_sites_setting_is_reported_on_that_site(): void { + $switches = []; + Functions\when( 'switch_to_blog' )->alias( + function ( $blog ) use ( &$switches ) { + $switches[] = $blog; + $this->blog = (int) $blog; + return true; + } + ); + Functions\when( 'restore_current_blog' )->alias( + function () { + $this->blog = 1; + return true; + } + ); + // Network Admin, Sites, Edit: WordPress switches to site 5 and back. + $this->blog = 5; + Collector::note_updated( 'blog_public', '1', '0' ); + $this->blog = 1; + Collector::note_updated( 'blogdescription', 'Old', 'New' ); + Collector::flush(); + + $this->assertSame( [ 5 ], $switches ); + $this->assertSame( [ 5, 1 ], $this->reported_on ); + $this->assertSame( [ 'blog_public', 'blogdescription' ], array_column( $this->reported, 'option' ) ); + $this->assertSame( 1, $this->blog, 'Back on the site of the request.' ); + } + + public function test_a_flush_with_nothing_noted_reads_nothing(): void { + Functions\expect( 'get_transient' )->never(); + Functions\expect( 'get_option' )->never(); + + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_flush_forgets_what_it_reported(): void { + Collector::note_updated( 'posts_per_page', '10', '12' ); + Collector::flush(); + Collector::flush(); + + $this->assertCount( 1, $this->reported ); + } +} diff --git a/tests/Unit/Events/SettingsChanges/SettingsTest.php b/tests/Unit/Events/SettingsChanges/SettingsTest.php new file mode 100644 index 0000000..c18fea1 --- /dev/null +++ b/tests/Unit/Events/SettingsChanges/SettingsTest.php @@ -0,0 +1,234 @@ +alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + } + + public function test_a_change_has_the_option_and_both_values_as_strings(): void { + $this->assertSame( + [ + 'option' => 'posts_per_page', + 'old' => '10', + 'new' => '12', + ], + Settings::change( 'posts_per_page', '10', 12 ) + ); + } + + public function test_the_site_title_and_tagline_are_sent_as_plain_text(): void { + $change = Settings::change( 'blogname', 'Tom & Jerry', 'Barry's Shop' ); + $this->assertSame( 'Tom & Jerry', $change['old'] ); + $this->assertSame( "Barry's Shop", $change['new'] ); + + $this->assertSame( 'Shop & more', Settings::change( 'blogdescription', 'Just another site', 'Shop & more' )['new'] ); + } + + public function test_search_engine_visibility_keeps_values_other_than_0_and_1(): void { + $this->assertSame( '-2', Settings::change( 'blog_public', '1', -2 )['new'] ); + $this->assertSame( '0', Settings::change( 'blog_public', '1', 0 )['new'] ); + } + + /** + * @dataProvider provide_unchanged_values + * + * @param string $option The option. + * @param mixed $old_value Old value. + * @param mixed $new_value New value. + */ + public function test_a_value_that_only_changed_type_is_no_change( string $option, $old_value, $new_value ): void { + $this->assertSame( [], Settings::change( $option, $old_value, $new_value ) ); + } + + /** + * @return array + */ + public function provide_unchanged_values(): array { + return [ + 'registration off, saved as an integer' => [ 'users_can_register', '0', 0 ], + 'registration off, saved as null' => [ 'users_can_register', '0', null ], + 'avatars off, saved as an empty string' => [ 'show_avatars', '0', '' ], + 'search engines allowed, saved as integer' => [ 'blog_public', '1', 1 ], + 'same role' => [ 'default_role', 'subscriber', 'subscriber' ], + 'posts per page as an integer' => [ 'posts_per_page', '10', 10 ], + 'no front page, saved as an empty string' => [ 'page_on_front', '0', '' ], + 'same word list, other line endings' => [ 'disallowed_keys', "spam\nviagra", "spam\r\nviagra\n" ], + ]; + } + + /** + * @dataProvider provide_changes + * + * @param string $option The option. + * @param mixed $old_value Old value. + * @param mixed $new_value New value. + */ + public function test_a_real_change_is_reported( string $option, $old_value, $new_value ): void { + $this->assertNotSame( [], Settings::change( $option, $old_value, $new_value ) ); + } + + /** + * @return array + */ + public function provide_changes(): array { + return [ + 'site address' => [ 'siteurl', 'http://scanfully.com', 'https://scanfully.com' ], + 'admin email' => [ 'admin_email', 'old@scanfully.com', 'new@scanfully.com' ], + 'registration opened' => [ 'users_can_register', '0', 1 ], + 'search engines discouraged' => [ 'blog_public', '1', 0 ], + 'tagline' => [ 'blogdescription', 'Old', 'New' ], + 'language' => [ 'WPLANG', '', 'nl_NL' ], + 'static front page' => [ 'page_on_front', '0', '12' ], + 'comments need approval' => [ 'comment_moderation', '', '1' ], + 'thumbnail width' => [ 'thumbnail_size_w', '150', '200' ], + 'category base' => [ 'category_base', '', 'topics' ], + 'privacy policy page' => [ 'wp_page_for_privacy_policy', '3', '7' ], + ]; + } + + public function test_an_option_outside_the_list_is_not_reported(): void { + $this->assertFalse( Settings::is_reported( 'active_plugins' ) ); + $this->assertFalse( Settings::is_reported( 'permalink_structure' ), 'PermalinksChanged reports the structure.' ); + $this->assertTrue( Settings::is_reported( 'blogdescription' ) ); + } + + public function test_secrets_only_say_they_changed(): void { + $this->assertSame( + [ + 'option' => 'mailserver_pass', + 'secret' => true, + ], + Settings::change( 'mailserver_pass', 'old-password', 'new-password' ) + ); + $this->assertSame( + [ + 'option' => 'mailserver_login', + 'secret' => true, + ], + Settings::change( 'mailserver_login', 'login@scanfully.com', 'other@scanfully.com' ) + ); + } + + public function test_word_lists_only_say_how_many_lines_were_added_and_removed(): void { + $change = Settings::change( 'disallowed_keys', "spam\n203.0.113.9\nbad@scanfully.com", "spam\nbad@scanfully.com\nviagra\ncasino" ); + + $this->assertSame( + [ + 'option' => 'disallowed_keys', + 'added' => 2, + 'removed' => 1, + ], + $change + ); + $this->assertStringNotContainsString( 'scanfully.com', (string) json_encode( $change ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + } + + public function test_a_line_listed_twice_and_kept_once_was_removed_once(): void { + $this->assertSame( [ [], [ 'spam' ] ], Settings::line_changes( "spam\nspam", 'spam' ) ); + } + + public function test_update_services_list_the_urls_added_and_removed(): void { + $this->assertSame( + [ + 'option' => 'ping_sites', + 'added' => [ 'https://ping.scanfully.com/' ], + 'removed' => [ 'http://rpc.pingomatic.com/' ], + ], + Settings::change( 'ping_sites', 'http://rpc.pingomatic.com/', "https://ping.scanfully.com/\n" ) + ); + } + + public function test_long_values_are_cut(): void { + $change = Settings::change( 'blogdescription', 'Short', str_repeat( 'a', 1500 ) ); + + $this->assertSame( Settings::MAX_VALUE, strlen( $change['new'] ) ); + } + + /** + * @dataProvider provide_timezones + * + * @param mixed $zone The timezone_string option. + * @param mixed $offset The gmt_offset option. + * @param string $expected The timezone as shown. + */ + public function test_the_timezone_is_the_zone_or_the_offset( $zone, $offset, string $expected ): void { + $this->assertSame( $expected, Settings::timezone( $zone, $offset ) ); + } + + /** + * @return array + */ + public function provide_timezones(): array { + return [ + 'a city' => [ 'Europe/Amsterdam', '2', 'Europe/Amsterdam' ], + 'UTC+2' => [ '', '2', 'UTC+2' ], + 'UTC-3:30' => [ '', '-3.5', 'UTC-3:30' ], + 'UTC+5:45' => [ '', 5.75, 'UTC+5:45' ], + 'UTC' => [ '', '0', 'UTC+0' ], + 'nothing saved at all' => [ false, false, 'UTC+0' ], + ]; + } + + public function test_the_job_adds_page_titles(): void { + Functions\when( 'get_post' )->alias( + static fn( $id ) => new \WP_Post( + (object) [ + 'ID' => $id, + 'post_title' => 12 === $id ? 'Home & away' : 'Blog', + ] + ) + ); + + $data = Settings::resolve( + [ + 'option' => 'page_on_front', + 'old' => '0', + 'new' => '12', + ] + ); + + $this->assertSame( 'Home & away', $data['new_name'] ); + $this->assertArrayNotHasKey( 'old_name', $data, 'No page before.' ); + } + + public function test_the_job_adds_an_example_of_a_date_format(): void { + Functions\when( 'wp_date' )->alias( static fn( $format, $timestamp ) => gmdate( $format, $timestamp ) ); + + $data = Settings::resolve( + [ + 'option' => 'date_format', + 'old' => 'F j, Y', + 'new' => 'd/m/Y', + ] + ); + + $this->assertSame( 'January 31, 2026', $data['old_example'] ); + $this->assertSame( '31/01/2026', $data['new_example'] ); + } + + public function test_the_job_leaves_other_settings_alone(): void { + $data = [ + 'option' => 'posts_per_page', + 'old' => '10', + 'new' => '12', + ]; + + $this->assertSame( $data, Settings::resolve( $data ) ); + } +} diff --git a/tests/Unit/Events/SiteEditor/CollectorTest.php b/tests/Unit/Events/SiteEditor/CollectorTest.php new file mode 100644 index 0000000..bea6a9a --- /dev/null +++ b/tests/Unit/Events/SiteEditor/CollectorTest.php @@ -0,0 +1,255 @@ +justReturn( false ); + Functions\when( 'get_stylesheet' )->justReturn( 'twentytwentyfive' ); + Functions\when( 'get_the_terms' )->alias( + static fn( $post, string $taxonomy ) => 'wp_theme' === $taxonomy ? [ (object) [ 'name' => 'twentytwentyfive' ] ] : [ (object) [ 'name' => 'footer' ] ] + ); + } + + protected function tearDown(): void { + Collector::reset(); + parent::tearDown(); + } + + /** + * A post. + * + * @param array $fields The fields. + * + * @return \WP_Post + */ + private function post( array $fields ): \WP_Post { + return new \WP_Post( + (object) array_merge( + [ + 'ID' => 5, + 'post_title' => '', + 'post_excerpt' => '', + 'post_content' => '', + 'post_status' => 'publish', + 'post_name' => '', + 'post_parent' => 0, + ], + $fields + ) + ); + } + + /** + * A global styles post. + * + * @param string $content The config. + * @param string $title The title. + * + * @return \WP_Post + */ + private function styles( string $content, string $title = 'Custom Styles' ): \WP_Post { + return $this->post( + [ + 'post_type' => 'wp_global_styles', + 'post_name' => 'wp-global-styles-twentytwentyfive', + 'post_title' => $title, + 'post_content' => $content, + ] + ); + } + + public function test_the_empty_styles_core_makes_are_not_a_change(): void { + Collector::note_saved( 5, $this->styles( '{"version": 3, "isGlobalStylesUserThemeJSON": true }' ), false, null ); + + $this->assertSame( [], Collector::styles_rows() ); + } + + public function test_a_styles_save_keeps_the_config_before_and_after_and_the_theme(): void { + $before = $this->styles( '{"version":3,"isGlobalStylesUserThemeJSON":true}' ); + $after = $this->styles( '{"version":3,"isGlobalStylesUserThemeJSON":true,"styles":{"color":{"background":"#000"}}}' ); + + Collector::note_saved( 5, $after, true, $before ); + $rows = Collector::styles_rows(); + + $this->assertCount( 1, $rows ); + $this->assertSame( 'twentytwentyfive', $rows[0]['stylesheet'] ); + $this->assertSame( $after->post_content, $rows[0]['content']['stash']['new'] ); + } + + public function test_a_variation_with_the_same_config_is_still_reported_by_its_title(): void { + $content = '{"version":3,"isGlobalStylesUserThemeJSON":true}'; + Collector::note_saved( 5, $this->styles( $content, 'Noon' ), true, $this->styles( $content ) ); + + $this->assertSame( + [ + 'old' => 'Custom Styles', + 'new' => 'Noon', + ], + Collector::styles_rows()[0]['title'] + ); + } + + /** + * A template. + * + * @param string $content The content. + * @param string $title The title. + * @param string $status The status. + * + * @return \WP_Post + */ + private function template( string $content, string $title = 'Pages', string $status = 'publish' ): \WP_Post { + return $this->post( + [ + 'post_type' => 'wp_template', + 'post_name' => 'page', + 'post_title' => $title, + 'post_content' => $content, + 'post_status' => $status, + ] + ); + } + + public function test_a_first_save_is_provisional_for_the_job(): void { + Collector::note_saved( 5, $this->template( '' ), false, null ); + $rows = Collector::template_rows(); + + $this->assertSame( 'TemplateChanged', $rows[0][0] ); + $this->assertTrue( $rows[0][1]['inserted'] ); + $this->assertSame( '', $rows[0][1]['content']['stash']['old'] ); + } + + public function test_an_edit_reports_the_title_and_content_and_an_unchanged_save_nothing(): void { + Collector::note_saved( 5, $this->template( 'b', 'Pages (shop)' ), true, $this->template( 'a' ) ); + $rows = Collector::template_rows(); + + $this->assertSame( + [ + 'old' => 'Pages', + 'new' => 'Pages (shop)', + ], + $rows[0][1]['changes']['title'] + ); + $this->assertSame( + [ + 'old' => 'a', + 'new' => 'b', + ], + $rows[0][1]['content']['stash'] + ); + + Collector::reset(); + Collector::note_saved( 5, $this->template( 'a' ), true, $this->template( 'a' ) ); + + $this->assertSame( [], Collector::template_rows() ); + } + + public function test_a_template_part_moved_to_another_area_is_a_change(): void { + $part = $this->post( + [ + 'post_type' => 'wp_template_part', + 'post_name' => 'footer', + 'post_content' => 'a', + ] + ); + Collector::note_terms( 5, [], [ 8 ], 'wp_template_part_area', false, [ 7 ] ); + Collector::note_saved( 5, $part, true, $part ); + + $this->assertSame( + [ + 'old' => [ 7 ], + 'new' => [ 8 ], + ], + Collector::template_rows()[0][1]['changes']['area'] + ); + } + + public function test_a_delete_or_trash_is_a_provisional_delete_with_the_content_before(): void { + Collector::note_deleting( 5, $this->template( 'gone' ) ); + $rows = Collector::template_rows(); + + $this->assertSame( 'TemplateDeleted', $rows[0][0] ); + $this->assertTrue( $rows[0][1]['removed'] ); + $this->assertSame( 'twentytwentyfive', $rows[0][1]['stylesheet'] ); + $this->assertSame( 'gone', $rows[0][1]['content']['stash']['old'] ); + + Collector::reset(); + Collector::note_saved( 5, $this->template( 'gone', 'Pages', 'trash' ), true, $this->template( 'gone' ) ); + + $this->assertSame( 'TemplateDeleted', Collector::template_rows()[0][0] ); + } + + public function test_font_families_and_variants_are_noted_per_family(): void { + Functions\when( 'get_post' )->justReturn( + $this->post( + [ + 'ID' => 9, + 'post_type' => 'wp_font_family', + 'post_title' => 'Inter', + 'post_name' => 'inter', + ] + ) + ); + + Collector::note_saved( + 12, + $this->post( + [ + 'ID' => 12, + 'post_type' => 'wp_font_face', + 'post_parent' => 9, + 'post_content' => '{"fontFamily":"Inter","fontStyle":"italic","fontWeight":"700","src":"https://scanfully.com/inter.woff2"}', + ] + ), + false, + null + ); + + $this->assertSame( + [ + [ + 'id' => 9, + 'name' => 'Inter', + 'slug' => 'inter', + 'family' => '', + 'faces' => [ + [ + 'action' => 'added', + 'style' => 'italic', + 'weight' => '700', + ], + ], + ], + ], + Collector::font_items() + ); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function test_nothing_is_noted_during_an_import(): void { + define( 'WP_IMPORTING', true ); + + Collector::note_saved( 5, $this->template( 'a' ), false, null ); + + $this->assertSame( [], Collector::template_rows() ); + } +} diff --git a/tests/Unit/Events/SiteEditor/FontsTest.php b/tests/Unit/Events/SiteEditor/FontsTest.php new file mode 100644 index 0000000..fbaf6cf --- /dev/null +++ b/tests/Unit/Events/SiteEditor/FontsTest.php @@ -0,0 +1,138 @@ +> $faces The variants added or removed. + * @param int $user The user ID. + * + * @return array + */ + private function entry( string $family, array $faces = [], int $user = 1 ): array { + return [ + 'user' => [ + 'id' => $user, + 'name' => 'Barry', + ], + 'items' => [ + [ + 'id' => 9, + 'name' => 'Inter', + 'slug' => 'inter', + 'family' => $family, + 'faces' => $faces, + ], + ], + ]; + } + + /** + * A variant added or removed. + * + * @param string $action `added` or `removed`. + * @param string $style The style. + * @param string $weight The weight. + * + * @return array + */ + private function face( string $action, string $style, string $weight ): array { + return [ + 'action' => $action, + 'style' => $style, + 'weight' => $weight, + ]; + } + + public function test_an_install_in_several_requests_is_one_row_with_its_variants_in_order(): void { + $rows = Fonts::rows( + [ + $this->entry( 'added' ), + $this->entry( '', [ $this->face( 'added', 'normal', '700' ) ] ), + $this->entry( '', [ $this->face( 'added', 'italic', '400' ) ] ), + $this->entry( '', [ $this->face( 'added', 'normal', '400' ) ] ), + ] + ); + + $this->assertCount( 1, $rows ); + [ $type, $user, $data ] = $rows[0]; + $this->assertSame( 'FontInstalled', $type ); + $this->assertSame( 1, $user['id'] ); + $this->assertTrue( $data['family'] ); + $this->assertSame( + [ 'normal 400', 'italic 400', 'normal 700' ], + array_map( static fn( array $v ): string => $v['style'] . ' ' . $v['weight'], $data['variants'] ) + ); + } + + public function test_variants_added_to_an_installed_family_are_not_a_new_family(): void { + $rows = Fonts::rows( [ $this->entry( '', [ $this->face( 'added', 'normal', '900' ) ] ) ] ); + + $this->assertSame( 'FontInstalled', $rows[0][0] ); + $this->assertFalse( $rows[0][2]['family'] ); + } + + public function test_a_family_removed_lists_its_variants(): void { + $rows = Fonts::rows( + [ + $this->entry( + 'removed', + [ + $this->face( 'removed', 'normal', '400' ), + $this->face( 'removed', 'normal', '700' ), + ] + ), + ] + ); + + $this->assertSame( 'FontDeleted', $rows[0][0] ); + $this->assertTrue( $rows[0][2]['family'] ); + $this->assertCount( 2, $rows[0][2]['variants'] ); + } + + public function test_a_variant_removed_alone_is_a_delete_of_that_variant(): void { + $rows = Fonts::rows( [ $this->entry( '', [ $this->face( 'removed', 'italic', '700' ) ] ) ] ); + + $this->assertSame( 'FontDeleted', $rows[0][0] ); + $this->assertFalse( $rows[0][2]['family'] ); + } + + public function test_what_is_undone_within_the_minute_is_left_out(): void { + $this->assertSame( [], Fonts::rows( [ $this->entry( 'added' ), $this->entry( 'removed' ) ] ) ); + $this->assertSame( + [], + Fonts::rows( + [ + $this->entry( '', [ $this->face( 'added', 'normal', '400' ) ] ), + $this->entry( '', [ $this->face( 'removed', 'normal', '400' ) ] ), + ] + ) + ); + } + + public function test_each_person_gets_a_row_of_their_own(): void { + $rows = Fonts::rows( + [ + $this->entry( '', [ $this->face( 'added', 'normal', '400' ) ], 1 ), + $this->entry( '', [ $this->face( 'added', 'normal', '700' ) ], 2 ), + ] + ); + + $this->assertSame( [ 1, 2 ], array_map( static fn( array $row ): int => $row[1]['id'], $rows ) ); + } +} diff --git a/tests/Unit/Events/SiteEditor/StyleChangesTest.php b/tests/Unit/Events/SiteEditor/StyleChangesTest.php new file mode 100644 index 0000000..40d350b --- /dev/null +++ b/tests/Unit/Events/SiteEditor/StyleChangesTest.php @@ -0,0 +1,165 @@ +alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + } + + /** + * A global styles config. + * + * @param array $styles The styles. + * @param array $settings The settings. + * + * @return array + */ + private function config( array $styles, array $settings = [] ): array { + return [ + 'version' => 3, + 'isGlobalStylesUserThemeJSON' => true, + 'styles' => $styles, + 'settings' => $settings, + ]; + } + + public function test_each_style_setting_is_one_change_with_its_values(): void { + $changes = Builder::style_changes( + $this->config( + [ + 'color' => [ + 'background' => '#ffffff', + 'text' => '#111111', + ], + 'blocks' => [ 'core/button' => [ 'border' => [ 'radius' => '4px' ] ] ], + ] + ), + $this->config( + [ + 'color' => [ 'background' => '#000000' ], + 'typography' => [ 'fontFamily' => 'var:preset|font-family|inter' ], + 'blocks' => [ 'core/button' => [ 'border' => [ 'radius' => '4px' ] ] ], + ] + ) + ); + + $this->assertSame( + [ + [ + 'path' => 'styles.color.background', + 'change' => 'changed', + 'old' => '#ffffff', + 'new' => '#000000', + ], + [ + 'path' => 'styles.color.text', + 'change' => 'removed', + 'old' => '#111111', + ], + [ + 'path' => 'styles.typography.fontFamily', + 'change' => 'added', + 'new' => 'var:preset|font-family|inter', + ], + ], + $changes['styles'] + ); + $this->assertArrayNotHasKey( 'css', $changes ); + } + + public function test_a_list_such_as_a_palette_is_one_value_and_long_values_are_only_large(): void { + $palette = []; + for ( $i = 0; $i < 10; $i++ ) { + $palette[] = [ + 'slug' => 'colour-' . $i, + 'color' => '#00000' . $i, + 'name' => 'Colour ' . $i, + ]; + } + + $changes = Builder::style_changes( $this->config( [] ), $this->config( [], [ 'color' => [ 'palette' => [ 'custom' => $palette ] ] ] ) ); + + $this->assertSame( + [ + [ + 'path' => 'settings.color.palette.custom', + 'change' => 'added', + 'large' => true, + ], + ], + $changes['styles'] + ); + } + + public function test_a_variation_is_named_and_a_reset_is_one_change(): void { + $old = $this->config( [ 'color' => [ 'background' => '#ffffff' ] ] ); + $new = $this->config( [ 'color' => [ 'background' => '#222222' ] ] ) + [ 'title' => 'Evening' ]; + + $this->assertSame( + [ + 'old' => '', + 'new' => 'Evening', + ], + Builder::style_changes( $old, $new )['variation'] + ); + $this->assertSame( [ 'reset' => true ], Builder::style_changes( $old, $this->config( [] ) ) ); + } + + public function test_a_variation_is_found_by_its_settings_and_the_whole_one_wins(): void { + $evening = [ + 'title' => 'Evening', + 'styles' => [ + 'color' => [ 'background' => '#1b1b1b' ], + 'typography' => [ 'fontFamily' => 'var:preset|font-family|inter' ], + ], + 'settings' => [ 'layout' => [ 'contentSize' => '700px' ] ], + ]; + $dark = [ + 'title' => 'Dark colours', + 'styles' => [ 'color' => [ 'background' => '#1b1b1b' ] ], + ]; + $new = $this->config( $evening['styles'], $evening['settings'] ); + $old = $this->config( [ 'color' => [ 'background' => '#ffffff' ] ] ); + $variation = Builder::matching_variation( $old, $new, [ $dark, $evening ] ); + + $this->assertSame( 'Evening', $variation ); + $this->assertSame( 'Dark colours', Builder::matching_variation( $old, $this->config( [ 'color' => [ 'background' => '#1b1b1b' ] ] ), [ $dark, $evening ] ) ); + $this->assertSame( '', Builder::matching_variation( $old, $this->config( [ 'color' => [ 'background' => '#222222' ] ] ), [ $dark, $evening ] ), 'No variation has these styles.' ); + $this->assertSame( '', Builder::matching_variation( $new, $new, [ $dark, $evening ] ), 'The variation was already there.' ); + $this->assertSame( 'Evening', Builder::variation_in( $new, [ $dark, $evening ] ) ); + $this->assertSame( '', Builder::variation_in( $old, [ $dark, $evening ] ) ); + } + + public function test_the_list_is_capped_and_says_how_many_more(): void { + $colors = []; + for ( $i = 0; $i < Builder::MAX_PATHS + 5; $i++ ) { + $colors[ 'c' . $i ] = '#' . $i; + } + + $changes = Builder::style_changes( $this->config( [] ), $this->config( [ 'color' => $colors ] ) ); + + $this->assertCount( Builder::MAX_PATHS, $changes['styles'] ); + $this->assertSame( 5, $changes['more'] ); + } + + public function test_nothing_changed_is_no_change(): void { + $config = $this->config( [ 'color' => [ 'background' => '#ffffff' ] ] ); + + $this->assertSame( [], Builder::style_changes( $config, $config ) ); + } +} diff --git a/tests/Unit/Events/TermChanges/CollectorTest.php b/tests/Unit/Events/TermChanges/CollectorTest.php new file mode 100644 index 0000000..7210e14 --- /dev/null +++ b/tests/Unit/Events/TermChanges/CollectorTest.php @@ -0,0 +1,293 @@ + + */ + private array $cache = []; + + /** + * What the collector reported: event type and data. + * + * @var array}> + */ + private array $reported = []; + + protected function setUp(): void { + parent::setUp(); + Collector::reset(); + PostCollector::reset(); + + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'get_transient' )->justReturn( false ); + Functions\when( 'set_transient' )->justReturn( true ); + Functions\when( 'wp_cache_get' )->alias( fn( $id, $group ) => 'terms' === $group ? ( $this->cache[ $id ] ?? false ) : false ); + Functions\when( 'get_taxonomy' )->alias( + static fn( $name ) => (object) [ + 'show_ui' => in_array( $name, [ 'category', 'post_tag', 'post_format' ], true ), + 'labels' => (object) [ + 'name' => 'category' === $name ? 'Categories' : 'Tags', + 'singular_name' => 'category' === $name ? 'Category' : 'Tag', + ], + ] + ); + + foreach ( [ 'TermCreated', 'TermChanged', 'TermDeleted', 'TermBulkAction' ] as $type ) { + Actions\expectDone( ContentEvent::hook( $type ) )->zeroOrMoreTimes()->whenHappen( + function ( $data ) use ( $type ) { + $this->reported[] = [ + 'type' => $type, + 'data' => $data, + ]; + } + ); + } + } + + protected function tearDown(): void { + Collector::reset(); + parent::tearDown(); + } + + /** + * Create a term the way wp_insert_term() calls the hooks. + * + * @param int $term_id The term ID (also its term taxonomy ID). + * @param string $name The name, as stored. + * @param string $taxonomy The taxonomy. + * @param int $parent_id The parent. + * + * @return void + */ + private function create( int $term_id, string $name, string $taxonomy = 'category', int $parent_id = 0 ): void { + Collector::note_inserting( + [ + 'name' => $name, + 'slug' => strtolower( $name ), + 'term_group' => 0, + ], + $taxonomy, + [ 'parent' => $parent_id ] + ); + Collector::note_created( $term_id, $term_id, $taxonomy ); + } + + /** + * Change term 5 the way wp_update_term() calls the hooks. + * + * @param array $old The term before. + * @param array $new The new values. + * + * @return void + */ + private function update( array $old, array $new ): void { + $before = array_merge( + [ + 'name' => 'News', + 'slug' => 'news', + 'parent' => 0, + 'description' => '', + ], + $old + ); + $after = array_merge( $before, $new ); + $this->cache[5] = (object) $before; + + Collector::note_updating( $after['parent'], 5, 'category', [ 'description' => $after['description'] ] ); + Collector::note_update_data( + [ + 'name' => $after['name'], + 'slug' => $after['slug'], + ], + 5, + 'category' + ); + Collector::note_edited( 5, 5, 'category' ); + } + + /** + * Delete a term the way wp_delete_term() calls the hook. + * + * @param int $term_id The term ID. + * @param string $name The name. + * @param int $posts How many posts had it. + * @param string $taxonomy The taxonomy. + * + * @return void + */ + private function delete( int $term_id, string $name, int $posts = 0, string $taxonomy = 'category' ): void { + $term = new \WP_Term( + (object) [ + 'term_id' => $term_id, + 'name' => $name, + 'slug' => strtolower( $name ), + ] + ); + Collector::note_deleted( $term_id, $term_id, $taxonomy, $term, $posts > 0 ? range( 1, $posts ) : [] ); + } + + public function test_a_new_term_is_reported_with_its_parent(): void { + $this->create( 9, 'Bread & butter', 'category', 4 ); + Collector::flush(); + + $this->assertSame( + [ + [ + 'type' => 'TermCreated', + 'data' => [ + 'id' => 9, + 'name' => 'Bread & butter', + 'slug' => 'bread & butter', + 'taxonomy' => 'category', + 'label' => 'Category', + 'parent' => [ 'id' => 4 ], + ], + ], + ], + $this->reported + ); + } + + public function test_terms_of_taxonomies_without_a_screen_and_post_formats_are_not_reported(): void { + $this->create( 9, 'Aside', 'post_format' ); + $this->create( 10, 'Main menu', 'nav_menu' ); + $this->delete( 11, 'Footer', 0, 'nav_menu' ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_rename_reports_the_old_and_new_name_and_slug(): void { + $this->update( + [], + [ + 'name' => 'Updates', + 'slug' => 'updates', + ] + ); + Collector::flush(); + + $this->assertSame( 'TermChanged', $this->reported[0]['type'] ); + $this->assertSame( 'Updates', $this->reported[0]['data']['name'] ); + $this->assertSame( + [ + 'name' => [ + 'old' => 'News', + 'new' => 'Updates', + ], + 'slug' => [ + 'old' => 'news', + 'new' => 'updates', + ], + ], + $this->reported[0]['data']['changes'] + ); + } + + public function test_a_new_parent_and_description_are_changes(): void { + $this->update( + [ 'parent' => 2 ], + [ + 'parent' => 3, + 'description' => str_repeat( 'a', 1200 ), + ] + ); + Collector::flush(); + + $changes = $this->reported[0]['data']['changes']; + $this->assertSame( + [ + 'old' => [ 'id' => 2 ], + 'new' => [ 'id' => 3 ], + ], + $changes['parent'] + ); + $this->assertSame( '', $changes['description']['old'] ); + $this->assertSame( 1000, strlen( $changes['description']['new'] ) ); + } + + public function test_saving_a_term_without_changes_is_not_reported(): void { + $this->update( [], [] ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_term_not_in_the_cache_is_not_compared(): void { + Collector::note_updating( 0, 5, 'category', [] ); + Collector::note_update_data( [ 'name' => 'Updates' ], 5, 'category' ); + Collector::note_edited( 5, 5, 'category' ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_deleted_term_reports_how_many_posts_had_it(): void { + $this->delete( 5, 'News', 12 ); + Collector::flush(); + + $this->assertSame( 'TermDeleted', $this->reported[0]['type'] ); + $this->assertSame( 12, $this->reported[0]['data']['posts'] ); + $this->assertSame( 'News', $this->reported[0]['data']['name'] ); + } + + public function test_a_term_made_and_deleted_in_one_request_is_not_reported(): void { + $this->create( 9, 'Temp' ); + $this->delete( 9, 'Temp' ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_term_changed_and_deleted_is_only_reported_as_deleted(): void { + $this->update( [], [ 'name' => 'Updates' ] ); + $this->delete( 5, 'Updates' ); + Collector::flush(); + + $this->assertSame( [ 'TermDeleted' ], array_column( $this->reported, 'type' ) ); + } + + public function test_a_new_term_renamed_in_the_same_request_is_reported_once_as_it_is_now(): void { + $this->create( 5, 'News' ); + $this->update( [], [ 'name' => 'Updates' ] ); + Collector::flush(); + + $this->assertSame( [ 'TermCreated' ], array_column( $this->reported, 'type' ) ); + $this->assertSame( 'Updates', $this->reported[0]['data']['name'] ); + } + + public function test_many_deleted_tags_are_one_row_with_every_tag(): void { + for ( $id = 1; $id <= 12; $id++ ) { + $this->delete( $id, 'Tag ' . $id, 1, 'post_tag' ); + } + Collector::flush(); + + $this->assertSame( [ 'TermBulkAction' ], array_column( $this->reported, 'type' ) ); + $data = $this->reported[0]['data']; + $this->assertSame( 'deleted', $data['action'] ); + $this->assertSame( 'Tags', $data['label'] ); + $this->assertSame( 12, $data['count'] ); + $this->assertSame( 12, $data['posts'] ); + $this->assertSame( 'Tag 12', $data['terms'][11]['name'] ); + } +} diff --git a/tests/Unit/Events/ThemeSettings/BuilderTest.php b/tests/Unit/Events/ThemeSettings/BuilderTest.php new file mode 100644 index 0000000..cca22cf --- /dev/null +++ b/tests/Unit/Events/ThemeSettings/BuilderTest.php @@ -0,0 +1,166 @@ +alias( + static fn( $stylesheet ) => new class( $stylesheet ) { + /** + * The stylesheet. + * + * @var string + */ + private string $stylesheet; + + /** + * Constructor. + * + * @param string $stylesheet The stylesheet. + */ + public function __construct( string $stylesheet ) { + $this->stylesheet = $stylesheet; + } + + /** + * Whether the theme exists. + * + * @return bool + */ + public function exists(): bool { + return 'twentyseventeen' === $this->stylesheet; + } + + /** + * A header of the theme. + * + * @param string $header The header. + * + * @return string + */ + public function get( string $header ): string { + return 'Twenty Seventeen & Co'; + } + } + ); + Functions\when( 'get_attached_file' )->alias( static fn( $id ) => 40 === $id ? '/var/www/wp-content/uploads/2026/10/logo-new.png' : false ); + Functions\when( 'wp_basename' )->alias( static fn( $path ) => basename( (string) $path ) ); + Functions\when( 'wp_parse_url' )->alias( static fn( $url, $component = -1 ) => parse_url( $url, $component ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- WordPress is not loaded in unit tests. + } + + public function test_the_theme_name_and_file_names_are_added(): void { + $data = Builder::resolve( + [ + 'stylesheet' => 'twentyseventeen', + 'settings' => [ + [ + 'id' => 'header_image', + 'kind' => 'media', + 'change' => 'changed', + 'old' => 'remove-header', + 'new' => 'https://scanfully.com/wp-content/uploads/2026/10/header.jpg?v=2', + ], + [ + 'id' => 'background_color', + 'kind' => 'color', + 'change' => 'changed', + 'old' => 'ffffff', + 'new' => '000000', + ], + ], + 'logo' => [ + 'old' => '', + 'new' => '40', + ], + ] + ); + + $this->assertSame( 'Twenty Seventeen & Co', $data['name'] ); + $this->assertArrayNotHasKey( 'old_file', $data['settings'][0] ); + $this->assertSame( 'header.jpg', $data['settings'][0]['new_file'] ); + $this->assertArrayNotHasKey( 'new_file', $data['settings'][1] ); + $this->assertSame( + [ + 'old' => [ + 'id' => '', + 'file' => '', + ], + 'new' => [ + 'id' => '40', + 'file' => 'logo-new.png', + ], + ], + $data['logo'] + ); + } + + public function test_page_choices_get_their_titles(): void { + Functions\when( 'get_post' )->alias( static fn( $id ) => 16 === $id ? new \WP_Post( (object) [ 'post_title' => 'About & us' ] ) : null ); + + $data = Builder::resolve( + [ + 'stylesheet' => 'twentyseventeen', + 'settings' => [ + [ + 'id' => 'panel_1', + 'kind' => 'page', + 'change' => 'changed', + 'old' => '0', + 'new' => '16', + ], + ], + ] + ); + + $this->assertArrayNotHasKey( 'old_name', $data['settings'][0] ); + $this->assertSame( 'About & us', $data['settings'][0]['new_name'] ); + } + + public function test_a_theme_that_no_longer_exists_keeps_its_stylesheet_as_name(): void { + $data = Builder::resolve( + [ + 'stylesheet' => 'gone', + 'logo' => [ + 'old' => '40', + 'new' => '', + ], + ] + ); + + $this->assertSame( 'gone', $data['name'] ); + } + + public function test_css_that_was_too_large_or_lost_is_only_reported_as_changed(): void { + $this->assertSame( + [ + 'changed' => true, + 'reason' => 'too_large', + ], + Builder::resolve( + [ + 'stylesheet' => 'twentyseventeen', + 'css' => [ 'too_large' => true ], + ] + )['css'] + ); + $this->assertSame( 'unavailable', Builder::resolve( [ 'css' => [] ] )['css']['reason'] ); + } + + public function test_nothing_left_is_nothing_to_send(): void { + $this->assertSame( [], Builder::resolve( [ 'stylesheet' => 'twentyseventeen' ] ) ); + } +} diff --git a/tests/Unit/Events/ThemeSettings/CollectorTest.php b/tests/Unit/Events/ThemeSettings/CollectorTest.php new file mode 100644 index 0000000..e586f57 --- /dev/null +++ b/tests/Unit/Events/ThemeSettings/CollectorTest.php @@ -0,0 +1,621 @@ + + */ + private \ArrayObject $store; + + /** + * Constructor. + * + * @param string $id The setting ID. + * @param \ArrayObject $store The stored values. + * @param string $type The setting type. + */ + public function __construct( string $id, \ArrayObject $store, string $type = 'theme_mod' ) { + $this->id = $id; + $this->store = $store; + $this->type = $type; + } + + /** + * The stored value. + * + * @return mixed + */ + public function value() { + return $this->store[ $this->id ] ?? null; + } + + /** + * The parts of the ID. + * + * @return array{base: string, keys: array} + */ + public function id_data(): array { + return [ + 'base' => (string) preg_replace( '/\[.*$/', '', $this->id ), + 'keys' => [], + ]; + } +} + +/** + * A Customizer for the tests. + */ +final class FakeManager { + + /** + * The settings, by ID. + * + * @var array + */ + public array $settings = []; + + /** + * The controls. + * + * @var array + */ + public array $controls = []; + + /** + * The changeset: setting ID to parameters. + * + * @var array> + */ + public array $changeset = []; + + /** + * The changed settings and their new values. + * + * @return array + */ + public function unsanitized_post_values( array $args = [] ): array { + $values = []; + foreach ( $this->changeset as $raw_id => $params ) { + $values[ (string) preg_replace( '/^.+?::/', '', (string) $raw_id ) ] = $params['value'] ?? null; + } + + return $values; + } + + /** + * The changeset data. + * + * @return array> + */ + public function changeset_data(): array { + return $this->changeset; + } + + /** + * A setting. + * + * @param string $id The setting ID. + * + * @return FakeSetting|null + */ + public function get_setting( string $id ): ?FakeSetting { + return $this->settings[ $id ] ?? null; + } + + /** + * The controls. + * + * @return array + */ + public function controls(): array { + return $this->controls; + } + + /** + * A section. + * + * @param string $id The section ID. + * + * @return object|null + */ + public function get_section( string $id ): ?object { + return 'colors' === $id ? (object) [ 'title' => 'Colors & fonts' ] : null; + } + + /** + * The theme being saved. + * + * @return string + */ + public function get_stylesheet(): string { + return 'twentyseventeen'; + } +} + +/** + * @covers \Scanfully\Events\ThemeSettings\Collector + */ +final class CollectorTest extends TestCase { + + /** + * The stored values the fake settings read. + * + * @var \ArrayObject + */ + private \ArrayObject $store; + + /** + * The signed-in user. + * + * @var int + */ + private int $user = 1; + + /** + * Whether cron runs. + * + * @var bool + */ + private bool $cron = false; + + /** + * The rows reported. + * + * @var array> + */ + private array $reported = []; + + protected function setUp(): void { + parent::setUp(); + Collector::reset(); + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->store = new \ArrayObject(); + + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'wp_installing' )->justReturn( false ); + Functions\when( 'did_action' )->justReturn( 0 ); + Functions\when( 'doing_action' )->justReturn( false ); + Functions\when( 'wp_doing_cron' )->alias( fn() => $this->cron ); + Functions\when( 'get_current_user_id' )->alias( fn() => $this->user ); + Functions\when( 'sanitize_text_field' )->returnArg(); + Functions\when( 'wp_unslash' )->returnArg(); + Functions\when( 'wp_strip_all_tags' )->alias( static fn( $text ) => strip_tags( (string) $text ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- WordPress is not loaded in unit tests. + Functions\when( 'get_stylesheet' )->justReturn( 'twentyseventeen' ); + Functions\when( 'get_theme_mod' )->alias( fn( $name, $default = false ) => $this->store[ $name ] ?? $default ); + Functions\when( 'get_theme_support' )->justReturn( 'https://scanfully.com/wp-content/themes/twentyseventeen/assets/images/header.jpg' ); + Functions\when( 'wp_load_alloptions' )->justReturn( [ 'site_logo' => '12' ] ); + Functions\when( 'wp_cache_get' )->justReturn( false ); + Functions\when( 'maybe_unserialize' )->returnArg(); + Functions\when( 'get_transient' )->justReturn( 0 ); + Functions\when( 'set_transient' )->justReturn( true ); + Functions\when( 'do_action' )->alias( + function ( $hook, $row = null ) { + if ( 'scanfully_content_event_ThemeSettingsChanged' === $hook ) { + $this->reported[] = $row; + } + } + ); + } + + protected function tearDown(): void { + Collector::reset(); + unset( $_SERVER['REQUEST_METHOD'] ); + parent::tearDown(); + } + + /** + * A Customizer with these settings changed from the store's values to + * the given ones, and a control per setting. + * + * @param array $changes Setting ID to new value. + * @param int $user Who changed them. + * + * @return FakeManager + */ + private function manager( array $changes, int $user = 1 ): FakeManager { + $manager = new FakeManager(); + foreach ( $changes as $id => $value ) { + $type = 0 === strpos( $id, 'blogname' ) || false !== strpos( $id, '[' ) ? 'option' : 'theme_mod'; + $manager->settings[ $id ] = new FakeSetting( $id, $this->store, $type ); + $manager->changeset[ 'twentyseventeen::' . $id ] = [ + 'value' => $value, + 'type' => $type, + 'user_id' => $user, + ]; + $manager->controls[ $id ] = (object) [ + 'label' => 'background_color' === $id ? 'Background Color' : '', + 'section' => 'colors', + 'type' => 'secret_key' === $id ? 'password' : 'text', + 'settings' => [ 'default' => $manager->settings[ $id ] ], + ]; + } + + return $manager; + } + + /** + * Publish a changeset: note the values before, store the new ones, note + * the values after, and flush. + * + * @param array $changes Setting ID to new value. + * @param int $user Who changed them. + * + * @return array|null The row reported. + */ + private function publish( array $changes, int $user = 1 ): ?array { + $manager = $this->manager( $changes, $user ); + Collector::note_publish_start( $manager ); + foreach ( $changes as $id => $value ) { + $this->store[ $id ] = $value; + } + Collector::note_publish_done( $manager ); + Collector::flush(); + + return $this->reported[0] ?? null; + } + + public function test_a_customizer_publish_lists_each_setting_with_its_label_and_values(): void { + $this->store['background_color'] = 'ffffff'; + $this->store['header_textcolor'] = '333333'; + + $row = $this->publish( + [ + 'background_color' => '1e73be', + 'header_textcolor' => 'blank', + ] + ); + + $this->assertSame( 'customizer', $row['source'] ); + $this->assertSame( 'twentyseventeen', $row['stylesheet'] ); + $this->assertSame( + [ + 'id' => 'background_color', + 'label' => 'Background Color', + 'section' => 'Colors & fonts', + 'kind' => 'color', + 'change' => 'changed', + 'old' => 'ffffff', + 'new' => '1e73be', + ], + $row['settings'][0] + ); + $this->assertSame( 'blank', $row['settings'][1]['new'] ); + $this->assertArrayNotHasKey( '_actor', $row, 'The signed-in user published it.' ); + } + + public function test_the_header_image_is_read_from_its_theme_mod(): void { + $this->store['header_image'] = 'remove-header'; + + $manager = $this->manager( + [ + 'header_image' => 'https://scanfully.com/wp-content/uploads/header.jpg', + 'header_image_data' => [ 'attachment_id' => 5 ], + ] + ); + Collector::note_publish_start( $manager ); + $this->store['header_image'] = 'https://scanfully.com/wp-content/uploads/header.jpg'; + Collector::note_publish_done( $manager ); + Collector::flush(); + + $this->assertSame( + [ + [ + 'id' => 'header_image', + 'section' => 'Colors & fonts', + 'kind' => 'media', + 'change' => 'changed', + 'old' => 'remove-header', + 'new' => 'https://scanfully.com/wp-content/uploads/header.jpg', + ], + ], + $this->reported[0]['settings'] + ); + } + + public function test_the_control_named_after_the_setting_gives_its_label(): void { + $this->store['header_textcolor'] = '333333'; + $manager = $this->manager( [ 'header_textcolor' => '1e73be' ] ); + // Core's "Display Site Title and Tagline" checkbox edits the same + // setting, and comes first. + $manager->controls = [ + 'display_header_text' => (object) [ + 'id' => 'display_header_text', + 'label' => 'Display Site Title and Tagline', + 'section' => 'title_tagline', + 'type' => 'checkbox', + 'settings' => [ 'default' => $manager->settings['header_textcolor'] ], + ], + 'header_textcolor' => (object) [ + 'id' => 'header_textcolor', + 'label' => 'Header Text Color', + 'section' => 'colors', + 'type' => 'color', + 'settings' => [ 'default' => $manager->settings['header_textcolor'] ], + ], + ]; + + Collector::note_publish_start( $manager ); + $this->store['header_textcolor'] = '1e73be'; + Collector::note_publish_done( $manager ); + Collector::flush(); + + $this->assertSame( 'Header Text Color', $this->reported[0]['settings'][0]['label'] ); + $this->assertSame( 'Colors & fonts', $this->reported[0]['settings'][0]['section'] ); + } + + public function test_a_page_choice_is_marked_for_its_title(): void { + $this->store['panel_1'] = 0; + $manager = $this->manager( [ 'panel_1' => 16 ] ); + $manager->controls['panel_1']->type = 'dropdown-pages'; + + Collector::note_publish_start( $manager ); + $this->store['panel_1'] = 16; + Collector::note_publish_done( $manager ); + Collector::flush(); + + $this->assertSame( 'page', $this->reported[0]['settings'][0]['kind'] ); + } + + public function test_an_unset_header_image_was_the_themes_default(): void { + $manager = $this->manager( [ 'header_image' => 'https://scanfully.com/wp-content/uploads/header.jpg' ] ); + Collector::note_publish_start( $manager ); + $this->store['header_image'] = 'https://scanfully.com/wp-content/uploads/header.jpg'; + Collector::note_publish_done( $manager ); + Collector::flush(); + + $this->assertSame( 'https://scanfully.com/wp-content/themes/twentyseventeen/assets/images/header.jpg', $this->reported[0]['settings'][0]['old'] ); + } + + public function test_settings_other_rows_report_are_left_out(): void { + $this->store['background_color'] = 'ffffff'; + + $row = $this->publish( + [ + 'background_color' => '000000', + 'blogname' => 'New title', + 'nav_menu_locations[top]' => 3, + 'sidebars_widgets[footer]' => [], + 'widget_text[2]' => [], + 'custom_css[twentyseventeen]' => 'body{}', + 'header_image_data' => [ 'attachment_id' => 5 ], + ] + ); + + $this->assertSame( [ 'background_color' ], array_column( $row['settings'], 'id' ) ); + } + + public function test_a_setting_saved_with_the_same_value_is_no_change(): void { + $this->store['background_color'] = 'ffffff'; + + $this->assertNull( $this->publish( [ 'background_color' => 'ffffff' ] ) ); + } + + public function test_the_logo_setting_is_reported_as_the_logo(): void { + $this->store['custom_logo'] = 12; + + $row = $this->publish( [ 'custom_logo' => 40 ] ); + + $this->assertSame( + [ + 'old' => '12', + 'new' => '40', + ], + $row['logo'] + ); + $this->assertArrayNotHasKey( 'settings', $row ); + } + + public function test_long_values_are_only_marked_large_and_secrets_never_sent(): void { + $this->store['footer_text'] = str_repeat( 'a', 300 ); + $this->store['secret_key'] = 'old-secret'; + + $row = $this->publish( + [ + 'footer_text' => str_repeat( 'b', 300 ), + 'secret_key' => 'new-secret', + ] + ); + + $this->assertSame( + [ + 'id' => 'footer_text', + 'section' => 'Colors & fonts', + 'change' => 'changed', + 'large' => true, + ], + $row['settings'][0] + ); + $this->assertTrue( $row['settings'][1]['secret'] ); + $this->assertStringNotContainsString( + 'secret', + (string) json_encode( + array_diff_key( + $row['settings'][1], + [ + 'secret' => 1, + 'id' => 1, + ] + ) + ) + ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + } + + public function test_a_scheduled_publish_names_the_person_who_made_it(): void { + $this->store['background_color'] = 'ffffff'; + $this->user = 0; + $this->cron = true; + + $row = $this->publish( [ 'background_color' => '000000' ], 7 ); + + $this->assertSame( 7, $row['_actor'] ); + $this->assertTrue( $row['scheduled'] ); + } + + public function test_theme_mods_changed_outside_the_customizer(): void { + Collector::note_updated( + 'theme_mods_twentyseventeen', + [ + 'background_color' => 'ffffff', + 'nav_menu_locations' => [ 'top' => 2 ], + 'custom_logo' => 12, + 'old_setting' => 'x', + ], + [ + 'background_color' => '000000', + 'nav_menu_locations' => [ 'top' => 3 ], + 'custom_logo' => 40, + 'header_image' => 'https://scanfully.com/wp-content/uploads/header.jpg', + ] + ); + Collector::flush(); + $row = $this->reported[0]; + + $this->assertSame( 'other', $row['source'] ); + $this->assertSame( [ 'background_color', 'old_setting', 'header_image' ], array_column( $row['settings'], 'id' ) ); + $this->assertSame( 'removed', $row['settings'][1]['change'] ); + $this->assertSame( 'media', $row['settings'][2]['kind'] ); + } + + public function test_theme_mods_of_another_theme_are_left_out(): void { + Collector::note_updated( 'theme_mods_twentytwentyone', [ 'background_color' => 'ffffff' ], [ 'background_color' => '000000' ] ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_page_views_change_nothing(): void { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + Collector::note_updated( 'theme_mods_twentyseventeen', [], [ 'background_color' => '000000' ] ); + Collector::note_updated( 'site_logo', 12, 40 ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } + + public function test_a_customizer_publish_ignores_the_theme_mods_it_writes_itself(): void { + $this->store['background_color'] = 'ffffff'; + $manager = $this->manager( [ 'background_color' => '000000' ] ); + + Collector::note_publish_start( $manager ); + $this->store['background_color'] = '000000'; + Collector::note_updated( + 'theme_mods_twentyseventeen', + [ 'background_color' => 'ffffff' ], + [ + 'background_color' => '000000', + 'theme_css_cache' => 'abc', + ] + ); + Collector::note_publish_done( $manager ); + Collector::flush(); + + $this->assertSame( [ 'background_color' ], array_column( $this->reported[0]['settings'], 'id' ) ); + } + + public function test_the_logo_option_set_and_removed(): void { + Collector::note_added( 'site_logo', '40' ); + Collector::flush(); + $this->assertSame( + [ + 'old' => '', + 'new' => '40', + ], + $this->reported[0]['logo'] + ); + + Collector::note_deleting( 'site_logo' ); + Collector::flush(); + $this->assertSame( + [ + 'old' => '12', + 'new' => '', + ], + $this->reported[1]['logo'] + ); + } + + public function test_additional_css_is_kept_for_the_job(): void { + $before = (object) [ + 'post_type' => 'custom_css', + 'post_title' => 'twentyseventeen', + 'post_content' => 'body { color: red; }', + ]; + $after = (object) [ + 'post_type' => 'custom_css', + 'post_title' => 'twentyseventeen', + 'post_content' => 'body { color: blue; }', + ]; + + Collector::note_post_saved( 9, $after, true, $before ); + Collector::flush(); + + $this->assertSame( + [ + 'stash' => [ + 'old' => 'body { color: red; }', + 'new' => 'body { color: blue; }', + ], + ], + $this->reported[0]['css'] + ); + } + + public function test_very_large_css_is_only_reported_as_changed(): void { + $after = (object) [ + 'post_type' => 'custom_css', + 'post_title' => 'twentyseventeen', + 'post_content' => str_repeat( 'a', Collector::MAX_CSS + 1 ), + ]; + + Collector::note_post_saved( 9, $after, false, null ); + Collector::flush(); + + $this->assertSame( [ 'too_large' => true ], $this->reported[0]['css'] ); + } + + public function test_other_posts_are_not_css(): void { + Collector::note_post_saved( + 9, + (object) [ + 'post_type' => 'page', + 'post_content' => 'x', + ], + true, + null + ); + Collector::flush(); + + $this->assertSame( [], $this->reported ); + } +} diff --git a/tests/Unit/Events/UpdateFailedTest.php b/tests/Unit/Events/UpdateFailedTest.php new file mode 100644 index 0000000..1bd2070 --- /dev/null +++ b/tests/Unit/Events/UpdateFailedTest.php @@ -0,0 +1,425 @@ +>> + */ + private array $reported = []; + + /** + * In-memory transient store. + * + * @var array + */ + private array $transients = []; + + protected function setUp(): void { + parent::setUp(); + $this->reported = []; + $this->transients = []; + + $reported = new ReflectionProperty( Controller::class, 'reported_failures' ); + $reported->setAccessible( true ); + $reported->setValue( null, [] ); + + Functions\when( 'is_wp_error' )->alias( static fn( $thing ) => $thing instanceof \WP_Error ); + Functions\when( 'wp_strip_all_tags' )->alias( 'strip_tags' ); + Functions\when( 'get_bloginfo' )->justReturn( '6.8.1' ); + Functions\when( 'get_theme_root' )->justReturn( ABSPATH . 'wp-content/themes' ); + Functions\when( 'get_temp_dir' )->justReturn( '/tmp/' ); + Functions\when( 'get_transient' )->alias( fn( string $key ) => array_key_exists( $key, $this->transients ) ? $this->transients[ $key ] : false ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value ) { + $this->transients[ $key ] = $value; + return true; + } + ); + + foreach ( [ 'plugin', 'theme', 'core' ] as $type ) { + $action = 'scanfully_' . $type . '_update_failed'; + Actions\expectDone( $action )->zeroOrMoreTimes()->whenHappen( + function ( $payload ) use ( $type ) { + $this->reported[ $type ][] = $payload; + } + ); + } + } + + /** + * A WP_Error double. + * + * @param string $message The error message. + * @param mixed $data The error data. + * + * @return \WP_Error + */ + private function error( string $message, $data = null ) { + $error = Mockery::mock( 'WP_Error' ); + $error->shouldReceive( 'get_error_message' )->andReturn( $message ); + $error->shouldReceive( 'get_error_data' )->andReturn( $data ); + + return $error; + } + + public function test_a_plugin_update_that_fails_while_installing_is_reported(): void { + $error = $this->error( 'The package could not be installed.' ); + + $returned = Controller::install_package_failed( + $error, + [ + 'plugin' => 'akismet/akismet.php', + 'scanfully_old_name' => 'Akismet', + 'scanfully_old_version' => '5.3', + 'scanfully_new_version' => '5.4', + ] + ); + + $this->assertSame( $error, $returned, 'The install result must be returned unchanged.' ); + $this->assertSame( + [ + [ + 'name' => 'Akismet', + 'slug' => 'akismet/akismet.php', + 'version' => '5.3', + 'new_version' => '5.4', + 'error' => 'The package could not be installed.', + ], + ], + $this->reported['plugin'] + ); + } + + public function test_a_theme_update_failure_is_reported_as_a_theme(): void { + Controller::install_package_failed( $this->error( 'Could not copy file.', '/wp-content/themes/twentytwentyfive/style.css' ), [ 'theme' => 'twentytwentyfive' ] ); + + $this->assertSame( 'twentytwentyfive', $this->reported['theme'][0]['name'], 'Without a remembered name, the slug is used.' ); + $this->assertSame( 'Could not copy file. …/style.css', $this->reported['theme'][0]['error'], 'An unknown absolute path keeps only its last part.' ); + $this->assertArrayNotHasKey( 'plugin', $this->reported ); + } + + /** + * @dataProvider provide_errors_with_paths + * + * @param string $message The error message. + * @param string $data The error data (core puts the path here). + * @param string $expected The error sent. + */ + public function test_server_paths_are_removed_from_the_error( string $message, string $data, string $expected ): void { + Controller::install_package_failed( $this->error( $message, $data ), [ 'plugin' => 'akismet/akismet.php' ] ); + + $this->assertSame( $expected, $this->reported['plugin'][0]['error'] ); + } + + /** + * Real core messages with the path WordPress adds as error data. + * + * @return array + */ + public function provide_errors_with_paths(): array { + return [ + 'mkdir_failed_destination' => [ 'Could not create directory.', WP_PLUGIN_DIR . '/akismet/', 'Could not create directory. wp-content/plugins/akismet/' ], + 'folder_exists' => [ 'Destination folder already exists.', ABSPATH . 'wp-content/themes/twentytwentyfive/', 'Destination folder already exists. wp-content/themes/twentytwentyfive/' ], + 'copy_failed_copy_dir' => [ 'Could not copy file.', WP_PLUGIN_DIR . '/akismet/class.akismet.php', 'Could not copy file. wp-content/plugins/akismet/class.akismet.php' ], + 'copy_failed_for_update_core' => [ 'The update cannot be installed because some files could not be copied.', ABSPATH . 'wp-admin/includes/update-core.php', 'The update cannot be installed because some files could not be copied. wp-admin/includes/update-core.php' ], + 'mkdir_failed_ziparchive' => [ 'Could not create directory.', '/tmp/akismet-Ab12/akismet/', 'Could not create directory. tmp/akismet-Ab12/akismet/' ], + 'mkdir_failed_move_dir, other' => [ 'Could not create directory.', '/srv/backups/upgrade-temp-backup/plugins/akismet', 'Could not create directory. …/akismet' ], + 'Windows path' => [ 'Could not copy file.', 'C:\\inetpub\\wwwroot\\wp-content\\upgrade\\akismet.tmp', 'Could not copy file. …/akismet.tmp' ], + 'the plugins directory itself' => [ 'Could not create directory.', WP_PLUGIN_DIR, 'Could not create directory. wp-content/plugins' ], + 'a URL is left alone' => [ 'Download failed.', 'https://downloads.wordpress.org/plugin/akismet.5.4.zip', 'Download failed. https://downloads.wordpress.org/plugin/akismet.5.4.zip' ], + 'no path' => [ 'Download failed.', 'Not Found', 'Download failed. Not Found' ], + 'and/or is not a path' => [ 'The package could not be installed.', 'The theme and/or plugin is missing.', 'The package could not be installed. The theme and/or plugin is missing.' ], + ]; + } + + public function test_paths_of_the_file_system_wordpress_writes_through_are_removed(): void { + $GLOBALS['wp_filesystem'] = new class() { + /** + * The site root as the FTP account sees it. + * + * @return string + */ + public function abspath() { + return '/public_html/'; + } + + /** + * The content directory as the FTP account sees it. + * + * @return string + */ + public function wp_content_dir() { + return '/public_html/wp-content/'; + } + }; + + Controller::install_package_failed( $this->error( 'Could not create directory.', '/public_html/wp-content/upgrade/akismet/' ), [ 'plugin' => 'akismet/akismet.php' ] ); + unset( $GLOBALS['wp_filesystem'] ); + + $this->assertSame( 'Could not create directory. wp-content/upgrade/akismet/', $this->reported['plugin'][0]['error'] ); + } + + public function test_a_root_file_system_path_is_not_used_as_a_root(): void { + $GLOBALS['wp_filesystem'] = new class() { + /** + * An FTP account that starts in the site. + * + * @return string + */ + public function abspath() { + return '/'; + } + }; + + Controller::automatic_updates_failed( + [ + 'plugin' => [ + $this->auto_update( + (object) [ 'plugin' => 'akismet/akismet.php' ], + null, + 'Akismet', + [ 'Downloading update from https://downloads.wordpress.org/plugin/akismet.5.4.zip…', 'Download failed. A valid URL was not provided.' ] + ), + ], + ] + ); + unset( $GLOBALS['wp_filesystem'] ); + + $this->assertSame( 'Download failed. A valid URL was not provided.', $this->reported['plugin'][0]['error'] ); + } + + public function test_names_from_the_automatic_updater_are_sent_as_plain_text(): void { + Controller::automatic_updates_failed( + [ + 'theme' => [ $this->auto_update( (object) [ 'theme' => 'tom-jerry' ], null, 'Tom & Jerry', [ 'Failed.' ] ) ], + ] + ); + + $this->assertSame( 'Tom & Jerry', $this->reported['theme'][0]['name'] ); + } + + public function test_scanfully_s_own_failed_update_is_reported(): void { + Controller::install_package_failed( $this->error( 'Failed.' ), [ 'plugin' => 'scanfully/scanfully.php' ] ); + + $this->assertCount( 1, $this->reported['plugin'] ); + } + + /** + * @dataProvider provide_ignored_install_results + * + * @param mixed $hook_extra Upgrader hook extras. + */ + public function test_successful_updates_and_installs_are_not_failures( $hook_extra ): void { + Controller::install_package_failed( [ 'destination' => WP_PLUGIN_DIR ], [ 'plugin' => 'akismet/akismet.php' ] ); + Controller::install_package_failed( $this->error( 'Failed.' ), $hook_extra ); + + $this->assertSame( [], $this->reported ); + } + + /** + * @return array + */ + public function provide_ignored_install_results(): array { + return [ + 'a failed new plugin install' => [ + [ + 'type' => 'plugin', + 'action' => 'install', + ], + ], + 'no hook extras' => [ null ], + ]; + } + + public function test_the_name_and_version_on_offer_are_remembered_before_the_update(): void { + Functions\when( 'get_file_data' )->justReturn( [ 'Name' => 'Akismet' ] ); + Functions\when( 'get_site_transient' )->justReturn( + (object) [ + 'response' => [ 'akismet/akismet.php' => (object) [ 'new_version' => '5.4' ] ], + ] + ); + + $options = Controller::remember_update_item( [ 'hook_extra' => [ 'plugin' => 'akismet/akismet.php' ] ] ); + + $this->assertSame( 'Akismet', $options['hook_extra']['scanfully_old_name'] ); + $this->assertSame( '5.4', $options['hook_extra']['scanfully_new_version'] ); + } + + /** + * An automatic update result as WordPress records it. + * + * @param object $item The update offer. + * @param mixed $result The update result. + * @param string $name The item name. + * @param array $messages The upgrader messages. + * + * @return object + */ + private function auto_update( object $item, $result, string $name = '', array $messages = [] ): object { + return (object) [ + 'item' => $item, + 'result' => $result, + 'name' => $name, + 'messages' => $messages, + ]; + } + + public function test_automatic_update_failures_before_the_install_are_reported_with_the_last_message(): void { + Controller::automatic_updates_failed( + [ + 'plugin' => [ + $this->auto_update( + (object) [ + 'plugin' => 'premium/premium.php', + 'current_version' => '1.0', + 'new_version' => '2.0', + ], + null, + 'Premium', + [ 'Updating plugin: Premium', 'Downloading update from https://scanfully.com/premium.zip…', 'Download failed. Unauthorized', '' ] + ), + $this->auto_update( (object) [ 'plugin' => 'akismet/akismet.php' ], true, 'Akismet' ), + ], + ] + ); + + $this->assertSame( + [ + [ + 'name' => 'Premium', + 'slug' => 'premium/premium.php', + 'version' => '1.0', + 'new_version' => '2.0', + 'error' => 'Download failed. Unauthorized', + ], + ], + $this->reported['plugin'] + ); + } + + public function test_an_automatic_update_failure_already_reported_while_installing_is_not_reported_twice(): void { + $error = $this->error( 'The package could not be installed.' ); + Controller::install_package_failed( $error, [ 'theme' => 'twentytwentyfive' ] ); + + Controller::automatic_updates_failed( + [ + 'theme' => [ $this->auto_update( (object) [ 'theme' => 'twentytwentyfive' ], $error, 'Twenty Twenty-Five' ) ], + ] + ); + + $this->assertCount( 1, $this->reported['theme'] ); + } + + public function test_a_failed_automatic_core_update_is_reported(): void { + Controller::automatic_updates_failed( + [ + 'core' => [ + $this->auto_update( + (object) [ + 'current' => '6.8.2', + 'version' => '6.8.2', + ], + $this->error( 'The update cannot be installed because some files could not be copied.' ), + 'WordPress 6.8.2' + ), + ], + 'translation' => [ $this->auto_update( (object) [], null ) ], + ] + ); + + $this->assertSame( + [ + [ + 'version' => '6.8.2', + 'old_version' => '6.8.1', + 'error' => 'The update cannot be installed because some files could not be copied.', + ], + ], + $this->reported['core'] + ); + $this->assertArrayNotHasKey( 'plugin', $this->reported ); + } + + public function test_a_successful_automatic_core_update_is_not_a_failure(): void { + Controller::automatic_updates_failed( + [ + 'core' => [ $this->auto_update( (object) [ 'current' => '6.8.2' ], '6.8.2', 'WordPress 6.8.2' ) ], + ] + ); + + $this->assertSame( [], $this->reported ); + } + + /** + * @dataProvider provide_failure_events + * + * @param string $event_class Event class. + */ + public function test_the_same_failure_is_reported_once_a_day( string $event_class ): void { + $event = new $event_class(); + $payload = [ + 'slug' => 'akismet/akismet.php', + 'version' => '5.3', + 'new_version' => '5.4', + 'error' => 'Failed.', + ]; + + $this->assertTrue( $event->should_fire( [ $payload ] ) ); + $this->assertFalse( $event->should_fire( [ $payload ] ), 'Again within a day.' ); + $this->assertTrue( $event->should_fire( [ array_merge( $payload, [ 'new_version' => '5.5' ] ) ] ), 'Another version on offer.' ); + + $this->transients = []; + $this->assertTrue( $event->should_fire( [ $payload ] ), 'After a day.' ); + } + + /** + * @return array + */ + public function provide_failure_events(): array { + return [ + 'plugin' => [ PluginUpdateFailed::class ], + 'theme' => [ ThemeUpdateFailed::class ], + 'core' => [ CoreUpdateFailed::class ], + ]; + } + + /** + * @dataProvider provide_failure_events + * + * @param string $event_class Event class. + */ + public function test_a_non_array_payload_is_ignored( string $event_class ): void { + $event = new $event_class(); + + $this->assertFalse( $event->should_fire( [ 'x' ] ) ); + $this->assertSame( [], $event->get_post_body( [ 'x' ] ) ); + } +} diff --git a/tests/Unit/Events/UserEventsTest.php b/tests/Unit/Events/UserEventsTest.php new file mode 100644 index 0000000..5144fd5 --- /dev/null +++ b/tests/Unit/Events/UserEventsTest.php @@ -0,0 +1,428 @@ + + */ + private array $users = []; + + /** + * In-memory transient store. + * + * @var array + */ + private array $transients = []; + + /** + * The signed-in user ID. + * + * @var int + */ + private int $current_user_id = 1; + + protected function setUp(): void { + parent::setUp(); + $this->transients = []; + $this->current_user_id = 1; + + $defaults = [ + 'creating_login' => '', + 'created_user_ids' => [], + 'fired' => [], + ]; + foreach ( $defaults as $property => $value ) { + $reset = new ReflectionProperty( UserRoleChanged::class, $property ); + $reset->setAccessible( true ); + $reset->setValue( null, $value ); + } + + Functions\when( 'get_userdata' )->alias( fn( int $id ) => $this->users[ $id ] ?? false ); + Functions\when( 'get_current_user_id' )->alias( fn() => $this->current_user_id ); + // Roles that can edit content or manage the site. + Functions\when( 'user_can' )->alias( + static fn( $user ) => [] !== array_intersect( (array) $user->roles, self::ELEVATED_ROLES ) + ); + Functions\when( 'get_role' )->alias( + static function ( string $name ) { + $role = Mockery::mock( 'WP_Role' ); + $role->shouldReceive( 'has_cap' )->andReturn( in_array( $name, self::ELEVATED_ROLES, true ) ); + return $role; + } + ); + Functions\when( 'is_email' )->alias( static fn( $email ) => false !== filter_var( $email, FILTER_VALIDATE_EMAIL ) ); + Functions\when( 'get_transient' )->alias( fn( string $key ) => array_key_exists( $key, $this->transients ) ? $this->transients[ $key ] : false ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value ) { + $this->transients[ $key ] = $value; + return true; + } + ); + } + + /** + * Add a user. + * + * @param int $id User ID. + * @param string $name Display name. + * @param array $roles Roles. + * + * @return \WP_User + */ + private function add_user( int $id, string $name, array $roles ) { + $user = Mockery::mock( 'WP_User' ); + $user->ID = $id; + $user->display_name = $name; + $user->roles = $roles; + $user->first_name = ''; + $user->last_name = ''; + $user->user_login = 'login-' . $id; + $user->user_email = 'user' . $id . '@scanfully.com'; + + $this->users[ $id ] = $user; + + return $user; + } + + public function test_a_new_user_with_elevated_rights_is_reported_with_the_email_address(): void { + $this->add_user( 7, 'Jane Editor', [ 'editor' ] ); + + $event = new UserCreated(); + + $this->assertTrue( $event->should_fire( [ 7 ] ) ); + $body = $event->get_post_body( [ 7 ] ); + $this->assertSame( + [ + 'id' => 7, + 'name' => 'Jane Editor', + 'email' => 'user7@scanfully.com', + 'roles' => [ 'editor' ], + ], + $body + ); + $this->assertStringNotContainsString( 'login-7', (string) json_encode( $body ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + } + + public function test_a_new_user_without_elevated_rights_is_reported_without_the_email_address(): void { + $this->add_user( 28, 'New subscriber', [ 'subscriber' ] ); + + $body = ( new UserCreated() )->get_post_body( [ 28 ] ); + + $this->assertSame( + [ + 'id' => 28, + 'name' => 'New subscriber', + 'roles' => [ 'subscriber' ], + ], + $body + ); + $this->assertStringNotContainsString( '@', (string) json_encode( $body ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + } + + public function test_a_display_name_that_is_an_email_address_is_not_sent(): void { + $user = $this->add_user( 8, 'jane@scanfully.com', [ 'editor' ] ); + $user->first_name = 'Jane'; + $user->last_name = 'Doe'; + $this->add_user( 9, 'john@scanfully.com', [ 'editor' ] ); + + $this->assertSame( 'Jane Doe', ( new UserCreated() )->get_post_body( [ 8 ] )['name'] ); + $this->assertSame( '', ( new UserCreated() )->get_post_body( [ 9 ] )['name'] ); + } + + /** + * @dataProvider provide_sign_ups + * + * @param array $roles Roles of the new user. + */ + public function test_a_visitor_signing_up_is_not_reported( array $roles ): void { + $this->current_user_id = 0; + $this->add_user( 10, 'New customer', $roles ); + + $this->assertFalse( ( new UserCreated() )->should_fire( [ 10 ] ) ); + } + + /** + * @return array}> + */ + public function provide_sign_ups(): array { + return [ + 'default role' => [ [ 'subscriber' ] ], + 'WooCommerce customer' => [ [ 'customer' ] ], + 'no role' => [ [] ], + ]; + } + + /** + * @dataProvider provide_elevated_sign_ups + * + * @param array $roles Roles of the new user. + */ + public function test_a_sign_up_that_can_edit_or_manage_the_site_is_reported( array $roles ): void { + $this->current_user_id = 0; + $this->add_user( 11, 'Suspicious', $roles ); + + $this->assertTrue( ( new UserCreated() )->should_fire( [ 11 ] ) ); + } + + /** + * Sign-ups with these roles are reported whatever the default role for + * new users is; with registration open and the default role set to + * Administrator, every sign-up is an administrator. + * + * @return array}> + */ + public function provide_elevated_sign_ups(): array { + return [ + 'default role set to administrator' => [ [ 'administrator' ] ], + 'default role set to editor' => [ [ 'editor' ] ], + 'shop manager' => [ [ 'shop_manager' ] ], + ]; + } + + public function test_a_user_created_by_someone_else_is_reported_whatever_the_role(): void { + $this->add_user( 22, 'New subscriber', [ 'subscriber' ] ); + + $this->assertTrue( ( new UserCreated() )->should_fire( [ 22 ] ) ); + } + + public function test_sites_can_report_sign_ups_with_a_filter(): void { + $this->current_user_id = 0; + $this->add_user( 12, 'New customer', [ 'customer' ] ); + Filters\expectApplied( 'scanfully_user_created_should_fire' )->once()->andReturn( true ); + + $this->assertTrue( ( new UserCreated() )->should_fire( [ 12 ] ) ); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function test_users_created_by_an_import_are_not_reported(): void { + define( 'WP_IMPORTING', true ); + $this->add_user( 13, 'Imported author', [ 'author' ] ); + + $this->assertFalse( ( new UserCreated() )->should_fire( [ 13 ] ) ); + } + + public function test_user_events_are_capped_per_minute_in_one_transient(): void { + Filters\expectApplied( 'scanfully_user_events_per_minute' )->andReturn( 2 ); + $this->add_user( 14, 'A', [ 'editor' ] ); + + $event = new UserDeleted(); + $this->assertTrue( $event->should_fire( [ 14 ] ) ); + $this->assertTrue( $event->should_fire( [ 14 ] ) ); + $this->assertFalse( $event->should_fire( [ 14 ] ) ); + $this->assertSame( [ 'scanfully_user_events_rate' ], array_keys( $this->transients ) ); + + // A new minute starts a new count in the same transient. + $this->transients['scanfully_user_events_rate'] = [ (int) floor( time() / MINUTE_IN_SECONDS ) - 1, 2 ]; + $this->assertTrue( $event->should_fire( [ 14 ] ) ); + } + + public function test_a_deleted_user_is_reported_with_id_name_and_roles(): void { + $this->add_user( 15, 'Old Admin', [ 'administrator' ] ); + $this->add_user( 29, 'Old Customer', [ 'customer' ] ); + + $event = new UserDeleted(); + + $this->assertTrue( $event->should_fire( [ 15, null ] ) ); + $this->assertSame( + [ + 'id' => 15, + 'name' => 'Old Admin', + 'email' => 'user15@scanfully.com', + 'roles' => [ 'administrator' ], + ], + $event->get_post_body( [ 15, null ] ) + ); + $this->assertArrayNotHasKey( 'email', $event->get_post_body( [ 29, null ] ), 'No email address for an account without elevated rights.' ); + $this->assertFalse( $event->should_fire( [ 999, null ] ), 'An unknown user.' ); + } + + public function test_a_role_change_has_the_new_and_old_roles(): void { + $this->add_user( 16, 'Promoted', [ 'administrator' ] ); + + $event = new UserRoleChanged(); + $data = [ 16, 'administrator', [ 'editor' ] ]; + + $this->assertTrue( $event->should_fire( $data ) ); + $this->assertSame( + [ + 'id' => 16, + 'name' => 'Promoted', + 'email' => 'user16@scanfully.com', + 'roles' => [ 'administrator' ], + 'old_roles' => [ 'editor' ], + ], + $event->get_post_body( $data ) + ); + } + + public function test_the_same_role_change_is_reported_once_per_request(): void { + $this->add_user( 17, 'Promoted', [ 'administrator' ] ); + $event = new UserRoleChanged(); + + $this->assertTrue( $event->should_fire( [ 17, 'administrator', [ 'editor' ] ] ) ); + $this->assertFalse( $event->should_fire( [ 17, 'administrator', [ 'editor' ] ] ) ); + } + + public function test_setting_the_role_a_user_already_has_is_not_a_change(): void { + $this->add_user( 18, 'Same', [ 'editor' ] ); + + $this->assertFalse( ( new UserRoleChanged() )->should_fire( [ 18, 'editor', [ 'editor' ] ] ) ); + } + + public function test_the_first_role_of_a_new_user_is_not_a_role_change(): void { + $this->add_user( 19, 'New', [ 'subscriber' ] ); + $event = new UserRoleChanged(); + + UserRoleChanged::note_user_insert( [ 'user_login' => 'login-19' ], false ); + $this->assertFalse( $event->should_fire( [ 19, 'subscriber', [] ] ), 'While the user is created.' ); + + UserRoleChanged::note_user_registered( 19 ); + $this->assertTrue( $event->should_fire( [ 19, 'subscriber', [] ] ), 'A role given later by someone signed in.' ); + } + + public function test_a_failed_insert_does_not_hide_a_later_role_change_of_another_user(): void { + $this->add_user( 26, 'Existing', [ 'editor' ] ); + $event = new UserRoleChanged(); + + // wp_insert_user() fails after this point (a database error), so + // user_register never runs. + UserRoleChanged::note_user_insert( [ 'user_login' => 'ghost' ], false ); + + $this->assertTrue( $event->should_fire( [ 26, 'editor', [] ] ) ); + } + + public function test_the_first_role_of_a_new_user_is_skipped_only_once(): void { + $this->add_user( 27, 'New', [ 'subscriber' ] ); + $event = new UserRoleChanged(); + + UserRoleChanged::note_user_insert( [ 'user_login' => 'login-27' ], false ); + + $this->assertFalse( $event->should_fire( [ 27, 'subscriber', [] ] ) ); + $this->assertTrue( $event->should_fire( [ 27, 'editor', [] ] ), 'A second role change in the same request.' ); + } + + public function test_a_role_set_right_after_a_plain_sign_up_is_not_a_role_change(): void { + $this->current_user_id = 0; + $this->add_user( 23, 'New customer', [ 'customer' ] ); + $event = new UserRoleChanged(); + + // Another plugin's user_register handler, or multisite adding the user to the site. + UserRoleChanged::note_user_registered( 23 ); + + $this->assertFalse( $event->should_fire( [ 23, 'customer', [ 'subscriber' ] ] ) ); + } + + public function test_a_role_set_right_after_a_sign_up_that_gives_elevated_rights_is_reported(): void { + $this->current_user_id = 0; + $this->add_user( 24, 'Promoted on sign-up', [ 'administrator' ] ); + $event = new UserRoleChanged(); + + UserRoleChanged::note_user_registered( 24 ); + + $this->assertTrue( $event->should_fire( [ 24, 'administrator', [ 'subscriber' ] ] ) ); + } + + public function test_a_role_change_of_an_older_user_without_anyone_signed_in_is_reported(): void { + $this->current_user_id = 0; + $this->add_user( 25, 'Cron change', [ 'customer' ] ); + + $this->assertTrue( ( new UserRoleChanged() )->should_fire( [ 25, 'customer', [ 'subscriber' ] ] ) ); + } + + public function test_a_role_change_while_a_user_is_updated_is_reported(): void { + $this->add_user( 20, 'Demoted', [ 'subscriber' ] ); + + $this->assertSame( [ 'x' => 1 ], UserRoleChanged::note_user_insert( [ 'x' => 1 ], true ), 'The user data must be returned unchanged.' ); + $this->assertTrue( ( new UserRoleChanged() )->should_fire( [ 20, 'subscriber', [ 'administrator' ] ] ) ); + } + + /** + * @dataProvider provide_role_change_emails + * + * @param string $role The new role. + * @param array $old_roles The roles before. + * @param bool $with_email Whether the email address is sent. + */ + public function test_a_role_change_has_the_email_address_when_elevated_before_or_after( string $role, array $old_roles, bool $with_email ): void { + $this->add_user( 30, 'Changed', [ $role ] ); + + $body = ( new UserRoleChanged() )->get_post_body( [ 30, $role, $old_roles ] ); + + $this->assertSame( $with_email, array_key_exists( 'email', $body ) ); + } + + /** + * @return array, bool}> + */ + public function provide_role_change_emails(): array { + return [ + 'promoted to administrator' => [ 'administrator', [ 'subscriber' ], true ], + 'administrator demoted' => [ 'subscriber', [ 'administrator' ], true ], + 'subscriber made a customer' => [ 'customer', [ 'subscriber' ], false ], + ]; + } + + public function test_the_actor_name_stays_scrubbed_when_the_subject_has_an_email_address(): void { + $scheduled = []; + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'wp_get_current_user' )->justReturn( + (object) [ + 'ID' => 1, + 'display_name' => 'admin@scanfully.com', + ] + ); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'as_schedule_single_action' )->alias( + static function ( $timestamp, $hook, $args ) use ( &$scheduled ) { + $scheduled[] = $args; + return 1; + } + ); + $this->add_user( 31, 'New Admin', [ 'administrator' ] ); + + ( new UserCreated() )->listener_callback( 31 ); + + $this->assertSame( '', $scheduled[0]['user']['name'] ); + $this->assertSame( 'user31@scanfully.com', $scheduled[0]['data']['email'] ); + } + + public function test_removing_every_role_is_reported_with_an_empty_role_list(): void { + $this->add_user( 21, 'No access', [] ); + $event = new UserRoleChanged(); + + $this->assertTrue( $event->should_fire( [ 21, '', [ 'editor' ] ] ) ); + $this->assertSame( [], $event->get_post_body( [ 21, '', [ 'editor' ] ] )['roles'] ); + } +} diff --git a/tests/Unit/Events/UserLoginTest.php b/tests/Unit/Events/UserLoginTest.php new file mode 100644 index 0000000..033ae5d --- /dev/null +++ b/tests/Unit/Events/UserLoginTest.php @@ -0,0 +1,253 @@ + + */ + private array $server = []; + + /** + * In-memory transient store. + * + * @var array + */ + private array $transients = []; + + /** + * Arguments of scheduled jobs. + * + * @var array> + */ + private array $scheduled = []; + + /** + * The failed login counters. + * + * @var FakeCounterTable + */ + private FakeCounterTable $counters; + + protected function setUp(): void { + parent::setUp(); + $this->counters = FakeCounterTable::install(); + $this->server = $_SERVER; + foreach ( self::SERVER_KEYS as $key ) { + unset( $_SERVER[ $key ] ); + } + + Functions\when( 'user_can' )->alias( static fn( $user ) => [] !== array_intersect( (array) $user->roles, [ 'administrator', 'editor' ] ) ); + Functions\when( 'is_email' )->alias( static fn( $email ) => false !== filter_var( $email, FILTER_VALIDATE_EMAIL ) ); + Functions\when( 'wp_unslash' )->returnArg(); + Functions\when( 'sanitize_text_field' )->alias( static fn( $value ) => trim( strip_tags( (string) $value ) ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- WordPress is not loaded in unit tests. + Functions\when( 'get_transient' )->alias( fn( string $key ) => array_key_exists( $key, $this->transients ) ? $this->transients[ $key ] : false ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value ) { + $this->transients[ $key ] = $value; + return true; + } + ); + Functions\when( 'get_option' )->justReturn( 'yes' ); + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'as_schedule_single_action' )->alias( + function ( $timestamp, $hook, $args ) { + $this->scheduled[] = $args; + return 1; + } + ); + } + + protected function tearDown(): void { + $_SERVER = $this->server; + parent::tearDown(); + } + + /** + * A user double. + * + * @param array $roles Roles. + * @param string $name Display name. + * + * @return \WP_User + */ + private function user( array $roles, string $name = 'Bob' ) { + $user = Mockery::mock( 'WP_User' ); + $user->ID = 4; + $user->display_name = $name; + $user->first_name = ''; + $user->last_name = ''; + $user->roles = $roles; + $user->user_login = 'bob'; + $user->user_email = 'bob@scanfully.com'; + + return $user; + } + + public function test_a_login_after_wrong_passwords_on_the_account_says_how_many(): void { + $hour = Store::hour(); + $this->counters->rows[ 'scanfully_lf_' . $hour . '_u_4' ] = 9; + $this->counters->rows[ 'scanfully_lf_' . ( $hour - 1 ) . '_u_4' ] = 5; + $this->counters->rows[ 'scanfully_lf_' . ( $hour - 2 ) . '_u_4' ] = 100; + $this->counters->rows[ 'scanfully_lf_' . $hour . '_u_5' ] = 3; + + ( new UserLogin() )->listener_callback( 'bob', $this->user( [ 'administrator' ] ) ); + + $this->assertSame( 14, $this->scheduled[0]['data']['failed_before'] ); + } + + public function test_a_login_without_wrong_passwords_has_no_count(): void { + ( new UserLogin() )->listener_callback( 'bob', $this->user( [ 'administrator' ] ) ); + + $this->assertArrayNotHasKey( 'failed_before', $this->scheduled[0]['data'] ); + } + + public function test_a_login_with_elevated_rights_is_reported_with_address_and_browser(): void { + $_SERVER['REMOTE_ADDR'] = '203.0.113.9'; + $_SERVER['HTTP_X_FORWARDED_FOR'] = '198.51.100.7, 203.0.113.9'; + $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/129.0'; + + Functions\expect( 'wp_get_current_user' )->never(); + ( new UserLogin() )->listener_callback( 'bob', $this->user( [ 'administrator' ] ) ); + + $this->assertCount( 1, $this->scheduled ); + $this->assertSame( 'UserLogin', $this->scheduled[0]['type'] ); + $this->assertSame( + [ + 'id' => 4, + 'name' => 'Bob', + ], + $this->scheduled[0]['user'], + 'The actor is the user logging in.' + ); + $this->assertSame( + [ + 'id' => 4, + 'name' => 'Bob', + 'email' => 'bob@scanfully.com', + 'roles' => [ 'administrator' ], + 'ip' => '203.0.113.9', + 'forwarded_for' => '198.51.100.7', + 'user_agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/129.0', + ], + $this->scheduled[0]['data'] + ); + } + + public function test_a_login_without_elevated_rights_is_not_reported(): void { + ( new UserLogin() )->listener_callback( 'bob', $this->user( [ 'subscriber' ] ) ); + ( new UserLogin() )->listener_callback( 'bob', $this->user( [ 'customer' ] ) ); + + $this->assertSame( [], $this->scheduled ); + } + + public function test_a_login_without_a_user_is_not_reported(): void { + $this->assertFalse( ( new UserLogin() )->should_fire( [ 'bob', null ] ) ); + $this->assertSame( [], ( new UserLogin() )->get_post_body( [ 'bob', null ] ) ); + } + + public function test_the_actor_name_is_scrubbed_but_the_subject_email_is_sent(): void { + ( new UserLogin() )->listener_callback( 'bob', $this->user( [ 'administrator' ], 'bob@scanfully.com' ) ); + + $this->assertSame( '', $this->scheduled[0]['user']['name'] ); + $this->assertSame( '', $this->scheduled[0]['data']['name'] ); + $this->assertSame( 'bob@scanfully.com', $this->scheduled[0]['data']['email'] ); + } + + public function test_logins_share_the_user_event_cap(): void { + Filters\expectApplied( 'scanfully_user_events_per_minute' )->andReturn( 1 ); + $event = new UserLogin(); + + $this->assertTrue( $event->should_fire( [ 'bob', $this->user( [ 'administrator' ] ) ] ) ); + $this->assertFalse( $event->should_fire( [ 'bob', $this->user( [ 'administrator' ] ) ] ) ); + } + + /** + * @dataProvider provide_forwarded_headers + * + * @param array $headers $_SERVER header values. + * @param string $expected The forwarded_for sent. + */ + public function test_the_forwarded_address( array $headers, string $expected ): void { + foreach ( $headers as $key => $value ) { + $_SERVER[ $key ] = $value; + } + + $body = ( new UserLogin() )->get_post_body( [ 'bob', $this->user( [ 'administrator' ] ) ] ); + + $this->assertSame( $expected, $body['forwarded_for'] ); + } + + /** + * @return array, string}> + */ + public function provide_forwarded_headers(): array { + return [ + 'no proxy headers' => [ [], '' ], + 'Cloudflare first' => [ + [ + 'HTTP_CF_CONNECTING_IP' => '198.51.100.7', + 'HTTP_X_REAL_IP' => '198.51.100.8', + 'HTTP_X_FORWARDED_FOR' => '198.51.100.9', + ], + '198.51.100.7', + ], + 'X-Real-IP before X-Forwarded-For' => [ + [ + 'HTTP_X_REAL_IP' => '198.51.100.8', + 'HTTP_X_FORWARDED_FOR' => '198.51.100.9', + ], + '198.51.100.8', + ], + 'first of a forwarded list' => [ [ 'HTTP_X_FORWARDED_FOR' => ' 2001:db8::1 , 198.51.100.9, 10.0.0.1' ], '2001:db8::1' ], + 'an invalid Cloudflare value' => [ + [ + 'HTTP_CF_CONNECTING_IP' => 'unknown', + 'HTTP_X_FORWARDED_FOR' => '198.51.100.9', + ], + '198.51.100.9', + ], + 'a spoofed list starting with junk' => [ [ 'HTTP_X_FORWARDED_FOR' => '' ], '' ], + ]; + } + + public function test_an_invalid_remote_address_is_sent_empty(): void { + $_SERVER['REMOTE_ADDR'] = 'not-an-ip'; + + $this->assertSame( '', ( new UserLogin() )->get_post_body( [ 'bob', $this->user( [ 'administrator' ] ) ] )['ip'] ); + } + + public function test_the_user_agent_is_cut_to_500_characters(): void { + $_SERVER['HTTP_USER_AGENT'] = str_repeat( 'a', 800 ); + + $this->assertSame( 500, strlen( ( new UserLogin() )->get_post_body( [ 'bob', $this->user( [ 'administrator' ] ) ] )['user_agent'] ) ); + } +} diff --git a/tests/Unit/Events/WidgetChanges/CollectorTest.php b/tests/Unit/Events/WidgetChanges/CollectorTest.php new file mode 100644 index 0000000..a8b361d --- /dev/null +++ b/tests/Unit/Events/WidgetChanges/CollectorTest.php @@ -0,0 +1,233 @@ + + */ + private array $areas = []; + + protected function setUp(): void { + parent::setUp(); + Collector::reset(); + $_SERVER['REQUEST_METHOD'] = 'POST'; + $this->areas = [ + 'wp_inactive_widgets' => [], + 'sidebar-1' => [ 'search-2', 'text-3' ], + 'footer' => [ 'block-4' ], + 'array_version' => 3, + ]; + + Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. + Functions\when( 'get_option' )->alias( fn( $name ) => 'sidebars_widgets' === $name ? $this->areas : false ); + Functions\when( 'wp_installing' )->justReturn( false ); + Functions\when( 'did_action' )->justReturn( 0 ); + Functions\when( 'doing_action' )->justReturn( false ); + Functions\when( 'wp_doing_cron' )->justReturn( false ); + Functions\when( 'sanitize_text_field' )->returnArg(); + Functions\when( 'wp_unslash' )->returnArg(); + } + + protected function tearDown(): void { + Collector::reset(); + unset( $_SERVER['REQUEST_METHOD'] ); + parent::tearDown(); + } + + /** + * The areas option with changes. + * + * @param array $changes Areas and their widgets. + * + * @return array + */ + private function areas_with( array $changes ): array { + return array_merge( $this->areas, $changes ); + } + + public function test_a_widget_added_to_an_area(): void { + Collector::note_updated( + 'widget_text', + [ 3 => [ 'title' => 'Hours' ] ], + [ + 3 => [ 'title' => 'Hours' ], + 5 => [ + 'title' => 'News', + 'text' => 'Hi', + ], + ] + ); + Collector::note_updated( 'sidebars_widgets', $this->areas, $this->areas_with( [ 'sidebar-1' => [ 'search-2', 'text-3', 'text-5' ] ] ) ); + + $row = Collector::row(); + + $this->assertSame( + [ + [ + 'id' => 'text-5', + 'type' => 'text', + 'action' => 'added', + 'title' => 'News', + 'area' => 'sidebar-1', + ], + ], + $row['widgets'] + ); + } + + public function test_a_changed_title_and_text_keep_the_old_title_and_the_text_for_the_diff(): void { + Collector::note_updated( + 'widget_text', + [ + 3 => [ + 'title' => 'Hours', + 'text' => "Mon\nTue", + ], + ], + [ + 3 => [ + 'title' => 'Opening hours', + 'text' => "Mon\nWed", + ], + ] + ); + + $widget = Collector::row()['widgets'][0]; + + $this->assertSame( 'changed', $widget['action'] ); + $this->assertSame( 'Hours', $widget['title_old'] ); + $this->assertSame( 'Opening hours', $widget['title'] ); + $this->assertSame( [ 'title', 'text' ], $widget['changed'] ); + $this->assertSame( "Mon\nWed", $widget['_text']['new'] ); + } + + public function test_short_settings_keep_their_values_and_long_ones_only_say_changed(): void { + $changes = Collector::setting_changes( + [ + 'number' => 5, + 'filter' => str_repeat( 'a', 300 ), + ], + [ + 'number' => '10', + 'filter' => str_repeat( 'b', 300 ), + ] + ); + + $this->assertSame( [ 'number', 'filter' ], $changes['changed'] ); + $this->assertSame( + [ + 'number' => [ + 'old' => '5', + 'new' => '10', + ], + ], + $changes['values'] + ); + } + + public function test_a_setting_that_only_changed_type_is_no_change(): void { + Collector::note_updated( 'widget_recent-posts', [ 2 => [ 'number' => 5 ] ], [ 2 => [ 'number' => '5' ] ] ); + $this->areas['sidebar-1'][] = 'recent-posts-2'; + + $this->assertSame( [], Collector::row() ); + } + + public function test_a_widget_moved_to_another_area(): void { + Collector::note_updated( + 'sidebars_widgets', + $this->areas, + $this->areas_with( + [ + 'sidebar-1' => [ 'search-2' ], + 'footer' => [ 'block-4', 'text-3' ], + ] + ) + ); + + $widget = Collector::row()['widgets'][0]; + + $this->assertSame( 'moved', $widget['action'] ); + $this->assertSame( 'footer', $widget['area'] ); + $this->assertSame( 'sidebar-1', $widget['old_area'] ); + } + + public function test_a_widget_taken_to_the_inactive_widgets_is_removed_and_deleting_it_is_deleted(): void { + Collector::note_updated( + 'sidebars_widgets', + $this->areas, + $this->areas_with( + [ + 'sidebar-1' => [ 'search-2' ], + 'wp_inactive_widgets' => [ 'text-3' ], + ] + ) + ); + $this->assertSame( 'removed', Collector::row()['widgets'][0]['action'] ); + + Collector::reset(); + Collector::note_updated( 'widget_text', [ 3 => [ 'title' => 'Hours' ] ], [] ); + Collector::note_updated( 'sidebars_widgets', $this->areas, $this->areas_with( [ 'sidebar-1' => [ 'search-2' ] ] ) ); + $widget = Collector::row()['widgets'][0]; + $this->assertSame( 'deleted', $widget['action'] ); + $this->assertSame( 'Hours', $widget['title'] ); + $this->assertSame( 'sidebar-1', $widget['old_area'] ); + } + + public function test_a_new_order_within_an_area_is_noted_once(): void { + Collector::note_updated( 'sidebars_widgets', $this->areas, $this->areas_with( [ 'sidebar-1' => [ 'text-3', 'search-2' ] ] ) ); + + $row = Collector::row(); + + $this->assertSame( [], $row['widgets'] ); + $this->assertSame( [ 'sidebar-1' ], $row['order_changed'] ); + } + + public function test_a_block_widget_carries_its_content_for_its_label(): void { + Collector::note_updated( 'widget_block', [ 4 => [ 'content' => '

Hi

' ] ], [ 4 => [ 'content' => '

Hello

' ] ] ); + + $widget = Collector::row()['widgets'][0]; + + $this->assertSame( 'changed', $widget['action'] ); + $this->assertSame( [ 'content' ], $widget['changed'] ); + $this->assertStringContainsString( 'Hello', $widget['_content'] ); + } + + public function test_read_requests_are_left_out(): void { + // The Widgets screen tidies widgets up when it loads. + $_SERVER['REQUEST_METHOD'] = 'GET'; + Collector::note_updated( + 'sidebars_widgets', + $this->areas, + $this->areas_with( + [ + 'sidebar-1' => [ 'search-2' ], + 'wp_inactive_widgets' => [ 'text-3' ], + ] + ) + ); + + $this->assertSame( [], Collector::row() ); + } + + public function test_other_options_are_ignored(): void { + Collector::note_updated( 'blogname', 'Old', 'New' ); + + $this->assertSame( [], Collector::row() ); + } +} diff --git a/tests/Unit/Health/MuPluginsTest.php b/tests/Unit/Health/MuPluginsTest.php new file mode 100644 index 0000000..fff2897 --- /dev/null +++ b/tests/Unit/Health/MuPluginsTest.php @@ -0,0 +1,232 @@ +content = sys_get_temp_dir() . '/scanfully-mu-' . bin2hex( random_bytes( 6 ) ); + mkdir( $this->content . '/mu-plugins', 0777, true ); + Functions\when( 'wp_strip_all_tags' )->alias( static fn( $text ) => strip_tags( (string) $text ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- WordPress is not loaded in unit tests. + } + + protected function tearDown(): void { + $this->remove( $this->content ); + parent::tearDown(); + } + + /** + * Remove a folder and everything in it. + * + * @param string $path The folder. + * + * @return void + */ + private function remove( string $path ): void { + if ( ! is_dir( $path ) ) { + return; + } + $items = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $path, \FilesystemIterator::SKIP_DOTS ), \RecursiveIteratorIterator::CHILD_FIRST ); + foreach ( $items as $item ) { + $item->isDir() ? rmdir( $item->getPathname() ) : unlink( $item->getPathname() ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- Test cleanup. + } + rmdir( $path ); + } + + /** + * Write a file, creating its folder, and return its modification time as + * the file system has it (the test suite's stream wrapper can shift what + * touch() sets). + * + * @param string $relative Path relative to `wp-content`. + * @param string $content The content. + * @param int $mtime The modification time to set. + * + * @return int + */ + private function write( string $relative, string $content, int $mtime = 1760000000 ): int { + $path = $this->content . '/' . $relative; + if ( ! is_dir( dirname( $path ) ) ) { + mkdir( dirname( $path ), 0777, true ); + } + file_put_contents( $path, $content ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test fixture. + touch( $path, $mtime ); + clearstatcache( true, $path ); + + return (int) filemtime( $path ); + } + + /** + * Scan the temporary folder. + * + * @param array> $mu_plugins Header data of the MU plugin files. + * @param array> $dropins Header data of the drop-ins. + * @param array $cache The hash cache; updated. + * + * @return array> Entries by kind and file. + */ + private function scan( array $mu_plugins, array $dropins = [], array &$cache = [] ): array { + $used = []; + $entries = MuPlugins::entries( $this->content . '/mu-plugins', $mu_plugins, $this->content, $dropins, $cache, $used ); + $cache = array_intersect_key( $cache, $used ); + $out = []; + foreach ( $entries as $entry ) { + $out[ $entry['kind'] . ':' . $entry['file'] ] = $entry; + } + + return $out; + } + + public function test_a_mu_plugin_file_has_its_header_size_time_and_content_hash(): void { + $mtime = $this->write( 'mu-plugins/custom-login.php', 'scan( + [ + 'custom-login.php' => [ + 'Name' => 'Custom Login', + 'Version' => '1.2.0', + 'Author' => 'Agency & Co', + 'Description' => 'Brands the login page.', + ], + ] + ); + + $this->assertSame( + [ + 'kind' => 'mu', + 'file' => 'custom-login.php', + 'name' => 'Custom Login', + 'version' => '1.2.0', + 'author' => 'Agency & Co', + 'description' => 'Brands the login page.', + 'size' => 37, + 'modified' => $mtime, + 'hash' => 'sha256:' . hash( 'sha256', 'write( 'mu-plugins/loader.php', 'assertSame( 'loader.php', $this->scan( [ 'loader.php' => [] ] )['mu:loader.php']['name'] ); + } + + public function test_a_folder_gets_a_fingerprint_over_its_files_and_their_content(): void { + $this->write( 'mu-plugins/agency/agency.php', 'a' ); + $newest = $this->write( 'mu-plugins/agency/includes/admin.php', 'bb', 1760000100 ); + + $folder = $this->scan( [] )['mu_folder:agency']; + + $this->assertSame( 2, $folder['files'] ); + $this->assertSame( 3, $folder['size'] ); + $this->assertSame( $newest, $folder['modified'] ); + $this->assertFalse( $folder['partial'] ); + $this->assertSame( 'sha256:' . hash( 'sha256', "agency.php\0sha256:" . hash( 'sha256', 'a' ) . "\nincludes/admin.php\0sha256:" . hash( 'sha256', 'bb' ) ), $folder['hash'] ); + } + + public function test_a_changed_file_in_a_folder_changes_its_fingerprint(): void { + $this->write( 'mu-plugins/agency/agency.php', 'a' ); + $before = $this->scan( [] )['mu_folder:agency']['hash']; + + $this->write( 'mu-plugins/agency/agency.php', 'b', 1760000500 ); + + $this->assertNotSame( $before, $this->scan( [] )['mu_folder:agency']['hash'] ); + } + + public function test_a_touched_but_unchanged_file_keeps_its_hash(): void { + $this->write( 'mu-plugins/agency/agency.php', 'same' ); + $cache = []; + $before = $this->scan( [], [], $cache )['mu_folder:agency']['hash']; + + $this->write( 'mu-plugins/agency/agency.php', 'same', 1760009999 ); + + $this->assertSame( $before, $this->scan( [], [], $cache )['mu_folder:agency']['hash'] ); + } + + public function test_a_cached_hash_is_used_while_size_and_time_are_the_same(): void { + $mtime = $this->write( 'mu-plugins/custom.php', 'abc' ); + $cache = [ 'mu-plugins/custom.php' => '3:' . $mtime . ':sha256:cached' ]; + + $this->assertSame( 'sha256:cached', $this->scan( [ 'custom.php' => [] ], [], $cache )['mu:custom.php']['hash'] ); + } + + public function test_the_cache_keeps_only_files_that_are_still_there(): void { + $this->write( 'mu-plugins/custom.php', 'abc' ); + $cache = [ 'mu-plugins/gone.php' => '1:1:sha256:x' ]; + + $this->scan( [ 'custom.php' => [] ], [], $cache ); + + $this->assertSame( [ 'mu-plugins/custom.php' ], array_keys( $cache ) ); + } + + public function test_drop_ins_are_listed_with_their_hash(): void { + $this->write( 'object-cache.php', 'scan( + [], + [ + 'object-cache.php' => [ + 'Name' => 'Redis Object Cache Drop-In', + 'Version' => '2.6.5', + ], + ] + )['dropin:object-cache.php']; + + $this->assertSame( 'Redis Object Cache Drop-In', $dropin['name'] ); + $this->assertSame( '2.6.5', $dropin['version'] ); + $this->assertSame( 'sha256:' . hash( 'sha256', 'assertSame( [], $this->scan( [ 'gone.php' => [ 'Name' => 'Gone' ] ], [ 'db.php' => [] ] ) ); + } + + public function test_a_missing_mu_plugins_folder_gives_no_entries(): void { + rmdir( $this->content . '/mu-plugins' ); + + $this->assertSame( [], $this->scan( [] ) ); + } + + public function test_the_quick_fingerprint_changes_with_a_new_file_or_a_new_time_and_reads_no_file(): void { + $this->write( 'mu-plugins/custom.php', 'abc' ); + $this->write( 'object-cache.php', 'x' ); + $first = MuPlugins::stat_fingerprint( $this->content . '/mu-plugins', $this->content, [ 'object-cache.php' ] ); + + $this->assertSame( $first, MuPlugins::stat_fingerprint( $this->content . '/mu-plugins', $this->content, [ 'object-cache.php' ] ) ); + + $this->write( 'mu-plugins/new.php', 'n' ); + $second = MuPlugins::stat_fingerprint( $this->content . '/mu-plugins', $this->content, [ 'object-cache.php' ] ); + $this->assertNotSame( $first, $second ); + + $this->write( 'object-cache.php', 'x', 1760000500 ); + $this->assertNotSame( $second, MuPlugins::stat_fingerprint( $this->content . '/mu-plugins', $this->content, [ 'object-cache.php' ] ) ); + } + + public function test_a_hidden_entry_is_left_out(): void { + $this->write( 'mu-plugins/.git/HEAD', 'ref' ); + + $this->assertSame( [], $this->scan( [] ) ); + } +} diff --git a/tests/Unit/WooCheckout/ControllerProbeTest.php b/tests/Unit/WooCheckout/ControllerProbeTest.php index 7e875fa..f9a4dc0 100644 --- a/tests/Unit/WooCheckout/ControllerProbeTest.php +++ b/tests/Unit/WooCheckout/ControllerProbeTest.php @@ -7,6 +7,7 @@ namespace Scanfully\Tests\Unit\WooCheckout; +use Brain\Monkey\Filters; use Brain\Monkey\Functions; use ReflectionProperty; use Scanfully\WooCheckout\Controller; @@ -14,6 +15,7 @@ /** * @covers \Scanfully\WooCheckout\Controller::is_probe_request + * @covers \Scanfully\WooCheckout\Controller::prime_probe_request_check */ final class ControllerProbeTest extends TestCase { @@ -111,6 +113,25 @@ public function test_priming_on_init_does_not_touch_the_rest_server(): void { $this->assertTrue( Controller::is_probe_request() ); } + public function test_a_probe_request_never_runs_cron_itself(): void { + $_SERVER['HTTP_X_SCANFULLY_PROBE'] = $this->header_for( $this->fresh_scan_id() ); + Functions\when( 'nocache_headers' )->justReturn(); + // With ALTERNATE_WP_CRON a page request runs due cron jobs itself, and + // in a probe request only the probe gateway is registered. + Filters\expectAdded( 'pre_get_ready_cron_jobs' )->once()->with( '__return_empty_array' ); + + Controller::prime_probe_request_check(); + } + + public function test_an_ordinary_request_keeps_its_cron(): void { + Functions\expect( 'nocache_headers' )->never(); + Filters\expectAdded( 'pre_get_ready_cron_jobs' )->never(); + + Controller::prime_probe_request_check(); + + $this->assertFalse( Controller::is_probe_request() ); + } + public function test_a_scan_id_older_than_two_hours_is_rejected(): void { $_SERVER['HTTP_X_SCANFULLY_PROBE'] = $this->header_for( $this->fresh_scan_id( -2 * HOUR_IN_SECONDS - 60 ) ); diff --git a/tests/Unit/WooCheckout/ProbeOrderTest.php b/tests/Unit/WooCheckout/ProbeOrderTest.php index 2794478..76f33c3 100644 --- a/tests/Unit/WooCheckout/ProbeOrderTest.php +++ b/tests/Unit/WooCheckout/ProbeOrderTest.php @@ -116,6 +116,39 @@ public function test_a_probe_payment_tags_and_cancels_the_subscriptions_it_creat $this->assertSame( 'success', $result['result'] ); } + public function test_a_subscription_already_cancelled_with_its_order_is_not_cancelled_again(): void { + $order = Mockery::mock( 'WC_Order' ); + $order->shouldReceive( 'update_meta_data' )->once()->with( '_scanfully_probe_order', 'true' ); + $order->shouldReceive( 'set_status' )->once()->with( 'cancelled', Mockery::type( 'string' ) ); + $order->shouldReceive( 'save' )->once(); + + // Loaded before the order is saved: still pending, only tagged. + $stale = Mockery::mock( 'WC_Order' ); + $stale->shouldReceive( 'update_meta_data' )->once()->with( '_scanfully_probe_order', 'true' ); + $stale->shouldReceive( 'save_meta_data' )->once(); + $stale->shouldNotReceive( 'update_status' ); + + // Loaded after: Subscriptions cancelled it along with the order. + $fresh = Mockery::mock( 'WC_Order' ); + $fresh->shouldReceive( 'has_status' )->with( 'cancelled' )->andReturn( true ); + $fresh->shouldNotReceive( 'update_status' ); + + $loads = 0; + Functions\when( 'wcs_get_subscriptions_for_order' )->alias( + static function () use ( $stale, $fresh, &$loads ) { + ++$loads; + return [ 101 => 1 === $loads ? $stale : $fresh ]; + } + ); + Functions\when( 'wc_get_order' )->justReturn( $order ); + Functions\when( 'home_url' )->justReturn( 'https://shop.test/' ); + Functions\when( 'add_query_arg' )->alias( static fn( $args, $url ) => $url . '?' . http_build_query( $args ) ); + + ( new ProbeGateway() )->process_payment( 12 ); + + $this->assertSame( 2, $loads, 'The subscriptions are read again after the order is saved.' ); + } + public function test_emails_about_probe_subscriptions_are_suppressed(): void { $subscription = $this->order(); @@ -205,4 +238,92 @@ public function test_cleanup_never_touches_orders_that_are_not_probe_orders(): v Cleanup::run(); } + + public function test_the_probe_gateway_lets_subscriptions_cancel_probe_subscriptions(): void { + // WC_Subscription::can_be_updated_to( 'cancelled' ) requires the + // subscription's gateway to declare this feature; without it the + // subscriptions a probe order creates can never leave pending. + $this->assertContains( 'subscription_cancellation', ( new ProbeGateway() )->supports ); + } + + public function test_cleanup_goes_on_when_a_probe_subscription_cannot_be_cancelled(): void { + $stuck = $this->order(); + $stuck->shouldReceive( 'get_id' )->andReturn( 101 ); + $stuck->shouldReceive( 'update_status' )->once()->andThrow( new \Exception( 'Unable to change subscription status to "cancelled".' ) ); + $next = $this->order(); + $pending_order = $this->order(); + $next->shouldReceive( 'update_status' )->once()->with( 'cancelled', Mockery::type( 'string' ) ); + $pending_order->shouldReceive( 'update_status' )->once()->with( 'cancelled', Mockery::type( 'string' ) ); + + $logger = Mockery::mock(); + $logger->shouldReceive( 'warning' )->once()->with( Mockery::pattern( '/could not cancel probe order #101/' ), [ 'source' => 'scanfully' ] ); + Functions\when( 'wc_get_logger' )->justReturn( $logger ); + + $queries = []; + Functions\when( 'wc_get_orders' )->alias( + function ( array $args ) use ( $stuck, $next, $pending_order, &$queries ) { + $queries[] = $args['type'] . ':' . $args['status'][0]; + if ( [ 'pending' ] !== $args['status'] ) { + return []; + } + return 'shop_subscription' === $args['type'] ? [ $stuck, $next ] : [ $pending_order ]; + } + ); + + Cleanup::run(); + + // The subscription that could not be cancelled did not end the run: + // the next subscription and every later pass were still handled. + $this->assertSame( [ 'shop_subscription:pending', 'shop_subscription:cancelled', 'shop_order:pending', 'shop_order:cancelled' ], $queries ); + } + + public function test_cleanup_goes_on_when_a_probe_order_cannot_be_deleted(): void { + $stuck = $this->order(); + $stuck->shouldReceive( 'get_id' )->andReturn( 7 ); + $stuck->shouldReceive( 'delete' )->once()->with( true )->andThrow( new \RuntimeException( 'Database error.' ) ); + $next = $this->order(); + $next->shouldReceive( 'delete' )->once()->with( true )->andReturn( true ); + + $logger = Mockery::mock(); + $logger->shouldReceive( 'warning' )->once()->with( Mockery::pattern( '/could not delete probe order #7/' ), [ 'source' => 'scanfully' ] ); + Functions\when( 'wc_get_logger' )->justReturn( $logger ); + + Functions\when( 'wc_get_orders' )->alias( + static function ( array $args ) use ( $stuck, $next ) { + return 'shop_order' === $args['type'] && [ 'cancelled' ] === $args['status'] ? [ $stuck, $next ] : []; + } + ); + + Cleanup::run(); + } + + public function test_cleanup_stops_batching_when_a_full_batch_changes_nothing(): void { + $stuck = []; + for ( $i = 1; $i <= 50; $i++ ) { + $order = $this->order(); + $order->shouldReceive( 'get_id' )->andReturn( $i ); + $order->shouldReceive( 'update_status' )->once()->andThrow( new \Exception( 'refused' ) ); + $stuck[] = $order; + } + $logger = Mockery::mock(); + $logger->shouldReceive( 'warning' )->times( 50 ); + Functions\when( 'wc_get_logger' )->justReturn( $logger ); + + $pending_queries = 0; + Functions\when( 'wc_get_orders' )->alias( + static function ( array $args ) use ( $stuck, &$pending_queries ) { + if ( 'shop_order' !== $args['type'] || [ 'pending' ] !== $args['status'] ) { + return []; + } + ++$pending_queries; + return $stuck; + } + ); + + Cleanup::run(); + + // A full batch that refused every change is not queried again and + // again: the same rows would only come back. + $this->assertSame( 1, $pending_queries ); + } } diff --git a/tests/stubs.php b/tests/stubs.php index 44fc196..a693500 100644 --- a/tests/stubs.php +++ b/tests/stubs.php @@ -17,6 +17,44 @@ // phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound, Universal.Namespaces.DisallowCurlyBraceSyntax, Universal.Namespaces.OneDeclarationPerFile, Universal.Namespaces.DisallowDeclarationWithoutName namespace { + if ( ! class_exists( 'WP_Post' ) ) { + /** + * Stub of WordPress' post, which copies the fields it is given. + */ + #[AllowDynamicProperties] + final class WP_Post { + /** + * Constructor. + * + * @param object $post The post fields. + */ + public function __construct( $post ) { + foreach ( get_object_vars( $post ) as $key => $value ) { + $this->$key = $value; + } + } + } + } + + if ( ! class_exists( 'WP_Term' ) ) { + /** + * Stub of WordPress' term, which copies the fields it is given. + */ + #[AllowDynamicProperties] + final class WP_Term { + /** + * Constructor. + * + * @param object $term The term fields. + */ + public function __construct( $term ) { + foreach ( get_object_vars( $term ) as $key => $value ) { + $this->$key = $value; + } + } + } + } + if ( ! class_exists( 'WP_REST_Request' ) ) { /** * Stub of WordPress' REST request, limited to headers.