/includes/class-wc-session-handler.php

https://github.com/crowdfavorite/woocommerce · PHP · 239 lines · 128 code · 35 blank · 76 comment · 23 complexity · 9244fb25f3f52962d857a93993ecea44 MD5 · raw file

  1. <?php
  2. if ( ! defined( 'ABSPATH' ) ) {
  3. exit;
  4. }
  5. /**
  6. * Handle data for the current customers session.
  7. * Implements the WC_Session abstract class
  8. *
  9. * Long term plan will be, if https://github.com/ericmann/wp-session-manager/ gains traction
  10. * in WP core, this will be switched out to use it and maintain backwards compatibility :)
  11. *
  12. * Partly based on WP SESSION by Eric Mann.
  13. *
  14. * @class WC_Session_Handler
  15. * @version 2.0.0
  16. * @package WooCommerce/Classes
  17. * @category Class
  18. * @author WooThemes
  19. */
  20. class WC_Session_Handler extends WC_Session {
  21. /** cookie name */
  22. private $_cookie;
  23. /** session due to expire timestamp */
  24. private $_session_expiring;
  25. /** session expiration timestamp */
  26. private $_session_expiration;
  27. /** Bool based on whether a cookie exists **/
  28. private $_has_cookie = false;
  29. /**
  30. * Constructor for the session class.
  31. */
  32. public function __construct() {
  33. $this->_cookie = 'wp_woocommerce_session_' . COOKIEHASH;
  34. if ( $cookie = $this->get_session_cookie() ) {
  35. $this->_customer_id = $cookie[0];
  36. $this->_session_expiration = $cookie[1];
  37. $this->_session_expiring = $cookie[2];
  38. $this->_has_cookie = true;
  39. // Update session if its close to expiring
  40. if ( time() > $this->_session_expiring ) {
  41. $this->set_session_expiration();
  42. $session_expiry_option = '_wc_session_expires_' . $this->_customer_id;
  43. // Check if option exists first to avoid auloading cleaned up sessions
  44. if ( false === get_option( $session_expiry_option ) ) {
  45. add_option( $session_expiry_option, $this->_session_expiration, '', 'no' );
  46. } else {
  47. update_option( $session_expiry_option, $this->_session_expiration );
  48. }
  49. }
  50. } else {
  51. $this->set_session_expiration();
  52. $this->_customer_id = $this->generate_customer_id();
  53. }
  54. $this->_data = $this->get_session_data();
  55. // Actions
  56. add_action( 'woocommerce_set_cart_cookies', array( $this, 'set_customer_session_cookie' ), 10 );
  57. add_action( 'woocommerce_cleanup_sessions', array( $this, 'cleanup_sessions' ), 10 );
  58. add_action( 'shutdown', array( $this, 'save_data' ), 20 );
  59. add_action( 'wp_logout', array( $this, 'destroy_session' ) );
  60. if ( ! is_user_logged_in() ) {
  61. add_action( 'woocommerce_thankyou', array( $this, 'destroy_session' ) );
  62. }
  63. }
  64. /**
  65. * Sets the session cookie on-demand (usually after adding an item to the cart).
  66. *
  67. * Since the cookie name (as of 2.1) is prepended with wp, cache systems like batcache will not cache pages when set.
  68. *
  69. * Warning: Cookies will only be set if this is called before the headers are sent.
  70. */
  71. public function set_customer_session_cookie( $set ) {
  72. if ( $set ) {
  73. // Set/renew our cookie
  74. $to_hash = $this->_customer_id . $this->_session_expiration;
  75. $cookie_hash = hash_hmac( 'md5', $to_hash, wp_hash( $to_hash ) );
  76. $cookie_value = $this->_customer_id . '||' . $this->_session_expiration . '||' . $this->_session_expiring . '||' . $cookie_hash;
  77. $this->_has_cookie = true;
  78. // Set the cookie
  79. wc_setcookie( $this->_cookie, $cookie_value, $this->_session_expiration, apply_filters( 'wc_session_use_secure_cookie', false ) );
  80. }
  81. }
  82. /**
  83. * Return true if the current user has an active session, i.e. a cookie to retrieve values
  84. * @return boolean
  85. */
  86. public function has_session() {
  87. return isset( $_COOKIE[ $this->_cookie ] ) || $this->_has_cookie || is_user_logged_in();
  88. }
  89. /**
  90. * set_session_expiration function.
  91. */
  92. public function set_session_expiration() {
  93. $this->_session_expiring = time() + intval( apply_filters( 'wc_session_expiring', 60 * 60 * 47 ) ); // 47 Hours
  94. $this->_session_expiration = time() + intval( apply_filters( 'wc_session_expiration', 60 * 60 * 48 ) ); // 48 Hours
  95. }
  96. /**
  97. * Generate a unique customer ID for guests, or return user ID if logged in.
  98. *
  99. * Uses Portable PHP password hashing framework to generate a unique cryptographically strong ID.
  100. *
  101. * @return int|string
  102. */
  103. public function generate_customer_id() {
  104. if ( is_user_logged_in() ) {
  105. return get_current_user_id();
  106. } else {
  107. require_once( ABSPATH . 'wp-includes/class-phpass.php');
  108. $hasher = new PasswordHash( 8, false );
  109. return md5( $hasher->get_random_bytes( 32 ) );
  110. }
  111. }
  112. /**
  113. * get_session_cookie function.
  114. *
  115. * @return bool|array
  116. */
  117. public function get_session_cookie() {
  118. if ( empty( $_COOKIE[ $this->_cookie ] ) ) {
  119. return false;
  120. }
  121. list( $customer_id, $session_expiration, $session_expiring, $cookie_hash ) = explode( '||', $_COOKIE[ $this->_cookie ] );
  122. // Validate hash
  123. $to_hash = $customer_id . $session_expiration;
  124. $hash = hash_hmac( 'md5', $to_hash, wp_hash( $to_hash ) );
  125. if ( $hash != $cookie_hash ) {
  126. return false;
  127. }
  128. return array( $customer_id, $session_expiration, $session_expiring, $cookie_hash );
  129. }
  130. /**
  131. * get_session_data function.
  132. *
  133. * @return array
  134. */
  135. public function get_session_data() {
  136. return $this->has_session() ? (array) get_option( '_wc_session_' . $this->_customer_id, array() ) : array();
  137. }
  138. /**
  139. * save_data function.
  140. */
  141. public function save_data() {
  142. // Dirty if something changed - prevents saving nothing new
  143. if ( $this->_dirty && $this->has_session() ) {
  144. $session_option = '_wc_session_' . $this->_customer_id;
  145. $session_expiry_option = '_wc_session_expires_' . $this->_customer_id;
  146. if ( false === get_option( $session_option ) ) {
  147. add_option( $session_option, $this->_data, '', 'no' );
  148. add_option( $session_expiry_option, $this->_session_expiration, '', 'no' );
  149. } else {
  150. update_option( $session_option, $this->_data );
  151. }
  152. // Mark session clean after saving
  153. $this->_dirty = false;
  154. }
  155. }
  156. /**
  157. * Destroy all session data
  158. */
  159. public function destroy_session() {
  160. // Clear cookie
  161. wc_setcookie( $this->_cookie, '', time() - YEAR_IN_SECONDS, apply_filters( 'wc_session_use_secure_cookie', false ) );
  162. // Delete session
  163. $session_option = '_wc_session_' . $this->_customer_id;
  164. $session_expiry_option = '_wc_session_expires_' . $this->_customer_id;
  165. delete_option( $session_option );
  166. delete_option( $session_expiry_option );
  167. // Clear cart
  168. wc_empty_cart();
  169. // Clear data
  170. $this->_data = array();
  171. $this->_dirty = false;
  172. $this->_customer_id = $this->generate_customer_id();
  173. }
  174. /**
  175. * cleanup_sessions function.
  176. */
  177. public function cleanup_sessions() {
  178. global $wpdb;
  179. if ( ! defined( 'WP_SETUP_CONFIG' ) && ! defined( 'WP_INSTALLING' ) ) {
  180. $now = time();
  181. $expired_sessions = array();
  182. $wc_session_expires = $wpdb->get_col( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE '\_wc\_session\_expires\_%' AND option_value < '$now'" );
  183. foreach ( $wc_session_expires as $option_name ) {
  184. $session_id = substr( $option_name, 20 );
  185. $expired_sessions[] = $option_name; // Expires key
  186. $expired_sessions[] = "_wc_session_$session_id"; // Session key
  187. }
  188. if ( ! empty( $expired_sessions ) ) {
  189. $expired_sessions_chunked = array_chunk( $expired_sessions, 100 );
  190. foreach ( $expired_sessions_chunked as $chunk ) {
  191. if ( wp_using_ext_object_cache() ) {
  192. // delete from object cache first, to avoid cached but deleted options
  193. foreach ( $chunk as $option ) {
  194. wp_cache_delete( $option, 'options' );
  195. }
  196. }
  197. // delete from options table
  198. $option_names = implode( "','", $chunk );
  199. $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name IN ('$option_names')" );
  200. }
  201. }
  202. }
  203. }
  204. }