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3.2.1 6.3.0-beta.1 3.2.2 6.3.0-rc.1 3.2.3 6.3.0-rc.2 3.2.4 6.3.1 3.2.5 6.3.2 3.2.6 6.4.0 3.3.0 6.4.0-beta.1 3.3.1 6.4.0-rc.1 3.3.2 6.4.1 3.3.2-rc.1 6.4.2 3.3.3 6.5.0 3.3.4 6.5.0-beta.1 3.3.5 6.5.0-rc.1 3.3.6 6.5.0-rc.2 3.4.0 6.5.1 3.4.0-beta.1 6.5.2 3.4.0-rc.2 6.6.0 3.4.1 6.6.0-beta.1 3.4.2 6.6.0-rc.1 3.4.3 6.6.0-rc.2 3.4.4 6.6.1 3.4.5 6.6.2 3.4.6 6.7.0 3.4.7 6.7.0-beta.1 3.4.8 6.7.0-beta.2 3.5.0 6.7.0-rc.1 3.5.0-beta.1 6.7.1 3.5.0-rc.1 6.8.0 3.5.0-rc.2 6.8.0-beta.1 3.5.1 6.8.0-beta.2 3.5.10 6.8.0-rc.1 3.5.2 6.8.1 3.5.3 6.8.2 3.5.4 6.8.3 3.5.5 6.9.0 3.5.6 6.9.0-beta.1 3.5.7 6.9.0-beta.2 3.5.8 6.9.0-rc.1 3.5.9 6.9.1 3.6.0 6.9.2 3.6.0-beta.1 6.9.3 3.6.0-rc.1 6.9.4 3.6.0-rc.2 6.9.5 3.6.0-rc.3 7.0.0 3.6.1 7.0.0-beta.1 3.6.2 7.0.0-beta.2 3.6.3 7.0.0-beta.3 3.6.4 7.0.0-rc.1 3.6.5 7.0.0-rc.2 3.6.6 7.0.1 3.6.7 7.0.2 3.7.0 7.1.0 3.7.0-beta.1 7.1.0-beta.1 3.7.0-rc.1 7.1.0-beta.2 3.7.0-rc.2 7.1.0-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 3 months ago admin 3 months ago blocks 10 months ago cli 7 months ago customizer 3 months ago data-stores 3 months ago emails 3 months ago export 1 year ago gateways 3 months ago import 3 months ago integrations 2 years ago interfaces 3 months ago legacy 3 months ago libraries 1 year ago log-handlers 1 year ago payment-tokens 5 years ago product-usage 1 year ago queue 3 months ago react-admin 3 months ago rest-api 3 months ago shipping 3 months ago shortcodes 3 months ago theme-support 2 years ago tracks 3 months ago traits 5 years ago walkers 5 years ago wccom-site 9 months ago widgets 6 months ago class-wc-ajax.php 3 months ago class-wc-auth.php 1 year ago class-wc-autoloader.php 7 months ago class-wc-background-emailer.php 5 years ago class-wc-background-updater.php 5 years ago class-wc-brands-brand-settings-manager.php 1 year ago class-wc-brands-coupons.php 1 year ago class-wc-brands.php 4 months ago class-wc-breadcrumb.php 3 months ago class-wc-cache-helper.php 7 months ago class-wc-cart-fees.php 2 years ago class-wc-cart-session.php 4 months ago class-wc-cart-totals.php 10 months ago class-wc-cart.php 3 months ago class-wc-checkout.php 3 months ago class-wc-cli.php 9 months ago class-wc-comments.php 3 months ago class-wc-countries.php 3 months ago class-wc-coupon.php 3 months ago class-wc-customer-download-log.php 5 years ago class-wc-customer-download.php 1 year ago class-wc-customer.php 3 months 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 3 years ago class-wc-discounts.php 10 months ago class-wc-download-handler.php 1 year ago class-wc-emails.php 3 months ago class-wc-embed.php 1 year ago class-wc-form-handler.php 4 months ago class-wc-frontend-scripts.php 3 months ago class-wc-geo-ip.php 7 months ago class-wc-geolite-integration.php 6 years ago class-wc-geolocation.php 3 months ago class-wc-https.php 2 years ago class-wc-install.php 3 months ago class-wc-integrations.php 5 years ago class-wc-log-levels.php 2 years ago class-wc-logger.php 3 months ago class-wc-meta-data.php 4 years ago class-wc-order-factory.php 3 months ago class-wc-order-item-coupon.php 4 years ago class-wc-order-item-fee.php 4 months ago class-wc-order-item-meta.php 4 years ago class-wc-order-item-product.php 4 months ago class-wc-order-item-shipping.php 4 months ago class-wc-order-item-tax.php 4 years ago class-wc-order-item.php 4 months ago class-wc-order-query.php 3 months ago class-wc-order-refund.php 1 year ago class-wc-order.php 3 months ago class-wc-payment-gateways.php 4 months ago class-wc-payment-tokens.php 3 years ago class-wc-post-data.php 3 months ago class-wc-post-types.php 4 months ago class-wc-privacy-background-process.php 1 year ago class-wc-privacy-erasers.php 9 months ago class-wc-privacy-exporters.php 4 years ago class-wc-privacy.php 11 months ago class-wc-product-attribute.php 3 months ago class-wc-product-download.php 3 months ago class-wc-product-external.php 1 year ago class-wc-product-factory.php 3 months ago class-wc-product-grouped.php 3 months ago class-wc-product-query.php 3 months ago class-wc-product-simple.php 10 months ago class-wc-product-variable.php 3 months ago class-wc-product-variation.php 1 year ago class-wc-query.php 3 months ago class-wc-rate-limiter.php 4 years ago class-wc-regenerate-images-request.php 3 years ago class-wc-regenerate-images.php 1 year ago class-wc-register-wp-admin-settings.php 4 years ago class-wc-rest-authentication.php 1 year ago class-wc-rest-exception.php 5 years ago class-wc-session-handler.php 7 months ago class-wc-shipping-rate.php 11 months ago class-wc-shipping-zone.php 5 years ago class-wc-shipping-zones.php 6 months ago class-wc-shipping.php 1 year ago class-wc-shortcodes.php 1 year ago class-wc-structured-data.php 3 months ago class-wc-tax.php 3 months ago class-wc-template-loader.php 6 months ago class-wc-tracker.php 7 months ago class-wc-validation.php 2 years ago class-wc-webhook.php 7 months ago class-woocommerce.php 3 months ago wc-account-functions.php 6 months ago wc-attribute-functions.php 9 months ago wc-brands-functions.php 1 year ago wc-cart-functions.php 4 months ago wc-conditional-functions.php 10 months ago wc-core-functions.php 3 months ago wc-coupon-functions.php 4 months ago wc-deprecated-functions.php 3 months ago wc-formatting-functions.php 6 months ago wc-interactivity-api-functions.php 3 months ago wc-notice-functions.php 4 months ago wc-order-functions.php 3 months ago wc-order-item-functions.php 3 years ago wc-order-step-logger-functions.php 3 months ago wc-page-functions.php 1 year ago wc-product-functions.php 3 months ago wc-rest-functions.php 6 months ago wc-stock-functions.php 6 months ago wc-template-functions.php 3 months ago wc-template-hooks.php 9 months ago wc-term-functions.php 6 months ago wc-update-functions.php 3 months ago wc-user-functions.php 6 months ago wc-webhook-functions.php 1 year ago wc-widget-functions.php 5 years ago
class-wc-session-handler.php
761 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, $this->_customer_id );
240 }
241
242 /**
243 * Restore the session data from the database.
244 *
245 * @since 10.0.0
246 */
247 private function restore_session_data() {
248 $session_data = $this->get_session_data();
249
250 /**
251 * Filters the session data when restoring from storage during initialization.
252 *
253 * This filter allows you to:
254 * 1. Modify the session data before it's loaded, including adding or removing specific session data entries
255 * 2. Clear the entire session by returning an empty array
256 *
257 * Note: If the filtered data is empty, the session will be destroyed and the
258 * guest's session cookie will be removed. This can be useful for high-traffic
259 * sites that prioritize page caching over maintaining all session data.
260 *
261 * @since 9.9.0
262 *
263 * @param array $session_data The session data loaded from storage.
264 * @return array Modified session data to be used for initialization.
265 */
266 $this->_data = (array) apply_filters( 'woocommerce_restored_session_data', $session_data );
267 }
268
269 /**
270 * Checks if session cookie is expired, or belongs to a logged out user.
271 *
272 * @return bool Whether session cookie is valid.
273 */
274 private function is_session_cookie_valid() {
275 // If session is expired, session cookie is invalid.
276 if ( time() > $this->_session_expiration ) {
277 return false;
278 }
279
280 // If user has logged out, session cookie is invalid.
281 if ( ! is_user_logged_in() && ! $this->is_customer_guest( $this->get_customer_id() ) ) {
282 return false;
283 }
284
285 // Session from a different user is not valid. (Although from a guest user will be valid).
286 if ( is_user_logged_in() && ! $this->is_customer_guest( $this->get_customer_id() ) && (string) get_current_user_id() !== $this->get_customer_id() ) {
287 return false;
288 }
289
290 return true;
291 }
292
293 /**
294 * Hooks into the wp action to maybe set the session cookie if the user is on a certain page e.g. a checkout endpoint.
295 *
296 * Certain gateways may rely on sessions and this ensures a session is present even if the customer does not have a
297 * cart.
298 */
299 public function maybe_set_customer_session_cookie() {
300 if ( is_wc_endpoint_url( 'order-pay' ) ) {
301 $this->set_customer_session_cookie( true );
302 }
303 }
304
305 /**
306 * Hash a value using wp_fast_hash (from WP 6.8 onwards).
307 *
308 * This method can be removed when the minimum version supported is 6.8.
309 *
310 * @param string $message Value to hash.
311 * @return string Hashed value.
312 */
313 private function hash( string $message ) {
314 if ( function_exists( 'wp_fast_hash' ) ) {
315 return wp_fast_hash( $message );
316 }
317 return hash_hmac( 'md5', $message, wp_hash( $message ) );
318 }
319
320 /**
321 * Verify a hash using wp_verify_fast_hash (from WP 6.8 onwards).
322 *
323 * This method can be removed when the minimum version supported is 6.8.
324 *
325 * @param string $message Message to verify.
326 * @param string $hash Hash to verify.
327 * @return bool Whether the hash is valid.
328 */
329 private function verify_hash( string $message, string $hash ) {
330 if ( function_exists( 'wp_verify_fast_hash' ) ) {
331 return wp_verify_fast_hash( $message, $hash );
332 }
333 return hash_equals( hash_hmac( 'md5', $message, wp_hash( $message ) ), $hash );
334 }
335
336 /**
337 * Sets the session cookie on-demand (usually after adding an item to the cart).
338 *
339 * Since the cookie name (as of 2.1) is prepended with wp, cache systems like batcache will not cache pages when set.
340 *
341 * Warning: Cookies will only be set if this is called before the headers are sent.
342 *
343 * @param bool $set Should the session cookie be set.
344 */
345 public function set_customer_session_cookie( $set ) {
346 if ( $set ) {
347 $cookie_hash = $this->hash( $this->get_customer_id() . '|' . (string) $this->_session_expiration );
348 $cookie_value = $this->get_customer_id() . '|' . (string) $this->_session_expiration . '|' . (string) $this->_session_expiring . '|' . $cookie_hash;
349
350 if ( ! isset( $_COOKIE[ $this->_cookie ] ) || $_COOKIE[ $this->_cookie ] !== $cookie_value ) {
351 wc_setcookie( $this->_cookie, $cookie_value, $this->_session_expiration, $this->use_secure_cookie(), true );
352 }
353
354 $this->_has_cookie = true;
355 }
356 }
357
358 /**
359 * Should the session cookie be secure?
360 *
361 * @since 3.6.0
362 * @return bool
363 */
364 protected function use_secure_cookie() {
365 /**
366 * Filter whether to use a secure cookie.
367 *
368 * @since 3.6.0
369 *
370 * @param bool $use_secure_cookie Whether to use a secure cookie.
371 */
372 return (bool) apply_filters( 'wc_session_use_secure_cookie', wc_site_is_https() && is_ssl() );
373 }
374
375 /**
376 * Return true if the current user has an active session, i.e. a cookie to retrieve values.
377 *
378 * @return bool
379 */
380 public function has_session() {
381 return isset( $_COOKIE[ $this->_cookie ] ) || $this->_has_cookie || is_user_logged_in();
382 }
383
384 /**
385 * Checks if the session is expiring.
386 *
387 * @return bool Whether session is expiring.
388 */
389 private function is_session_expiring() {
390 return time() > $this->_session_expiring;
391 }
392
393 /**
394 * Set session expiration.
395 */
396 public function set_session_expiration() {
397 $default_expiring_seconds = DAY_IN_SECONDS;
398 $default_expiration_seconds = is_user_logged_in() ? WEEK_IN_SECONDS : 2 * DAY_IN_SECONDS;
399 $max_expiration_seconds = MONTH_IN_SECONDS;
400 $max_expiring_seconds = $max_expiration_seconds - DAY_IN_SECONDS;
401 $session_limit_exceeded = false;
402
403 /**
404 * Filters the session expiration.
405 *
406 * @since 5.0.0
407 * @param int $expiration_seconds The expiration time in seconds.
408 */
409 $expiring_seconds = intval( apply_filters( 'wc_session_expiring', $default_expiring_seconds ) ) ?: $default_expiring_seconds; // phpcs:ignore Universal.Operators.DisallowShortTernary.Found
410
411 if ( $expiring_seconds > $max_expiring_seconds ) {
412 $session_limit_exceeded = true;
413 }
414 /**
415 * Filters the session expiration.
416 *
417 * @since 5.0.0
418 * @param int $expiration_seconds The expiration time in seconds.
419 */
420 $expiration_seconds = intval( apply_filters( 'wc_session_expiration', $default_expiration_seconds ) ) ?: $default_expiration_seconds; // phpcs:ignore Universal.Operators.DisallowShortTernary.Found
421
422 // We limit the expiration time to 30 days to avoid performance issues and the session table growing too large.
423 if ( $expiration_seconds > $max_expiration_seconds ) {
424 $session_limit_exceeded = true;
425 }
426
427 if ( $session_limit_exceeded ) {
428 $transient_key = 'wc_session_handler_warning';
429 if ( false === get_transient( $transient_key ) ) {
430 wc_get_logger()->warning(
431 sprintf(
432 '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.',
433 $max_expiration_seconds / DAY_IN_SECONDS
434 ),
435 array( 'source' => 'wc_session_handler' )
436 );
437 set_transient( $transient_key, true, $max_expiration_seconds );
438 }
439 }
440
441 // If the expiring time is greater than the expiration time, set the expiring time to 90% of the expiration time.
442 if ( $expiring_seconds > $expiration_seconds ) {
443 $expiring_seconds = $expiration_seconds * 0.9;
444 }
445
446 $this->_session_expiring = time() + $expiring_seconds;
447 $this->_session_expiration = time() + $expiration_seconds;
448 }
449
450 /**
451 * Generate a unique customer ID for guests, or return user ID if logged in.
452 *
453 * @return string
454 */
455 public function generate_customer_id() {
456 return is_user_logged_in() ? (string) get_current_user_id() : wc_rand_hash( 't_', 30 );
457 }
458
459 /**
460 * Checks if this is an auto-generated customer ID.
461 *
462 * @param string $customer_id Customer ID to check.
463 * @return bool Whether customer ID is randomly generated.
464 */
465 private function is_customer_guest( $customer_id ) {
466 return empty( $customer_id ) || 't_' === substr( $customer_id, 0, 2 );
467 }
468
469 /**
470 * Get session unique ID for requests if session is initialized or user ID if logged in.
471 * Introduced to help with unit tests.
472 *
473 * @since 5.3.0
474 * @return string
475 */
476 public function get_customer_unique_id() {
477 $customer_id = '';
478
479 if ( $this->has_session() && $this->get_customer_id() ) {
480 $customer_id = $this->get_customer_id();
481 } elseif ( is_user_logged_in() ) {
482 $customer_id = (string) get_current_user_id();
483 }
484
485 return $customer_id;
486 }
487
488 /**
489 * Get the session cookie, if set. Otherwise return false.
490 *
491 * Session cookies without a customer ID are invalid.
492 *
493 * @return bool|array
494 */
495 public function get_session_cookie() {
496 $cookie_value = isset( $_COOKIE[ $this->_cookie ] ) ? wc_clean( wp_unslash( (string) $_COOKIE[ $this->_cookie ] ) ) : '';
497
498 if ( empty( $cookie_value ) ) {
499 return false;
500 }
501
502 // Check if the cookie value contains '||' instead of '|' to support older versions of the cookie. This can be removed in WC 11.0.0.
503 if ( strpos( $cookie_value, '||' ) !== false ) {
504 $parsed_cookie = explode( '||', $cookie_value );
505 } else {
506 $parsed_cookie = explode( '|', $cookie_value );
507 }
508
509 if ( count( $parsed_cookie ) !== 4 ) {
510 return false;
511 }
512
513 list( $customer_id, $session_expiration, $session_expiring, $cookie_hash ) = $parsed_cookie;
514
515 if ( empty( $customer_id ) ) {
516 return false;
517 }
518
519 $verify_hash = $this->verify_hash( $customer_id . '|' . $session_expiration, $cookie_hash );
520
521 if ( ! $verify_hash ) {
522 return false;
523 }
524
525 return array( $customer_id, $session_expiration, $session_expiring, $cookie_hash );
526 }
527
528 /**
529 * Get session data.
530 *
531 * @return array
532 */
533 public function get_session_data() {
534 return $this->has_session() ? (array) $this->get_session( $this->get_customer_id(), array() ) : array();
535 }
536
537 /**
538 * Gets a cache prefix. This is used in session names so the entire cache can be invalidated with 1 function call.
539 *
540 * @return string
541 */
542 private function get_cache_prefix() {
543 return WC_Cache_Helper::get_cache_prefix( WC_SESSION_CACHE_GROUP );
544 }
545
546 /**
547 * Save data and delete guest session.
548 *
549 * @param string|mixed $old_session_key Optional session ID prior to user log-in. If $old_session_key is not tied
550 * to a user, the session will be deleted with the assumption that it was migrated
551 * to the current session being saved.
552 */
553 public function save_data( $old_session_key = '' ) {
554 // Dirty if something changed - prevents saving nothing new.
555 if ( $this->_dirty && $this->has_session() ) {
556 global $wpdb;
557
558 $wpdb->query(
559 $wpdb->prepare(
560 'INSERT INTO %i (`session_key`, `session_value`, `session_expiry`) VALUES (%s, %s, %d)
561 ON DUPLICATE KEY UPDATE `session_value` = VALUES(`session_value`), `session_expiry` = VALUES(`session_expiry`)',
562 $this->_table,
563 $this->get_customer_id(),
564 maybe_serialize( $this->_data ),
565 $this->_session_expiration
566 )
567 );
568 wp_cache_set( $this->get_cache_prefix() . $this->get_customer_id(), $this->_data, WC_SESSION_CACHE_GROUP, $this->_session_expiration - time() );
569 $this->_dirty = false;
570
571 /**
572 * Ideally, the removal of guest session data migrated to a logged-in user would occur within
573 * self::init_session_cookie() upon user login detection initially occurs. However, since some third-party
574 * extensions override this method, relocating this logic could break backward compatibility.
575 */
576 if ( ! empty( $old_session_key ) && $this->get_customer_id() !== $old_session_key && ! is_object( get_user_by( 'id', $old_session_key ) ) ) {
577 $this->delete_session( $old_session_key );
578 }
579 }
580 }
581
582 /**
583 * Destroy all session data.
584 */
585 public function destroy_session() {
586 $this->delete_session( $this->get_customer_id() );
587 $this->forget_session();
588 $this->set_session_expiration();
589 }
590
591 /**
592 * Forget all session data without destroying it.
593 */
594 public function forget_session() {
595 wc_setcookie( $this->_cookie, '', time() - YEAR_IN_SECONDS, $this->use_secure_cookie(), true );
596
597 if ( ! is_admin() ) {
598 include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
599 wc_empty_cart();
600 }
601
602 $this->_data = array();
603 $this->_dirty = false;
604 $this->_customer_id = $this->generate_customer_id();
605 $this->_has_cookie = false;
606 }
607
608 /**
609 * When a user is logged out, ensure they have a unique nonce to manage cart and more using the customer/session ID.
610 * This filter runs everything `wp_verify_nonce()` and `wp_create_nonce()` gets called.
611 *
612 * @since 5.3.0
613 * @param int $uid User ID.
614 * @param int|string $action The nonce action.
615 * @return int|string
616 */
617 public function maybe_update_nonce_user_logged_out( $uid, $action ) {
618 if ( is_string( $action ) && StringUtil::starts_with( $action, 'woocommerce' ) ) {
619 return $this->has_session() && $this->get_customer_id() ? $this->get_customer_id() : $uid;
620 }
621 return $uid;
622 }
623
624 /**
625 * Cleanup session data from the database and clear caches.
626 */
627 public function cleanup_sessions() {
628 global $wpdb;
629
630 // Batch size of 100 and sleep time of 10ms = max 100 SQL queries and 10K entries deletion per second.
631 $batch_size = 100;
632 $deleted_entries_total = 0;
633 do {
634 $deleted_entries_count = (int) $wpdb->query(
635 $wpdb->prepare(
636 'DELETE FROM %i WHERE session_expiry < %d ORDER BY session_expiry LIMIT %d',
637 $this->_table,
638 time(),
639 $batch_size
640 )
641 );
642 $deleted_entries_total += $deleted_entries_count;
643 usleep( ( 10_000 / $batch_size ) * $deleted_entries_count );
644 } while ( $deleted_entries_count === $batch_size );
645
646 if ( $deleted_entries_total > 0 && class_exists( 'WC_Cache_Helper' ) ) {
647 WC_Cache_Helper::invalidate_cache_group( WC_SESSION_CACHE_GROUP );
648 }
649 }
650
651 /**
652 * Returns the session.
653 *
654 * @param string $customer_id Customer ID.
655 * @param mixed $default_value Default session value.
656 * @return mixed Returns either the session data or the default value. Returns false if WP setup is in progress.
657 */
658 public function get_session( $customer_id, $default_value = false ) {
659 global $wpdb;
660
661 if ( Constants::is_defined( 'WP_SETUP_CONFIG' ) ) {
662 return $default_value;
663 }
664
665 // Try to get it from the cache, it will return false if not present or if object cache not in use.
666 $value = wp_cache_get( $this->get_cache_prefix() . $customer_id, WC_SESSION_CACHE_GROUP );
667
668 if ( false === $value ) {
669 $value = $wpdb->get_var( $wpdb->prepare( 'SELECT session_value FROM %i WHERE session_key = %s', $this->_table, $customer_id ) );
670
671 if ( is_null( $value ) ) {
672 $value = $default_value;
673 }
674
675 $cache_duration = $this->_session_expiration - time();
676 if ( 0 < $cache_duration ) {
677 wp_cache_add( $this->get_cache_prefix() . $customer_id, $value, WC_SESSION_CACHE_GROUP, $cache_duration );
678 }
679 }
680
681 return maybe_unserialize( $value );
682 }
683
684 /**
685 * Delete the session from the cache and database.
686 *
687 * @param string $customer_id Customer session ID.
688 */
689 public function delete_session( $customer_id ) {
690 if ( ! $customer_id ) {
691 return;
692 }
693 $GLOBALS['wpdb']->delete( $this->_table, array( 'session_key' => $customer_id ) );
694 wp_cache_delete( $this->get_cache_prefix() . $customer_id, WC_SESSION_CACHE_GROUP );
695 }
696
697 /**
698 * Update the session expiry timestamp.
699 *
700 * @param string $customer_id Customer ID.
701 * @param int $timestamp Timestamp to expire the cookie.
702 */
703 public function update_session_timestamp( $customer_id, $timestamp ) {
704 if ( ! $customer_id ) {
705 return;
706 }
707 $GLOBALS['wpdb']->update( $this->_table, array( 'session_expiry' => $timestamp ), array( 'session_key' => $customer_id ), array( '%d' ) );
708 }
709
710 /**
711 * Destroys the WooCommerce session if it contains no data for non-logged-in users.
712 *
713 * This method helps improve caching performance by removing session cookies when they
714 * are no longer needed, allowing non-logged-in customers to receive cached pages.
715 * Only runs if the destroy-empty-sessions feature is enabled.
716 *
717 * @return void
718 *
719 * @since 10.3.0
720 *
721 * @internal For exclusive usage of WooCommerce core, backwards compatibility not guaranteed.
722 */
723 public function destroy_session_if_empty() {
724 if ( is_user_logged_in() || ! $this->_has_cookie ) {
725 return;
726 }
727
728 if ( ! isset( $_COOKIE[ $this->_cookie ] ) ) {
729 // If $_COOKIE isn't set, then something triggered setting the cookie during this request. So we won't
730 // yet destroy the session if it is empty to expand compatibility at the cost of one additional request being uncached.
731 return;
732 }
733
734 if ( ! empty( $this->_data ) ) {
735 return;
736 }
737
738 if ( is_object( WC()->cart ) && ! WC()->cart->is_empty() ) {
739 // There is a pending cart to save that isn't yet in the session data.
740 return;
741 }
742
743 $feature_controller = wc_get_container()->get( FeaturesController::class );
744 if ( ! $feature_controller->feature_is_enabled( 'destroy-empty-sessions' ) ) {
745 return;
746 }
747
748 $this->destroy_session();
749 }
750
751 /**
752 * Check if a session exists in the database.
753 *
754 * @param string $customer_id Customer ID.
755 * @return bool
756 */
757 private function session_exists( $customer_id ) {
758 return $customer_id && null !== $GLOBALS['wpdb']->get_var( $GLOBALS['wpdb']->prepare( 'SELECT session_key FROM %i WHERE session_key = %s', $this->_table, $customer_id ) );
759 }
760 }
761