Passed
Pull Request — master (#217)
by Patrik
03:45
created

WPInv_Session_Handler::get_session_cookie()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
nc 8
nop 0
dl 0
loc 23
rs 8.6186
c 0
b 0
f 0
1
<?php
2
/**
3
 * Handle data for the current customers session.
4
 * Implements the WPInv_Session abstract class.
5
 *
6
 */
7
8
defined( 'ABSPATH' ) || exit;
9
10
/**
11
 * Session handler class.
12
 */
13
class WPInv_Session_Handler extends WPInv_Session {
14
15
	/**
16
	 * Cookie name used for the session.
17
	 *
18
	 * @var string cookie name
19
	 */
20
	protected $_cookie;
21
22
	/**
23
	 * Stores session expiry.
24
	 *
25
	 * @var int session due to expire timestamp
26
	 */
27
	protected $_session_expiring;
28
29
	/**
30
	 * Stores session due to expire timestamp.
31
	 *
32
	 * @var string session expiration timestamp
33
	 */
34
	protected $_session_expiration;
35
36
	/**
37
	 * True when the cookie exists.
38
	 *
39
	 * @var bool Based on whether a cookie exists.
40
	 */
41
	protected $_has_cookie = false;
42
43
	/**
44
	 * Table name for session data.
45
	 *
46
	 * @var string Custom session table name
47
	 */
48
	protected $_table;
49
50
	/**
51
	 * Constructor for the session class.
52
	 */
53
	public function __construct() {
54
55
	    $this->_cookie = apply_filters( 'wpinv_cookie', 'wpinv_session_' . COOKIEHASH );
56
        add_action( 'init', array( $this, 'init' ), -1 );
57
		add_action( 'wp_logout', array( $this, 'destroy_session' ) );
58
		add_action( 'wp', array( $this, 'set_customer_session_cookie' ), 10 );
59
		add_action( 'shutdown', array( $this, 'save_data' ), 20 );
60
	}
61
62
	/**
63
	 * Init hooks and session data.
64
	 *
65
	 * @since 3.3.0
66
	 */
67
	public function init() {
68
		$this->init_session_cookie();
69
70
		if ( ! is_user_logged_in() ) {
71
			add_filter( 'nonce_user_logged_out', array( $this, 'nonce_user_logged_out' ) );
72
		}
73
	}
74
75
	/**
76
	 * Setup cookie and customer ID.
77
	 *
78
	 * @since 3.6.0
79
	 */
80
	public function init_session_cookie() {
81
		$cookie = $this->get_session_cookie();
82
83
		if ( $cookie ) {
84
			$this->_customer_id        = $cookie[0];
85
			$this->_session_expiration = $cookie[1];
86
			$this->_session_expiring   = $cookie[2];
87
			$this->_has_cookie         = true;
88
			$this->_data               = $this->get_session_data();
89
90
			// If the user logs in, update session.
91
			if ( is_user_logged_in() && get_current_user_id() != $this->_customer_id ) {
92
				$this->_customer_id = get_current_user_id();
93
				$this->_dirty       = true;
94
				$this->save_data();
95
				$this->set_customer_session_cookie( true );
96
			}
97
98
			// Update session if its close to expiring.
99
			if ( time() > $this->_session_expiring ) {
100
				$this->set_session_expiration();
101
				$this->update_session_timestamp( $this->_customer_id, $this->_session_expiration );
102
			}
103
		} else {
104
			$this->set_session_expiration();
105
			$this->_customer_id = $this->generate_customer_id();
0 ignored issues
show
Documentation Bug introduced by
The property $_customer_id was declared of type integer, but $this->generate_customer_id() is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
106
			$this->_data        = $this->get_session_data();
107
		}
108
	}
109
110
	/**
111
	 * Sets the session cookie on-demand (usually after adding an item to the cart).
112
	 *
113
	 * Since the cookie name (as of 2.1) is prepended with wp, cache systems like batcache will not cache pages when set.
114
	 *
115
	 * Warning: Cookies will only be set if this is called before the headers are sent.
116
	 *
117
	 * @param bool $set Should the session cookie be set.
118
	 */
119
	public function set_customer_session_cookie( $set ) {
120
		if ( $set ) {
121
			$to_hash           = $this->_customer_id . '|' . $this->_session_expiration;
122
			$cookie_hash       = hash_hmac( 'md5', $to_hash, wp_hash( $to_hash ) );
123
			$cookie_value      = $this->_customer_id . '||' . $this->_session_expiration . '||' . $this->_session_expiring . '||' . $cookie_hash;
124
			$this->_has_cookie = true;
125
126
			if ( ! isset( $_COOKIE[ $this->_cookie ] ) || $_COOKIE[ $this->_cookie ] !== $cookie_value ) {
127
				$this->setcookie( $this->_cookie, $cookie_value, $this->_session_expiration, $this->use_secure_cookie(), true );
128
			}
129
		}
130
	}
131
132
	public function setcookie($name, $value, $expire = 0, $secure = false, $httponly = false){
133
        if ( ! headers_sent() ) {
134
            setcookie( $name, $value, $expire, COOKIEPATH ? COOKIEPATH : '/', COOKIE_DOMAIN, $secure, apply_filters( 'wpinv_cookie_httponly', $httponly, $name, $value, $expire, $secure ) );
135
        } elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
136
            headers_sent( $file, $line );
137
            trigger_error( "{$name} cookie cannot be set - headers already sent by {$file} on line {$line}", E_USER_NOTICE ); // @codingStandardsIgnoreLine
138
        }
139
    }
140
141
	/**
142
	 * Should the session cookie be secure?
143
	 *
144
	 * @since 3.6.0
145
	 * @return bool
146
	 */
147
	protected function use_secure_cookie() {
148
        $is_https = false !== strstr( get_option( 'home' ), 'https:' );
149
		return apply_filters( 'wpinv_session_use_secure_cookie', $is_https && is_ssl() );
150
	}
151
152
	/**
153
	 * Return true if the current user has an active session, i.e. a cookie to retrieve values.
154
	 *
155
	 * @return bool
156
	 */
157
	public function has_session() {
158
		return isset( $_COOKIE[ $this->_cookie ] ) || $this->_has_cookie || is_user_logged_in(); // @codingStandardsIgnoreLine.
159
	}
160
161
	/**
162
	 * Set session expiration.
163
	 */
164
	public function set_session_expiration() {
165
		$this->_session_expiring   = time() + intval( apply_filters( 'wpinv_session_expiring', 60 * 60 * 47 ) ); // 47 Hours.
166
		$this->_session_expiration = time() + intval( apply_filters( 'wpinv_session_expiration', 60 * 60 * 48 ) ); // 48 Hours.
0 ignored issues
show
Documentation Bug introduced by
The property $_session_expiration was declared of type string, but time() + intval(apply_fi...ration', 60 * 60 * 48)) is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
167
	}
168
169
	/**
170
	 * Generate a unique customer ID for guests, or return user ID if logged in.
171
	 *
172
	 * Uses Portable PHP password hashing framework to generate a unique cryptographically strong ID.
173
	 *
174
	 * @return string
175
	 */
176
	public function generate_customer_id() {
177
		$customer_id = '';
178
179
		if ( is_user_logged_in() ) {
180
			$customer_id = get_current_user_id();
181
		}
182
183
		if ( empty( $customer_id ) ) {
184
            $customer_id = wp_create_nonce('wpinv-session-customer-id');
185
		}
186
187
		return $customer_id;
188
	}
189
190
	/**
191
	 * Get the session cookie, if set. Otherwise return false.
192
	 *
193
	 * Session cookies without a customer ID are invalid.
194
	 *
195
	 * @return bool|array
196
	 */
197
	public function get_session_cookie() {
198
		$cookie_value = isset( $_COOKIE[ $this->_cookie ] ) ? wp_unslash( $_COOKIE[ $this->_cookie ] ) : false; // @codingStandardsIgnoreLine.
199
200
		if ( empty( $cookie_value ) || ! is_string( $cookie_value ) ) {
201
			return false;
202
		}
203
204
		list( $customer_id, $session_expiration, $session_expiring, $cookie_hash ) = explode( '||', $cookie_value );
205
206
		if ( empty( $customer_id ) ) {
207
			return false;
208
		}
209
210
		// Validate hash.
211
		$to_hash = $customer_id . '|' . $session_expiration;
212
		$hash    = hash_hmac( 'md5', $to_hash, wp_hash( $to_hash ) );
213
214
		if ( empty( $cookie_hash ) || ! hash_equals( $hash, $cookie_hash ) ) {
215
			return false;
216
		}
217
218
		return array( $customer_id, $session_expiration, $session_expiring, $cookie_hash );
219
	}
220
221
	/**
222
	 * Get session data.
223
	 *
224
	 * @return array
225
	 */
226
	public function get_session_data() {
227
		return $this->has_session() ? (array) $this->get_session( $this->_customer_id ) : array();
228
	}
229
230
	public function generate_key($customer_id){
231
        if(!$customer_id){
232
            return;
233
        }
234
235
        return 'wpi_trans_'.$customer_id;
236
    }
237
238
	/**
239
	 * Save data.
240
	 */
241
	public function save_data() {
242
		// Dirty if something changed - prevents saving nothing new.
243
		if ( $this->_dirty && $this->has_session() ) {
244
245
            set_transient( $this->generate_key($this->_customer_id), $this->_data, $this->_session_expiration);
246
247
			$this->_dirty = false;
248
		}
249
	}
250
251
	/**
252
	 * Destroy all session data.
253
	 */
254
	public function destroy_session() {
255
		$this->delete_session( $this->_customer_id );
256
		$this->forget_session();
257
	}
258
259
	/**
260
	 * Forget all session data without destroying it.
261
	 */
262
	public function forget_session() {
263
		$this->setcookie( $this->_cookie, '', time() - YEAR_IN_SECONDS, $this->use_secure_cookie(), true );
264
265
		wpinv_empty_cart();
266
267
		$this->_data        = array();
268
		$this->_dirty       = false;
269
		$this->_customer_id = $this->generate_customer_id();
0 ignored issues
show
Documentation Bug introduced by
The property $_customer_id was declared of type integer, but $this->generate_customer_id() is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
270
	}
271
272
	/**
273
	 * When a user is logged out, ensure they have a unique nonce by using the customer/session ID.
274
	 *
275
	 * @param int $uid User ID.
276
	 * @return string
277
	 */
278
	public function nonce_user_logged_out( $uid ) {
279
		return $this->has_session() && $this->_customer_id ? $this->_customer_id : $uid;
280
	}
281
282
	/**
283
	 * Returns the session.
284
	 *
285
	 * @param string $customer_id Customer ID.
286
	 * @param mixed  $default Default session value.
287
	 * @return string|array
288
	 */
289
	public function get_session( $customer_id, $default = false ) {
290
291
		if ( defined( 'WP_SETUP_CONFIG' ) ) {
292
			return array();
293
		}
294
295
        if ( !is_user_logged_in() ) {
296
            if(!wp_verify_nonce( $customer_id, 'wpinv-session-customer-id' )){
297
                return array();
298
            }
299
        }
300
301
        $key = $this->generate_key($customer_id);
302
        $value = get_transient($key);
303
304
        if ( !$value ) {
305
            $value = $default;
306
        }
307
308
		return maybe_unserialize( $value );
309
	}
310
311
	/**
312
	 * Delete the session from the cache and database.
313
	 *
314
	 * @param int $customer_id Customer ID.
315
	 */
316
	public function delete_session( $customer_id ) {
317
318
        $key = $this->generate_key($customer_id);
319
320
		delete_transient($key);
321
	}
322
323
	/**
324
	 * Update the session expiry timestamp.
325
	 *
326
	 * @param string $customer_id Customer ID.
327
	 * @param int    $timestamp Timestamp to expire the cookie.
328
	 */
329
	public function update_session_timestamp( $customer_id, $timestamp ) {
330
331
        set_transient( $this->generate_key($customer_id), maybe_serialize( $this->_data ), $timestamp);
332
333
	}
334
}
335
336
global $wpi_session;
337
$wpi_session = new WPInv_Session_Handler();