Storage.php
273 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Email unsubscribes Storage class file. |
| 4 | */ |
| 5 | |
| 6 | declare( strict_types = 1 ); |
| 7 | |
| 8 | namespace Automattic\WooCommerce\Internal\Email\Unsubscribes; |
| 9 | |
| 10 | /** |
| 11 | * Storage and lookup for customer "do not send me this kind of email" preferences. |
| 12 | * |
| 13 | * Generic across email types: each row pairs a SHA-256 hash of the normalized |
| 14 | * email with a free-form `email_kind` string (typically the email's `$this->id`, |
| 15 | * e.g. `customer_checkout_recovery`). Multiple emails can route through the same |
| 16 | * table without colliding. |
| 17 | * |
| 18 | * Stored in a dedicated table (`wp_wc_email_unsubscribes`) rather than user meta |
| 19 | * so guest checkouts — common for the abandoned-checkout case — can opt out |
| 20 | * without needing a WP_User record. The hash is computed from the lowercased + |
| 21 | * trimmed email so casing or whitespace variations resolve to the same row. |
| 22 | * |
| 23 | * The table is installed via `WC_Install::get_schema()`. `init()` is auto-called |
| 24 | * by the container after instantiation; it registers the GDPR personal-data |
| 25 | * eraser so the WP "Erase Personal Data" tool clears this table too. |
| 26 | * |
| 27 | * @internal Just for internal use. |
| 28 | * |
| 29 | * @since 11.0.0 |
| 30 | */ |
| 31 | class Storage { |
| 32 | |
| 33 | /** |
| 34 | * The unqualified table name (no `$wpdb->prefix`). |
| 35 | */ |
| 36 | private const TABLE = 'wc_email_unsubscribes'; |
| 37 | |
| 38 | /** |
| 39 | * Action label stored on the row. Kept as a varchar column rather than a |
| 40 | * boolean so we can add further actions (e.g. resubscribed) later without |
| 41 | * a schema migration. Today there's only one. |
| 42 | */ |
| 43 | public const ACTION_UNSUBSCRIBED = 'unsubscribed'; |
| 44 | |
| 45 | /** |
| 46 | * Shape of a valid email hash: 64 lowercase hex chars, matching the output |
| 47 | * of `hash('sha256', …)`. Shared with the public unsubscribe endpoint so |
| 48 | * the two validation sites can't drift apart. |
| 49 | */ |
| 50 | public const HASH_PATTERN = '/^[a-f0-9]{64}$/'; |
| 51 | |
| 52 | /** |
| 53 | * Register the GDPR personal-data eraser. |
| 54 | * |
| 55 | * The table itself is installed via `WC_Install::get_schema()` so it's |
| 56 | * present on every site (including the test bootstrap) regardless of |
| 57 | * whether the checkout-recovery feature flag is enabled. |
| 58 | * |
| 59 | * Auto-called by the WC dependency container after instantiation. |
| 60 | * |
| 61 | * @internal |
| 62 | */ |
| 63 | final public function init(): void { |
| 64 | add_filter( 'wp_privacy_personal_data_erasers', array( $this, 'register_personal_data_eraser' ) ); |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Database schema for the unsubscribes table. |
| 69 | * |
| 70 | * Called from `WC_Install::get_schema()` so the table is created/updated |
| 71 | * alongside the rest of WC's tables on activate/upgrade. |
| 72 | * |
| 73 | * @return string SQL CREATE TABLE statement. |
| 74 | */ |
| 75 | public function get_database_schema(): string { |
| 76 | global $wpdb; |
| 77 | $table = $this->get_table_name(); |
| 78 | $collate = $wpdb->has_cap( 'collation' ) ? $wpdb->get_charset_collate() : ''; |
| 79 | |
| 80 | return "CREATE TABLE {$table} ( |
| 81 | id bigint(20) unsigned NOT NULL AUTO_INCREMENT, |
| 82 | email_hash char(64) NOT NULL, |
| 83 | email_kind varchar(64) NOT NULL, |
| 84 | action varchar(20) NOT NULL, |
| 85 | created_at datetime NOT NULL, |
| 86 | PRIMARY KEY (id), |
| 87 | KEY email_hash_kind (email_hash, email_kind) |
| 88 | ) {$collate};"; |
| 89 | } |
| 90 | |
| 91 | /** |
| 92 | * Hash a raw email address for use as the lookup key. |
| 93 | * |
| 94 | * Normalizes (trim + strtolower) before hashing so equivalent addresses |
| 95 | * collide on the same row. Returns an empty string for empty input so |
| 96 | * callers can early-out without raising. |
| 97 | * |
| 98 | * @param string $email Raw email address. |
| 99 | * @return string 64-char hex SHA-256 hash, or '' if input was empty. |
| 100 | */ |
| 101 | public static function hash_email( string $email ): string { |
| 102 | $normalized = strtolower( trim( $email ) ); |
| 103 | if ( '' === $normalized ) { |
| 104 | return ''; |
| 105 | } |
| 106 | return hash( 'sha256', $normalized ); |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * Whether the given email is currently unsubscribed from a specific kind. |
| 111 | * |
| 112 | * @param string $email Raw email address. |
| 113 | * @param string $kind Email-kind identifier (the email class's `$this->id`). |
| 114 | * @return bool |
| 115 | */ |
| 116 | public function is_unsubscribed( string $email, string $kind ): bool { |
| 117 | $hash = self::hash_email( $email ); |
| 118 | if ( '' === $hash || '' === $kind ) { |
| 119 | return false; |
| 120 | } |
| 121 | |
| 122 | global $wpdb; |
| 123 | $table = $this->get_table_name(); |
| 124 | |
| 125 | // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name hard-coded above; values bound. |
| 126 | $action = $wpdb->get_var( |
| 127 | $wpdb->prepare( |
| 128 | "SELECT action FROM {$table} WHERE email_hash = %s AND email_kind = %s ORDER BY id DESC LIMIT 1", |
| 129 | $hash, |
| 130 | $kind |
| 131 | ) |
| 132 | ); |
| 133 | // phpcs:enable |
| 134 | |
| 135 | return self::ACTION_UNSUBSCRIBED === $action; |
| 136 | } |
| 137 | |
| 138 | /** |
| 139 | * Record an unsubscribe for the given email + kind. Idempotent — repeated |
| 140 | * calls append new rows but the lookup only cares about the most recent. |
| 141 | * |
| 142 | * @param string $email Raw email address. |
| 143 | * @param string $kind Email-kind identifier. |
| 144 | * @return bool True if a row was written, false if input was empty. |
| 145 | */ |
| 146 | public function mark_unsubscribed( string $email, string $kind ): bool { |
| 147 | return $this->record_action( self::hash_email( $email ), $kind, self::ACTION_UNSUBSCRIBED ); |
| 148 | } |
| 149 | |
| 150 | /** |
| 151 | * Record an unsubscribe directly by SHA-256 hash, for callers (e.g. the |
| 152 | * public unsubscribe endpoint) that operate on the hash already and never |
| 153 | * need to handle the raw email. |
| 154 | * |
| 155 | * Validates the hash matches `HASH_PATTERN` as defense in depth — the |
| 156 | * Endpoint already shape-checks the URL value, but any future caller that |
| 157 | * forgets to would otherwise insert a junk row. |
| 158 | * |
| 159 | * @param string $hash SHA-256 hex digest of the normalized email. |
| 160 | * @param string $kind Email-kind identifier. |
| 161 | * @return bool True if a row was written. |
| 162 | */ |
| 163 | public function mark_unsubscribed_by_hash( string $hash, string $kind ): bool { |
| 164 | if ( 1 !== preg_match( self::HASH_PATTERN, $hash ) ) { |
| 165 | return false; |
| 166 | } |
| 167 | return $this->record_action( $hash, $kind, self::ACTION_UNSUBSCRIBED ); |
| 168 | } |
| 169 | |
| 170 | /** |
| 171 | * Remove all rows (across every kind) for an email — used by the GDPR |
| 172 | * personal-data eraser so a customer's "right to be forgotten" request |
| 173 | * clears their opt-out record along with the rest of their data. |
| 174 | * |
| 175 | * @param string $email Raw email address. |
| 176 | * @return int Number of rows deleted. |
| 177 | */ |
| 178 | public function erase_for_email( string $email ): int { |
| 179 | $hash = self::hash_email( $email ); |
| 180 | if ( '' === $hash ) { |
| 181 | return 0; |
| 182 | } |
| 183 | |
| 184 | global $wpdb; |
| 185 | $table = $this->get_table_name(); |
| 186 | |
| 187 | // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name hard-coded; hash bound. |
| 188 | $deleted = $wpdb->query( |
| 189 | $wpdb->prepare( |
| 190 | "DELETE FROM {$table} WHERE email_hash = %s", |
| 191 | $hash |
| 192 | ) |
| 193 | ); |
| 194 | // phpcs:enable |
| 195 | |
| 196 | return is_numeric( $deleted ) ? (int) $deleted : 0; |
| 197 | } |
| 198 | |
| 199 | /** |
| 200 | * Filter callback that adds this repository's eraser to WP's GDPR registry. |
| 201 | * |
| 202 | * @internal |
| 203 | * |
| 204 | * @param array<string, array{eraser_friendly_name: string, callback: callable}> $erasers Existing erasers. |
| 205 | * @return array<string, array{eraser_friendly_name: string, callback: callable}> |
| 206 | */ |
| 207 | public function register_personal_data_eraser( array $erasers ): array { |
| 208 | $erasers['wc-email-unsubscribes'] = array( |
| 209 | 'eraser_friendly_name' => __( 'WooCommerce Email Unsubscribes', 'woocommerce' ), |
| 210 | 'callback' => array( $this, 'handle_personal_data_erasure' ), |
| 211 | ); |
| 212 | return $erasers; |
| 213 | } |
| 214 | |
| 215 | /** |
| 216 | * Callback for the WP personal-data eraser. |
| 217 | * |
| 218 | * @internal |
| 219 | * |
| 220 | * @param string $email Email address being erased. |
| 221 | * @return array{items_removed: bool, items_retained: bool, messages: string[], done: bool} |
| 222 | */ |
| 223 | public function handle_personal_data_erasure( string $email ): array { |
| 224 | $removed = $this->erase_for_email( $email ) > 0; |
| 225 | |
| 226 | return array( |
| 227 | 'items_removed' => $removed, |
| 228 | 'items_retained' => false, |
| 229 | 'messages' => array(), |
| 230 | 'done' => true, |
| 231 | ); |
| 232 | } |
| 233 | |
| 234 | /** |
| 235 | * Append an action row. |
| 236 | * |
| 237 | * @param string $hash SHA-256 hex digest of the normalized email. |
| 238 | * @param string $kind Email-kind identifier. |
| 239 | * @param string $action `unsubscribed` or `resubscribed`. |
| 240 | * @return bool |
| 241 | */ |
| 242 | private function record_action( string $hash, string $kind, string $action ): bool { |
| 243 | if ( '' === $hash || '' === $kind ) { |
| 244 | return false; |
| 245 | } |
| 246 | |
| 247 | global $wpdb; |
| 248 | |
| 249 | // phpcs:disable WordPress.DB.DirectDatabaseQuery -- write to an internal preference table. |
| 250 | $inserted = $wpdb->insert( |
| 251 | $this->get_table_name(), |
| 252 | array( |
| 253 | 'email_hash' => $hash, |
| 254 | 'email_kind' => $kind, |
| 255 | 'action' => $action, |
| 256 | 'created_at' => current_time( 'mysql', true ), |
| 257 | ), |
| 258 | array( '%s', '%s', '%s', '%s' ) |
| 259 | ); |
| 260 | // phpcs:enable |
| 261 | |
| 262 | return false !== $inserted; |
| 263 | } |
| 264 | |
| 265 | /** |
| 266 | * Fully-qualified table name including the wpdb prefix. |
| 267 | */ |
| 268 | private function get_table_name(): string { |
| 269 | global $wpdb; |
| 270 | return $wpdb->prefix . self::TABLE; |
| 271 | } |
| 272 | } |
| 273 |