Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/stream/abilities/class-ability-create-alert.php
+++ b/stream/abilities/class-ability-create-alert.php
@@ -54,7 +54,7 @@
'properties' => array(
'alert_type' => array(
'type' => 'string',
- 'description' => 'Notifier slug. Built-in types are none, highlight, email, ifttt, slack. Other slugs may be registered by extensions.',
+ 'description' => 'Notifier slug. Built-in types are none, highlight, email, slack, webhook. The ifttt type is deprecated and cannot be created; existing IFTTT alerts still fire. Other slugs may be registered by extensions.',
),
'trigger_author' => array(
'type' => 'string',
@@ -132,6 +132,21 @@
),
array( 'status' => 400 )
);
+ }
+
+ $type_objects = isset( $this->plugin->alerts->alert_types )
+ ? (array) $this->plugin->alerts->alert_types
+ : array();
+ if ( isset( $type_objects[ $input['alert_type'] ] ) && empty( $type_objects[ $input['alert_type'] ]->creatable ) ) {
+ return new WP_Error(
+ 'stream_alert_type_not_creatable',
+ sprintf(
+ /* translators: %s: alert_type slug supplied by caller */
+ __( 'Alert type "%s" is deprecated and cannot be created.', 'stream' ),
+ (string) $input['alert_type']
+ ),
+ array( 'status' => 400 )
+ );
}
// Mirror the admin form's connector-context split so Alert::get_title()
--- a/stream/abilities/class-ability-create-exclusion-rule.php
+++ b/stream/abilities/class-ability-create-exclusion-rule.php
@@ -165,16 +165,10 @@
);
}
- // Validate connector against the full site-wide list, including
- // admin-only connectors (settings, editor, menus, etc.). get_slugs()
- // alone returns only request-context-loaded connectors, so REST
- // callers would otherwise be unable to exclude valid admin-only
- // connectors even though those are real and configurable in wp-admin.
- if ( '' !== $sanitized['connector'] ) {
- $known = isset( $this->plugin->connectors )
- ? $this->plugin->connectors->get_all_slugs_including_admin_only()
- : array();
- if ( ! empty( $known ) && ! in_array( $sanitized['connector'], $known, true ) ) {
+ // Validate connector against all available connectors, including non-active connectors (eg: admin-only).
+ if ( '' !== $sanitized['connector'] && isset( $this->plugin->connectors ) ) {
+ $known = $this->plugin->connectors->get_slugs( true );
+ if ( ! in_array( $sanitized['connector'], $known, true ) ) {
return new WP_Error(
'stream_unknown_connector',
/* translators: %s: connector slug */
--- a/stream/abilities/class-ability-get-connectors.php
+++ b/stream/abilities/class-ability-get-connectors.php
@@ -32,7 +32,7 @@
* {@inheritDoc}
*/
public function get_description() {
- return __( 'List all registered Stream connectors with their available contexts and actions. Useful for understanding what activity Stream can track on this site.', 'stream' );
+ return __( 'List all Stream connectors this plugin ships, including inactive connectors and those whose dependencies are not currently satisfied. Use this to filter historical records that may have been logged when those connectors were active.', 'stream' );
}
/**
@@ -42,7 +42,7 @@
return array(
'readonly' => true,
'idempotent' => true,
- 'instructions' => __( 'Use to discover the valid connector / context / action values for filters in stream/get-records and stream/create-exclusion-rule. Connector slugs are stable identifiers, so cache the result if you call abilities repeatedly.', 'stream' ),
+ 'instructions' => __( 'Use to discover the valid connector / context / action values for filters in stream/get-records and stream/create-exclusion-rule. The list is the plugin's shipped inventory, not only connectors whose dependencies are met on this site. Connector slugs are stable identifiers, so cache the result if you call abilities repeatedly.', 'stream' ),
);
}
@@ -59,7 +59,7 @@
public function get_output_schema() {
return array(
'type' => 'array',
- 'description' => 'Registered connectors.',
+ 'description' => 'Connectors this plugin ships, including inactive and unsatisfied-dependency connectors.',
'items' => array(
'type' => 'object',
'additionalProperties' => false,
@@ -99,11 +99,18 @@
return array();
}
- // Use the metadata-only accessor that includes admin-only connectors
- // (settings, editor, menus, etc.) so REST/MCP callers see the same
- // connector inventory an admin sees in wp-admin. The plain get_all()
- // reflects only connectors registered for the current request type,
- // which is the wrong frame for the abilities-facing "what exists on this site" answer.
- return $this->plugin->connectors->get_all_including_admin_only();
+ // Shipped inventory, including inactive / unsatisfied-dependency
+ // connectors, so historical records remain filterable via abilities.
+ /**
+ * Filter the connector list returned by the get-connectors ability.
+ *
+ * @param array $connectors Registered connector instances.
+ */
+ $connectors = apply_filters(
+ 'wp_stream_abilities_connectors',
+ $this->plugin->connectors->get_all( true )
+ );
+
+ return $connectors;
}
}
--- a/stream/abilities/class-ability-purge-records.php
+++ b/stream/abilities/class-ability-purge-records.php
@@ -123,7 +123,7 @@
// Stream stores `created` in UTC (Log::log() writes current_time('mysql', true)).
// MySQL's NOW() uses the server timezone, so comparing against it can
// delete too many or too few rows on hosts where the server is not UTC.
- // Mirror Admin::purge_scheduled_action(): compute a UTC cutoff in PHP
+ // Mirror Admin_Purge::purge_scheduled_action(): compute a UTC cutoff in PHP
// and bind it as a string.
$cutoff = ( new DateTime( 'now', new DateTimeZone( 'UTC' ) ) )
->sub( DateInterval::createFromDateString( ( (int) $input['older_than_days'] ) . ' days' ) )
@@ -174,9 +174,9 @@
// Count matching parent rows up-front so the response reports the number
// of *records* deleted, independent of how many meta rows were attached.
// $params is guaranteed non-empty here by the $filter_count > 0 guard above.
- // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
+ // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- reason: table name is $wpdb->stream; WHERE is assembled from allowlisted columns.
$count_sql = "SELECT COUNT(*) FROM {$wpdb->stream} AS stream WHERE {$where_sql}";
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared -- reason: $count_sql is prepared on the next call; Stream tables are not object-cached.
$deleted = (int) $wpdb->get_var( $wpdb->prepare( $count_sql, $params ) );
if ( 0 === $deleted ) {
@@ -184,15 +184,15 @@
}
// Delete matching stream rows AND their meta in a single multi-table DELETE,
- // mirroring Admin::purge_scheduled_action(). Doing both sides in one statement
+ // mirroring Admin_Purge::purge_scheduled_action(). Doing both sides in one statement
// avoids a follow-up full-table scan over $wpdb->streammeta to clean up
// orphans, which on busy sites could lock the meta table for a long time.
- // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery
+ // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery -- reason: table names are $wpdb properties; WHERE is assembled from allowlisted columns.
$delete_sql = "DELETE stream, meta
FROM {$wpdb->stream} AS stream
LEFT JOIN {$wpdb->streammeta} AS meta ON meta.record_id = stream.ID
WHERE {$where_sql}";
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared -- reason: $delete_sql is prepared on the next call; Stream tables are not object-cached.
$result = $wpdb->query( $wpdb->prepare( $delete_sql, $params ) );
// $wpdb->query() returns false on database error. Don't report a
--- a/stream/abilities/class-ability-update-settings.php
+++ b/stream/abilities/class-ability-update-settings.php
@@ -103,13 +103,14 @@
// Build allowlist of {section}_{field} keys from registered settings,
// and a parallel list of which keys correspond to checkbox fields.
- // We need the latter because Settings::sanitize_setting_by_field_type()
+ // We need the latter because Settings_Sanitizer::sanitize_setting_by_field_type()
// only accepts numeric values for checkboxes (is_numeric() rejects PHP
// booleans), so true/false from a JSON client would otherwise be
// silently coerced to '' instead of 0/1.
$valid_keys = array();
$checkbox_keys = array();
- foreach ( $this->plugin->settings->get_fields() as $section => $section_data ) {
+ $fields = $this->plugin->settings->registry->get_fields();
+ foreach ( $fields as $section => $section_data ) {
if ( empty( $section_data['fields'] ) || ! is_array( $section_data['fields'] ) ) {
continue;
}
@@ -147,7 +148,7 @@
// Run only the incoming keys through Stream's sanitize pipeline so
// values are normalized to their declared field type, then merge over
// the existing options so unrelated keys are preserved.
- $sanitized = $this->plugin->settings->sanitize_settings( $filtered );
+ $sanitized = $this->plugin->settings->sanitizer->sanitize_settings( $filtered, $fields );
$merged = array_merge( $current, $sanitized );
// update_all_setting_values() persists to the correct store and
--- a/stream/alerts/class-alert-trigger-action.php
+++ b/stream/alerts/class-alert-trigger-action.php
@@ -16,24 +16,18 @@
/**
* Unique identifier
- *
- * @var string
*/
- public $slug = 'action';
+ public string $slug = 'action';
/**
* Meta key used in forms.
- *
- * @var string
*/
- public $meta_key = 'trigger_action';
+ public string $meta_key = 'trigger_action';
/**
* Field key used in database
- *
- * @var string
*/
- public $field_key = 'wp_stream_trigger_action';
+ public string $field_key = 'wp_stream_trigger_action';
/**
* Checks if a record matches the criteria from the trigger.
@@ -80,7 +74,7 @@
'placeholder' => __( 'Any Action', 'stream' ),
),
);
- $form->add_field( 'select2', $args );
+ $form->add_field( 'grouped_select', $args );
}
/**
--- a/stream/alerts/class-alert-trigger-author.php
+++ b/stream/alerts/class-alert-trigger-author.php
@@ -16,17 +16,13 @@
/**
* Unique identifier
- *
- * @var string
*/
- public $slug = 'author';
+ public string $slug = 'author';
/**
* Field key used in database
- *
- * @var string
*/
- public $field_key = 'wp_stream_trigger_author';
+ public string $field_key = 'wp_stream_trigger_author';
/**
* Checks if a record matches the criteria from the trigger.
@@ -41,7 +37,10 @@
* @return bool False on failure, otherwise should return original value of $success.
*/
public function check_record( $success, $record_id, $recordarr, $alert ) {
- if ( ! empty( $alert->alert_meta['trigger_author'] ) && intval( $alert->alert_meta['trigger_author'] ) !== intval( $recordarr['user_id'] ) ) {
+ // The stored value may be '0' (WP-CLI), which empty() would drop and
+ // turn the trigger into "any author".
+ $trigger_author = isset( $alert->alert_meta['trigger_author'] ) ? (string) $alert->alert_meta['trigger_author'] : '';
+ if ( '' !== $trigger_author && (int) $trigger_author !== (int) $recordarr['user_id'] ) {
return false;
}
@@ -64,16 +63,35 @@
$value = $alert->alert_meta['trigger_author'];
}
- $args = array(
- 'name' => esc_attr( $this->field_key ),
- 'value' => esc_attr( $value ),
- 'options' => $this->get_values(),
- 'classes' => 'wp_stream_ajax_forward',
- 'data' => array(
- 'placeholder' => __( 'Any Author', 'stream' ),
- ),
+ $picker = $this->plugin->user_picker->get( $this->plugin->admin->get_preload_users_max() );
+
+ // Over the preload cap: Ajax user combobox instead of a preloaded select.
+ if ( $picker['ajax'] ) {
+ $form->add_field(
+ 'user_combobox',
+ array(
+ 'name' => esc_attr( $this->field_key ),
+ 'value' => esc_attr( $value ),
+ 'selected_label' => $this->plugin->user_picker->label_for_value( $value ),
+ 'data' => array(
+ 'placeholder' => __( 'Any Author', 'stream' ),
+ ),
+ )
+ );
+ return;
+ }
+
+ $form->add_field(
+ 'grouped_select',
+ array(
+ 'name' => esc_attr( $this->field_key ),
+ 'value' => esc_attr( $value ),
+ 'options' => $this->append_stored_value_option( $this->get_values(), $value ),
+ 'data' => array(
+ 'placeholder' => __( 'Any Author', 'stream' ),
+ ),
+ )
);
- $form->add_field( 'select2', $args );
}
/**
@@ -84,13 +102,6 @@
public function get_values() {
$all_records = array();
- $user_count = count_users();
- $total_users = $user_count['total_users'];
-
- if ( $total_users > $this->plugin->admin->preload_users_max ) {
- return array();
- }
-
$users = array_map(
function ( $user_id ) {
return new Author( $user_id );
@@ -123,7 +134,7 @@
$all_records[] = array(
'id' => $user->id,
'value' => $user->id,
- 'text' => $user->get_display_name(),
+ 'text' => $this->plugin->user_picker->label( $user->id ),
);
}
@@ -141,11 +152,37 @@
*/
public function save_fields( $alert ) {
$input = wp_stream_filter_input( INPUT_POST, $this->field_key );
- if ( array_key_exists( $input, $this->get_values( $alert ) ) ) {
- $alert->alert_meta['trigger_author'] = $input;
- } else {
- $alert->alert_meta['trigger_author'] = '';
+ $input = is_scalar( $input ) ? (string) $input : '';
+
+ // Only a user ID (or 0 for WP-CLI) is stored; anything else clears the
+ // trigger. Membership checks are impossible in combobox (Ajax) mode,
+ // where the option list is not rendered server-side.
+ $alert->alert_meta['trigger_author'] = ctype_digit( $input ) ? $input : '';
+ }
+
+ /**
+ * Append the stored author to the option list when missing (e.g. deleted user).
+ *
+ * @param array $options Picker options.
+ * @param string $current Stored author id.
+ * @return array
+ */
+ private function append_stored_value_option( array $options, $current ) {
+ if ( ! ctype_digit( (string) $current ) ) {
+ return $options;
+ }
+
+ $values = array_map( 'strval', array_column( $options, 'value' ) );
+ if ( in_array( (string) $current, $values, true ) ) {
+ return $options;
}
+
+ $options[] = array(
+ 'value' => (string) $current,
+ 'text' => $this->plugin->user_picker->label( (int) $current ),
+ );
+
+ return $options;
}
/**
@@ -159,18 +196,17 @@
* @return string
*/
public function get_display_value( $context = 'normal', $alert = null ) {
- $author = ( ! empty( $alert->alert_meta['trigger_author'] ) ) ? $alert->alert_meta['trigger_author'] : null;
- if ( empty( $author ) ) {
- $author = __( 'Any User', 'stream' );
- } elseif ( is_numeric( $author ) ) {
- $author_data = get_userdata( $author );
- if ( $author_data ) {
- $author = $author_data->display_name;
- } else {
- $author = __( 'Unknown User', 'stream' );
- }
+ // Note: the stored value may be '0' (WP-CLI), which is falsy — use isset().
+ $trigger_author = $alert->alert_meta['trigger_author'] ?? '';
+
+ if ( '' === $trigger_author ) {
+ return __( 'Any User', 'stream' );
+ }
+
+ if ( ctype_digit( $trigger_author ) ) {
+ return $this->plugin->user_picker->label( (int) $trigger_author );
}
- return ucfirst( $author );
+ return ucfirst( $trigger_author );
}
}
--- a/stream/alerts/class-alert-trigger-context.php
+++ b/stream/alerts/class-alert-trigger-context.php
@@ -16,17 +16,13 @@
/**
* Unique identifier
- *
- * @var string
*/
- public $slug = 'context';
+ public string $slug = 'context';
/**
* Field key used in database
- *
- * @var string
*/
- public $field_key = 'wp_stream_trigger_context';
+ public string $field_key = 'wp_stream_trigger_context';
/**
* Checks if a record matches the criteria from the trigger.
@@ -76,7 +72,7 @@
$context_values = array();
$form->add_field(
- 'select2',
+ 'grouped_select',
array(
'name' => 'wp_stream_trigger_connector_or_context',
'options' => $this->get_values(),
--- a/stream/alerts/class-alert-type-die.php
+++ b/stream/alerts/class-alert-type-die.php
@@ -16,17 +16,13 @@
/**
* Alert type name
- *
- * @var string
*/
- public $name = 'Die Notifier';
+ public string $name = 'Die Notifier';
/**
* Alert type slug
- *
- * @var string
*/
- public $slug = 'die';
+ public string $slug = 'die';
/**
* Triggers a script exit when an alert is triggered. Debugging use only.
@@ -38,7 +34,7 @@
*/
public function alert( $record_id, $recordarr, $options ) {
echo '<pre>';
- print_r( $recordarr ); // @codingStandardsIgnoreLine debug not loaded in production
+ print_r( $recordarr ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r -- reason: die alert type is a debug notifier and dumps the record on purpose.
echo '</pre>';
die( 'You have been notified!' );
}
--- a/stream/alerts/class-alert-type-email.php
+++ b/stream/alerts/class-alert-type-email.php
@@ -18,17 +18,13 @@
/**
* Alert type name
- *
- * @var string
*/
- public $name = 'Email';
+ public string $name = 'Email';
/**
* Alert type slug
- *
- * @var string
*/
- public $slug = 'email';
+ public string $slug = 'email';
/**
* Class Constructor
--- a/stream/alerts/class-alert-type-highlight.php
+++ b/stream/alerts/class-alert-type-highlight.php
@@ -33,17 +33,13 @@
/**
* Alert type name
- *
- * @var string
*/
- public $name = 'Highlight';
+ public string $name = 'Highlight';
/**
* Alert type slug
- *
- * @var string
*/
- public $slug = 'highlight';
+ public string $slug = 'highlight';
/**
* The single Alert ID.
@@ -53,21 +49,13 @@
public $single_alert_id;
/**
- * The Plugin
- *
- * @var Plugin
- */
- public $plugin;
-
- /**
* Class Constructor
*
* @param Plugin $plugin Plugin object.
* @return void
*/
- public function __construct( $plugin ) {
+ public function __construct( Plugin $plugin ) {
parent::__construct( $plugin );
- $this->plugin = $plugin;
if ( ! is_admin() ) {
return;
}
--- a/stream/alerts/class-alert-type-ifttt.php
+++ b/stream/alerts/class-alert-type-ifttt.php
@@ -52,17 +52,20 @@
/**
* Alert type name
- *
- * @var string
*/
- public $name = 'IFTTT';
+ public string $name = 'IFTTT';
/**
* Alert type slug
+ */
+ public string $slug = 'ifttt';
+
+ /**
+ * Hidden from the new-alert UI; existing IFTTT alerts still fire.
*
- * @var string
+ * @var bool
*/
- public $slug = 'ifttt';
+ public bool $creatable = false;
/**
* Class Constructor
@@ -226,10 +229,9 @@
*
* Defaults to 'user_login'.
*
- * @param object $alert The Alert object.
- * @param array $recordarr Array of Record data.
- *
- * @return string
+ * @param string $user_field User data field name.
+ * @param object $alert The Alert object.
+ * @param array $recordarr Array of Record data.
*/
$user_field = apply_filters( 'wp_stream_alert_ifttt_user_data_value', 'user_login', $alert, $recordarr );
$user_value = ! empty( $user->$user_field ) ? $user->$user_field : $user->user_login;
@@ -241,9 +243,9 @@
*
* Defaults to 'Y-m-d H:i:s'.
*
- * @param object $alert The Alert.
- * @param array $recordarray The Record's data.
- * @return string
+ * @param string $date_format Date format string.
+ * @param object $alert The Alert.
+ * @param array $recordarr The Record's data.
*/
$date_format = apply_filters( 'wp_stream_alert_ifttt_date_format', 'Y-m-d H:i:s', $alert, $recordarr );
$date = gmdate( $date_format, strtotime( $created ) );
@@ -274,10 +276,9 @@
/**
* Filter the first IFTTT alert value
*
- * @param string $summary The Record's summary.
- * @param object $alert The Alert.
+ * @param string $summary The Record's summary.
+ * @param object $alert The Alert.
* @param array $recordarr Array of Record data.
- * @return mixed
*/
'value1' => apply_filters( 'wp_stream_alert_ifttt_value_one', $record_data['summary'], $alert, $recordarr ),
@@ -285,20 +286,18 @@
* Filter the second IFTTT alert value
*
* @param string $user_value The user meta value requested above.
- * @param int $user_id The user ID who fired the Alert.
- * @param object $alert The Alert.
- * @param array $recordarr Array of Record data.
- * @return mixed
+ * @param int $user_id The user ID who fired the Alert.
+ * @param object $alert The Alert.
+ * @param array $recordarr Array of Record data.
*/
'value2' => apply_filters( 'wp_stream_alert_ifttt_value_two', $user_value, $user_id, $alert, $recordarr ),
/**
* Filter the third IFTTT alert value
*
- * @param string $date The Record's date.
- * @param object $alert The Alert.
+ * @param string $date The Record's date.
+ * @param object $alert The Alert.
* @param array $recordarr Array of Record data.
- * @return mixed
*/
'value3' => apply_filters( 'wp_stream_alert_ifttt_value_three', $date, $alert, $recordarr ),
)
--- a/stream/alerts/class-alert-type-menu-alert.php
+++ b/stream/alerts/class-alert-type-menu-alert.php
@@ -16,17 +16,13 @@
/**
* Alert type name
- *
- * @var string
*/
- public $name = 'Create Menu Alert';
+ public string $name = 'Create Menu Alert';
/**
* Alert type slug
- *
- * @var string
*/
- public $slug = 'menu-alert';
+ public string $slug = 'menu-alert';
/**
* Class Constructor
--- a/stream/alerts/class-alert-type-none.php
+++ b/stream/alerts/class-alert-type-none.php
@@ -15,17 +15,13 @@
class Alert_Type_None extends Alert_Type {
/**
* Notifier name
- *
- * @var string
*/
- public $name = 'Do Nothing';
+ public string $name = 'Do Nothing';
/**
* Notifier slug
- *
- * @var string
*/
- public $slug = 'none';
+ public string $slug = 'none';
/**
* Does not notify user.
--- a/stream/alerts/class-alert-type-slack.php
+++ b/stream/alerts/class-alert-type-slack.php
@@ -16,17 +16,13 @@
/**
* Alert type name
- *
- * @var string
*/
- public $name = 'Slack';
+ public string $name = 'Slack';
/**
* Alert type slug
- *
- * @var string
*/
- public $slug = 'slack';
+ public string $slug = 'slack';
/**
* Class Constructor
--- a/stream/alerts/class-alert-type-webhook.php
+++ b/stream/alerts/class-alert-type-webhook.php
@@ -0,0 +1,444 @@
+<?php
+/**
+ * Outgoing Webhook Alerts.
+ *
+ * @package WP_Stream
+ */
+
+namespace WP_Stream;
+
+/**
+ * Class Alert_Type_Webhook
+ *
+ * @package WP_Stream
+ */
+class Alert_Type_Webhook extends Alert_Type {
+
+ /**
+ * Record keys that may appear as {{field}} placeholders in the body template.
+ */
+ const PLACEHOLDER_FIELDS = array(
+ 'summary',
+ 'connector',
+ 'context',
+ 'action',
+ 'user_id',
+ 'user_role',
+ 'ip',
+ 'object_id',
+ 'blog_id',
+ 'created',
+ );
+
+ /**
+ * Allowed Content-Type header values.
+ */
+ const ALLOWED_CONTENT_TYPES = array(
+ 'application/json',
+ 'application/json; charset=utf-8',
+ 'text/plain',
+ 'application/x-www-form-urlencoded',
+ );
+
+ /**
+ * HTTP header names that must not be overridden by configuration.
+ */
+ const BLOCKED_HEADER_NAMES = array(
+ 'host',
+ 'content-length',
+ 'transfer-encoding',
+ );
+
+ /**
+ * Alert type name
+ *
+ * @var string
+ */
+ public string $name = 'Outgoing Webhook';
+
+ /**
+ * Alert type slug
+ *
+ * @var string
+ */
+ public string $slug = 'webhook';
+
+ /**
+ * Class Constructor
+ *
+ * @param Plugin $plugin Plugin object.
+ */
+ public function __construct( Plugin $plugin ) {
+ parent::__construct( $plugin );
+
+ $this->register_hooks();
+ }
+
+ /**
+ * Register hooks for the alert type.
+ *
+ * @return void
+ */
+ private function register_hooks() {
+ if ( ! is_admin() ) {
+ return;
+ }
+
+ add_filter(
+ 'wp_stream_alerts_save_meta',
+ array( $this, 'add_alert_meta' ),
+ 10,
+ 2
+ );
+ }
+
+ /**
+ * Send an HTTP request for the matching record.
+ *
+ * @param int $record_id Record that triggered notification.
+ * @param array $recordarr Record details.
+ * @param Alert $alert Alert options.
+ * @return void
+ */
+ public function alert( $record_id, $recordarr, $alert ) {
+ unset( $record_id );
+
+ $options = wp_parse_args(
+ is_object( $alert ) ? $alert->alert_meta : array(),
+ array(
+ 'url' => '',
+ 'method' => 'POST',
+ 'content_type' => 'application/json',
+ 'headers' => array(),
+ 'body_template' => '',
+ )
+ );
+
+ $url = is_string( $options['url'] ) ? trim( $options['url'] ) : '';
+ if ( '' === $url || false === wp_http_validate_url( $url ) ) {
+ return;
+ }
+
+ $method = strtoupper( (string) $options['method'] );
+ if ( ! in_array( $method, array( 'POST', 'PUT' ), true ) ) {
+ $method = 'POST';
+ }
+
+ $template = is_string( $options['body_template'] ) ? $options['body_template'] : '';
+ if ( '' === trim( $template ) ) {
+ $template = self::default_body_template();
+ }
+
+ $body = self::substitute_placeholders( $template, (array) $recordarr );
+ $headers = self::build_request_headers( $options['content_type'], $options['headers'] );
+
+ $response = wp_safe_remote_request(
+ $url,
+ array(
+ 'method' => $method,
+ 'headers' => $headers,
+ 'body' => $body,
+ 'timeout' => 15,
+ )
+ );
+
+ if ( is_wp_error( $response ) && defined( 'WP_DEBUG' ) && WP_DEBUG ) {
+ error_log( sprintf( 'Stream webhook alert request failed: %s', $response->get_error_message() ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- reason: opt-in WP_DEBUG logging of a failed outbound request.
+ }
+ }
+
+ /**
+ * Compact JSON object with placeholders for every supported record field.
+ *
+ * @return string
+ */
+ public static function default_body_template() {
+ $parts = array();
+ foreach ( self::PLACEHOLDER_FIELDS as $field ) {
+ $parts[] = '"' . $field . '":{{' . $field . '}}';
+ }
+
+ return '{' . implode( ',', $parts ) . '}';
+ }
+
+ /**
+ * Replace {{field}} tokens with JSON-encoded record values.
+ *
+ * @param string $template JSON body template.
+ * @param array $recordarr Record details.
+ * @return string
+ */
+ public static function substitute_placeholders( $template, $recordarr ) {
+ $replacements = array();
+ foreach ( self::PLACEHOLDER_FIELDS as $field ) {
+ $value = array_key_exists( $field, $recordarr ) ? $recordarr[ $field ] : '';
+ $replacements[ '{{' . $field . '}}' ] = wp_json_encode( $value );
+ }
+
+ return strtr( (string) $template, $replacements );
+ }
+
+ /**
+ * Merge Content-Type with extra header rows; drop blocked names.
+ *
+ * @param string $content_type Requested Content-Type.
+ * @param array $header_rows Stored header rows.
+ * @return array
+ */
+ public static function build_request_headers( $content_type, $header_rows ) {
+ $headers = array(
+ 'Content-Type' => self::sanitize_content_type( $content_type ),
+ );
+
+ foreach ( self::normalize_header_rows( $header_rows ) as $row ) {
+ $name = $row['name'];
+ $value = $row['value'];
+ $key = strtolower( $name );
+ if ( in_array( $key, self::BLOCKED_HEADER_NAMES, true ) ) {
+ continue;
+ }
+ if ( 'content-type' === $key ) {
+ $headers['Content-Type'] = self::sanitize_content_type( $value );
+ continue;
+ }
+ $headers[ $name ] = $value;
+ }
+
+ return $headers;
+ }
+
+ /**
+ * Restrict Content-Type to the allowlist.
+ *
+ * @param string $content_type Raw Content-Type.
+ * @return string
+ */
+ public static function sanitize_content_type( $content_type ) {
+ $normalized = strtolower( trim( (string) $content_type ) );
+ foreach ( self::ALLOWED_CONTENT_TYPES as $allowed ) {
+ if ( strtolower( $allowed ) === $normalized ) {
+ return $allowed;
+ }
+ }
+
+ return 'application/json';
+ }
+
+ /**
+ * Normalize stored or posted headers into name/value rows.
+ *
+ * @param mixed $headers Header rows, associative map, or textarea string.
+ * @return array<int, array{name: string, value: string}>
+ */
+ public static function normalize_header_rows( $headers ) {
+ if ( is_string( $headers ) ) {
+ return self::parse_header_textarea( $headers );
+ }
+
+ if ( ! is_array( $headers ) ) {
+ return array();
+ }
+
+ $rows = array();
+ foreach ( $headers as $key => $entry ) {
+ if ( is_array( $entry ) && isset( $entry['name'] ) ) {
+ $name = (string) $entry['name'];
+ $value = isset( $entry['value'] ) ? (string) $entry['value'] : '';
+ } elseif ( is_string( $key ) && ! is_numeric( $key ) ) {
+ $name = $key;
+ $value = is_scalar( $entry ) ? (string) $entry : '';
+ } else {
+ continue;
+ }
+
+ $sanitized = self::sanitize_header_pair( $name, $value );
+ if ( null !== $sanitized ) {
+ $rows[] = $sanitized;
+ }
+ }
+
+ return $rows;
+ }
+
+ /**
+ * Parse "Name: value" lines from the additional-headers field.
+ *
+ * @param string $text Textarea contents.
+ * @return array<int, array{name: string, value: string}>
+ */
+ public static function parse_header_textarea( $text ) {
+ $rows = array();
+ $lines = preg_split( '/rn|r|n/', (string) $text );
+ if ( ! is_array( $lines ) ) {
+ return array();
+ }
+
+ foreach ( $lines as $line ) {
+ $line = trim( $line );
+ if ( '' === $line || false === strpos( $line, ':' ) ) {
+ continue;
+ }
+ $parts = explode( ':', $line, 2 );
+ $sanitized = self::sanitize_header_pair( $parts[0], $parts[1] );
+ if ( null !== $sanitized ) {
+ $rows[] = $sanitized;
+ }
+ }
+
+ return $rows;
+ }
+
+ /**
+ * Sanitize one HTTP header name/value pair.
+ *
+ * @param string $name Header name.
+ * @param string $value Header value.
+ * @return array{name: string, value: string}|null
+ */
+ public static function sanitize_header_pair( $name, $value ) {
+ $name = trim( (string) $name );
+ $value = trim( str_replace( array( "r", "n" ), '', (string) $value ) );
+ if ( '' === $name || ! preg_match( '/^[A-Za-z0-9-]+$/', $name ) ) {
+ return null;
+ }
+ if ( in_array( strtolower( $name ), self::BLOCKED_HEADER_NAMES, true ) ) {
+ return null;
+ }
+
+ return array(
+ 'name' => $name,
+ 'value' => $value,
+ );
+ }
+
+ /**
+ * Display settings form for this alert type.
+ *
+ * @param Alert $alert Alert currently being worked on.
+ * @return void
+ */
+ public function display_fields( $alert ) {
+ $alert_meta = array();
+ if ( is_object( $alert ) ) {
+ $alert_meta = $alert->alert_meta;
+ }
+ $options = wp_parse_args(
+ $alert_meta,
+ array(
+ 'url' => '',
+ 'method' => 'POST',
+ 'content_type' => 'application/json',
+ 'headers' => array(),
+ 'body_template' => self::default_body_template(),
+ )
+ );
+
+ $header_text = '';
+ foreach ( self::normalize_header_rows( $options['headers'] ) as $row ) {
+ $header_text .= $row['name'] . ': ' . $row['value'] . "n";
+ }
+
+ $content_type_options = array();
+ foreach ( self::ALLOWED_CONTENT_TYPES as $type ) {
+ $content_type_options[ $type ] = $type;
+ }
+
+ $form = new Form_Generator();
+ echo '<span class="wp_stream_alert_type_description">' . esc_html__( 'Send an HTTP POST or PUT request to a URL with a JSON body.', 'stream' ) . '</span>';
+
+ echo '<label for="wp_stream_webhook_url"><span class="title">' . esc_html__( 'URL', 'stream' ) . '</span>';
+ echo '<span class="input-text-wrap">';
+ $form->render_field(
+ 'text',
+ array(
+ 'name' => 'wp_stream_webhook_url',
+ 'title' => esc_attr( __( 'URL', 'stream' ) ),
+ 'value' => $options['url'],
+ )
+ );
+ echo '</span>';
+ echo '<span class="input-text-wrap">' . esc_html__( 'Must be a valid HTTP or HTTPS URL.', 'stream' ) . '</span>';
+ echo '</label>';
+
+ echo '<label for="wp_stream_webhook_method"><span class="title">' . esc_html__( 'Method', 'stream' ) . '</span>';
+ echo '<span class="input-text-wrap">';
+ $form->render_field(
+ 'select',
+ array(
+ 'name' => 'wp_stream_webhook_method',
+ 'value' => in_array( $options['method'], array( 'POST', 'PUT' ), true ) ? $options['method'] : 'POST',
+ 'options' => array(
+ 'POST' => 'POST',
+ 'PUT' => 'PUT',
+ ),
+ )
+ );
+ echo '</span></label>';
+
+ echo '<label for="wp_stream_webhook_content_type"><span class="title">' . esc_html__( 'Content-Type', 'stream' ) . '</span>';
+ echo '<span class="input-text-wrap">';
+ $form->render_field(
+ 'select',
+ array(
+ 'name' => 'wp_stream_webhook_content_type',
+ 'value' => self::sanitize_content_type( $options['content_type'] ),
+ 'options' => $content_type_options,
+ )
+ );
+ echo '</span></label>';
+
+ echo '<label for="wp_stream_webhook_headers"><span class="title">' . esc_html__( 'Headers', 'stream' ) . '</span>';
+ echo '<span class="input-text-wrap">';
+ printf(
+ '<textarea name="wp_stream_webhook_headers" id="wp_stream_webhook_headers" rows="3" class="large-text">%s</textarea>',
+ esc_textarea( $header_text )
+ );
+ echo '</span>';
+ echo '<span class="input-text-wrap">' . esc_html__( 'Optional extra headers, one per line as Name: value. Host cannot be overridden.', 'stream' ) . '</span>';
+ echo '</label>';
+
+ echo '<label for="wp_stream_webhook_body_template"><span class="title">' . esc_html__( 'Body template', 'stream' ) . '</span>';
+ echo '<span class="input-text-wrap">';
+ printf(
+ '<textarea name="wp_stream_webhook_body_template" id="wp_stream_webhook_body_template" rows="5" class="large-text code">%s</textarea>',
+ esc_textarea( $options['body_template'] )
+ );
+ echo '</span>';
+ echo '<span class="input-text-wrap">' . esc_html__( 'JSON with {{summary}}, {{connector}}, {{context}}, {{action}}, {{user_id}}, {{user_role}}, {{ip}}, {{object_id}}, {{blog_id}}, {{created}}. Values are JSON-encoded.', 'stream' ) . '</span>';
+ echo '</label>';
+ }
+
+ /**
+ * Add webhook fields when this alert type is saved.
+ *
+ * @param array $alert_meta The metadata to be inserted for this alert.
+ * @param string $alert_type The type of alert being added or updated.
+ *
+ * @return array
+ */
+ public function add_alert_meta( $alert_meta, $alert_type ) {
+ if ( 'webhook' !== $alert_type ) {
+ return $alert_meta;
+ }
+
+ $url = wp_stream_filter_input( INPUT_POST, 'wp_stream_webhook_url' );
+ if ( ! empty( $url ) ) {
+ $alert_meta['url'] = esc_url_raw( $url );
+ }
+
+ $method = wp_stream_filter_input( INPUT_POST, 'wp_stream_webhook_method' );
+ $method = is_string( $method ) ? strtoupper( $method ) : 'POST';
+ $alert_meta['method'] = in_array( $method, array( 'POST', 'PUT' ), true ) ? $method : 'POST';
+
+ $content_type = wp_stream_filter_input( INPUT_POST, 'wp_stream_webhook_content_type' );
+ $alert_meta['content_type'] = self::sanitize_content_type( (string) $content_type );
+
+ $headers_raw = wp_stream_filter_input( INPUT_POST, 'wp_stream_webhook_headers' );
+ $alert_meta['headers'] = self::normalize_header_rows( is_string( $headers_raw ) ? $headers_raw : '' );
+
+ $body_template = wp_stream_filter_input( INPUT_POST, 'wp_stream_webhook_body_template' );
+ $alert_meta['body_template'] = is_string( $body_template ) ? $body_template : '';
+
+ return $alert_meta;
+ }
+}
--- a/stream/build/admin-exclude.asset.php
+++ b/stream/build/admin-exclude.asset.php
@@ -1 +1,6 @@
-<?php return array('dependencies' => array('jquery'), 'version' => 'e49dd106802784284396');
+<?php return array(
+ 'dependencies' => array(
+ 'jquery'
+ ),
+ 'version' => 'a28078fddce61c1ba54b'
+);
--- a/stream/build/admin.asset.php
+++ b/stream/build/admin.asset.php
@@ -1 +1,6 @@
-<?php return array('dependencies' => array('jquery'), 'version' => '5449b50c823a31ce68e5');
+<?php return array(
+ 'dependencies' => array(
+ 'jquery'
+ ),
+ 'version' => '177c8f1cf64dc8373d62'
+);
--- a/stream/build/alert-type-highlight.asset.php
+++ b/stream/build/alert-type-highlight.asset.php
@@ -1 +1,6 @@
-<?php return array('dependencies' => array('jquery'), 'version' => '8d4d6d562fe8a63e5900');
+<?php return array(
+ 'dependencies' => array(
+ 'jquery'
+ ),
+ 'version' => 'fa8379ae3ed4ca4afc0f'
+);
--- a/stream/build/alerts-list.asset.php
+++ b/stream/build/alerts-list.asset.php
@@ -1 +1,6 @@
-<?php return array('dependencies' => array('jquery'), 'version' => '73d30a33feaca0bd15d9');
+<?php return array(
+ 'dependencies' => array(
+ 'jquery'
+ ),
+ 'version' => '4c87abaa08a963cae3bc'
+);
--- a/stream/build/alerts.asset.php
+++ b/stream/build/alerts.asset.php
@@ -1 +1,6 @@
-<?php return array('dependencies' => array('jquery'), 'version' => '86ad7dfdea3b20c95239');
+<?php return array(
+ 'dependencies' => array(
+ 'jquery'
+ ),
+ 'version' => 'd5d3eb30ed44c8fe4e55'
+);
--- a/stream/build/global.asset.php
+++ b/stream/build/global.asset.php
@@ -1 +1,6 @@
-<?php return array('dependencies' => array('jquery'), 'version' => '58b4d1d0a6e59adf3eed');
+<?php return array(
+ 'dependencies' => array(
+ 'jquery'
+ ),
+ 'version' => 'c544639066c64c41d311'
+);
--- a/stream/build/live-updates.asset.php
+++ b/stream/build/live-updates.asset.php
@@ -1 +1,6 @@
-<?php return array('dependencies' => array('jquery'), 'version' => 'd737b08424e05c666a80');
+<?php return array(
+ 'dependencies' => array(
+ 'jquery'
+ ),
+ 'version' => '25a2dd5a128edf732c3a'
+);
--- a/stream/build/settings.asset.php
+++ b/stream/build/settings.asset.php
@@ -1 +1,6 @@
-<?php return array('dependencies' => array('jquery'), 'version' => 'd6bd6b1ec5e2d0300ab3');
+<?php return array(
+ 'dependencies' => array(
+ 'jquery'
+ ),
+ 'version' => 'd882ca7431fcf676d075'
+);
--- a/stream/build/wpseo-admin.asset.php
+++ b/stream/build/wpseo-admin.asset.php
@@ -1 +1,6 @@
-<?php return array('dependencies' => array('jquery'), 'version' => '9d5a3be36540ef387df2');
+<?php return array(
+ 'dependencies' => array(
+ 'jquery'
+ ),
+ 'version' => '70b468992e517397a6ca'
+);
--- a/stream/classes/class-abilities.php
+++ b/stream/classes/class-abilities.php
@@ -35,17 +35,15 @@
/**
* Holds instance of plugin object.
- *
- * @var Plugin
*/
- public $plugin;
+ public Plugin $plugin;
/**
* Registered ability objects keyed by namespaced name.
*
* @var array<string, Ability>
*/
- public $abilities = array();
+ public array $abilities = array();
/**
* Class constructor.
--- a/stream/classes/class-ability.php
+++ b/stream/classes/class-ability.php
@@ -19,10 +19,8 @@
/**
* Holds instance of plugin object.
- *
- * @var Plugin
*/
- protected $plugin;
+ protected Plugin $plugin;
/**
* Class constructor.
@@ -145,6 +143,8 @@
const SECRET_ALERT_META_KEYS = array(
'webhook',
'maker_key',
+ 'url',
+ 'headers',
);
/**
--- a/stream/classes/class-admin-ajax.php
+++ b/stream/classes/class-admin-ajax.php
@@ -0,0 +1,205 @@
+<?php
+/**
+ * Handles Stream admin Ajax endpoints.
+ *
+ * @package WP_Stream
+ */
+
+namespace WP_Stream;
+
+/**
+ * Class - Admin_Ajax
+ */
+class Admin_Ajax {
+
+ /**
+ * Admin façade.
+ *
+ * @var Admin
+ */
+ private Admin $admin;
+
+ /**
+ * Purge / erase collaborator.
+ *
+ * @var Admin_Purge
+ */
+ private Admin_Purge $purge;
+
+ /**
+ * Class constructor.
+ *
+ * @param Admin $admin Admin façade.
+ * @param Admin_Purge $purge Purge / erase collaborator.
+ */
+ public function __construct( Admin $admin, Admin_Purge $purge ) {
+ $this->admin = $admin;
+ $this->purge = $purge;
+ $this->register_hooks();
+ }
+
+ /**
+ * Register WordPress actions and filters for admin Ajax handlers.
+ */
+ private function register_hooks(): void {
+ add_action( 'wp_ajax_wp_stream_reset', array( $this, 'wp_ajax_reset' ) );
+ add_action( 'wp_ajax_wp_stream_clean_orphan_meta', array( $this, 'wp_ajax_clean_orphan_meta' ) );
+ add_action( 'wp_ajax_wp_stream_filters', array( $this, 'ajax_filters' ) );
+ add_action( 'admin_notices', array( $this, 'maybe_display_message' ) );
+ add_action( 'network_admin_notices', array( $this, 'maybe_display_message' ) );
+ }
+
+ /**
+ * Handle the reset AJAX request to reset logs.
+ *
+ * @return bool
+ */
+ public function wp_ajax_reset() {
+ check_ajax_referer( 'stream_nonce_reset', 'wp_stream_nonce_reset' );
+
+ if ( ! current_user_can( $this->admin->settings_cap ) ) {
+ wp_die(
+ esc_html__( "You don't have sufficient privileges to do this action.", 'stream' )
+ );
+ }
+
+ // Ensure the database tables exist before attempting to clear records.
+ // Install::check() short-circuits on DOING_AJAX, so call install()
+ // directly. dbDelta is idempotent and safe to run when tables already
+ // exist.
+ $this->admin->plugin->install->install( $this->admin->plugin->get_version() );
+
+ $this->purge->erase_stream_records();
+
+ if ( defined( 'WP_STREAM_TESTS' ) && WP_STREAM_TESTS ) {
+ return true;
+ }
+
+ wp_safe_redirect(
+ add_query_arg(
+ array(
+ 'page' => is_network_admin() ? $this->admin->network->network_settings_page_slug : $this->admin->settings_page_slug,
+ 'message' => 'data_erased',
+ ),
+ self_admin_url( $this->admin->admin_parent_page )
+ )
+ );
+
+ exit;
+ }
+
+ /**
+ * Ajax handler for the "Clean orphaned meta now" button on
+ * Settings → Advanced.
+ *
+ * Schedules an immediate async run of the orphan reaper. Idempotent:
+ * if a reaper is already scheduled, returns without enqueuing a second.
+ *
+ * Returns true under WP_STREAM_TESTS so PHPUnit can call this directly
+ * without exiting the worker.
+ *
+ * @return bool|void True under tests; otherwise redirects and exits.
+ */
+ public function wp_ajax_clean_orphan_meta() {
+ if ( ! current_user_can( $this->admin->settings_cap ) ) {
+ wp_die( esc_html__( 'You do not have permission to do this.', 'stream' ), 403 );
+ }
+
+ check_ajax_referer( 'stream_nonce_clean_orphan_meta', 'wp_stream_nonce_clean_orphan_meta' );
+
+ if ( empty( $this->admin->plugin->scheduler ) ) {
+ wp_die( esc_html__( 'No scheduler is available.', 'stream' ), 500 );
+ }
+
+ // Idempotency: skip enqueue when any auto-purge action is already
+ // pending or running. is_running_auto_purge() checks PENDING + RUNNING
+ // across the batch worker and the reaper, so a chain that will run its
+ // own terminal reaper is not duplicated by a manual click landing in
+ // the small CSRF/stale-URL window where the UI link is hidden.
+ if ( ! $this->purge->is_running_auto_purge() ) {
+ $this->admin->plugin->scheduler->enqueue_async( Admin::AUTO_PURGE_REAPER_ACTION, array(), Admin::AUTO_PURGE_GROUP );
+ }
+
+ if ( defined( 'WP_STREAM_TESTS' ) && WP_STREAM_TESTS ) {
+ return true;
+ }
+
+ $is_network = $this->admin->plugin->is_multisite_network_activated();
+ $page_slug = $is_network ? $this->admin->network->network_settings_page_slug : $this->admin->settings_page_slug;
+ $base_url = $is_network ? network_admin_url( $this->admin->admin_parent_page ) : admin_url( $this->admin->admin_parent_page );
+
+ wp_safe_redirect(
+ add_query_arg(
+ array(
+ 'page' => $page_slug,
+ 'wp_stream_message' => 'orphan_meta_cleanup_scheduled',
+ ),
+ $base_url
+ )
+ );
+ exit;
+ }
+
+ /**
+ * Ajax callback for return a user list.
+ *
+ * @action wp_ajax_wp_stream_filters
+ */
+ public function ajax_filters() {
+ if ( ! wp_doing_ajax() || ! current_user_can( $this->admin->settings_cap ) ) {
+ wp_die( '-1' );
+ }
+
+ check_ajax_referer( 'stream_filters_user_search_nonce', 'nonce' );
+
+ switch ( wp_stream_filter_input( INPUT_GET, 'filter' ) ) {
+ // User picker search: shared by the records filter, settings exclude
+ // rules, and alert author trigger comboboxes. See the DB user picker
+ // section for the option-source contract.
+ case 'user_id':
+ $search = wp_stream_filter_input( INPUT_GET, 'q' );
+ $search = is_string( $search ) ? $search : '';
+ $limit = max( 20, $this->admin->get_preload_users_max() );
+
+ $results = $this->admin->plugin->user_picker->search( $search, $limit );
+
+ break;
+ }
+
+ if ( isset( $results ) ) {
+ echo wp_json_encode( $results );
+ }
+
+ die();
+ }
+ /**
+ * Render confirmation notices keyed by the wp_stream_message query arg.
+ *
+ * @action admin_notices
+ * @action network_admin_notices
+ *
+ * @return void
+ */
+ public function maybe_display_message() {
+ $message = wp_stream_filter_input( INPUT_GET, 'wp_stream_message' );
+ if ( empty( $message ) ) {
+ return;
+ }
+
+ $notices = array(
+ 'orphan_meta_cleanup_scheduled' => __(
+ 'Orphaned meta cleanup scheduled. Progress is visible under Tools → Scheduled Actions.',
+ 'stream'
+ ),
+ );
+
+ if ( ! isset( $notices[ $message ] ) ) {
+ return;
+ }
+
+ printf(
+ '<div class="notice notice-success is-dismissible"><p>%s</p></div>',
+ esc_html( $notices[ $message ] )
+ );
+ }
+}
--- a/stream/classes/class-admin-assets.php
+++ b/stream/classes/class-admin-assets.php
@@ -0,0 +1,248 @@
+<?php
+/**
+ * Enqueues Stream admin assets and screen chrome.
+ *
+ * @package WP_Stream
+ */
+
+namespace WP_Stream;
+
+/**
+ * Class - Admin_Assets
+ */
+class Admin_Assets {
+
+ /**
+ * Admin façade.
+ *
+ * @var Admin
+ */
+ private Admin $admin;
+
+ /**
+ * Class constructor.
+ *
+ * @param Admin $admin Admin façade.
+ */
+ public function __construct( Admin $admin ) {
+ $this->admin = $admin;
+ $this->register_hooks();
+ }
+
+ /**
+ * Register WordPress actions and filters for admin assets.
+ */
+ private function register_hooks(): void {
+ add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
+ add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
+ add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
+ }
+
+ /**
+ * Script data shared by every screen that renders the user combobox.
+ *
+ * @return array{userSearchNonce: string, userSearchI18n: array<string, string>}
+ */
+ public function user_combobox_l10n(): array {
+ return array(
+ 'userSearchNonce' => wp_create_nonce( 'stream_filters_user_search_nonce' ),
+ 'userSearchI18n' => array(
+ 'noUsers' => __( 'No users found.', 'stream' ),
+ 'searchError' => __( 'Unable to search users.', 'stream' ),
+ 'minChars' => __( 'Type at least 2 characters to search users.', 'stream' ),
+ /* translators: %d: number of matching users */
+ 'foundSingular' => _n( '%d user found.', '%d users found.', 1, 'stream' ),
+ /* translators: %d: number of matching users */
+ 'foundPlural' => _n( '%d user found.', '%d users found.', 2, 'stream' ),
+ 'rolesHeader' => __( 'Roles', 'stream' ),
+ 'usersHeader' => __( 'Users', 'stream' ),
+ 'searchUsersHint' => __( 'Start typing to search users.', 'stream' ),
+ ),
+ );
+ }
+
+ /**
+ * Enqueue scripts/styles for admin screen
+ *
+ * @action admin_enqueue_scripts
+ *
+ * @param string $hook Current hook.
+ *
+ * @return void
+ */
+ public function admin_enqueue_scripts( $hook ) {
+ if ( in_array( $hook, $this->admin->menu->screen_id, true ) ) {
+ $this->admin->plugin->enqueue_asset(
+ 'admin',
+ array(
+ 'wp-a11y',
+ ),
+ array_merge(
+ array(
+ 'i18n' => array(
+ 'confirm_purge' => __( 'Are you sure you want to delete all Stream activity records from the database? This cannot be undone.', 'stream' ),
+ 'confirm_defaults' => __( 'Are you sure you want to reset all site settings to default? This cannot be undone.', 'stream' ),
+ ),
+ 'locale' => strtolower( substr( get_locale(), 0, 2 ) ),
+ 'gmt_offset' => get_option( 'gmt_offset' ),
+ ),
+ $this->user_combobox_l10n()
+ )
+ );
+
+ $this->admin->plugin->enqueue_asset(
+ 'admin-exclude',
+ array(
+ 'wp-a11y',
+ ),
+ array_merge(
+ array(
+ 'getActionsNonce' => wp_create_nonce( 'stream_get_actions' ),
+ ),
+ $this->user_combobox_l10n()
+ )
+ );
+
+ $current_order = isset( $_GET['order'] ) ? sanitize_key( wp_unslash( $_GET['order'] ) ) : 'desc'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- reason: list-table sort is a read-only query arg, not a state-changing request.
+ if ( ! in_array( $current_order, array( 'asc', 'desc' ), true ) ) {
+ $current_order = 'desc';
+ }
+ $current_query = map_deep( wp_unslash( $_GET ), 'sanitize_text_field' ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- reason: live-updates echo current list filters; GET is sanitized and not used to change data.
+
+ $this->admin->plugin->enqueue_asset(
+ 'live-updates',
+ array( 'heartbeat' ),
+ array(
+ 'current_screen' => $hook,
+ 'current_page' => isset( $_GET['paged'] ) ? absint( wp_unslash( $_GET['paged'] ) ) : '1', // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- reason: pagination is a read-only query arg.
+ 'current_order' => $current_order,
+ 'current_query' => wp_json_encode( $current_query ),
+ 'current_query_count' => count( $current_query ),
+ )
+ );
+ }
+
+ /**
+ * The maximum number of items that can be updated in bulk without receiving a warning.
+ *
+ * Stream watches for bulk actions performed in the WordPress Admin (such as updating
+ * many posts at once) and warns the user before proceeding if the number of items they
+ * are attempting to update exceeds this threshold value. Since Stream will try to save
+ * a log for each item, it will take longer than usual to complete the operation.
+ *
+ * The default threshold is 100 items.
+ *
+ * @param int $bulk_actions_threshold
+ */
+ $bulk_actions_threshold = apply_filters( 'wp_stream_bulk_actions_threshold', 100 );
+
+ $this->admin->plugin->enqueue_asset(
+ 'global',
+ array(),
+ array(
+ 'bulk_actions' => array(
+ 'i18n' => array(
+ /* translators: %s: a number of items (e.g. "1,742") */
+ 'confirm_action' => sprintf( __( 'Are you sure you want to perform bulk actions on over %s items? This process could take a while to complete.', 'stream' ), number_format( absint( $bulk_actions_threshold ) ) ),
+ ),
+ 'threshold' => absint( $bulk_actions_threshold ),
+ ),
+ 'plugins_screen_url' => self_admin_url( 'plugins.php#stream' ),
+ )
+ );
+ }
+
+ /**
+ * Check whether or not the current admin screen belongs to Stream
+ *
+ * @return bool
+ */
+ public function is_stream_screen() {
+ if ( ! is_admin() ) {
+ return false;
+ }
+
+ $page = wp_stream_filter_input( INPUT_GET, 'page' );
+ if ( is_string( $page ) && false !== strpos( $page, $this->admin->records_page_slug ) ) {
+ return true;
+ }
+
+ if ( is_admin() && function_exists( 'get_current_screen' ) ) {
+ $screen = get_current_screen();
+
+ return ( Alerts::POST_TYPE === $screen->post_type );
+ }
+
+ return false;
+ }
+
+ /**
+ * Add a specific body class to all Stream admin screens
+ *
+ * @param string $classes CSS classes to output to body.
+ *
+ * @filter admin_body_class
+ *
+ * @return string
+ */
+ public function admin_body_class( $classes ) {
+ $stream_classes = array();
+
+ if ( $this->is_stream_screen() ) {
+ $stream_classes[] = $this->admin->admin_body_class;
+
+ if ( isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- reason: admin body class reads the current screen slug from the URL.
+ $stream_classes[] = sanitize_key( $_GET['page'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- reason: page slug is sanitized with sanitize_key() for CSS classes only.
+ }
+ }
+
+ /**
+ * Filter the Stream admin body classes
+ *
+ * @param array $stream_classes
+ */
+ $stream_classes = apply_filters( 'wp_stream_admin_body_classes', $stream_classes );
+ $stream_classes = implode( ' ', array_map( 'trim', $stream_classes ) );
+
+ return sprintf( '%s %s ', $classes, $stream_classes );
+ }
+
+ /**
+ * Add menu styles for various WP Admin skins.
+ *
+ * @action admin_enqueue_scripts
+ */
+ public function admin_menu_css() {
+ // Make sure we're working off a clean version.
+ if ( ! file_exists( ABSPATH . WPINC . '/version.php' ) ) {
+ return;
+ }
+ include ABSPATH . WPINC . '/version.php';
+
+ if ( ! isset( $wp_version ) ) {
+ return;
+ }
+
+ $css = "
+ body.{$this->admin->admin_body_class} #wpbody-content .wrap h1:nth-child(1):before {
+ content: '';
+ display: inline-block;
+ width: 24px;
+ height: 24px;
+ margin-right: 8px;
+ vertical-align: text-bottom;
+ background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDI0IDEwMjQiIGZpbGw9ImN1cnJlbnRjb2xvciI+Cgk8cGF0aCBkPSJNOTAzLjExNSA1MTUuNDEzYy00OS4zOTIgMC05MS40NzQgMzEuMzM3LTEwNy40NiA3NS4yMDNsLTEyNC40MTEtMS41MzJjLTExLjM3Ny0uMzQ2LTIyLjc1MS0uNjg5LTM0LjEyOS0uOTk4bC0uMjQxLjU3NC0yMi40MzYtLjI3OC0uMTUzLS45Mi0xNS4wNTYtODIuOTMzLTIwLjE0Ni0xMDguNDA1LTIwLjU0NC0xMDguMzM3TDUwMy45ODIgMGwtNTMuMTQxIDQyOS4wMTMtMTYuMjE0IDEzNy45MzUtMTIuMDE2IDEwNi45MjQtMTE3LjI4Ni0yODUuMjItMTguMzUzIDIwMi44MWMtNDIuNTYyIDEuNDU0LTg1LjEyNyAyLjkzNC0xMjcuNjg4IDQuNzM4LTUzLjA5NyAyLjI5Mi0xMDYuMTg3IDQuNDczLTE1OS4yODQgNy41MzZ2NDIuMDQyYzUzLjA5NyAzLjA2IDEwNi4xODcgNS4yNDcgMTU5LjI4NCA3LjUzMyA1My4wOTMgMi4yNDUgMTA2LjE4IDQuMTk0IDE1OS4yNzMgNS45MDNsMTQuMjQuNDY1IDE3LjM1MSA0OC4zOWMxOC44NDIgNTEuODc0IDM3LjU0MiAxMDMuODA2IDU2Ljc2NSAxNTUuNTQxTDQ2Ni41MiAxMDI0bDQxLjUxMi0zMDguMjkzIDE3LjYzMy0xMzYuNjg1IDEwLjc3NiA1MC4zMjkgNTQuODE1IDI0OC41NDQgNzIuNTE2LTIxNy4yMTdoMTI5LjI2MWMxMy40OTMgNDguMTIxIDU3LjY1NSA4My40MjkgMTEwLjA3NSA4My40MjkgNjMuMTYgMCAxMTQuMzUyLTUxLjIwNSAxMTQuMzUyLTExNC4zNDggMC02My4xMzktNTEuMTg5LTExNC4zNDUtMTE0LjM0OS0xMTQuMzQ1bC4wMDQtLjAwMVoiIC8+Cjwvc3ZnPgo=');
+ }
+ #menu-posts-feedback .wp-menu-image:before {
+ font-family: dashicons !important;
+ content: '\f175';
+ }
+ #adminmenu #menu-posts-feedback div.wp-menu-image {
+ background: none !important;
+ background-repeat: no-repeat;
+ }
+ ";
+
+ wp_add_inline_style( 'wp-admin', $css );
+ }
+}
--- a/stream/classes/class-admin-menu.php
+++ b/stream/classes/class-admin-menu.php
@@ -0,0 +1,148 @@
+<?php
+/**
+ * Registers the Stream admin menu and submenu pages.
+ *
+ * @package WP_Stream
+ */
+
+namespace WP_Stream;
+
+/**
+ * Class - Admin_Menu
+ */
+class Admin_Menu {
+
+ /**
+ * Menu page screen ids keyed by page (main, settings, network_settings).
+ *
+ * @var array<string, string>
+ */
+ public array $screen_id = array();
+
+ /**
+ * Admin façade.
+ *
+ * @var Admin
+ */
+ private Admin $admin;
+
+ /**
+ * Class constructor.
+ *
+ * @param Admin $admin Admin façade.
+ */
+ public function __construct( Admin $admin ) {
+ $this->admin = $admin;
+ $this->register_hooks();
+ }
+
+ /**
+ * Register WordPress actions for the admin menu.
+ *
+ * @return void
+ */
+ private function register_hooks(): void {
+ if ( ! $this->is_site_access_disabled() ) {
+ add_action( 'admin_menu', array( $this, 'register_menu' ) );
+ }
+ }
+
+ /**
+ * Whether site-level Stream admin is disabled by network settings.
+ *
+ * On network-activated multisite, the network admin can turn off per-site
+ * access; only the network admin UI remains available when disabled.
+ *
+ * @return bool
+ */
+ private function is_site_access_disabled(): bool {
+ if ( ! $this->admin->plugin->is_multisite_network_activated() || is_network_admin() ) {
+ return false;
+ }
+
+ $options = (array) get_site_option( 'wp_stream_network', array() );
+ $option = isset( $options['general_site_access'] ) ? absint( $options['general_site_access'] ) : 1;
+
+ return ! $option;
+ }
+
+ /**
+ * Register menu page
+ *
+ * @action admin_menu
+ *
+ * @return void
+ */
+ public function register_menu() {
+ /**
+ * Filter the main admin menu title
+ *
+ * @param string $main_menu_title
+ */
+ $main_menu_title = apply_filters( 'wp_stream_admin_menu_title', esc_html__( 'Stream', 'stream' ) );
+
+ /**
+ * Filter the main admin menu position
+ *
+ * Note: Using longtail decimal string to reduce the chance of position conflicts, see Codex
+ *
+ * @param string $main_menu_position
+ */
+ $main_menu_position = apply_filters( 'wp_stream_menu_position', '2.999999' );
+
+ /**
+ * Filter the main admin page title
+ *
+ * @param string $main_page_title
+ */
+ $main_page_title = apply_filters( 'wp_stream_admin_page_title', esc_html__( 'Stream Records', 'stream' ) );
+
+ $this->screen_id['main'] = add_menu_page(
+ $main_page_title,
+ $main_menu_title,
+ $this->admin->view_cap,
+ $this->admin->records_page_slug,
+ array( $this->admin->records, 'render_list_table' ),
+ 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDI0IDEwMjQiIGZpbGw9IjAwMCI+Cgk8cGF0aCBkPSJNOTAzLjExNSA1MTUuNDEzYy00OS4zOTIgMC05MS40NzQgMzEuMzM3LTEwNy40NiA3NS4yMDNsLTEyNC40MTEtMS41MzJjLTExLjM3Ny0uMzQ2LTIyLjc1MS0uNjg5LTM0LjEyOS0uOTk4bC0uMjQxLjU3NC0yMi40MzYtLjI3OC0uMTUzLS45Mi0xNS4wNTYtODIuOTMzLTIwLjE0Ni0xMDguNDA1LTIwLjU0NC0xMDguMzM3TDUwMy45ODIgMGwtNTMuMTQxIDQyOS4wMTMtMTYuMjE0IDEzNy45MzUtMTIuMDE2IDEwNi45MjQtMTE3LjI4Ni0yODUuMjItMTguMzUzIDIwMi44MWMtNDIuNTYyIDEuNDU0LTg1LjEyNyAyLjkzNC0xMjcuNjg4IDQuNzM4LTUzLjA5NyAyLjI5Mi0xMDYuMTg3IDQuNDczLTE1OS4yODQgNy41MzZ2NDIuMDQyYzUzLjA5NyAzLjA2IDEwNi4xODcgNS4yNDcgMTU5LjI4NCA3LjUzMyA1My4wOTMgMi4yNDUgMTA2LjE4IDQuMTk0IDE1OS4yNzMgNS45MDNsMTQuMjQuNDY1IDE3LjM1MSA0OC4zOWMxOC44NDIgNTEuODc0IDM3LjU0MiAxMDMuODA2IDU2Ljc2NSAxNTUuNTQxTDQ2Ni41MiAxMDI0bDQxLjUxMi0zMDguMjkzIDE3LjYzMy0xMzYuNjg1IDEwLjc3NiA1MC4zMjkgNTQuODE1IDI0OC41NDQgNzIuNTE2LTIxNy4yMTdoMTI5LjI2MWMxMy40OTMgNDguMTIxIDU3LjY1NSA4My40MjkgMTEwLjA3NSA4My40MjkgNjMuMTYgMCAxMTQuMzUyLTUxLjIwNSAxMTQuMzUyLTExNC4zNDggMC02My4xMzktNTEuMTg5LTExNC4zNDUtMTE0LjM0OS0xMTQuMzQ1bC4wMDQtLjAwMVoiIC8+Cjwvc3ZnPgo=',
+ $main_menu_position
+ );
+
+ /**
+ * Fires before submenu items are added to the Stream menu
+ * allowing plugins to add menu items before Settings
+ */
+ do_action( 'wp_stream_admin_menu' );
+
+ /**
+ * Filter the Settings admin page title
+ *
+ * @param string $settings_page_title
+ */
+ $settings_page_title = apply_filters( 'wp_stream_settings_form_title', esc_html__( 'Stream Settings', 'stream' ) );
+
+ $this->screen_id['settings'] = add_submenu_page(
+ $this->admin->records_page_slug,
+ $settings_page_title,
+ esc_html__( 'Settings', 'stream' ),
+ $this->admin->settings_cap,
+ $this->admin->settings_page_slug,
+ array( $this->admin->settings, 'render_settings_page' )
+ );
+
+ if ( isset( $this->screen_id['main'] ) ) {
+ /**
+ * Fires just before the Stream list table is registered.
+ */
+ do_action( 'wp_stream_admin_menu_screens' );
+
+ // Register the list table early, so it associates the column headers with 'Screen settings'.
+ add_action(
+ 'load-' . $this->screen_id['main'],
+ array(
+ $this->admin->rec