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-beta.1 10.0.2 5.2.0-rc.1 10.0.3 5.2.0-rc.2 10.0.4 5.2.1 10.0.5 5.2.2 10.0.6 5.2.3 10.1.0 5.2.4 10.1.0-rc.1 5.2.5 10.1.0-rc.2 5.3.0 10.1.0-rc.3 5.3.0-beta.1 10.1.0-rc.4 5.3.0-rc.1 10.1.1 5.3.0-rc.2 10.1.2 5.3.1 10.1.3 5.3.2 10.1.4 5.3.3 10.2.0 5.4.0 10.2.0-beta.1 5.4.0-beta.1 10.2.0-beta.2 5.4.0-rc.1 10.2.0-rc.1 5.4.1 10.2.1 5.4.2 10.2.2 5.4.3 10.2.3 5.4.4 10.2.4 5.4.5 10.3.0 5.5.0 10.3.0-beta.1 5.5.0-beta.1 10.3.0-beta.2 5.5.0-rc.1 10.3.0-rc.1 5.5.0-rc.2 10.3.0-rc.2 5.5.1 10.3.1 5.5.2 10.3.2 5.5.3 10.3.3 5.5.4 10.3.4 5.5.5 10.3.5 5.6.0 10.3.6 5.6.0-beta.1 10.3.7 5.6.0-rc.1 10.3.8 5.6.0-rc.2 10.4.0 5.6.1 10.4.0-beta.1 5.6.2 10.4.0-beta.2 5.6.3 10.4.0-rc.1 5.7.0 10.4.1 5.7.0-beta.1 10.4.2 5.7.0-rc.1 10.4.3 5.7.1 10.4.4 5.7.2 10.5.0 5.7.3 10.5.0-beta.1 5.8.0 10.5.0-beta.2 5.8.0-beta.1 10.5.0-rc.1 5.8.0-beta.2 10.5.0-rc.2 5.8.0-rc.1 10.5.0-rc.3 5.8.1 10.5.1 5.8.2 10.5.2 5.9.0 10.5.3 5.9.0-beta.1 10.6.0 5.9.0-rc.1 10.6.0-beta.1 5.9.0-rc.2 10.6.0-beta.2 5.9.1 10.6.0-rc.1 5.9.2 10.6.1 6.0.0 10.6.2 6.0.0-beta.1 10.7.0 6.0.0-rc.1 10.7.0-beta.1 6.0.1 10.7.0-beta.2 6.0.2 10.7.0-rc.1 6.1.0 3.0.0 6.1.0-beta.1 3.0.1 6.1.0-rc.1 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rc.1 3.7.1 7.1.0-rc.2 3.7.2 7.1.1
woocommerce / includes / class-wc-session-handler.php
woocommerce / includes Last commit date
abstracts 1 month ago admin 3 weeks ago blocks 1 month ago cli 2 months ago customizer 6 months ago data-stores 1 month ago emails 1 month ago export 1 month ago gateways 2 months ago import 1 month ago integrations 1 month ago interfaces 6 months ago legacy 1 month ago libraries 2 months ago log-handlers 1 year ago payment-tokens 6 years ago product-usage 1 year ago queue 6 months ago react-admin 1 month ago rest-api 3 weeks ago shipping 5 months ago shortcodes 1 month ago theme-support 2 years ago tracks 2 months ago traits 5 years ago walkers 5 years ago wccom-site 2 months ago widgets 1 month ago class-wc-ajax.php 1 month ago class-wc-auth.php 2 years ago class-wc-autoloader.php 10 months ago class-wc-background-emailer.php 3 months ago class-wc-background-updater.php 6 years ago class-wc-brands-brand-settings-manager.php 1 year ago class-wc-brands-coupons.php 1 year ago class-wc-brands.php 1 month ago class-wc-breadcrumb.php 6 months ago class-wc-cache-helper.php 2 months ago class-wc-cart-fees.php 2 years ago class-wc-cart-session.php 5 months ago class-wc-cart-totals.php 1 year ago class-wc-cart.php 1 month ago class-wc-checkout.php 1 month ago class-wc-cli.php 1 year ago class-wc-comments.php 6 months ago class-wc-countries.php 3 months ago class-wc-coupon.php 3 months ago class-wc-customer-download-log.php 6 years ago class-wc-customer-download.php 2 years ago class-wc-customer.php 1 month ago class-wc-data-exception.php 8 years ago class-wc-data-store.php 3 years ago class-wc-datetime.php 4 years ago class-wc-deprecated-action-hooks.php 2 years ago class-wc-deprecated-filter-hooks.php 5 months ago class-wc-discounts.php 1 year ago class-wc-download-handler.php 1 month ago class-wc-emails.php 1 month ago class-wc-embed.php 3 weeks ago class-wc-form-handler.php 1 month ago class-wc-frontend-scripts.php 4 weeks ago class-wc-geo-ip.php 10 months ago class-wc-geolite-integration.php 6 years ago class-wc-geolocation.php 1 month ago class-wc-https.php 3 years ago class-wc-install.php 1 month ago class-wc-integrations.php 6 years ago class-wc-log-levels.php 2 years ago class-wc-logger.php 6 months ago class-wc-meta-data.php 2 months ago class-wc-order-factory.php 3 months ago class-wc-order-item-coupon.php 4 years ago class-wc-order-item-fee.php 1 month ago class-wc-order-item-meta.php 4 years ago class-wc-order-item-product.php 2 months ago class-wc-order-item-shipping.php 7 months ago class-wc-order-item-tax.php 2 months ago class-wc-order-item.php 1 month ago class-wc-order-query.php 2 months ago class-wc-order-refund.php 1 year ago class-wc-order.php 1 month ago class-wc-payment-gateways.php 1 month ago class-wc-payment-tokens.php 3 years ago class-wc-post-data.php 1 month ago class-wc-post-types.php 1 month ago class-wc-privacy-background-process.php 1 year ago class-wc-privacy-erasers.php 1 year ago class-wc-privacy-exporters.php 5 years ago class-wc-privacy.php 1 year ago class-wc-product-attribute.php 6 months ago class-wc-product-download.php 1 month ago class-wc-product-external.php 1 year ago class-wc-product-factory.php 5 months ago class-wc-product-grouped.php 1 month ago class-wc-product-query.php 6 months ago class-wc-product-simple.php 1 year ago class-wc-product-variable.php 2 months ago class-wc-product-variation.php 2 months ago class-wc-query.php 1 month ago class-wc-rate-limiter.php 4 years ago class-wc-regenerate-images-request.php 3 years ago class-wc-regenerate-images.php 1 month ago class-wc-register-wp-admin-settings.php 5 years ago class-wc-rest-authentication.php 2 years ago class-wc-rest-exception.php 5 years ago class-wc-session-handler.php 3 weeks ago class-wc-shipping-rate.php 1 year ago class-wc-shipping-zone.php 5 years ago class-wc-shipping-zones.php 9 months ago class-wc-shipping.php 1 month ago class-wc-shortcodes.php 1 year ago class-wc-structured-data.php 1 month ago class-wc-tax.php 1 month ago class-wc-template-loader.php 9 months ago class-wc-tracker.php 1 month ago class-wc-validation.php 1 month ago class-wc-webhook.php 2 months ago class-woocommerce.php 3 weeks ago wc-account-functions.php 2 months ago wc-attribute-functions.php 1 month ago wc-brands-functions.php 1 year ago wc-cart-functions.php 2 months ago wc-conditional-functions.php 1 year ago wc-core-functions.php 3 months ago wc-coupon-functions.php 7 months ago wc-deprecated-functions.php 2 months ago wc-formatting-functions.php 1 month ago wc-interactivity-api-functions.php 3 months ago wc-notice-functions.php 7 months ago wc-order-functions.php 3 months ago wc-order-item-functions.php 3 years ago wc-order-step-logger-functions.php 3 weeks ago wc-page-functions.php 1 month ago wc-product-functions.php 3 weeks ago wc-rest-functions.php 9 months ago wc-stock-functions.php 1 month ago wc-template-functions.php 2 months ago wc-template-hooks.php 1 year ago wc-term-functions.php 1 month ago wc-update-functions.php 1 month ago wc-user-functions.php 1 month ago wc-webhook-functions.php 2 months ago wc-widget-functions.php 6 years ago
class-wc-session-handler.php
771 lines
1 <?php
2 /**
3 * Handle data for the current customers session.
4 * Implements the WC_Session abstract class.
5 *
6 * From 2.5 this uses a custom table for session storage. Based on https://github.com/kloon/woocommerce-large-sessions.
7 *
8 * @class WC_Session_Handler
9 * @package WooCommerce\Classes
10 */
11
12 declare(strict_types=1);
13
14 use Automattic\Jetpack\Constants;
15 use Automattic\WooCommerce\Internal\Features\FeaturesController;
16 use Automattic\WooCommerce\Utilities\StringUtil;
17 use Automattic\WooCommerce\StoreApi\Utilities\CartTokenUtils;
18
19 defined( 'ABSPATH' ) || exit;
20
21 /**
22 * Session handler class.
23 */
24 class WC_Session_Handler extends WC_Session {
25
26 /**
27 * Cookie name used for the session.
28 *
29 * @var string cookie name
30 */
31 protected $_cookie = ''; // phpcs:ignore PSR2.Classes.PropertyDeclaration.Underscore
32
33 /**
34 * Stores session expiry.
35 *
36 * @var int session due to expire timestamp
37 */
38 protected $_session_expiring = 0; // phpcs:ignore PSR2.Classes.PropertyDeclaration.Underscore
39
40 /**
41 * Stores session due to expire timestamp.
42 *
43 * @var int session expiration timestamp
44 */
45 protected $_session_expiration = 0; // phpcs:ignore PSR2.Classes.PropertyDeclaration.Underscore
46
47 /**
48 * True when the cookie exists.
49 *
50 * @var bool Based on whether a cookie exists.
51 */
52 protected $_has_cookie = false; // phpcs:ignore PSR2.Classes.PropertyDeclaration.Underscore
53
54 /**
55 * Table name for session data.
56 *
57 * @var string Custom session table name
58 */
59 protected $_table = ''; // phpcs:ignore PSR2.Classes.PropertyDeclaration.Underscore
60
61 /**
62 * Constructor for the session class.
63 */
64 public function __construct() {
65 /**
66 * Filter the cookie name.
67 *
68 * @since 3.6.0
69 *
70 * @param string $cookie Cookie name.
71 */
72 $this->_cookie = (string) apply_filters( 'woocommerce_cookie', 'wp_woocommerce_session_' . COOKIEHASH );
73 $this->_table = $GLOBALS['wpdb']->prefix . 'woocommerce_sessions';
74 $this->set_session_expiration();
75 }
76
77 /**
78 * Init hooks and session data.
79 *
80 * @since 3.3.0
81 */
82 public function init() {
83 $this->init_hooks();
84 $this->init_session();
85 }
86
87 /**
88 * Initialize the hooks.
89 */
90 protected function init_hooks() {
91 add_action( 'woocommerce_set_cart_cookies', array( $this, 'set_customer_session_cookie' ), 10 );
92 add_action( 'wp', array( $this, 'maybe_set_customer_session_cookie' ), 99 );
93 add_action( 'template_redirect', array( $this, 'destroy_session_if_empty' ), 999 );
94 add_action( 'shutdown', array( $this, 'save_data' ), 20 );
95 add_action( 'wp_logout', array( $this, 'destroy_session' ) );
96
97 if ( ! is_user_logged_in() ) {
98 add_filter( 'nonce_user_logged_out', array( $this, 'maybe_update_nonce_user_logged_out' ), 10, 2 );
99 }
100 }
101
102 /**
103 * Initialize the session from either the request or the cookie.
104 */
105 private function init_session() {
106 if ( ! $this->init_session_from_request() ) {
107 $this->init_session_cookie();
108 }
109 }
110
111 /**
112 * Initialize the session from the query string parameter.
113 *
114 * If the current user is logged in, the token session will replace the current user's session.
115 * If the current user is logged out, the token session will be cloned to a new session.
116 *
117 * Only guest sessions are restored, hence the check for the t_ prefix on the customer ID.
118 *
119 * @return bool
120 */
121 private function init_session_from_request() {
122 $session_token = is_string( $_GET['session'] ?? '' ) ? wc_clean( wp_unslash( $_GET['session'] ?? '' ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
123
124 if ( empty( $session_token ) || ! CartTokenUtils::validate_cart_token( $session_token ) ) {
125 return false;
126 }
127
128 $payload = CartTokenUtils::get_cart_token_payload( $session_token );
129
130 if ( ! $this->is_customer_guest( $payload['user_id'] ) || ! $this->session_exists( $payload['user_id'] ) ) {
131 return false;
132 }
133
134 // Check to see if the current user has a session before proceeding with token handling.
135 $cookie = $this->get_session_cookie();
136
137 if ( $cookie ) {
138 // User owns this token. Return and use cookie session.
139 if ( $cookie[0] === $payload['user_id'] ) {
140 return false;
141 }
142
143 $cookie_session_data = (array) $this->get_session( $cookie[0], array() );
144
145 // Cookie session was originally created via this token. Return and use cookie session to prevent creating a new clone.
146 if ( isset( $cookie_session_data['previous_customer_id'] ) && $cookie_session_data['previous_customer_id'] === $payload['user_id'] ) {
147 return false;
148 }
149 }
150
151 // Generate new customer ID for the new session before cloning the data.
152 $this->_customer_id = $this->generate_customer_id();
153 $this->set_customer_session_cookie( true );
154 $this->clone_session_data( $payload['user_id'] );
155
156 return true;
157 }
158
159 /**
160 * Setup cookie and customer ID.
161 *
162 * @since 3.6.0
163 */
164 public function init_session_cookie() {
165 $cookie = $this->get_session_cookie();
166
167 if ( ! $cookie ) {
168 // If there is no cookie, generate a new session/customer ID.
169 $this->_customer_id = $this->generate_customer_id();
170 $this->_data = $this->get_session_data();
171 return;
172 }
173
174 // Customer ID will be an MD5 hash id this is a guest session.
175 $this->_customer_id = $cookie[0];
176 $this->_session_expiration = (int) $cookie[1];
177 $this->_session_expiring = (int) $cookie[2];
178 $this->_has_cookie = true;
179
180 $this->restore_session_data();
181
182 /**
183 * This clears the session if the cookie is invalid.
184 */
185 if ( ! $this->is_session_cookie_valid() ) {
186 $this->destroy_session();
187 }
188
189 // If the user logs in, update session.
190 if ( is_user_logged_in() && (string) get_current_user_id() !== $this->get_customer_id() ) {
191 $this->migrate_guest_session_to_user_session();
192 }
193
194 // Update session if its close to expiring.
195 if ( $this->is_session_expiring() ) {
196 $this->set_session_expiration();
197 $this->update_session_timestamp( $this->get_customer_id(), $this->_session_expiration );
198 }
199 }
200
201 /**
202 * Clones a session to the current session. Exclude customer details for privacy reasons.
203 *
204 * @param string $clone_from_customer_id The customer ID to clone from.
205 */
206 private function clone_session_data( string $clone_from_customer_id ) {
207 $session_data = (array) $this->get_session( $clone_from_customer_id, array() );
208 $session_data['previous_customer_id'] = $clone_from_customer_id;
209 $session_data = array_diff_key( $session_data, array( 'customer' => true ) );
210 $this->_data = $session_data;
211 $this->_dirty = true;
212 $this->save_data();
213 }
214
215 /**
216 * Migrates a guest session to the current user session.
217 */
218 private function migrate_guest_session_to_user_session() {
219 $guest_session_id = $this->_customer_id;
220 $user_session_id = (string) get_current_user_id();
221
222 $this->_data = $this->get_session( $guest_session_id, array() );
223 $this->_dirty = true;
224 $this->_customer_id = $user_session_id;
225 $this->save_data( $guest_session_id );
226
227 /**
228 * Fires after a customer has logged in, and their guest session id has been
229 * deleted with its data migrated to a customer id.
230 *
231 * This hook gives extensions the chance to connect the old session id to the
232 * customer id, if the key is being used externally.
233 *
234 * @since 8.8.0
235 *
236 * @param string $guest_session_id The former session ID, as generated by `::generate_customer_id()`.
237 * @param string $user_session_id The Customer ID that the former session was converted to.
238 */
239 do_action( 'woocommerce_guest_session_to_user_id', $guest_session_id, $user_session_id );
240
241 $this->set_session_expiration();
242 $this->update_session_timestamp( $this->get_customer_id(), $this->_session_expiration );
243 // Set cookie to user session. Otherwise next request still has guest id and the session is empty.
244 $this->set_customer_session_cookie( true );
245 }
246
247 /**
248 * Restore the session data from the database.
249 *
250 * @since 10.0.0
251 */
252 private function restore_session_data() {
253 $session_data = $this->get_session_data();
254
255 /**
256 * Filters the session data when restoring from storage during initialization.
257 *
258 * This filter allows you to:
259 * 1. Modify the session data before it's loaded, including adding or removing specific session data entries
260 * 2. Clear the entire session by returning an empty array
261 *
262 * Note: If the filtered data is empty, the session will be destroyed and the
263 * guest's session cookie will be removed. This can be useful for high-traffic
264 * sites that prioritize page caching over maintaining all session data.
265 *
266 * @since 9.9.0
267 *
268 * @param array $session_data The session data loaded from storage.
269 * @return array Modified session data to be used for initialization.
270 */
271 $this->_data = (array) apply_filters( 'woocommerce_restored_session_data', $session_data );
272 }
273
274 /**
275 * Checks if session cookie is expired, or belongs to a logged out user.
276 *
277 * @return bool Whether session cookie is valid.
278 */
279 private function is_session_cookie_valid() {
280 // If session is expired, session cookie is invalid.
281 if ( time() > $this->_session_expiration ) {
282 return false;
283 }
284
285 // If user has logged out, session cookie is invalid.
286 if ( ! is_user_logged_in() && ! $this->is_customer_guest( $this->get_customer_id() ) ) {
287 return false;
288 }
289
290 // Session from a different user is not valid. (Although from a guest user will be valid).
291 if ( is_user_logged_in() && ! $this->is_customer_guest( $this->get_customer_id() ) && (string) get_current_user_id() !== $this->get_customer_id() ) {
292 return false;
293 }
294
295 return true;
296 }
297
298 /**
299 * Hooks into the wp action to maybe set the session cookie if the user is on a certain page e.g. a checkout endpoint.
300 *
301 * Certain gateways may rely on sessions and this ensures a session is present even if the customer does not have a
302 * cart.
303 */
304 public function maybe_set_customer_session_cookie() {
305 if ( is_wc_endpoint_url( 'order-pay' ) ) {
306 $this->set_customer_session_cookie( true );
307 }
308 }
309
310 /**
311 * Hash a value for the session cookie integrity tag.
312 *
313 * @param string $message Value to hash.
314 * @return string Hashed value.
315 */
316 private function hash( string $message ) {
317 return hash_hmac( 'md5', $message, wp_hash( $message ) );
318 }
319
320 /**
321 * Verify a hash produced by self::hash().
322 *
323 * Hashes produced by the previous `wp_fast_hash()` implementation are still accepted so that guest sessions
324 * created before this change are not invalidated. That fallback can be removed in 11.1.0 forward after those cookies have expired.
325 *
326 * @param string $message Message to verify.
327 * @param string $hash Hash to verify.
328 * @return bool Whether the hash is valid.
329 */
330 private function verify_hash( string $message, string $hash ) {
331 if ( hash_equals( $this->hash( $message ), $hash ) ) {
332 return true;
333 }
334
335 // `wp_fast_hash()` prefixes its output with `$generic$`, so only those cookies take the legacy path.
336 if ( function_exists( 'wp_verify_fast_hash' ) && str_starts_with( $hash, '$generic$' ) ) {
337 return wp_verify_fast_hash( $message, $hash );
338 }
339
340 return false;
341 }
342
343 /**
344 * Sets the session cookie on-demand (usually after adding an item to the cart).
345 *
346 * Since the cookie name (as of 2.1) is prepended with wp, cache systems like batcache will not cache pages when set.
347 *
348 * Warning: Cookies will only be set if this is called before the headers are sent.
349 *
350 * @param bool $set Should the session cookie be set.
351 */
352 public function set_customer_session_cookie( $set ) {
353 if ( $set ) {
354 $cookie_hash = $this->hash( $this->get_customer_id() . '|' . (string) $this->_session_expiration );
355 $cookie_value = $this->get_customer_id() . '|' . (string) $this->_session_expiration . '|' . (string) $this->_session_expiring . '|' . $cookie_hash;
356
357 if ( ! isset( $_COOKIE[ $this->_cookie ] ) || $_COOKIE[ $this->_cookie ] !== $cookie_value ) {
358 wc_setcookie( $this->_cookie, $cookie_value, $this->_session_expiration, $this->use_secure_cookie(), true );
359 }
360
361 $this->_has_cookie = true;
362 }
363 }
364
365 /**
366 * Should the session cookie be secure?
367 *
368 * @since 3.6.0
369 * @return bool
370 */
371 protected function use_secure_cookie() {
372 /**
373 * Filter whether to use a secure cookie.
374 *
375 * @since 3.6.0
376 *
377 * @param bool $use_secure_cookie Whether to use a secure cookie.
378 */
379 return (bool) apply_filters( 'wc_session_use_secure_cookie', wc_site_is_https() && is_ssl() );
380 }
381
382 /**
383 * Return true if the current user has an active session, i.e. a cookie to retrieve values.
384 *
385 * @return bool
386 */
387 public function has_session() {
388 return isset( $_COOKIE[ $this->_cookie ] ) || $this->_has_cookie || is_user_logged_in();
389 }
390
391 /**
392 * Checks if the session is expiring.
393 *
394 * @return bool Whether session is expiring.
395 */
396 private function is_session_expiring() {
397 return time() > $this->_session_expiring;
398 }
399
400 /**
401 * Set session expiration.
402 */
403 public function set_session_expiration() {
404 $default_expiring_seconds = DAY_IN_SECONDS;
405 $default_expiration_seconds = is_user_logged_in() ? WEEK_IN_SECONDS : 2 * DAY_IN_SECONDS;
406 $max_expiration_seconds = MONTH_IN_SECONDS;
407 $max_expiring_seconds = $max_expiration_seconds - DAY_IN_SECONDS;
408 $session_limit_exceeded = false;
409
410 /**
411 * Filters the session expiration.
412 *
413 * @since 5.0.0
414 * @param int $expiration_seconds The expiration time in seconds.
415 */
416 $expiring_seconds = intval( apply_filters( 'wc_session_expiring', $default_expiring_seconds ) ) ?: $default_expiring_seconds; // phpcs:ignore Universal.Operators.DisallowShortTernary.Found
417
418 if ( $expiring_seconds > $max_expiring_seconds ) {
419 $session_limit_exceeded = true;
420 }
421 /**
422 * Filters the session expiration.
423 *
424 * @since 5.0.0
425 * @param int $expiration_seconds The expiration time in seconds.
426 */
427 $expiration_seconds = intval( apply_filters( 'wc_session_expiration', $default_expiration_seconds ) ) ?: $default_expiration_seconds; // phpcs:ignore Universal.Operators.DisallowShortTernary.Found
428
429 // We limit the expiration time to 30 days to avoid performance issues and the session table growing too large.
430 if ( $expiration_seconds > $max_expiration_seconds ) {
431 $session_limit_exceeded = true;
432 }
433
434 if ( $session_limit_exceeded ) {
435 $transient_key = 'wc_session_handler_warning';
436 if ( false === get_transient( $transient_key ) ) {
437 wc_get_logger()->warning(
438 sprintf(
439 'Keeping sessions for longer than %d days can cause performance issues and larger session tables. Monitor usage and adjust lifetimes via the wc_session_expiring and wc_session_expiration filters as needed.',
440 $max_expiration_seconds / DAY_IN_SECONDS
441 ),
442 array( 'source' => 'wc_session_handler' )
443 );
444 set_transient( $transient_key, true, $max_expiration_seconds );
445 }
446 }
447
448 // If the expiring time is greater than the expiration time, set the expiring time to 90% of the expiration time.
449 if ( $expiring_seconds > $expiration_seconds ) {
450 $expiring_seconds = $expiration_seconds * 0.9;
451 }
452
453 $this->_session_expiring = time() + $expiring_seconds;
454 $this->_session_expiration = time() + $expiration_seconds;
455 }
456
457 /**
458 * Generate a unique customer ID for guests, or return user ID if logged in.
459 *
460 * @return string
461 */
462 public function generate_customer_id() {
463 return is_user_logged_in() ? (string) get_current_user_id() : wc_rand_hash( 't_', 30 );
464 }
465
466 /**
467 * Checks if this is an auto-generated customer ID.
468 *
469 * @param string $customer_id Customer ID to check.
470 * @return bool Whether customer ID is randomly generated.
471 */
472 private function is_customer_guest( $customer_id ) {
473 return empty( $customer_id ) || 't_' === substr( $customer_id, 0, 2 );
474 }
475
476 /**
477 * Get session unique ID for requests if session is initialized or user ID if logged in.
478 * Introduced to help with unit tests.
479 *
480 * @since 5.3.0
481 * @return string
482 */
483 public function get_customer_unique_id() {
484 $customer_id = '';
485
486 if ( $this->has_session() && $this->get_customer_id() ) {
487 $customer_id = $this->get_customer_id();
488 } elseif ( is_user_logged_in() ) {
489 $customer_id = (string) get_current_user_id();
490 }
491
492 return $customer_id;
493 }
494
495 /**
496 * Get the session cookie, if set. Otherwise return false.
497 *
498 * Session cookies without a customer ID are invalid.
499 *
500 * @return bool|array
501 */
502 public function get_session_cookie() {
503 $cookie_value = isset( $_COOKIE[ $this->_cookie ] ) ? wc_clean( wp_unslash( (string) $_COOKIE[ $this->_cookie ] ) ) : '';
504
505 if ( empty( $cookie_value ) ) {
506 return false;
507 }
508
509 // Check if the cookie value contains '||' instead of '|' to support older versions of the cookie. This can be removed in WC 11.0.0.
510 if ( strpos( $cookie_value, '||' ) !== false ) {
511 $parsed_cookie = explode( '||', $cookie_value );
512 } else {
513 $parsed_cookie = explode( '|', $cookie_value );
514 }
515
516 if ( count( $parsed_cookie ) !== 4 ) {
517 return false;
518 }
519
520 list( $customer_id, $session_expiration, $session_expiring, $cookie_hash ) = $parsed_cookie;
521
522 if ( empty( $customer_id ) ) {
523 return false;
524 }
525
526 $verify_hash = $this->verify_hash( $customer_id . '|' . $session_expiration, $cookie_hash );
527
528 if ( ! $verify_hash ) {
529 return false;
530 }
531
532 return array( $customer_id, $session_expiration, $session_expiring, $cookie_hash );
533 }
534
535 /**
536 * Get session data fresh from storage.
537 *
538 * This re-reads session data from the database rather than returning
539 * in-memory data, ensuring the latest persisted state is returned.
540 *
541 * @return array
542 */
543 public function get_session_data() {
544 return $this->has_session() ? (array) $this->get_session( $this->get_customer_id(), array() ) : array();
545 }
546
547 /**
548 * Gets a cache prefix. This is used in session names so the entire cache can be invalidated with 1 function call.
549 *
550 * @return string
551 */
552 private function get_cache_prefix() {
553 return WC_Cache_Helper::get_cache_prefix( WC_SESSION_CACHE_GROUP );
554 }
555
556 /**
557 * Save data and delete guest session.
558 *
559 * @param string|mixed $old_session_key Optional session ID prior to user log-in. If $old_session_key is not tied
560 * to a user, the session will be deleted with the assumption that it was migrated
561 * to the current session being saved.
562 */
563 public function save_data( $old_session_key = '' ) {
564 // Dirty if something changed - prevents saving nothing new.
565 if ( $this->_dirty && $this->has_session() ) {
566 global $wpdb;
567
568 $wpdb->query(
569 $wpdb->prepare(
570 'INSERT INTO %i (`session_key`, `session_value`, `session_expiry`) VALUES (%s, %s, %d)
571 ON DUPLICATE KEY UPDATE `session_value` = VALUES(`session_value`), `session_expiry` = VALUES(`session_expiry`)',
572 $this->_table,
573 $this->get_customer_id(),
574 maybe_serialize( $this->_data ),
575 $this->_session_expiration
576 )
577 );
578 wp_cache_set( $this->get_cache_prefix() . $this->get_customer_id(), $this->_data, WC_SESSION_CACHE_GROUP, $this->_session_expiration - time() );
579 $this->_dirty = false;
580
581 /**
582 * Ideally, the removal of guest session data migrated to a logged-in user would occur within
583 * self::init_session_cookie() upon user login detection initially occurs. However, since some third-party
584 * extensions override this method, relocating this logic could break backward compatibility.
585 */
586 if ( ! empty( $old_session_key ) && $this->get_customer_id() !== $old_session_key && ! is_object( get_user_by( 'id', $old_session_key ) ) ) {
587 $this->delete_session( $old_session_key );
588 }
589 }
590 }
591
592 /**
593 * Destroy all session data.
594 */
595 public function destroy_session() {
596 $this->delete_session( $this->get_customer_id() );
597 $this->forget_session();
598 $this->set_session_expiration();
599 }
600
601 /**
602 * Forget all session data without destroying it.
603 */
604 public function forget_session() {
605 wc_setcookie( $this->_cookie, '', time() - YEAR_IN_SECONDS, $this->use_secure_cookie(), true );
606
607 if ( ! is_admin() ) {
608 include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
609 wc_empty_cart();
610 }
611
612 $this->_data = array();
613 $this->_dirty = false;
614 $this->_customer_id = $this->generate_customer_id();
615 $this->_has_cookie = false;
616 }
617
618 /**
619 * When a user is logged out, ensure they have a unique nonce to manage cart and more using the customer/session ID.
620 * This filter runs everything `wp_verify_nonce()` and `wp_create_nonce()` gets called.
621 *
622 * @since 5.3.0
623 * @param int $uid User ID.
624 * @param int|string $action The nonce action.
625 * @return int|string
626 */
627 public function maybe_update_nonce_user_logged_out( $uid, $action ) {
628 if ( is_string( $action ) && StringUtil::starts_with( $action, 'woocommerce' ) ) {
629 return $this->has_session() && $this->get_customer_id() ? $this->get_customer_id() : $uid;
630 }
631 return $uid;
632 }
633
634 /**
635 * Cleanup session data from the database and clear caches.
636 */
637 public function cleanup_sessions() {
638 global $wpdb;
639
640 // Batch size of 100 and sleep time of 10ms = max 100 SQL queries and 10K entries deletion per second.
641 $batch_size = 100;
642 $deleted_entries_total = 0;
643 do {
644 $deleted_entries_count = (int) $wpdb->query(
645 $wpdb->prepare(
646 'DELETE FROM %i WHERE session_expiry < %d ORDER BY session_expiry LIMIT %d',
647 $this->_table,
648 time(),
649 $batch_size
650 )
651 );
652 $deleted_entries_total += $deleted_entries_count;
653 usleep( ( 10_000 / $batch_size ) * $deleted_entries_count );
654 } while ( $deleted_entries_count === $batch_size );
655
656 if ( $deleted_entries_total > 0 && class_exists( 'WC_Cache_Helper' ) ) {
657 WC_Cache_Helper::invalidate_cache_group( WC_SESSION_CACHE_GROUP );
658 }
659 }
660
661 /**
662 * Returns the session.
663 *
664 * @param string $customer_id Customer ID.
665 * @param mixed $default_value Default session value.
666 * @return mixed Returns either the session data or the default value. Returns false if WP setup is in progress.
667 */
668 public function get_session( $customer_id, $default_value = false ) {
669 global $wpdb;
670
671 if ( Constants::is_defined( 'WP_SETUP_CONFIG' ) ) {
672 return $default_value;
673 }
674
675 // Try to get it from the cache, it will return false if not present or if object cache not in use.
676 $value = wp_cache_get( $this->get_cache_prefix() . $customer_id, WC_SESSION_CACHE_GROUP );
677
678 if ( false === $value ) {
679 $value = $wpdb->get_var( $wpdb->prepare( 'SELECT session_value FROM %i WHERE session_key = %s', $this->_table, $customer_id ) );
680
681 if ( is_null( $value ) ) {
682 $value = $default_value;
683 }
684
685 $cache_duration = $this->_session_expiration - time();
686 if ( 0 < $cache_duration ) {
687 wp_cache_add( $this->get_cache_prefix() . $customer_id, $value, WC_SESSION_CACHE_GROUP, $cache_duration );
688 }
689 }
690
691 return maybe_unserialize( $value );
692 }
693
694 /**
695 * Delete the session from the cache and database.
696 *
697 * @param string $customer_id Customer session ID.
698 */
699 public function delete_session( $customer_id ) {
700 if ( ! $customer_id ) {
701 return;
702 }
703 $GLOBALS['wpdb']->delete( $this->_table, array( 'session_key' => $customer_id ) );
704 wp_cache_delete( $this->get_cache_prefix() . $customer_id, WC_SESSION_CACHE_GROUP );
705 }
706
707 /**
708 * Update the session expiry timestamp.
709 *
710 * @param string $customer_id Customer ID.
711 * @param int $timestamp Timestamp to expire the cookie.
712 */
713 public function update_session_timestamp( $customer_id, $timestamp ) {
714 if ( ! $customer_id ) {
715 return;
716 }
717 $GLOBALS['wpdb']->update( $this->_table, array( 'session_expiry' => $timestamp ), array( 'session_key' => $customer_id ), array( '%d' ) );
718 }
719
720 /**
721 * Destroys the WooCommerce session if it contains no data for non-logged-in users.
722 *
723 * This method helps improve caching performance by removing session cookies when they
724 * are no longer needed, allowing non-logged-in customers to receive cached pages.
725 * Only runs if the destroy-empty-sessions feature is enabled.
726 *
727 * @return void
728 *
729 * @since 10.3.0
730 *
731 * @internal For exclusive usage of WooCommerce core, backwards compatibility not guaranteed.
732 */
733 public function destroy_session_if_empty() {
734 if ( is_user_logged_in() || ! $this->_has_cookie ) {
735 return;
736 }
737
738 if ( ! isset( $_COOKIE[ $this->_cookie ] ) ) {
739 // If $_COOKIE isn't set, then something triggered setting the cookie during this request. So we won't
740 // yet destroy the session if it is empty to expand compatibility at the cost of one additional request being uncached.
741 return;
742 }
743
744 if ( ! empty( $this->_data ) ) {
745 return;
746 }
747
748 if ( is_object( WC()->cart ) && ! WC()->cart->is_empty() ) {
749 // There is a pending cart to save that isn't yet in the session data.
750 return;
751 }
752
753 $feature_controller = wc_get_container()->get( FeaturesController::class );
754 if ( ! $feature_controller->feature_is_enabled( 'destroy-empty-sessions' ) ) {
755 return;
756 }
757
758 $this->destroy_session();
759 }
760
761 /**
762 * Check if a session exists in the database.
763 *
764 * @param string $customer_id Customer ID.
765 * @return bool
766 */
767 private function session_exists( $customer_id ) {
768 return $customer_id && null !== $GLOBALS['wpdb']->get_var( $GLOBALS['wpdb']->prepare( 'SELECT session_key FROM %i WHERE session_key = %s', $this->_table, $customer_id ) );
769 }
770 }
771