1: <?php
2: /**
3: * WordPress session managment.
4: *
5: * Standardizes WordPress session data using database-backed options for storage.
6: * for storing user session information.
7: *
8: * @package WordPress
9: * @subpackage Session
10: * @since 3.7.0
11: */
12:
13: // Exit if accessed directly.
14: if ( ! defined( 'ABSPATH' ) ) {
15: exit;
16: }
17:
18: /**
19: * WordPress Session class for managing user session data.
20: *
21: * @package WordPress
22: * @since 3.7.0
23: */
24: final class WP_Session extends Recursive_ArrayAccess implements Iterator, Countable {
25: /**
26: * ID of the current session.
27: *
28: * @var string
29: */
30: public $session_id;
31:
32: /**
33: * Unix timestamp when session expires.
34: *
35: * @var int
36: */
37: protected $expires;
38:
39: /**
40: * Unix timestamp indicating when the expiration time needs to be reset.
41: *
42: * @var int
43: */
44: protected $exp_variant;
45:
46: /**
47: * Singleton instance.
48: *
49: * @var bool|WP_Session
50: */
51: private static $instance = false;
52:
53: /**
54: * Retrieve the current session instance.
55: *
56: * @return bool|WP_Session
57: */
58: public static function get_instance() {
59: if ( ! self::$instance ) {
60: self::$instance = new self();
61: }
62: return self::$instance;
63: }
64:
65: /**
66: * Default constructor.
67: * Will rebuild the session collection from the given session ID if it exists. Otherwise, will
68: * create a new session with that ID.
69: *
70: * @uses apply_filters Calls `wp_session_expiration` to determine how long until sessions expire.
71: * @since 3.5.1 Uses $this->get_session_delimiter('||') to get delimiter.
72: * @since 3.5.3 Updated to return local timestamp.
73: */
74: protected function __construct() {
75: if ( isset( $_COOKIE[ WP_SESSION_COOKIE ] ) ) {
76: $cookie = stripslashes( $_COOKIE[ WP_SESSION_COOKIE ] );
77: $cookie_crumbs = explode( $this->get_session_delimiter( '||' ), $cookie );
78:
79: if ( $this->is_valid_md5( $cookie_crumbs[0] ) ) {
80: $this->session_id = $cookie_crumbs[0];
81: } else {
82: $this->regenerate_id( true );
83: }
84:
85: $this->expires = $cookie_crumbs[1];
86: $this->exp_variant = $cookie_crumbs[2];
87:
88: // Update the session expiration if we're past the variant time.
89: if ( epl_get_local_timestamp() > $this->exp_variant ) {
90: $this->set_expiration();
91: delete_option( "_wp_session_expires_{$this->session_id}" );
92: add_option( "_wp_session_expires_{$this->session_id}", $this->expires, '', 'no' );
93: }
94: } else {
95: $this->session_id = $this->generate_id();
96: $this->set_expiration();
97: }
98:
99: $this->read_data();
100:
101: $this->set_cookie();
102: }
103:
104: /**
105: * Session delimiter. Provides filter to change the default || delimiter.
106: *
107: * A notice for session might appear when we switch delimiter while already a cookie is set,
108: * That's because new delimiter tries to explode session cookies saved using old delimiter.
109: *
110: * @param string $delimiter Delimiter for the session.
111: *
112: * @since 3.5.1
113: */
114: protected function get_session_delimiter( $delimiter = '||' ) {
115: return apply_filters( 'epl_wp_session_delimiter', $delimiter );
116: }
117:
118: /**
119: * Set both the expiration time and the expiration variant.
120: *
121: * If the current time is below the variant, we don't update the session's expiration time. If it's
122: * greater than the variant, then we update the expiration time in the database. This prevents
123: * writing to the database on every page load for active sessions and only updates the expiration
124: * time if we're nearing when the session actually expires.
125: *
126: * By default, the expiration time is set to 30 minutes.
127: * By default, the expiration variant is set to 24 minutes.
128: *
129: * As a result, the session expiration time - at a maximum - will only be written to the database once
130: * every 24 minutes. After 30 minutes, the session will have been expired. No cookie will be sent by
131: * the browser, and the old session will be queued for deletion by the garbage collector.
132: *
133: * @uses apply_filters Calls `wp_session_expiration_variant` to get the max update window for session data.
134: * @uses apply_filters Calls `wp_session_expiration` to get the standard expiration time for sessions.
135: *
136: * @since 3.5.3 Updated to return local timestamp.
137: */
138: protected function set_expiration() {
139: $this->exp_variant = epl_get_local_timestamp() + (int) apply_filters( 'wp_session_expiration_variant', 24 * 60 );
140: $this->expires = epl_get_local_timestamp() + (int) apply_filters( 'wp_session_expiration', 30 * 60 );
141: }
142:
143: /**
144: * Set the session cookie
145: *
146: * @since 3.5.1 Uses $this->get_session_delimiter('||') to get delimiter.
147: */
148: protected function set_cookie() {
149: $delimiter = $this->get_session_delimiter( '||' );
150: // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
151: @setcookie( WP_SESSION_COOKIE, $this->session_id . $delimiter . $this->expires . $delimiter . $this->exp_variant, $this->expires, ( defined( 'COOKIEPATH' ) ? COOKIEPATH : '/' ), ( defined( 'COOKIE_DOMAIN' ) ? COOKIE_DOMAIN : '' ) );
152: }
153:
154: /**
155: * Generate a cryptographically strong unique ID for the session token.
156: *
157: * @return string
158: */
159: protected function generate_id() {
160: require_once ABSPATH . 'wp-includes/class-phpass.php';
161: $hasher = new PasswordHash( 8, false );
162:
163: return md5( $hasher->get_random_bytes( 32 ) );
164: }
165:
166: /**
167: * Checks if is valid md5 string
168: *
169: * @param string $md5 String.
170: * @return int
171: */
172: protected function is_valid_md5( $md5 = '' ) {
173: return preg_match( '/^[a-f0-9]{32}$/', $md5 );
174: }
175:
176: /**
177: * Read data from a transient for the current session.
178: *
179: * Automatically resets the expiration time for the session transient to some time in the future.
180: *
181: * @return array
182: */
183: protected function read_data() {
184: $this->container = get_option( "_wp_session_{$this->session_id}", array() );
185:
186: return $this->container;
187: }
188:
189: /**
190: * Write the data from the current session to the data storage system.
191: */
192: public function write_data() {
193: $option_key = "_wp_session_{$this->session_id}";
194:
195: // Only write the collection to the DB if it's changed.
196: if ( $this->dirty ) {
197: if ( false === get_option( $option_key ) ) {
198: add_option( "_wp_session_{$this->session_id}", $this->container, '', 'no' );
199: add_option( "_wp_session_expires_{$this->session_id}", $this->expires, '', 'no' );
200: } else {
201: delete_option( "_wp_session_{$this->session_id}" );
202: add_option( "_wp_session_{$this->session_id}", $this->container, '', 'no' );
203: }
204: }
205: }
206:
207: /**
208: * Output the current container contents as a JSON-encoded string.
209: *
210: * @return string
211: *
212: * @since 3.5.18 Using wp json out function.
213: */
214: public function json_out() {
215: return wp_json_encode( $this->container );
216: }
217:
218: /**
219: * Decodes a JSON string and, if the object is an array, overwrites the session container with its contents.
220: *
221: * @param string $data Data.
222: *
223: * @return bool
224: */
225: public function json_in( $data ) {
226: $array = json_decode( $data );
227:
228: if ( is_array( $array ) ) {
229: $this->container = $array;
230: return true;
231: }
232:
233: return false;
234: }
235:
236: /**
237: * Regenerate the current session's ID.
238: *
239: * @param bool $delete_old Flag whether or not to delete the old session data from the server.
240: */
241: public function regenerate_id( $delete_old = false ) {
242: if ( $delete_old ) {
243: delete_option( "_wp_session_{$this->session_id}" );
244: }
245:
246: $this->session_id = $this->generate_id();
247:
248: $this->set_cookie();
249: }
250:
251: /**
252: * Check if a session has been initialized.
253: *
254: * @return bool
255: */
256: public function session_started() {
257: return ! ! self::$instance;
258: }
259:
260: /**
261: * Return the read-only cache expiration value.
262: *
263: * @return int
264: */
265: public function cache_expiration() {
266: return $this->expires;
267: }
268:
269: /**
270: * Flushes all session variables.
271: */
272: public function reset() {
273: $this->container = array();
274: }
275:
276: // Iterator Implementation.
277:
278: /**
279: * Current position of the array.
280: *
281: * @link http://php.net/manual/en/iterator.current.php
282: *
283: * @return mixed
284: */
285: #[\ReturnTypeWillChange] // phpcs:ignore PHPCompatibility.LanguageConstructs.NewLanguageConstructs.t_ns_separatorFound
286: public function current() { // phpcs:ignore Squiz.Commenting.FunctionComment.Missing
287: return current( $this->container );
288: }
289:
290: /**
291: * Key of the current element.
292: *
293: * @link http://php.net/manual/en/iterator.key.php
294: *
295: * @return mixed
296: */
297: #[\ReturnTypeWillChange] // phpcs:ignore PHPCompatibility.LanguageConstructs.NewLanguageConstructs.t_ns_separatorFound
298: public function key() { // phpcs:ignore Squiz.Commenting.FunctionComment.Missing
299: return key( $this->container );
300: }
301:
302: /**
303: * Move the internal point of the container array to the next item
304: *
305: * @link http://php.net/manual/en/iterator.next.php
306: *
307: * @return void
308: */
309: #[\ReturnTypeWillChange] // phpcs:ignore PHPCompatibility.LanguageConstructs.NewLanguageConstructs.t_ns_separatorFound
310: public function next() { // phpcs:ignore Squiz.Commenting.FunctionComment.Missing
311: next( $this->container );
312: }
313:
314: /**
315: * Rewind the internal point of the container array.
316: *
317: * @link http://php.net/manual/en/iterator.rewind.php
318: *
319: * @return void
320: */
321: #[\ReturnTypeWillChange] // phpcs:ignore PHPCompatibility.LanguageConstructs.NewLanguageConstructs.t_ns_separatorFound
322: public function rewind() { // phpcs:ignore Squiz.Commenting.FunctionComment.Missing
323: reset( $this->container );
324: }
325:
326: /**
327: * Is the current key valid?
328: *
329: * @link http://php.net/manual/en/iterator.rewind.php
330: *
331: * @return bool
332: */
333: #[\ReturnTypeWillChange] // phpcs:ignore PHPCompatibility.LanguageConstructs.NewLanguageConstructs.t_ns_separatorFound
334: public function valid() { // phpcs:ignore Squiz.Commenting.FunctionComment.Missing
335: return $this->offsetExists( $this->key() );
336: }
337:
338: // Countable Implementation.
339:
340: /**
341: * Get the count of elements in the container array.
342: *
343: * @link http://php.net/manual/en/countable.count.php
344: *
345: * @return int
346: */
347: #[\ReturnTypeWillChange] // phpcs:ignore PHPCompatibility.LanguageConstructs.NewLanguageConstructs.t_ns_separatorFound
348: public function count() { // phpcs:ignore Squiz.Commenting.FunctionComment.Missing
349: return count( $this->container );
350: }
351: }
352: