Completed
Branch FET/Gutenberg/11400/block-mana... (1c7938)
by
unknown
13:59 queued 16s
created
core/EE_Session.core.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
     /**
543 543
      * @initiate session
544 544
      * @access   private
545
-     * @return TRUE on success, FALSE on fail
545
+     * @return boolean on success, FALSE on fail
546 546
      * @throws EE_Error
547 547
      * @throws InvalidArgumentException
548 548
      * @throws InvalidDataTypeException
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
      * @update session data  prior to saving to the db
779 779
      * @access public
780 780
      * @param bool $new_session
781
-     * @return TRUE on success, FALSE on fail
781
+     * @return boolean on success, FALSE on fail
782 782
      * @throws EE_Error
783 783
      * @throws InvalidArgumentException
784 784
      * @throws InvalidDataTypeException
@@ -879,7 +879,7 @@  discard block
 block discarded – undo
879 879
      * _save_session_to_db
880 880
      *
881 881
      * @param bool $clear_session
882
-     * @return string
882
+     * @return boolean
883 883
      * @throws EE_Error
884 884
      * @throws InvalidArgumentException
885 885
      * @throws InvalidDataTypeException
Please login to merge, or discard this patch.
Indentation   +1226 added lines, -1226 removed lines patch added patch discarded remove patch
@@ -22,1229 +22,1229 @@  discard block
 block discarded – undo
22 22
 class EE_Session implements SessionIdentifierInterface
23 23
 {
24 24
 
25
-    const session_id_prefix    = 'ee_ssn_';
26
-
27
-    const hash_check_prefix    = 'ee_shc_';
28
-
29
-    const OPTION_NAME_SETTINGS = 'ee_session_settings';
30
-
31
-    const STATUS_CLOSED        = 0;
32
-
33
-    const STATUS_OPEN          = 1;
34
-
35
-    /**
36
-     * instance of the EE_Session object
37
-     *
38
-     * @var EE_Session
39
-     */
40
-    private static $_instance;
41
-
42
-    /**
43
-     * @var CacheStorageInterface $cache_storage
44
-     */
45
-    protected $cache_storage;
46
-
47
-    /**
48
-     * EE_Encryption object
49
-     *
50
-     * @var EE_Encryption
51
-     */
52
-    protected $encryption;
53
-
54
-    /**
55
-     * the session id
56
-     *
57
-     * @var string
58
-     */
59
-    private $_sid;
60
-
61
-    /**
62
-     * session id salt
63
-     *
64
-     * @var string
65
-     */
66
-    private $_sid_salt;
67
-
68
-    /**
69
-     * session data
70
-     *
71
-     * @var array
72
-     */
73
-    private $_session_data = array();
74
-
75
-    /**
76
-     * how long an EE session lasts
77
-     * default session lifespan of 1 hour (for not so instant IPNs)
78
-     *
79
-     * @var SessionLifespan $session_lifespan
80
-     */
81
-    private $session_lifespan;
82
-
83
-    /**
84
-     * session expiration time as Unix timestamp in GMT
85
-     *
86
-     * @var int
87
-     */
88
-    private $_expiration;
89
-
90
-    /**
91
-     * whether or not session has expired at some point
92
-     *
93
-     * @var boolean
94
-     */
95
-    private $_expired = false;
96
-
97
-    /**
98
-     * current time as Unix timestamp in GMT
99
-     *
100
-     * @var int
101
-     */
102
-    private $_time;
103
-
104
-    /**
105
-     * whether to encrypt session data
106
-     *
107
-     * @var bool
108
-     */
109
-    private $_use_encryption;
110
-
111
-    /**
112
-     * well... according to the server...
113
-     *
114
-     * @var null
115
-     */
116
-    private $_user_agent;
117
-
118
-    /**
119
-     * do you really trust the server ?
120
-     *
121
-     * @var null
122
-     */
123
-    private $_ip_address;
124
-
125
-    /**
126
-     * current WP user_id
127
-     *
128
-     * @var null
129
-     */
130
-    private $_wp_user_id;
131
-
132
-    /**
133
-     * array for defining default session vars
134
-     *
135
-     * @var array
136
-     */
137
-    private $_default_session_vars = array(
138
-        'id'            => null,
139
-        'user_id'       => null,
140
-        'ip_address'    => null,
141
-        'user_agent'    => null,
142
-        'init_access'   => null,
143
-        'last_access'   => null,
144
-        'expiration'    => null,
145
-        'pages_visited' => array(),
146
-    );
147
-
148
-    /**
149
-     * timestamp for when last garbage collection cycle was performed
150
-     *
151
-     * @var int $_last_gc
152
-     */
153
-    private $_last_gc;
154
-
155
-    /**
156
-     * @var RequestInterface $request
157
-     */
158
-    protected $request;
159
-
160
-    /**
161
-     * whether session is active or not
162
-     *
163
-     * @var int $status
164
-     */
165
-    private $status = EE_Session::STATUS_CLOSED;
166
-
167
-
168
-
169
-    /**
170
-     * @singleton method used to instantiate class object
171
-     * @param CacheStorageInterface $cache_storage
172
-     * @param SessionLifespan|null  $lifespan
173
-     * @param RequestInterface      $request
174
-     * @param EE_Encryption         $encryption
175
-     * @return EE_Session
176
-     * @throws InvalidArgumentException
177
-     * @throws InvalidDataTypeException
178
-     * @throws InvalidInterfaceException
179
-     */
180
-    public static function instance(
181
-        CacheStorageInterface $cache_storage = null,
182
-        SessionLifespan $lifespan = null,
183
-        RequestInterface $request = null,
184
-        EE_Encryption $encryption = null
185
-    ) {
186
-        // check if class object is instantiated
187
-        // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
188
-        // add_filter( 'FHEE_load_EE_Session', '__return_false' );
189
-        if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
190
-            self::$_instance = new self(
191
-                $cache_storage,
192
-                $lifespan,
193
-                $request,
194
-                $encryption
195
-            );
196
-        }
197
-        return self::$_instance;
198
-    }
199
-
200
-
201
-    /**
202
-     * protected constructor to prevent direct creation
203
-     *
204
-     * @param CacheStorageInterface $cache_storage
205
-     * @param SessionLifespan       $lifespan
206
-     * @param RequestInterface      $request
207
-     * @param EE_Encryption         $encryption
208
-     * @throws InvalidArgumentException
209
-     * @throws InvalidDataTypeException
210
-     * @throws InvalidInterfaceException
211
-     */
212
-    protected function __construct(
213
-        CacheStorageInterface $cache_storage,
214
-        SessionLifespan $lifespan,
215
-        RequestInterface $request,
216
-        EE_Encryption $encryption = null
217
-    ) {
218
-        // session loading is turned ON by default,
219
-        // but prior to the 'AHEE__EE_System__core_loaded_and_ready' hook
220
-        // (which currently fires on the init hook at priority 9),
221
-        // can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
222
-        if (! apply_filters('FHEE_load_EE_Session', true)) {
223
-            return;
224
-        }
225
-        $this->session_lifespan = $lifespan;
226
-        $this->request          = $request;
227
-        if (! defined('ESPRESSO_SESSION')) {
228
-            define('ESPRESSO_SESSION', true);
229
-        }
230
-        // retrieve session options from db
231
-        $session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
232
-        if (! empty($session_settings)) {
233
-            // cycle though existing session options
234
-            foreach ($session_settings as $var_name => $session_setting) {
235
-                // set values for class properties
236
-                $var_name          = '_' . $var_name;
237
-                $this->{$var_name} = $session_setting;
238
-            }
239
-        }
240
-        $this->cache_storage = $cache_storage;
241
-        // are we using encryption?
242
-        $this->_use_encryption = $encryption instanceof EE_Encryption
243
-                                 && EE_Registry::instance()->CFG->admin->encode_session_data();
244
-        // encrypt data via: $this->encryption->encrypt();
245
-        $this->encryption = $encryption;
246
-        // filter hook allows outside functions/classes/plugins to change default empty cart
247
-        $extra_default_session_vars = apply_filters('FHEE__EE_Session__construct__extra_default_session_vars', array());
248
-        array_merge($this->_default_session_vars, $extra_default_session_vars);
249
-        // apply default session vars
250
-        $this->_set_defaults();
251
-        add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
252
-        // check request for 'clear_session' param
253
-        add_action('AHEE__EE_Request_Handler__construct__complete', array($this, 'wp_loaded'));
254
-        // once everything is all said and done,
255
-        add_action('shutdown', array($this, 'update'), 100);
256
-        add_action('shutdown', array($this, 'garbageCollection'), 1000);
257
-        $this->configure_garbage_collection_filters();
258
-    }
259
-
260
-
261
-    /**
262
-     * @return bool
263
-     * @throws InvalidArgumentException
264
-     * @throws InvalidDataTypeException
265
-     * @throws InvalidInterfaceException
266
-     */
267
-    public static function isLoadedAndActive()
268
-    {
269
-        return did_action('AHEE__EE_System__core_loaded_and_ready')
270
-               && EE_Session::instance() instanceof EE_Session
271
-               && EE_Session::instance()->isActive();
272
-    }
273
-
274
-
275
-    /**
276
-     * @return bool
277
-     */
278
-    public function isActive()
279
-    {
280
-        return $this->status === EE_Session::STATUS_OPEN;
281
-    }
282
-
283
-
284
-
285
-    /**
286
-     * @return void
287
-     * @throws EE_Error
288
-     * @throws InvalidArgumentException
289
-     * @throws InvalidDataTypeException
290
-     * @throws InvalidInterfaceException
291
-     * @throws InvalidSessionDataException
292
-     */
293
-    public function open_session()
294
-    {
295
-        // check for existing session and retrieve it from db
296
-        if (! $this->_espresso_session()) {
297
-            // or just start a new one
298
-            $this->_create_espresso_session();
299
-        }
300
-    }
301
-
302
-
303
-
304
-    /**
305
-     * @return bool
306
-     */
307
-    public function expired()
308
-    {
309
-        return $this->_expired;
310
-    }
311
-
312
-
313
-
314
-    /**
315
-     * @return void
316
-     */
317
-    public function reset_expired()
318
-    {
319
-        $this->_expired = false;
320
-    }
321
-
322
-
323
-    /**
324
-     * @return int
325
-     */
326
-    public function expiration()
327
-    {
328
-        return $this->_expiration;
329
-    }
330
-
331
-
332
-
333
-    /**
334
-     * @return int
335
-     */
336
-    public function extension()
337
-    {
338
-        return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS);
339
-    }
340
-
341
-
342
-
343
-    /**
344
-     * @param int $time number of seconds to add to session expiration
345
-     */
346
-    public function extend_expiration($time = 0)
347
-    {
348
-        $time              = $time ? $time : $this->extension();
349
-        $this->_expiration += absint($time);
350
-    }
351
-
352
-
353
-
354
-    /**
355
-     * @return int
356
-     */
357
-    public function lifespan()
358
-    {
359
-        return $this->session_lifespan->inSeconds();
360
-    }
361
-
362
-
363
-
364
-    /**
365
-     * This just sets some defaults for the _session data property
366
-     *
367
-     * @access private
368
-     * @return void
369
-     */
370
-    private function _set_defaults()
371
-    {
372
-        // set some defaults
373
-        foreach ($this->_default_session_vars as $key => $default_var) {
374
-            if (is_array($default_var)) {
375
-                $this->_session_data[ $key ] = array();
376
-            } else {
377
-                $this->_session_data[ $key ] = '';
378
-            }
379
-        }
380
-    }
25
+	const session_id_prefix    = 'ee_ssn_';
26
+
27
+	const hash_check_prefix    = 'ee_shc_';
28
+
29
+	const OPTION_NAME_SETTINGS = 'ee_session_settings';
30
+
31
+	const STATUS_CLOSED        = 0;
32
+
33
+	const STATUS_OPEN          = 1;
34
+
35
+	/**
36
+	 * instance of the EE_Session object
37
+	 *
38
+	 * @var EE_Session
39
+	 */
40
+	private static $_instance;
41
+
42
+	/**
43
+	 * @var CacheStorageInterface $cache_storage
44
+	 */
45
+	protected $cache_storage;
46
+
47
+	/**
48
+	 * EE_Encryption object
49
+	 *
50
+	 * @var EE_Encryption
51
+	 */
52
+	protected $encryption;
53
+
54
+	/**
55
+	 * the session id
56
+	 *
57
+	 * @var string
58
+	 */
59
+	private $_sid;
60
+
61
+	/**
62
+	 * session id salt
63
+	 *
64
+	 * @var string
65
+	 */
66
+	private $_sid_salt;
67
+
68
+	/**
69
+	 * session data
70
+	 *
71
+	 * @var array
72
+	 */
73
+	private $_session_data = array();
74
+
75
+	/**
76
+	 * how long an EE session lasts
77
+	 * default session lifespan of 1 hour (for not so instant IPNs)
78
+	 *
79
+	 * @var SessionLifespan $session_lifespan
80
+	 */
81
+	private $session_lifespan;
82
+
83
+	/**
84
+	 * session expiration time as Unix timestamp in GMT
85
+	 *
86
+	 * @var int
87
+	 */
88
+	private $_expiration;
89
+
90
+	/**
91
+	 * whether or not session has expired at some point
92
+	 *
93
+	 * @var boolean
94
+	 */
95
+	private $_expired = false;
96
+
97
+	/**
98
+	 * current time as Unix timestamp in GMT
99
+	 *
100
+	 * @var int
101
+	 */
102
+	private $_time;
103
+
104
+	/**
105
+	 * whether to encrypt session data
106
+	 *
107
+	 * @var bool
108
+	 */
109
+	private $_use_encryption;
110
+
111
+	/**
112
+	 * well... according to the server...
113
+	 *
114
+	 * @var null
115
+	 */
116
+	private $_user_agent;
117
+
118
+	/**
119
+	 * do you really trust the server ?
120
+	 *
121
+	 * @var null
122
+	 */
123
+	private $_ip_address;
124
+
125
+	/**
126
+	 * current WP user_id
127
+	 *
128
+	 * @var null
129
+	 */
130
+	private $_wp_user_id;
131
+
132
+	/**
133
+	 * array for defining default session vars
134
+	 *
135
+	 * @var array
136
+	 */
137
+	private $_default_session_vars = array(
138
+		'id'            => null,
139
+		'user_id'       => null,
140
+		'ip_address'    => null,
141
+		'user_agent'    => null,
142
+		'init_access'   => null,
143
+		'last_access'   => null,
144
+		'expiration'    => null,
145
+		'pages_visited' => array(),
146
+	);
147
+
148
+	/**
149
+	 * timestamp for when last garbage collection cycle was performed
150
+	 *
151
+	 * @var int $_last_gc
152
+	 */
153
+	private $_last_gc;
154
+
155
+	/**
156
+	 * @var RequestInterface $request
157
+	 */
158
+	protected $request;
159
+
160
+	/**
161
+	 * whether session is active or not
162
+	 *
163
+	 * @var int $status
164
+	 */
165
+	private $status = EE_Session::STATUS_CLOSED;
166
+
167
+
168
+
169
+	/**
170
+	 * @singleton method used to instantiate class object
171
+	 * @param CacheStorageInterface $cache_storage
172
+	 * @param SessionLifespan|null  $lifespan
173
+	 * @param RequestInterface      $request
174
+	 * @param EE_Encryption         $encryption
175
+	 * @return EE_Session
176
+	 * @throws InvalidArgumentException
177
+	 * @throws InvalidDataTypeException
178
+	 * @throws InvalidInterfaceException
179
+	 */
180
+	public static function instance(
181
+		CacheStorageInterface $cache_storage = null,
182
+		SessionLifespan $lifespan = null,
183
+		RequestInterface $request = null,
184
+		EE_Encryption $encryption = null
185
+	) {
186
+		// check if class object is instantiated
187
+		// session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
188
+		// add_filter( 'FHEE_load_EE_Session', '__return_false' );
189
+		if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
190
+			self::$_instance = new self(
191
+				$cache_storage,
192
+				$lifespan,
193
+				$request,
194
+				$encryption
195
+			);
196
+		}
197
+		return self::$_instance;
198
+	}
199
+
200
+
201
+	/**
202
+	 * protected constructor to prevent direct creation
203
+	 *
204
+	 * @param CacheStorageInterface $cache_storage
205
+	 * @param SessionLifespan       $lifespan
206
+	 * @param RequestInterface      $request
207
+	 * @param EE_Encryption         $encryption
208
+	 * @throws InvalidArgumentException
209
+	 * @throws InvalidDataTypeException
210
+	 * @throws InvalidInterfaceException
211
+	 */
212
+	protected function __construct(
213
+		CacheStorageInterface $cache_storage,
214
+		SessionLifespan $lifespan,
215
+		RequestInterface $request,
216
+		EE_Encryption $encryption = null
217
+	) {
218
+		// session loading is turned ON by default,
219
+		// but prior to the 'AHEE__EE_System__core_loaded_and_ready' hook
220
+		// (which currently fires on the init hook at priority 9),
221
+		// can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
222
+		if (! apply_filters('FHEE_load_EE_Session', true)) {
223
+			return;
224
+		}
225
+		$this->session_lifespan = $lifespan;
226
+		$this->request          = $request;
227
+		if (! defined('ESPRESSO_SESSION')) {
228
+			define('ESPRESSO_SESSION', true);
229
+		}
230
+		// retrieve session options from db
231
+		$session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
232
+		if (! empty($session_settings)) {
233
+			// cycle though existing session options
234
+			foreach ($session_settings as $var_name => $session_setting) {
235
+				// set values for class properties
236
+				$var_name          = '_' . $var_name;
237
+				$this->{$var_name} = $session_setting;
238
+			}
239
+		}
240
+		$this->cache_storage = $cache_storage;
241
+		// are we using encryption?
242
+		$this->_use_encryption = $encryption instanceof EE_Encryption
243
+								 && EE_Registry::instance()->CFG->admin->encode_session_data();
244
+		// encrypt data via: $this->encryption->encrypt();
245
+		$this->encryption = $encryption;
246
+		// filter hook allows outside functions/classes/plugins to change default empty cart
247
+		$extra_default_session_vars = apply_filters('FHEE__EE_Session__construct__extra_default_session_vars', array());
248
+		array_merge($this->_default_session_vars, $extra_default_session_vars);
249
+		// apply default session vars
250
+		$this->_set_defaults();
251
+		add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
252
+		// check request for 'clear_session' param
253
+		add_action('AHEE__EE_Request_Handler__construct__complete', array($this, 'wp_loaded'));
254
+		// once everything is all said and done,
255
+		add_action('shutdown', array($this, 'update'), 100);
256
+		add_action('shutdown', array($this, 'garbageCollection'), 1000);
257
+		$this->configure_garbage_collection_filters();
258
+	}
259
+
260
+
261
+	/**
262
+	 * @return bool
263
+	 * @throws InvalidArgumentException
264
+	 * @throws InvalidDataTypeException
265
+	 * @throws InvalidInterfaceException
266
+	 */
267
+	public static function isLoadedAndActive()
268
+	{
269
+		return did_action('AHEE__EE_System__core_loaded_and_ready')
270
+			   && EE_Session::instance() instanceof EE_Session
271
+			   && EE_Session::instance()->isActive();
272
+	}
273
+
274
+
275
+	/**
276
+	 * @return bool
277
+	 */
278
+	public function isActive()
279
+	{
280
+		return $this->status === EE_Session::STATUS_OPEN;
281
+	}
282
+
283
+
284
+
285
+	/**
286
+	 * @return void
287
+	 * @throws EE_Error
288
+	 * @throws InvalidArgumentException
289
+	 * @throws InvalidDataTypeException
290
+	 * @throws InvalidInterfaceException
291
+	 * @throws InvalidSessionDataException
292
+	 */
293
+	public function open_session()
294
+	{
295
+		// check for existing session and retrieve it from db
296
+		if (! $this->_espresso_session()) {
297
+			// or just start a new one
298
+			$this->_create_espresso_session();
299
+		}
300
+	}
301
+
302
+
303
+
304
+	/**
305
+	 * @return bool
306
+	 */
307
+	public function expired()
308
+	{
309
+		return $this->_expired;
310
+	}
311
+
312
+
313
+
314
+	/**
315
+	 * @return void
316
+	 */
317
+	public function reset_expired()
318
+	{
319
+		$this->_expired = false;
320
+	}
321
+
322
+
323
+	/**
324
+	 * @return int
325
+	 */
326
+	public function expiration()
327
+	{
328
+		return $this->_expiration;
329
+	}
330
+
331
+
332
+
333
+	/**
334
+	 * @return int
335
+	 */
336
+	public function extension()
337
+	{
338
+		return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS);
339
+	}
340
+
341
+
342
+
343
+	/**
344
+	 * @param int $time number of seconds to add to session expiration
345
+	 */
346
+	public function extend_expiration($time = 0)
347
+	{
348
+		$time              = $time ? $time : $this->extension();
349
+		$this->_expiration += absint($time);
350
+	}
351
+
352
+
353
+
354
+	/**
355
+	 * @return int
356
+	 */
357
+	public function lifespan()
358
+	{
359
+		return $this->session_lifespan->inSeconds();
360
+	}
361
+
362
+
363
+
364
+	/**
365
+	 * This just sets some defaults for the _session data property
366
+	 *
367
+	 * @access private
368
+	 * @return void
369
+	 */
370
+	private function _set_defaults()
371
+	{
372
+		// set some defaults
373
+		foreach ($this->_default_session_vars as $key => $default_var) {
374
+			if (is_array($default_var)) {
375
+				$this->_session_data[ $key ] = array();
376
+			} else {
377
+				$this->_session_data[ $key ] = '';
378
+			}
379
+		}
380
+	}
381 381
 
382 382
 
383
-
384
-    /**
385
-     * @retrieve  session data
386
-     * @access    public
387
-     * @return    string
388
-     */
389
-    public function id()
390
-    {
391
-        return $this->_sid;
392
-    }
383
+
384
+	/**
385
+	 * @retrieve  session data
386
+	 * @access    public
387
+	 * @return    string
388
+	 */
389
+	public function id()
390
+	{
391
+		return $this->_sid;
392
+	}
393 393
 
394 394
 
395 395
 
396
-    /**
397
-     * @param \EE_Cart $cart
398
-     * @return bool
399
-     */
400
-    public function set_cart(EE_Cart $cart)
401
-    {
402
-        $this->_session_data['cart'] = $cart;
403
-        return true;
404
-    }
405
-
406
-
407
-
408
-    /**
409
-     * reset_cart
410
-     */
411
-    public function reset_cart()
412
-    {
413
-        do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
414
-        $this->_session_data['cart'] = null;
415
-    }
416
-
417
-
418
-
419
-    /**
420
-     * @return \EE_Cart
421
-     */
422
-    public function cart()
423
-    {
424
-        return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
425
-            ? $this->_session_data['cart']
426
-            : null;
427
-    }
428
-
429
-
430
-
431
-    /**
432
-     * @param \EE_Checkout $checkout
433
-     * @return bool
434
-     */
435
-    public function set_checkout(EE_Checkout $checkout)
436
-    {
437
-        $this->_session_data['checkout'] = $checkout;
438
-        return true;
439
-    }
440
-
441
-
442
-
443
-    /**
444
-     * reset_checkout
445
-     */
446
-    public function reset_checkout()
447
-    {
448
-        do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
449
-        $this->_session_data['checkout'] = null;
450
-    }
451
-
452
-
453
-
454
-    /**
455
-     * @return \EE_Checkout
456
-     */
457
-    public function checkout()
458
-    {
459
-        return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
460
-            ? $this->_session_data['checkout']
461
-            : null;
462
-    }
463
-
464
-
465
-
466
-    /**
467
-     * @param \EE_Transaction $transaction
468
-     * @return bool
469
-     * @throws EE_Error
470
-     */
471
-    public function set_transaction(EE_Transaction $transaction)
472
-    {
473
-        // first remove the session from the transaction before we save the transaction in the session
474
-        $transaction->set_txn_session_data(null);
475
-        $this->_session_data['transaction'] = $transaction;
476
-        return true;
477
-    }
478
-
479
-
480
-
481
-    /**
482
-     * reset_transaction
483
-     */
484
-    public function reset_transaction()
485
-    {
486
-        do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
487
-        $this->_session_data['transaction'] = null;
488
-    }
489
-
490
-
491
-
492
-    /**
493
-     * @return \EE_Transaction
494
-     */
495
-    public function transaction()
496
-    {
497
-        return isset($this->_session_data['transaction'])
498
-               && $this->_session_data['transaction'] instanceof EE_Transaction
499
-            ? $this->_session_data['transaction']
500
-            : null;
501
-    }
502
-
503
-
504
-    /**
505
-     * retrieve session data
506
-     *
507
-     * @param null $key
508
-     * @param bool $reset_cache
509
-     * @return array
510
-     */
511
-    public function get_session_data($key = null, $reset_cache = false)
512
-    {
513
-        if ($reset_cache) {
514
-            $this->reset_cart();
515
-            $this->reset_checkout();
516
-            $this->reset_transaction();
517
-        }
518
-        if (! empty($key)) {
519
-            return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
520
-        }
521
-        return $this->_session_data;
522
-    }
523
-
524
-
525
-    /**
526
-     * Returns TRUE on success, FALSE on fail
527
-     *
528
-     * @param array $data
529
-     * @return bool
530
-     */
531
-    public function set_session_data($data)
532
-    {
533
-        // nothing ??? bad data ??? go home!
534
-        if (empty($data) || ! is_array($data)) {
535
-            EE_Error::add_error(
536
-                esc_html__(
537
-                    'No session data or invalid session data was provided.',
538
-                    'event_espresso'
539
-                ),
540
-                __FILE__, __FUNCTION__, __LINE__
541
-            );
542
-            return false;
543
-        }
544
-        foreach ($data as $key => $value) {
545
-            if (isset($this->_default_session_vars[ $key ])) {
546
-                EE_Error::add_error(
547
-                    sprintf(
548
-                        esc_html__(
549
-                            'Sorry! %s is a default session datum and can not be reset.',
550
-                            'event_espresso'
551
-                        ),
552
-                        $key
553
-                    ),
554
-                    __FILE__, __FUNCTION__, __LINE__
555
-                );
556
-                return false;
557
-            }
558
-            $this->_session_data[ $key ] = $value;
559
-        }
560
-        return true;
561
-    }
562
-
563
-
564
-
565
-    /**
566
-     * @initiate session
567
-     * @access   private
568
-     * @return TRUE on success, FALSE on fail
569
-     * @throws EE_Error
570
-     * @throws InvalidArgumentException
571
-     * @throws InvalidDataTypeException
572
-     * @throws InvalidInterfaceException
573
-     * @throws InvalidSessionDataException
574
-     */
575
-    private function _espresso_session()
576
-    {
577
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
578
-        // check that session has started
579
-        if (session_id() === '') {
580
-            //starts a new session if one doesn't already exist, or re-initiates an existing one
581
-            session_start();
582
-        }
583
-        $this->status = EE_Session::STATUS_OPEN;
584
-        // get our modified session ID
585
-        $this->_sid = $this->_generate_session_id();
586
-        // and the visitors IP
587
-        $this->_ip_address = $this->request->ipAddress();
588
-        // set the "user agent"
589
-        $this->_user_agent = $this->request->userAgent();
590
-        // now let's retrieve what's in the db
591
-        $session_data = $this->_retrieve_session_data();
592
-        if (! empty($session_data)) {
593
-            // get the current time in UTC
594
-            $this->_time = $this->_time !== null ? $this->_time : time();
595
-            // and reset the session expiration
596
-            $this->_expiration = isset($session_data['expiration'])
597
-                ? $session_data['expiration']
598
-                : $this->_time + $this->session_lifespan->inSeconds();
599
-        } else {
600
-            // set initial site access time and the session expiration
601
-            $this->_set_init_access_and_expiration();
602
-            // set referer
603
-            $this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
604
-                ? esc_attr($_SERVER['HTTP_REFERER'])
605
-                : '';
606
-            // no previous session = go back and create one (on top of the data above)
607
-            return false;
608
-        }
609
-        // now the user agent
610
-        if ($session_data['user_agent'] !== $this->_user_agent) {
611
-            return false;
612
-        }
613
-        // wait a minute... how old are you?
614
-        if ($this->_time > $this->_expiration) {
615
-            // yer too old fer me!
616
-            $this->_expired = true;
617
-            // wipe out everything that isn't a default session datum
618
-            $this->clear_session(__CLASS__, __FUNCTION__);
619
-        }
620
-        // make event espresso session data available to plugin
621
-        $this->_session_data = array_merge($this->_session_data, $session_data);
622
-        return true;
623
-    }
624
-
625
-
626
-
627
-    /**
628
-     * _get_session_data
629
-     * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup
630
-     * databases
631
-     *
632
-     * @return array
633
-     * @throws EE_Error
634
-     * @throws InvalidArgumentException
635
-     * @throws InvalidSessionDataException
636
-     * @throws InvalidDataTypeException
637
-     * @throws InvalidInterfaceException
638
-     */
639
-    protected function _retrieve_session_data()
640
-    {
641
-        $ssn_key = EE_Session::session_id_prefix . $this->_sid;
642
-        try {
643
-            // we're using WP's Transient API to store session data using the PHP session ID as the option name
644
-            $session_data = $this->cache_storage->get($ssn_key, false);
645
-            if (empty($session_data)) {
646
-                return array();
647
-            }
648
-            if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
649
-                $hash_check = $this->cache_storage->get(
650
-                    EE_Session::hash_check_prefix . $this->_sid,
651
-                    false
652
-                );
653
-                if ($hash_check && $hash_check !== md5($session_data)) {
654
-                    EE_Error::add_error(
655
-                        sprintf(
656
-                            __(
657
-                                'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
658
-                                'event_espresso'
659
-                            ),
660
-                            EE_Session::session_id_prefix . $this->_sid
661
-                        ),
662
-                        __FILE__, __FUNCTION__, __LINE__
663
-                    );
664
-                }
665
-            }
666
-        } catch (Exception $e) {
667
-            // let's just eat that error for now and attempt to correct any corrupted data
668
-            global $wpdb;
669
-            $row          = $wpdb->get_row(
670
-                $wpdb->prepare(
671
-                    "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
672
-                    '_transient_' . $ssn_key
673
-                )
674
-            );
675
-            $session_data = is_object($row) ? $row->option_value : null;
676
-            if ($session_data) {
677
-                $session_data = preg_replace_callback(
678
-                    '!s:(d+):"(.*?)";!',
679
-                    function ($match)
680
-                    {
681
-                        return $match[1] === strlen($match[2])
682
-                            ? $match[0]
683
-                            : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
684
-                    },
685
-                    $session_data
686
-                );
687
-            }
688
-            $session_data = maybe_unserialize($session_data);
689
-        }
690
-        // in case the data is encoded... try to decode it
691
-        $session_data = $this->encryption instanceof EE_Encryption
692
-            ? $this->encryption->base64_string_decode($session_data)
693
-            : $session_data;
694
-        if (! is_array($session_data)) {
695
-            try {
696
-                $session_data = maybe_unserialize($session_data);
697
-            } catch (Exception $e) {
698
-                $msg = esc_html__(
699
-                    'An error occurred while attempting to unserialize the session data.',
700
-                    'event_espresso'
701
-                );
702
-                $msg .= WP_DEBUG
703
-                    ? '<br><pre>'
704
-                      . print_r($session_data, true)
705
-                      . '</pre><br>'
706
-                      . $this->find_serialize_error($session_data)
707
-                    : '';
708
-                $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
709
-                throw new InvalidSessionDataException($msg, 0, $e);
710
-            }
711
-        }
712
-        // just a check to make sure the session array is indeed an array
713
-        if (! is_array($session_data)) {
714
-            // no?!?! then something is wrong
715
-            $msg = esc_html__(
716
-                'The session data is missing, invalid, or corrupted.',
717
-                'event_espresso'
718
-            );
719
-            $msg .= WP_DEBUG
720
-                ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
721
-                : '';
722
-            $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
723
-            throw new InvalidSessionDataException($msg);
724
-        }
725
-        if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
726
-            $session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
727
-                $session_data['transaction']
728
-            );
729
-        }
730
-        return $session_data;
731
-    }
732
-
733
-
734
-
735
-    /**
736
-     * _generate_session_id
737
-     * Retrieves the PHP session id either directly from the PHP session,
738
-     * or from the $_REQUEST array if it was passed in from an AJAX request.
739
-     * The session id is then salted and hashed (mmm sounds tasty)
740
-     * so that it can be safely used as a $_REQUEST param
741
-     *
742
-     * @return string
743
-     */
744
-    protected function _generate_session_id()
745
-    {
746
-        // check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
747
-        if (isset($_REQUEST['EESID'])) {
748
-            $session_id = sanitize_text_field($_REQUEST['EESID']);
749
-        } else {
750
-            $session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
751
-        }
752
-        return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * _get_sid_salt
759
-     *
760
-     * @return string
761
-     */
762
-    protected function _get_sid_salt()
763
-    {
764
-        // was session id salt already saved to db ?
765
-        if (empty($this->_sid_salt)) {
766
-            // no?  then maybe use WP defined constant
767
-            if (defined('AUTH_SALT')) {
768
-                $this->_sid_salt = AUTH_SALT;
769
-            }
770
-            // if salt doesn't exist or is too short
771
-            if (strlen($this->_sid_salt) < 32) {
772
-                // create a new one
773
-                $this->_sid_salt = wp_generate_password(64);
774
-            }
775
-            // and save it as a permanent session setting
776
-            $this->updateSessionSettings(array('sid_salt' => $this->_sid_salt));
777
-        }
778
-        return $this->_sid_salt;
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * _set_init_access_and_expiration
785
-     *
786
-     * @return void
787
-     */
788
-    protected function _set_init_access_and_expiration()
789
-    {
790
-        $this->_time       = time();
791
-        $this->_expiration = $this->_time + $this->session_lifespan->inSeconds();
792
-        // set initial site access time
793
-        $this->_session_data['init_access'] = $this->_time;
794
-        // and the session expiration
795
-        $this->_session_data['expiration'] = $this->_expiration;
796
-    }
797
-
798
-
799
-
800
-    /**
801
-     * @update session data  prior to saving to the db
802
-     * @access public
803
-     * @param bool $new_session
804
-     * @return TRUE on success, FALSE on fail
805
-     * @throws EE_Error
806
-     * @throws InvalidArgumentException
807
-     * @throws InvalidDataTypeException
808
-     * @throws InvalidInterfaceException
809
-     */
810
-    public function update($new_session = false)
811
-    {
812
-        $this->_session_data = $this->_session_data !== null
813
-                               && is_array($this->_session_data)
814
-                               && isset($this->_session_data['id'])
815
-            ? $this->_session_data
816
-            : array();
817
-        if (empty($this->_session_data)) {
818
-            $this->_set_defaults();
819
-        }
820
-        $session_data = array();
821
-        foreach ($this->_session_data as $key => $value) {
822
-
823
-            switch ($key) {
824
-
825
-                case 'id' :
826
-                    // session ID
827
-                    $session_data['id'] = $this->_sid;
828
-                    break;
829
-                case 'ip_address' :
830
-                    // visitor ip address
831
-                    $session_data['ip_address'] = $this->request->ipAddress();
832
-                    break;
833
-                case 'user_agent' :
834
-                    // visitor user_agent
835
-                    $session_data['user_agent'] = $this->_user_agent;
836
-                    break;
837
-                case 'init_access' :
838
-                    $session_data['init_access'] = absint($value);
839
-                    break;
840
-                case 'last_access' :
841
-                    // current access time
842
-                    $session_data['last_access'] = $this->_time;
843
-                    break;
844
-                case 'expiration' :
845
-                    // when the session expires
846
-                    $session_data['expiration'] = ! empty($this->_expiration)
847
-                        ? $this->_expiration
848
-                        : $session_data['init_access'] + $this->session_lifespan->inSeconds();
849
-                    break;
850
-                case 'user_id' :
851
-                    // current user if logged in
852
-                    $session_data['user_id'] = $this->_wp_user_id();
853
-                    break;
854
-                case 'pages_visited' :
855
-                    $page_visit = $this->_get_page_visit();
856
-                    if ($page_visit) {
857
-                        // set pages visited where the first will be the http referrer
858
-                        $this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
859
-                        // we'll only save the last 10 page visits.
860
-                        $session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
861
-                    }
862
-                    break;
863
-                default :
864
-                    // carry any other data over
865
-                    $session_data[ $key ] = $this->_session_data[ $key ];
866
-            }
867
-        }
868
-        $this->_session_data = $session_data;
869
-        // creating a new session does not require saving to the db just yet
870
-        if (! $new_session) {
871
-            // ready? let's save
872
-            if ($this->_save_session_to_db()) {
873
-                return true;
874
-            }
875
-            return false;
876
-        }
877
-        // meh, why not?
878
-        return true;
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * @create session data array
885
-     * @access public
886
-     * @return bool
887
-     * @throws EE_Error
888
-     * @throws InvalidArgumentException
889
-     * @throws InvalidDataTypeException
890
-     * @throws InvalidInterfaceException
891
-     */
892
-    private function _create_espresso_session()
893
-    {
894
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
895
-        // use the update function for now with $new_session arg set to TRUE
896
-        return $this->update(true) ? true : false;
897
-    }
898
-
899
-
900
-
901
-    /**
902
-     * _save_session_to_db
903
-     *
904
-     * @param bool $clear_session
905
-     * @return string
906
-     * @throws EE_Error
907
-     * @throws InvalidArgumentException
908
-     * @throws InvalidDataTypeException
909
-     * @throws InvalidInterfaceException
910
-     */
911
-    private function _save_session_to_db($clear_session = false)
912
-    {
913
-        // don't save sessions for crawlers
914
-        // and unless we're deleting the session data, don't save anything if there isn't a cart
915
-        if ($this->request->isBot() || (! $clear_session && ! $this->cart() instanceof EE_Cart)) {
916
-            return false;
917
-        }
918
-        $transaction = $this->transaction();
919
-        if ($transaction instanceof EE_Transaction) {
920
-            if (! $transaction->ID()) {
921
-                $transaction->save();
922
-            }
923
-            $this->_session_data['transaction'] = $transaction->ID();
924
-        }
925
-        // then serialize all of our session data
926
-        $session_data = serialize($this->_session_data);
927
-        // do we need to also encode it to avoid corrupted data when saved to the db?
928
-        $session_data = $this->_use_encryption
929
-            ? $this->encryption->base64_string_encode($session_data)
930
-            : $session_data;
931
-        // maybe save hash check
932
-        if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
933
-            $this->cache_storage->add(
934
-                EE_Session::hash_check_prefix . $this->_sid,
935
-                md5($session_data),
936
-                $this->session_lifespan->inSeconds()
937
-            );
938
-        }
939
-        // we're using the Transient API for storing session data,
940
-        return $this->cache_storage->add(
941
-            EE_Session::session_id_prefix . $this->_sid,
942
-            $session_data,
943
-            $this->session_lifespan->inSeconds()
944
-        );
945
-    }
946
-
947
-
948
-    /**
949
-     * @get    the full page request the visitor is accessing
950
-     * @access public
951
-     * @return string
952
-     */
953
-    public function _get_page_visit()
954
-    {
955
-        $page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
956
-        // check for request url
957
-        if (isset($_SERVER['REQUEST_URI'])) {
958
-            $http_host   = '';
959
-            $page_id     = '?';
960
-            $e_reg       = '';
961
-            $request_uri = esc_url($_SERVER['REQUEST_URI']);
962
-            $ru_bits     = explode('?', $request_uri);
963
-            $request_uri = $ru_bits[0];
964
-            // check for and grab host as well
965
-            if (isset($_SERVER['HTTP_HOST'])) {
966
-                $http_host = esc_url($_SERVER['HTTP_HOST']);
967
-            }
968
-            // check for page_id in SERVER REQUEST
969
-            if (isset($_REQUEST['page_id'])) {
970
-                // rebuild $e_reg without any of the extra parameters
971
-                $page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
972
-            }
973
-            // check for $e_reg in SERVER REQUEST
974
-            if (isset($_REQUEST['ee'])) {
975
-                // rebuild $e_reg without any of the extra parameters
976
-                $e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
977
-            }
978
-            $page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
979
-        }
980
-        return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
981
-    }
982
-
983
-
984
-
985
-    /**
986
-     * @the    current wp user id
987
-     * @access public
988
-     * @return int
989
-     */
990
-    public function _wp_user_id()
991
-    {
992
-        // if I need to explain the following lines of code, then you shouldn't be looking at this!
993
-        $this->_wp_user_id = get_current_user_id();
994
-        return $this->_wp_user_id;
995
-    }
996
-
997
-
998
-
999
-    /**
1000
-     * Clear EE_Session data
1001
-     *
1002
-     * @access public
1003
-     * @param string $class
1004
-     * @param string $function
1005
-     * @return void
1006
-     * @throws EE_Error
1007
-     * @throws InvalidArgumentException
1008
-     * @throws InvalidDataTypeException
1009
-     * @throws InvalidInterfaceException
1010
-     */
1011
-    public function clear_session($class = '', $function = '')
1012
-    {
396
+	/**
397
+	 * @param \EE_Cart $cart
398
+	 * @return bool
399
+	 */
400
+	public function set_cart(EE_Cart $cart)
401
+	{
402
+		$this->_session_data['cart'] = $cart;
403
+		return true;
404
+	}
405
+
406
+
407
+
408
+	/**
409
+	 * reset_cart
410
+	 */
411
+	public function reset_cart()
412
+	{
413
+		do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
414
+		$this->_session_data['cart'] = null;
415
+	}
416
+
417
+
418
+
419
+	/**
420
+	 * @return \EE_Cart
421
+	 */
422
+	public function cart()
423
+	{
424
+		return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
425
+			? $this->_session_data['cart']
426
+			: null;
427
+	}
428
+
429
+
430
+
431
+	/**
432
+	 * @param \EE_Checkout $checkout
433
+	 * @return bool
434
+	 */
435
+	public function set_checkout(EE_Checkout $checkout)
436
+	{
437
+		$this->_session_data['checkout'] = $checkout;
438
+		return true;
439
+	}
440
+
441
+
442
+
443
+	/**
444
+	 * reset_checkout
445
+	 */
446
+	public function reset_checkout()
447
+	{
448
+		do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
449
+		$this->_session_data['checkout'] = null;
450
+	}
451
+
452
+
453
+
454
+	/**
455
+	 * @return \EE_Checkout
456
+	 */
457
+	public function checkout()
458
+	{
459
+		return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
460
+			? $this->_session_data['checkout']
461
+			: null;
462
+	}
463
+
464
+
465
+
466
+	/**
467
+	 * @param \EE_Transaction $transaction
468
+	 * @return bool
469
+	 * @throws EE_Error
470
+	 */
471
+	public function set_transaction(EE_Transaction $transaction)
472
+	{
473
+		// first remove the session from the transaction before we save the transaction in the session
474
+		$transaction->set_txn_session_data(null);
475
+		$this->_session_data['transaction'] = $transaction;
476
+		return true;
477
+	}
478
+
479
+
480
+
481
+	/**
482
+	 * reset_transaction
483
+	 */
484
+	public function reset_transaction()
485
+	{
486
+		do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
487
+		$this->_session_data['transaction'] = null;
488
+	}
489
+
490
+
491
+
492
+	/**
493
+	 * @return \EE_Transaction
494
+	 */
495
+	public function transaction()
496
+	{
497
+		return isset($this->_session_data['transaction'])
498
+			   && $this->_session_data['transaction'] instanceof EE_Transaction
499
+			? $this->_session_data['transaction']
500
+			: null;
501
+	}
502
+
503
+
504
+	/**
505
+	 * retrieve session data
506
+	 *
507
+	 * @param null $key
508
+	 * @param bool $reset_cache
509
+	 * @return array
510
+	 */
511
+	public function get_session_data($key = null, $reset_cache = false)
512
+	{
513
+		if ($reset_cache) {
514
+			$this->reset_cart();
515
+			$this->reset_checkout();
516
+			$this->reset_transaction();
517
+		}
518
+		if (! empty($key)) {
519
+			return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
520
+		}
521
+		return $this->_session_data;
522
+	}
523
+
524
+
525
+	/**
526
+	 * Returns TRUE on success, FALSE on fail
527
+	 *
528
+	 * @param array $data
529
+	 * @return bool
530
+	 */
531
+	public function set_session_data($data)
532
+	{
533
+		// nothing ??? bad data ??? go home!
534
+		if (empty($data) || ! is_array($data)) {
535
+			EE_Error::add_error(
536
+				esc_html__(
537
+					'No session data or invalid session data was provided.',
538
+					'event_espresso'
539
+				),
540
+				__FILE__, __FUNCTION__, __LINE__
541
+			);
542
+			return false;
543
+		}
544
+		foreach ($data as $key => $value) {
545
+			if (isset($this->_default_session_vars[ $key ])) {
546
+				EE_Error::add_error(
547
+					sprintf(
548
+						esc_html__(
549
+							'Sorry! %s is a default session datum and can not be reset.',
550
+							'event_espresso'
551
+						),
552
+						$key
553
+					),
554
+					__FILE__, __FUNCTION__, __LINE__
555
+				);
556
+				return false;
557
+			}
558
+			$this->_session_data[ $key ] = $value;
559
+		}
560
+		return true;
561
+	}
562
+
563
+
564
+
565
+	/**
566
+	 * @initiate session
567
+	 * @access   private
568
+	 * @return TRUE on success, FALSE on fail
569
+	 * @throws EE_Error
570
+	 * @throws InvalidArgumentException
571
+	 * @throws InvalidDataTypeException
572
+	 * @throws InvalidInterfaceException
573
+	 * @throws InvalidSessionDataException
574
+	 */
575
+	private function _espresso_session()
576
+	{
577
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
578
+		// check that session has started
579
+		if (session_id() === '') {
580
+			//starts a new session if one doesn't already exist, or re-initiates an existing one
581
+			session_start();
582
+		}
583
+		$this->status = EE_Session::STATUS_OPEN;
584
+		// get our modified session ID
585
+		$this->_sid = $this->_generate_session_id();
586
+		// and the visitors IP
587
+		$this->_ip_address = $this->request->ipAddress();
588
+		// set the "user agent"
589
+		$this->_user_agent = $this->request->userAgent();
590
+		// now let's retrieve what's in the db
591
+		$session_data = $this->_retrieve_session_data();
592
+		if (! empty($session_data)) {
593
+			// get the current time in UTC
594
+			$this->_time = $this->_time !== null ? $this->_time : time();
595
+			// and reset the session expiration
596
+			$this->_expiration = isset($session_data['expiration'])
597
+				? $session_data['expiration']
598
+				: $this->_time + $this->session_lifespan->inSeconds();
599
+		} else {
600
+			// set initial site access time and the session expiration
601
+			$this->_set_init_access_and_expiration();
602
+			// set referer
603
+			$this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
604
+				? esc_attr($_SERVER['HTTP_REFERER'])
605
+				: '';
606
+			// no previous session = go back and create one (on top of the data above)
607
+			return false;
608
+		}
609
+		// now the user agent
610
+		if ($session_data['user_agent'] !== $this->_user_agent) {
611
+			return false;
612
+		}
613
+		// wait a minute... how old are you?
614
+		if ($this->_time > $this->_expiration) {
615
+			// yer too old fer me!
616
+			$this->_expired = true;
617
+			// wipe out everything that isn't a default session datum
618
+			$this->clear_session(__CLASS__, __FUNCTION__);
619
+		}
620
+		// make event espresso session data available to plugin
621
+		$this->_session_data = array_merge($this->_session_data, $session_data);
622
+		return true;
623
+	}
624
+
625
+
626
+
627
+	/**
628
+	 * _get_session_data
629
+	 * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup
630
+	 * databases
631
+	 *
632
+	 * @return array
633
+	 * @throws EE_Error
634
+	 * @throws InvalidArgumentException
635
+	 * @throws InvalidSessionDataException
636
+	 * @throws InvalidDataTypeException
637
+	 * @throws InvalidInterfaceException
638
+	 */
639
+	protected function _retrieve_session_data()
640
+	{
641
+		$ssn_key = EE_Session::session_id_prefix . $this->_sid;
642
+		try {
643
+			// we're using WP's Transient API to store session data using the PHP session ID as the option name
644
+			$session_data = $this->cache_storage->get($ssn_key, false);
645
+			if (empty($session_data)) {
646
+				return array();
647
+			}
648
+			if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
649
+				$hash_check = $this->cache_storage->get(
650
+					EE_Session::hash_check_prefix . $this->_sid,
651
+					false
652
+				);
653
+				if ($hash_check && $hash_check !== md5($session_data)) {
654
+					EE_Error::add_error(
655
+						sprintf(
656
+							__(
657
+								'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
658
+								'event_espresso'
659
+							),
660
+							EE_Session::session_id_prefix . $this->_sid
661
+						),
662
+						__FILE__, __FUNCTION__, __LINE__
663
+					);
664
+				}
665
+			}
666
+		} catch (Exception $e) {
667
+			// let's just eat that error for now and attempt to correct any corrupted data
668
+			global $wpdb;
669
+			$row          = $wpdb->get_row(
670
+				$wpdb->prepare(
671
+					"SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
672
+					'_transient_' . $ssn_key
673
+				)
674
+			);
675
+			$session_data = is_object($row) ? $row->option_value : null;
676
+			if ($session_data) {
677
+				$session_data = preg_replace_callback(
678
+					'!s:(d+):"(.*?)";!',
679
+					function ($match)
680
+					{
681
+						return $match[1] === strlen($match[2])
682
+							? $match[0]
683
+							: 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
684
+					},
685
+					$session_data
686
+				);
687
+			}
688
+			$session_data = maybe_unserialize($session_data);
689
+		}
690
+		// in case the data is encoded... try to decode it
691
+		$session_data = $this->encryption instanceof EE_Encryption
692
+			? $this->encryption->base64_string_decode($session_data)
693
+			: $session_data;
694
+		if (! is_array($session_data)) {
695
+			try {
696
+				$session_data = maybe_unserialize($session_data);
697
+			} catch (Exception $e) {
698
+				$msg = esc_html__(
699
+					'An error occurred while attempting to unserialize the session data.',
700
+					'event_espresso'
701
+				);
702
+				$msg .= WP_DEBUG
703
+					? '<br><pre>'
704
+					  . print_r($session_data, true)
705
+					  . '</pre><br>'
706
+					  . $this->find_serialize_error($session_data)
707
+					: '';
708
+				$this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
709
+				throw new InvalidSessionDataException($msg, 0, $e);
710
+			}
711
+		}
712
+		// just a check to make sure the session array is indeed an array
713
+		if (! is_array($session_data)) {
714
+			// no?!?! then something is wrong
715
+			$msg = esc_html__(
716
+				'The session data is missing, invalid, or corrupted.',
717
+				'event_espresso'
718
+			);
719
+			$msg .= WP_DEBUG
720
+				? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
721
+				: '';
722
+			$this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
723
+			throw new InvalidSessionDataException($msg);
724
+		}
725
+		if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
726
+			$session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
727
+				$session_data['transaction']
728
+			);
729
+		}
730
+		return $session_data;
731
+	}
732
+
733
+
734
+
735
+	/**
736
+	 * _generate_session_id
737
+	 * Retrieves the PHP session id either directly from the PHP session,
738
+	 * or from the $_REQUEST array if it was passed in from an AJAX request.
739
+	 * The session id is then salted and hashed (mmm sounds tasty)
740
+	 * so that it can be safely used as a $_REQUEST param
741
+	 *
742
+	 * @return string
743
+	 */
744
+	protected function _generate_session_id()
745
+	{
746
+		// check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
747
+		if (isset($_REQUEST['EESID'])) {
748
+			$session_id = sanitize_text_field($_REQUEST['EESID']);
749
+		} else {
750
+			$session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
751
+		}
752
+		return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * _get_sid_salt
759
+	 *
760
+	 * @return string
761
+	 */
762
+	protected function _get_sid_salt()
763
+	{
764
+		// was session id salt already saved to db ?
765
+		if (empty($this->_sid_salt)) {
766
+			// no?  then maybe use WP defined constant
767
+			if (defined('AUTH_SALT')) {
768
+				$this->_sid_salt = AUTH_SALT;
769
+			}
770
+			// if salt doesn't exist or is too short
771
+			if (strlen($this->_sid_salt) < 32) {
772
+				// create a new one
773
+				$this->_sid_salt = wp_generate_password(64);
774
+			}
775
+			// and save it as a permanent session setting
776
+			$this->updateSessionSettings(array('sid_salt' => $this->_sid_salt));
777
+		}
778
+		return $this->_sid_salt;
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * _set_init_access_and_expiration
785
+	 *
786
+	 * @return void
787
+	 */
788
+	protected function _set_init_access_and_expiration()
789
+	{
790
+		$this->_time       = time();
791
+		$this->_expiration = $this->_time + $this->session_lifespan->inSeconds();
792
+		// set initial site access time
793
+		$this->_session_data['init_access'] = $this->_time;
794
+		// and the session expiration
795
+		$this->_session_data['expiration'] = $this->_expiration;
796
+	}
797
+
798
+
799
+
800
+	/**
801
+	 * @update session data  prior to saving to the db
802
+	 * @access public
803
+	 * @param bool $new_session
804
+	 * @return TRUE on success, FALSE on fail
805
+	 * @throws EE_Error
806
+	 * @throws InvalidArgumentException
807
+	 * @throws InvalidDataTypeException
808
+	 * @throws InvalidInterfaceException
809
+	 */
810
+	public function update($new_session = false)
811
+	{
812
+		$this->_session_data = $this->_session_data !== null
813
+							   && is_array($this->_session_data)
814
+							   && isset($this->_session_data['id'])
815
+			? $this->_session_data
816
+			: array();
817
+		if (empty($this->_session_data)) {
818
+			$this->_set_defaults();
819
+		}
820
+		$session_data = array();
821
+		foreach ($this->_session_data as $key => $value) {
822
+
823
+			switch ($key) {
824
+
825
+				case 'id' :
826
+					// session ID
827
+					$session_data['id'] = $this->_sid;
828
+					break;
829
+				case 'ip_address' :
830
+					// visitor ip address
831
+					$session_data['ip_address'] = $this->request->ipAddress();
832
+					break;
833
+				case 'user_agent' :
834
+					// visitor user_agent
835
+					$session_data['user_agent'] = $this->_user_agent;
836
+					break;
837
+				case 'init_access' :
838
+					$session_data['init_access'] = absint($value);
839
+					break;
840
+				case 'last_access' :
841
+					// current access time
842
+					$session_data['last_access'] = $this->_time;
843
+					break;
844
+				case 'expiration' :
845
+					// when the session expires
846
+					$session_data['expiration'] = ! empty($this->_expiration)
847
+						? $this->_expiration
848
+						: $session_data['init_access'] + $this->session_lifespan->inSeconds();
849
+					break;
850
+				case 'user_id' :
851
+					// current user if logged in
852
+					$session_data['user_id'] = $this->_wp_user_id();
853
+					break;
854
+				case 'pages_visited' :
855
+					$page_visit = $this->_get_page_visit();
856
+					if ($page_visit) {
857
+						// set pages visited where the first will be the http referrer
858
+						$this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
859
+						// we'll only save the last 10 page visits.
860
+						$session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
861
+					}
862
+					break;
863
+				default :
864
+					// carry any other data over
865
+					$session_data[ $key ] = $this->_session_data[ $key ];
866
+			}
867
+		}
868
+		$this->_session_data = $session_data;
869
+		// creating a new session does not require saving to the db just yet
870
+		if (! $new_session) {
871
+			// ready? let's save
872
+			if ($this->_save_session_to_db()) {
873
+				return true;
874
+			}
875
+			return false;
876
+		}
877
+		// meh, why not?
878
+		return true;
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * @create session data array
885
+	 * @access public
886
+	 * @return bool
887
+	 * @throws EE_Error
888
+	 * @throws InvalidArgumentException
889
+	 * @throws InvalidDataTypeException
890
+	 * @throws InvalidInterfaceException
891
+	 */
892
+	private function _create_espresso_session()
893
+	{
894
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
895
+		// use the update function for now with $new_session arg set to TRUE
896
+		return $this->update(true) ? true : false;
897
+	}
898
+
899
+
900
+
901
+	/**
902
+	 * _save_session_to_db
903
+	 *
904
+	 * @param bool $clear_session
905
+	 * @return string
906
+	 * @throws EE_Error
907
+	 * @throws InvalidArgumentException
908
+	 * @throws InvalidDataTypeException
909
+	 * @throws InvalidInterfaceException
910
+	 */
911
+	private function _save_session_to_db($clear_session = false)
912
+	{
913
+		// don't save sessions for crawlers
914
+		// and unless we're deleting the session data, don't save anything if there isn't a cart
915
+		if ($this->request->isBot() || (! $clear_session && ! $this->cart() instanceof EE_Cart)) {
916
+			return false;
917
+		}
918
+		$transaction = $this->transaction();
919
+		if ($transaction instanceof EE_Transaction) {
920
+			if (! $transaction->ID()) {
921
+				$transaction->save();
922
+			}
923
+			$this->_session_data['transaction'] = $transaction->ID();
924
+		}
925
+		// then serialize all of our session data
926
+		$session_data = serialize($this->_session_data);
927
+		// do we need to also encode it to avoid corrupted data when saved to the db?
928
+		$session_data = $this->_use_encryption
929
+			? $this->encryption->base64_string_encode($session_data)
930
+			: $session_data;
931
+		// maybe save hash check
932
+		if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
933
+			$this->cache_storage->add(
934
+				EE_Session::hash_check_prefix . $this->_sid,
935
+				md5($session_data),
936
+				$this->session_lifespan->inSeconds()
937
+			);
938
+		}
939
+		// we're using the Transient API for storing session data,
940
+		return $this->cache_storage->add(
941
+			EE_Session::session_id_prefix . $this->_sid,
942
+			$session_data,
943
+			$this->session_lifespan->inSeconds()
944
+		);
945
+	}
946
+
947
+
948
+	/**
949
+	 * @get    the full page request the visitor is accessing
950
+	 * @access public
951
+	 * @return string
952
+	 */
953
+	public function _get_page_visit()
954
+	{
955
+		$page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
956
+		// check for request url
957
+		if (isset($_SERVER['REQUEST_URI'])) {
958
+			$http_host   = '';
959
+			$page_id     = '?';
960
+			$e_reg       = '';
961
+			$request_uri = esc_url($_SERVER['REQUEST_URI']);
962
+			$ru_bits     = explode('?', $request_uri);
963
+			$request_uri = $ru_bits[0];
964
+			// check for and grab host as well
965
+			if (isset($_SERVER['HTTP_HOST'])) {
966
+				$http_host = esc_url($_SERVER['HTTP_HOST']);
967
+			}
968
+			// check for page_id in SERVER REQUEST
969
+			if (isset($_REQUEST['page_id'])) {
970
+				// rebuild $e_reg without any of the extra parameters
971
+				$page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
972
+			}
973
+			// check for $e_reg in SERVER REQUEST
974
+			if (isset($_REQUEST['ee'])) {
975
+				// rebuild $e_reg without any of the extra parameters
976
+				$e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
977
+			}
978
+			$page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
979
+		}
980
+		return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
981
+	}
982
+
983
+
984
+
985
+	/**
986
+	 * @the    current wp user id
987
+	 * @access public
988
+	 * @return int
989
+	 */
990
+	public function _wp_user_id()
991
+	{
992
+		// if I need to explain the following lines of code, then you shouldn't be looking at this!
993
+		$this->_wp_user_id = get_current_user_id();
994
+		return $this->_wp_user_id;
995
+	}
996
+
997
+
998
+
999
+	/**
1000
+	 * Clear EE_Session data
1001
+	 *
1002
+	 * @access public
1003
+	 * @param string $class
1004
+	 * @param string $function
1005
+	 * @return void
1006
+	 * @throws EE_Error
1007
+	 * @throws InvalidArgumentException
1008
+	 * @throws InvalidDataTypeException
1009
+	 * @throws InvalidInterfaceException
1010
+	 */
1011
+	public function clear_session($class = '', $function = '')
1012
+	{
1013 1013
 //         echo '
1014 1014
 // <h3 style="color:#999;line-height:.9em;">
1015 1015
 // <span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/>
1016 1016
 // <span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b>
1017 1017
 // </h3>';
1018
-        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1019
-        $this->reset_cart();
1020
-        $this->reset_checkout();
1021
-        $this->reset_transaction();
1022
-        // wipe out everything that isn't a default session datum
1023
-        $this->reset_data(array_keys($this->_session_data));
1024
-        // reset initial site access time and the session expiration
1025
-        $this->_set_init_access_and_expiration();
1026
-        $this->_save_session_to_db(true);
1027
-    }
1028
-
1029
-
1030
-    /**
1031
-     * resets all non-default session vars. Returns TRUE on success, FALSE on fail
1032
-     *
1033
-     * @param array|mixed $data_to_reset
1034
-     * @param bool        $show_all_notices
1035
-     * @return bool
1036
-     */
1037
-    public function reset_data($data_to_reset = array(), $show_all_notices = false)
1038
-    {
1039
-        // if $data_to_reset is not in an array, then put it in one
1040
-        if (! is_array($data_to_reset)) {
1041
-            $data_to_reset = array($data_to_reset);
1042
-        }
1043
-        // nothing ??? go home!
1044
-        if (empty($data_to_reset)) {
1045
-            EE_Error::add_error(__('No session data could be reset, because no session var name was provided.',
1046
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1047
-            return false;
1048
-        }
1049
-        $return_value = true;
1050
-        // since $data_to_reset is an array, cycle through the values
1051
-        foreach ($data_to_reset as $reset) {
1052
-
1053
-            // first check to make sure it is a valid session var
1054
-            if (isset($this->_session_data[ $reset ])) {
1055
-                // then check to make sure it is not a default var
1056
-                if (! array_key_exists($reset, $this->_default_session_vars)) {
1057
-                    // remove session var
1058
-                    unset($this->_session_data[ $reset ]);
1059
-                    if ($show_all_notices) {
1060
-                        EE_Error::add_success(sprintf(__('The session variable %s was removed.', 'event_espresso'),
1061
-                            $reset), __FILE__, __FUNCTION__, __LINE__);
1062
-                    }
1063
-                } else {
1064
-                    // yeeeeeeeeerrrrrrrrrrr OUT !!!!
1065
-                    if ($show_all_notices) {
1066
-                        EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
1067
-                            'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1068
-                    }
1069
-                    $return_value = false;
1070
-                }
1071
-            } elseif ($show_all_notices) {
1072
-                // oops! that session var does not exist!
1073
-                EE_Error::add_error(sprintf(__('The session item provided, %s, is invalid or does not exist.',
1074
-                    'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1075
-                $return_value = false;
1076
-            }
1077
-        } // end of foreach
1078
-        return $return_value;
1079
-    }
1080
-
1081
-
1082
-
1083
-    /**
1084
-     *   wp_loaded
1085
-     *
1086
-     * @access public
1087
-     * @throws EE_Error
1088
-     * @throws InvalidDataTypeException
1089
-     * @throws InvalidInterfaceException
1090
-     * @throws InvalidArgumentException
1091
-     */
1092
-    public function wp_loaded()
1093
-    {
1094
-        if ($this->request->requestParamIsSet('clear_session')) {
1095
-            $this->clear_session(__CLASS__, __FUNCTION__);
1096
-        }
1097
-    }
1098
-
1099
-
1100
-
1101
-    /**
1102
-     * Used to reset the entire object (for tests).
1103
-     *
1104
-     * @since 4.3.0
1105
-     * @throws EE_Error
1106
-     * @throws InvalidDataTypeException
1107
-     * @throws InvalidInterfaceException
1108
-     * @throws InvalidArgumentException
1109
-     */
1110
-    public function reset_instance()
1111
-    {
1112
-        $this->clear_session();
1113
-        self::$_instance = null;
1114
-    }
1115
-
1116
-
1117
-
1118
-    public function configure_garbage_collection_filters()
1119
-    {
1120
-        // run old filter we had for controlling session cleanup
1121
-        $expired_session_transient_delete_query_limit = absint(
1122
-            apply_filters(
1123
-                'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1124
-                50
1125
-            )
1126
-        );
1127
-        // is there a value? or one that is different than the default 50 records?
1128
-        if ($expired_session_transient_delete_query_limit === 0) {
1129
-            // hook into TransientCacheStorage in case Session cleanup was turned off
1130
-            add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1131
-        } elseif ($expired_session_transient_delete_query_limit !== 50) {
1132
-            // or use that for the new transient cleanup query limit
1133
-            add_filter(
1134
-                'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1135
-                function () use ($expired_session_transient_delete_query_limit)
1136
-                {
1137
-                    return $expired_session_transient_delete_query_limit;
1138
-                }
1139
-            );
1140
-        }
1141
-    }
1142
-
1143
-
1144
-
1145
-    /**
1146
-     * @see http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset/21389439#10152996
1147
-     * @param $data1
1148
-     * @return string
1149
-     */
1150
-    private function find_serialize_error($data1)
1151
-    {
1152
-        $error = '<pre>';
1153
-        $data2 = preg_replace_callback(
1154
-            '!s:(\d+):"(.*?)";!',
1155
-            function ($match)
1156
-            {
1157
-                return ($match[1] === strlen($match[2]))
1158
-                    ? $match[0]
1159
-                    : 's:'
1160
-                      . strlen($match[2])
1161
-                      . ':"'
1162
-                      . $match[2]
1163
-                      . '";';
1164
-            },
1165
-            $data1
1166
-        );
1167
-        $max   = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1168
-        $error .= $data1 . PHP_EOL;
1169
-        $error .= $data2 . PHP_EOL;
1170
-        for ($i = 0; $i < $max; $i++) {
1171
-            if (@$data1[ $i ] !== @$data2[ $i ]) {
1172
-                $error  .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1173
-                $error  .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1174
-                $error  .= "\t-> Line Number = $i" . PHP_EOL;
1175
-                $start  = ($i - 20);
1176
-                $start  = ($start < 0) ? 0 : $start;
1177
-                $length = 40;
1178
-                $point  = $max - $i;
1179
-                if ($point < 20) {
1180
-                    $rlength = 1;
1181
-                    $rpoint  = -$point;
1182
-                } else {
1183
-                    $rpoint  = $length - 20;
1184
-                    $rlength = 1;
1185
-                }
1186
-                $error .= "\t-> Section Data1  = ";
1187
-                $error .= substr_replace(
1188
-                    substr($data1, $start, $length),
1189
-                    "<b style=\"color:green\">{$data1[ $i ]}</b>",
1190
-                    $rpoint,
1191
-                    $rlength
1192
-                );
1193
-                $error .= PHP_EOL;
1194
-                $error .= "\t-> Section Data2  = ";
1195
-                $error .= substr_replace(
1196
-                    substr($data2, $start, $length),
1197
-                    "<b style=\"color:red\">{$data2[ $i ]}</b>",
1198
-                    $rpoint,
1199
-                    $rlength
1200
-                );
1201
-                $error .= PHP_EOL;
1202
-            }
1203
-        }
1204
-        $error .= '</pre>';
1205
-        return $error;
1206
-    }
1207
-
1208
-
1209
-    /**
1210
-     * Saves an  array of settings used for configuring aspects of session behaviour
1211
-     *
1212
-     * @param array $updated_settings
1213
-     */
1214
-    private function updateSessionSettings(array $updated_settings = array())
1215
-    {
1216
-        // add existing settings, but only if not included in incoming $updated_settings array
1217
-        $updated_settings += get_option(EE_Session::OPTION_NAME_SETTINGS, array());
1218
-        update_option(EE_Session::OPTION_NAME_SETTINGS, $updated_settings);
1219
-    }
1220
-
1221
-
1222
-    /**
1223
-     * garbage_collection
1224
-     */
1225
-    public function garbageCollection()
1226
-    {
1227
-        // only perform during regular requests if last garbage collection was over an hour ago
1228
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1229
-            $this->_last_gc = time();
1230
-            $this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1231
-            /** @type WPDB $wpdb */
1232
-            global $wpdb;
1233
-            // filter the query limit. Set to 0 to turn off garbage collection
1234
-            $expired_session_transient_delete_query_limit = absint(
1235
-                apply_filters(
1236
-                    'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1237
-                    50
1238
-                )
1239
-            );
1240
-            // non-zero LIMIT means take out the trash
1241
-            if ($expired_session_transient_delete_query_limit) {
1242
-                $session_key    = str_replace('_', '\_', EE_Session::session_id_prefix);
1243
-                $hash_check_key = str_replace('_', '\_', EE_Session::hash_check_prefix);
1244
-                // since transient expiration timestamps are set in the future, we can compare against NOW
1245
-                // but we only want to pick up any trash that's been around for more than a day
1246
-                $expiration = time() - DAY_IN_SECONDS;
1247
-                $SQL        = "
1018
+		do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1019
+		$this->reset_cart();
1020
+		$this->reset_checkout();
1021
+		$this->reset_transaction();
1022
+		// wipe out everything that isn't a default session datum
1023
+		$this->reset_data(array_keys($this->_session_data));
1024
+		// reset initial site access time and the session expiration
1025
+		$this->_set_init_access_and_expiration();
1026
+		$this->_save_session_to_db(true);
1027
+	}
1028
+
1029
+
1030
+	/**
1031
+	 * resets all non-default session vars. Returns TRUE on success, FALSE on fail
1032
+	 *
1033
+	 * @param array|mixed $data_to_reset
1034
+	 * @param bool        $show_all_notices
1035
+	 * @return bool
1036
+	 */
1037
+	public function reset_data($data_to_reset = array(), $show_all_notices = false)
1038
+	{
1039
+		// if $data_to_reset is not in an array, then put it in one
1040
+		if (! is_array($data_to_reset)) {
1041
+			$data_to_reset = array($data_to_reset);
1042
+		}
1043
+		// nothing ??? go home!
1044
+		if (empty($data_to_reset)) {
1045
+			EE_Error::add_error(__('No session data could be reset, because no session var name was provided.',
1046
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1047
+			return false;
1048
+		}
1049
+		$return_value = true;
1050
+		// since $data_to_reset is an array, cycle through the values
1051
+		foreach ($data_to_reset as $reset) {
1052
+
1053
+			// first check to make sure it is a valid session var
1054
+			if (isset($this->_session_data[ $reset ])) {
1055
+				// then check to make sure it is not a default var
1056
+				if (! array_key_exists($reset, $this->_default_session_vars)) {
1057
+					// remove session var
1058
+					unset($this->_session_data[ $reset ]);
1059
+					if ($show_all_notices) {
1060
+						EE_Error::add_success(sprintf(__('The session variable %s was removed.', 'event_espresso'),
1061
+							$reset), __FILE__, __FUNCTION__, __LINE__);
1062
+					}
1063
+				} else {
1064
+					// yeeeeeeeeerrrrrrrrrrr OUT !!!!
1065
+					if ($show_all_notices) {
1066
+						EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
1067
+							'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1068
+					}
1069
+					$return_value = false;
1070
+				}
1071
+			} elseif ($show_all_notices) {
1072
+				// oops! that session var does not exist!
1073
+				EE_Error::add_error(sprintf(__('The session item provided, %s, is invalid or does not exist.',
1074
+					'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1075
+				$return_value = false;
1076
+			}
1077
+		} // end of foreach
1078
+		return $return_value;
1079
+	}
1080
+
1081
+
1082
+
1083
+	/**
1084
+	 *   wp_loaded
1085
+	 *
1086
+	 * @access public
1087
+	 * @throws EE_Error
1088
+	 * @throws InvalidDataTypeException
1089
+	 * @throws InvalidInterfaceException
1090
+	 * @throws InvalidArgumentException
1091
+	 */
1092
+	public function wp_loaded()
1093
+	{
1094
+		if ($this->request->requestParamIsSet('clear_session')) {
1095
+			$this->clear_session(__CLASS__, __FUNCTION__);
1096
+		}
1097
+	}
1098
+
1099
+
1100
+
1101
+	/**
1102
+	 * Used to reset the entire object (for tests).
1103
+	 *
1104
+	 * @since 4.3.0
1105
+	 * @throws EE_Error
1106
+	 * @throws InvalidDataTypeException
1107
+	 * @throws InvalidInterfaceException
1108
+	 * @throws InvalidArgumentException
1109
+	 */
1110
+	public function reset_instance()
1111
+	{
1112
+		$this->clear_session();
1113
+		self::$_instance = null;
1114
+	}
1115
+
1116
+
1117
+
1118
+	public function configure_garbage_collection_filters()
1119
+	{
1120
+		// run old filter we had for controlling session cleanup
1121
+		$expired_session_transient_delete_query_limit = absint(
1122
+			apply_filters(
1123
+				'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1124
+				50
1125
+			)
1126
+		);
1127
+		// is there a value? or one that is different than the default 50 records?
1128
+		if ($expired_session_transient_delete_query_limit === 0) {
1129
+			// hook into TransientCacheStorage in case Session cleanup was turned off
1130
+			add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1131
+		} elseif ($expired_session_transient_delete_query_limit !== 50) {
1132
+			// or use that for the new transient cleanup query limit
1133
+			add_filter(
1134
+				'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1135
+				function () use ($expired_session_transient_delete_query_limit)
1136
+				{
1137
+					return $expired_session_transient_delete_query_limit;
1138
+				}
1139
+			);
1140
+		}
1141
+	}
1142
+
1143
+
1144
+
1145
+	/**
1146
+	 * @see http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset/21389439#10152996
1147
+	 * @param $data1
1148
+	 * @return string
1149
+	 */
1150
+	private function find_serialize_error($data1)
1151
+	{
1152
+		$error = '<pre>';
1153
+		$data2 = preg_replace_callback(
1154
+			'!s:(\d+):"(.*?)";!',
1155
+			function ($match)
1156
+			{
1157
+				return ($match[1] === strlen($match[2]))
1158
+					? $match[0]
1159
+					: 's:'
1160
+					  . strlen($match[2])
1161
+					  . ':"'
1162
+					  . $match[2]
1163
+					  . '";';
1164
+			},
1165
+			$data1
1166
+		);
1167
+		$max   = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1168
+		$error .= $data1 . PHP_EOL;
1169
+		$error .= $data2 . PHP_EOL;
1170
+		for ($i = 0; $i < $max; $i++) {
1171
+			if (@$data1[ $i ] !== @$data2[ $i ]) {
1172
+				$error  .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1173
+				$error  .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1174
+				$error  .= "\t-> Line Number = $i" . PHP_EOL;
1175
+				$start  = ($i - 20);
1176
+				$start  = ($start < 0) ? 0 : $start;
1177
+				$length = 40;
1178
+				$point  = $max - $i;
1179
+				if ($point < 20) {
1180
+					$rlength = 1;
1181
+					$rpoint  = -$point;
1182
+				} else {
1183
+					$rpoint  = $length - 20;
1184
+					$rlength = 1;
1185
+				}
1186
+				$error .= "\t-> Section Data1  = ";
1187
+				$error .= substr_replace(
1188
+					substr($data1, $start, $length),
1189
+					"<b style=\"color:green\">{$data1[ $i ]}</b>",
1190
+					$rpoint,
1191
+					$rlength
1192
+				);
1193
+				$error .= PHP_EOL;
1194
+				$error .= "\t-> Section Data2  = ";
1195
+				$error .= substr_replace(
1196
+					substr($data2, $start, $length),
1197
+					"<b style=\"color:red\">{$data2[ $i ]}</b>",
1198
+					$rpoint,
1199
+					$rlength
1200
+				);
1201
+				$error .= PHP_EOL;
1202
+			}
1203
+		}
1204
+		$error .= '</pre>';
1205
+		return $error;
1206
+	}
1207
+
1208
+
1209
+	/**
1210
+	 * Saves an  array of settings used for configuring aspects of session behaviour
1211
+	 *
1212
+	 * @param array $updated_settings
1213
+	 */
1214
+	private function updateSessionSettings(array $updated_settings = array())
1215
+	{
1216
+		// add existing settings, but only if not included in incoming $updated_settings array
1217
+		$updated_settings += get_option(EE_Session::OPTION_NAME_SETTINGS, array());
1218
+		update_option(EE_Session::OPTION_NAME_SETTINGS, $updated_settings);
1219
+	}
1220
+
1221
+
1222
+	/**
1223
+	 * garbage_collection
1224
+	 */
1225
+	public function garbageCollection()
1226
+	{
1227
+		// only perform during regular requests if last garbage collection was over an hour ago
1228
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1229
+			$this->_last_gc = time();
1230
+			$this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1231
+			/** @type WPDB $wpdb */
1232
+			global $wpdb;
1233
+			// filter the query limit. Set to 0 to turn off garbage collection
1234
+			$expired_session_transient_delete_query_limit = absint(
1235
+				apply_filters(
1236
+					'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1237
+					50
1238
+				)
1239
+			);
1240
+			// non-zero LIMIT means take out the trash
1241
+			if ($expired_session_transient_delete_query_limit) {
1242
+				$session_key    = str_replace('_', '\_', EE_Session::session_id_prefix);
1243
+				$hash_check_key = str_replace('_', '\_', EE_Session::hash_check_prefix);
1244
+				// since transient expiration timestamps are set in the future, we can compare against NOW
1245
+				// but we only want to pick up any trash that's been around for more than a day
1246
+				$expiration = time() - DAY_IN_SECONDS;
1247
+				$SQL        = "
1248 1248
                     SELECT option_name
1249 1249
                     FROM {$wpdb->options}
1250 1250
                     WHERE
@@ -1253,19 +1253,19 @@  discard block
 block discarded – undo
1253 1253
                     AND option_value < {$expiration}
1254 1254
                     LIMIT {$expired_session_transient_delete_query_limit}
1255 1255
                 ";
1256
-                // produces something like:
1257
-                // SELECT option_name FROM wp_options
1258
-                // WHERE ( option_name LIKE '\_transient\_timeout\_ee\_ssn\_%'
1259
-                // OR option_name LIKE '\_transient\_timeout\_ee\_shc\_%' )
1260
-                // AND option_value < 1508368198 LIMIT 50
1261
-                $expired_sessions = $wpdb->get_col($SQL);
1262
-                // valid results?
1263
-                if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1264
-                    $this->cache_storage->deleteMany($expired_sessions, true);
1265
-                }
1266
-            }
1267
-        }
1268
-    }
1256
+				// produces something like:
1257
+				// SELECT option_name FROM wp_options
1258
+				// WHERE ( option_name LIKE '\_transient\_timeout\_ee\_ssn\_%'
1259
+				// OR option_name LIKE '\_transient\_timeout\_ee\_shc\_%' )
1260
+				// AND option_value < 1508368198 LIMIT 50
1261
+				$expired_sessions = $wpdb->get_col($SQL);
1262
+				// valid results?
1263
+				if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1264
+					$this->cache_storage->deleteMany($expired_sessions, true);
1265
+				}
1266
+			}
1267
+		}
1268
+	}
1269 1269
 
1270 1270
 
1271 1271
 
Please login to merge, or discard this patch.
Spacing   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
         // check if class object is instantiated
187 187
         // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
188 188
         // add_filter( 'FHEE_load_EE_Session', '__return_false' );
189
-        if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
189
+        if ( ! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
190 190
             self::$_instance = new self(
191 191
                 $cache_storage,
192 192
                 $lifespan,
@@ -219,21 +219,21 @@  discard block
 block discarded – undo
219 219
         // but prior to the 'AHEE__EE_System__core_loaded_and_ready' hook
220 220
         // (which currently fires on the init hook at priority 9),
221 221
         // can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
222
-        if (! apply_filters('FHEE_load_EE_Session', true)) {
222
+        if ( ! apply_filters('FHEE_load_EE_Session', true)) {
223 223
             return;
224 224
         }
225 225
         $this->session_lifespan = $lifespan;
226 226
         $this->request          = $request;
227
-        if (! defined('ESPRESSO_SESSION')) {
227
+        if ( ! defined('ESPRESSO_SESSION')) {
228 228
             define('ESPRESSO_SESSION', true);
229 229
         }
230 230
         // retrieve session options from db
231 231
         $session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
232
-        if (! empty($session_settings)) {
232
+        if ( ! empty($session_settings)) {
233 233
             // cycle though existing session options
234 234
             foreach ($session_settings as $var_name => $session_setting) {
235 235
                 // set values for class properties
236
-                $var_name          = '_' . $var_name;
236
+                $var_name          = '_'.$var_name;
237 237
                 $this->{$var_name} = $session_setting;
238 238
             }
239 239
         }
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
     public function open_session()
294 294
     {
295 295
         // check for existing session and retrieve it from db
296
-        if (! $this->_espresso_session()) {
296
+        if ( ! $this->_espresso_session()) {
297 297
             // or just start a new one
298 298
             $this->_create_espresso_session();
299 299
         }
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
      */
346 346
     public function extend_expiration($time = 0)
347 347
     {
348
-        $time              = $time ? $time : $this->extension();
348
+        $time = $time ? $time : $this->extension();
349 349
         $this->_expiration += absint($time);
350 350
     }
351 351
 
@@ -372,9 +372,9 @@  discard block
 block discarded – undo
372 372
         // set some defaults
373 373
         foreach ($this->_default_session_vars as $key => $default_var) {
374 374
             if (is_array($default_var)) {
375
-                $this->_session_data[ $key ] = array();
375
+                $this->_session_data[$key] = array();
376 376
             } else {
377
-                $this->_session_data[ $key ] = '';
377
+                $this->_session_data[$key] = '';
378 378
             }
379 379
         }
380 380
     }
@@ -515,8 +515,8 @@  discard block
 block discarded – undo
515 515
             $this->reset_checkout();
516 516
             $this->reset_transaction();
517 517
         }
518
-        if (! empty($key)) {
519
-            return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
518
+        if ( ! empty($key)) {
519
+            return isset($this->_session_data[$key]) ? $this->_session_data[$key] : null;
520 520
         }
521 521
         return $this->_session_data;
522 522
     }
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
             return false;
543 543
         }
544 544
         foreach ($data as $key => $value) {
545
-            if (isset($this->_default_session_vars[ $key ])) {
545
+            if (isset($this->_default_session_vars[$key])) {
546 546
                 EE_Error::add_error(
547 547
                     sprintf(
548 548
                         esc_html__(
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
                 );
556 556
                 return false;
557 557
             }
558
-            $this->_session_data[ $key ] = $value;
558
+            $this->_session_data[$key] = $value;
559 559
         }
560 560
         return true;
561 561
     }
@@ -589,7 +589,7 @@  discard block
 block discarded – undo
589 589
         $this->_user_agent = $this->request->userAgent();
590 590
         // now let's retrieve what's in the db
591 591
         $session_data = $this->_retrieve_session_data();
592
-        if (! empty($session_data)) {
592
+        if ( ! empty($session_data)) {
593 593
             // get the current time in UTC
594 594
             $this->_time = $this->_time !== null ? $this->_time : time();
595 595
             // and reset the session expiration
@@ -600,7 +600,7 @@  discard block
 block discarded – undo
600 600
             // set initial site access time and the session expiration
601 601
             $this->_set_init_access_and_expiration();
602 602
             // set referer
603
-            $this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
603
+            $this->_session_data['pages_visited'][$this->_session_data['init_access']] = isset($_SERVER['HTTP_REFERER'])
604 604
                 ? esc_attr($_SERVER['HTTP_REFERER'])
605 605
                 : '';
606 606
             // no previous session = go back and create one (on top of the data above)
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
      */
639 639
     protected function _retrieve_session_data()
640 640
     {
641
-        $ssn_key = EE_Session::session_id_prefix . $this->_sid;
641
+        $ssn_key = EE_Session::session_id_prefix.$this->_sid;
642 642
         try {
643 643
             // we're using WP's Transient API to store session data using the PHP session ID as the option name
644 644
             $session_data = $this->cache_storage->get($ssn_key, false);
@@ -647,7 +647,7 @@  discard block
 block discarded – undo
647 647
             }
648 648
             if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
649 649
                 $hash_check = $this->cache_storage->get(
650
-                    EE_Session::hash_check_prefix . $this->_sid,
650
+                    EE_Session::hash_check_prefix.$this->_sid,
651 651
                     false
652 652
                 );
653 653
                 if ($hash_check && $hash_check !== md5($session_data)) {
@@ -657,7 +657,7 @@  discard block
 block discarded – undo
657 657
                                 'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
658 658
                                 'event_espresso'
659 659
                             ),
660
-                            EE_Session::session_id_prefix . $this->_sid
660
+                            EE_Session::session_id_prefix.$this->_sid
661 661
                         ),
662 662
                         __FILE__, __FUNCTION__, __LINE__
663 663
                     );
@@ -666,21 +666,21 @@  discard block
 block discarded – undo
666 666
         } catch (Exception $e) {
667 667
             // let's just eat that error for now and attempt to correct any corrupted data
668 668
             global $wpdb;
669
-            $row          = $wpdb->get_row(
669
+            $row = $wpdb->get_row(
670 670
                 $wpdb->prepare(
671 671
                     "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
672
-                    '_transient_' . $ssn_key
672
+                    '_transient_'.$ssn_key
673 673
                 )
674 674
             );
675 675
             $session_data = is_object($row) ? $row->option_value : null;
676 676
             if ($session_data) {
677 677
                 $session_data = preg_replace_callback(
678 678
                     '!s:(d+):"(.*?)";!',
679
-                    function ($match)
679
+                    function($match)
680 680
                     {
681 681
                         return $match[1] === strlen($match[2])
682 682
                             ? $match[0]
683
-                            : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
683
+                            : 's:'.strlen($match[2]).':"'.$match[2].'";';
684 684
                     },
685 685
                     $session_data
686 686
                 );
@@ -691,7 +691,7 @@  discard block
 block discarded – undo
691 691
         $session_data = $this->encryption instanceof EE_Encryption
692 692
             ? $this->encryption->base64_string_decode($session_data)
693 693
             : $session_data;
694
-        if (! is_array($session_data)) {
694
+        if ( ! is_array($session_data)) {
695 695
             try {
696 696
                 $session_data = maybe_unserialize($session_data);
697 697
             } catch (Exception $e) {
@@ -705,21 +705,21 @@  discard block
 block discarded – undo
705 705
                       . '</pre><br>'
706 706
                       . $this->find_serialize_error($session_data)
707 707
                     : '';
708
-                $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
708
+                $this->cache_storage->delete(EE_Session::session_id_prefix.$this->_sid);
709 709
                 throw new InvalidSessionDataException($msg, 0, $e);
710 710
             }
711 711
         }
712 712
         // just a check to make sure the session array is indeed an array
713
-        if (! is_array($session_data)) {
713
+        if ( ! is_array($session_data)) {
714 714
             // no?!?! then something is wrong
715 715
             $msg = esc_html__(
716 716
                 'The session data is missing, invalid, or corrupted.',
717 717
                 'event_espresso'
718 718
             );
719 719
             $msg .= WP_DEBUG
720
-                ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
720
+                ? '<br><pre>'.print_r($session_data, true).'</pre><br>'.$this->find_serialize_error($session_data)
721 721
                 : '';
722
-            $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
722
+            $this->cache_storage->delete(EE_Session::session_id_prefix.$this->_sid);
723 723
             throw new InvalidSessionDataException($msg);
724 724
         }
725 725
         if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
@@ -747,7 +747,7 @@  discard block
 block discarded – undo
747 747
         if (isset($_REQUEST['EESID'])) {
748 748
             $session_id = sanitize_text_field($_REQUEST['EESID']);
749 749
         } else {
750
-            $session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
750
+            $session_id = md5(session_id().get_current_blog_id().$this->_get_sid_salt());
751 751
         }
752 752
         return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
753 753
     }
@@ -855,19 +855,19 @@  discard block
 block discarded – undo
855 855
                     $page_visit = $this->_get_page_visit();
856 856
                     if ($page_visit) {
857 857
                         // set pages visited where the first will be the http referrer
858
-                        $this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
858
+                        $this->_session_data['pages_visited'][$this->_time] = $page_visit;
859 859
                         // we'll only save the last 10 page visits.
860 860
                         $session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
861 861
                     }
862 862
                     break;
863 863
                 default :
864 864
                     // carry any other data over
865
-                    $session_data[ $key ] = $this->_session_data[ $key ];
865
+                    $session_data[$key] = $this->_session_data[$key];
866 866
             }
867 867
         }
868 868
         $this->_session_data = $session_data;
869 869
         // creating a new session does not require saving to the db just yet
870
-        if (! $new_session) {
870
+        if ( ! $new_session) {
871 871
             // ready? let's save
872 872
             if ($this->_save_session_to_db()) {
873 873
                 return true;
@@ -912,12 +912,12 @@  discard block
 block discarded – undo
912 912
     {
913 913
         // don't save sessions for crawlers
914 914
         // and unless we're deleting the session data, don't save anything if there isn't a cart
915
-        if ($this->request->isBot() || (! $clear_session && ! $this->cart() instanceof EE_Cart)) {
915
+        if ($this->request->isBot() || ( ! $clear_session && ! $this->cart() instanceof EE_Cart)) {
916 916
             return false;
917 917
         }
918 918
         $transaction = $this->transaction();
919 919
         if ($transaction instanceof EE_Transaction) {
920
-            if (! $transaction->ID()) {
920
+            if ( ! $transaction->ID()) {
921 921
                 $transaction->save();
922 922
             }
923 923
             $this->_session_data['transaction'] = $transaction->ID();
@@ -931,14 +931,14 @@  discard block
 block discarded – undo
931 931
         // maybe save hash check
932 932
         if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
933 933
             $this->cache_storage->add(
934
-                EE_Session::hash_check_prefix . $this->_sid,
934
+                EE_Session::hash_check_prefix.$this->_sid,
935 935
                 md5($session_data),
936 936
                 $this->session_lifespan->inSeconds()
937 937
             );
938 938
         }
939 939
         // we're using the Transient API for storing session data,
940 940
         return $this->cache_storage->add(
941
-            EE_Session::session_id_prefix . $this->_sid,
941
+            EE_Session::session_id_prefix.$this->_sid,
942 942
             $session_data,
943 943
             $this->session_lifespan->inSeconds()
944 944
         );
@@ -952,7 +952,7 @@  discard block
 block discarded – undo
952 952
      */
953 953
     public function _get_page_visit()
954 954
     {
955
-        $page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
955
+        $page_visit = home_url('/').'wp-admin/admin-ajax.php';
956 956
         // check for request url
957 957
         if (isset($_SERVER['REQUEST_URI'])) {
958 958
             $http_host   = '';
@@ -968,14 +968,14 @@  discard block
 block discarded – undo
968 968
             // check for page_id in SERVER REQUEST
969 969
             if (isset($_REQUEST['page_id'])) {
970 970
                 // rebuild $e_reg without any of the extra parameters
971
-                $page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
971
+                $page_id = '?page_id='.esc_attr($_REQUEST['page_id']).'&amp;';
972 972
             }
973 973
             // check for $e_reg in SERVER REQUEST
974 974
             if (isset($_REQUEST['ee'])) {
975 975
                 // rebuild $e_reg without any of the extra parameters
976
-                $e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
976
+                $e_reg = 'ee='.esc_attr($_REQUEST['ee']);
977 977
             }
978
-            $page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
978
+            $page_visit = rtrim($http_host.$request_uri.$page_id.$e_reg, '?');
979 979
         }
980 980
         return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
981 981
     }
@@ -1015,7 +1015,7 @@  discard block
 block discarded – undo
1015 1015
 // <span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/>
1016 1016
 // <span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b>
1017 1017
 // </h3>';
1018
-        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1018
+        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : '.$class.'::'.$function.'()');
1019 1019
         $this->reset_cart();
1020 1020
         $this->reset_checkout();
1021 1021
         $this->reset_transaction();
@@ -1037,7 +1037,7 @@  discard block
 block discarded – undo
1037 1037
     public function reset_data($data_to_reset = array(), $show_all_notices = false)
1038 1038
     {
1039 1039
         // if $data_to_reset is not in an array, then put it in one
1040
-        if (! is_array($data_to_reset)) {
1040
+        if ( ! is_array($data_to_reset)) {
1041 1041
             $data_to_reset = array($data_to_reset);
1042 1042
         }
1043 1043
         // nothing ??? go home!
@@ -1051,11 +1051,11 @@  discard block
 block discarded – undo
1051 1051
         foreach ($data_to_reset as $reset) {
1052 1052
 
1053 1053
             // first check to make sure it is a valid session var
1054
-            if (isset($this->_session_data[ $reset ])) {
1054
+            if (isset($this->_session_data[$reset])) {
1055 1055
                 // then check to make sure it is not a default var
1056
-                if (! array_key_exists($reset, $this->_default_session_vars)) {
1056
+                if ( ! array_key_exists($reset, $this->_default_session_vars)) {
1057 1057
                     // remove session var
1058
-                    unset($this->_session_data[ $reset ]);
1058
+                    unset($this->_session_data[$reset]);
1059 1059
                     if ($show_all_notices) {
1060 1060
                         EE_Error::add_success(sprintf(__('The session variable %s was removed.', 'event_espresso'),
1061 1061
                             $reset), __FILE__, __FUNCTION__, __LINE__);
@@ -1132,7 +1132,7 @@  discard block
 block discarded – undo
1132 1132
             // or use that for the new transient cleanup query limit
1133 1133
             add_filter(
1134 1134
                 'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1135
-                function () use ($expired_session_transient_delete_query_limit)
1135
+                function() use ($expired_session_transient_delete_query_limit)
1136 1136
                 {
1137 1137
                     return $expired_session_transient_delete_query_limit;
1138 1138
                 }
@@ -1152,7 +1152,7 @@  discard block
 block discarded – undo
1152 1152
         $error = '<pre>';
1153 1153
         $data2 = preg_replace_callback(
1154 1154
             '!s:(\d+):"(.*?)";!',
1155
-            function ($match)
1155
+            function($match)
1156 1156
             {
1157 1157
                 return ($match[1] === strlen($match[2]))
1158 1158
                     ? $match[0]
@@ -1164,14 +1164,14 @@  discard block
 block discarded – undo
1164 1164
             },
1165 1165
             $data1
1166 1166
         );
1167
-        $max   = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1168
-        $error .= $data1 . PHP_EOL;
1169
-        $error .= $data2 . PHP_EOL;
1167
+        $max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1168
+        $error .= $data1.PHP_EOL;
1169
+        $error .= $data2.PHP_EOL;
1170 1170
         for ($i = 0; $i < $max; $i++) {
1171
-            if (@$data1[ $i ] !== @$data2[ $i ]) {
1172
-                $error  .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1173
-                $error  .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1174
-                $error  .= "\t-> Line Number = $i" . PHP_EOL;
1171
+            if (@$data1[$i] !== @$data2[$i]) {
1172
+                $error  .= 'Difference '.@$data1[$i].' != '.@$data2[$i].PHP_EOL;
1173
+                $error  .= "\t-> ORD number ".ord(@$data1[$i]).' != '.ord(@$data2[$i]).PHP_EOL;
1174
+                $error  .= "\t-> Line Number = $i".PHP_EOL;
1175 1175
                 $start  = ($i - 20);
1176 1176
                 $start  = ($start < 0) ? 0 : $start;
1177 1177
                 $length = 40;
@@ -1186,7 +1186,7 @@  discard block
 block discarded – undo
1186 1186
                 $error .= "\t-> Section Data1  = ";
1187 1187
                 $error .= substr_replace(
1188 1188
                     substr($data1, $start, $length),
1189
-                    "<b style=\"color:green\">{$data1[ $i ]}</b>",
1189
+                    "<b style=\"color:green\">{$data1[$i]}</b>",
1190 1190
                     $rpoint,
1191 1191
                     $rlength
1192 1192
                 );
@@ -1194,7 +1194,7 @@  discard block
 block discarded – undo
1194 1194
                 $error .= "\t-> Section Data2  = ";
1195 1195
                 $error .= substr_replace(
1196 1196
                     substr($data2, $start, $length),
1197
-                    "<b style=\"color:red\">{$data2[ $i ]}</b>",
1197
+                    "<b style=\"color:red\">{$data2[$i]}</b>",
1198 1198
                     $rpoint,
1199 1199
                     $rlength
1200 1200
                 );
@@ -1225,7 +1225,7 @@  discard block
 block discarded – undo
1225 1225
     public function garbageCollection()
1226 1226
     {
1227 1227
         // only perform during regular requests if last garbage collection was over an hour ago
1228
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1228
+        if ( ! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1229 1229
             $this->_last_gc = time();
1230 1230
             $this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1231 1231
             /** @type WPDB $wpdb */
@@ -1260,7 +1260,7 @@  discard block
 block discarded – undo
1260 1260
                 // AND option_value < 1508368198 LIMIT 50
1261 1261
                 $expired_sessions = $wpdb->get_col($SQL);
1262 1262
                 // valid results?
1263
-                if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1263
+                if ( ! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1264 1264
                     $this->cache_storage->deleteMany($expired_sessions, true);
1265 1265
                 }
1266 1266
             }
Please login to merge, or discard this patch.
core/services/request/Request.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
      * returns true if a match is found or false if not
232 232
      *
233 233
      * @param string $pattern
234
-     * @return false|int
234
+     * @return boolean
235 235
      */
236 236
     public function matches($pattern)
237 237
     {
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
      * would return true if default parameters were set
300 300
      *
301 301
      * @param string $callback
302
-     * @param        $key
302
+     * @param        string $key
303 303
      * @param null   $default
304 304
      * @param array  $request_params
305 305
      * @return bool|mixed|null
Please login to merge, or discard this patch.
Indentation   +584 added lines, -584 removed lines patch added patch discarded remove patch
@@ -20,590 +20,590 @@
 block discarded – undo
20 20
 class Request implements InterminableInterface, RequestInterface
21 21
 {
22 22
 
23
-    /**
24
-     * $_GET parameters
25
-     *
26
-     * @var array $get
27
-     */
28
-    private $get;
29
-
30
-    /**
31
-     * $_POST parameters
32
-     *
33
-     * @var array $post
34
-     */
35
-    private $post;
36
-
37
-    /**
38
-     * $_COOKIE parameters
39
-     *
40
-     * @var array $cookie
41
-     */
42
-    private $cookie;
43
-
44
-    /**
45
-     * $_SERVER parameters
46
-     *
47
-     * @var array $server
48
-     */
49
-    private $server;
50
-
51
-    /**
52
-     * $_REQUEST parameters
53
-     *
54
-     * @var array $request
55
-     */
56
-    private $request;
57
-
58
-    /**
59
-     * @var RequestTypeContextCheckerInterface
60
-     */
61
-    private $request_type;
62
-
63
-    /**
64
-     * IP address for request
65
-     *
66
-     * @var string $ip_address
67
-     */
68
-    private $ip_address;
69
-
70
-    /**
71
-     * @var string $user_agent
72
-     */
73
-    private $user_agent;
74
-
75
-    /**
76
-     * true if current user appears to be some kind of bot
77
-     *
78
-     * @var bool $is_bot
79
-     */
80
-    private $is_bot;
81
-
82
-
83
-
84
-    /**
85
-     * @param array                              $get
86
-     * @param array                              $post
87
-     * @param array                              $cookie
88
-     * @param array                              $server
89
-     */
90
-    public function __construct(array $get, array $post, array $cookie, array $server)
91
-    {
92
-        // grab request vars
93
-        $this->get        = $get;
94
-        $this->post       = $post;
95
-        $this->cookie     = $cookie;
96
-        $this->server     = $server;
97
-        $this->request    = array_merge($this->get, $this->post);
98
-        $this->ip_address = $this->visitorIp();
99
-    }
100
-
101
-
102
-    /**
103
-     * @param RequestTypeContextCheckerInterface $type
104
-     */
105
-    public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type)
106
-    {
107
-        $this->request_type = $type;
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * @return array
114
-     */
115
-    public function getParams()
116
-    {
117
-        return $this->get;
118
-    }
119
-
120
-
121
-
122
-    /**
123
-     * @return array
124
-     */
125
-    public function postParams()
126
-    {
127
-        return $this->post;
128
-    }
129
-
130
-
131
-
132
-    /**
133
-     * @return array
134
-     */
135
-    public function cookieParams()
136
-    {
137
-        return $this->cookie;
138
-    }
139
-
140
-
141
-    /**
142
-     * @return array
143
-     */
144
-    public function serverParams()
145
-    {
146
-        return $this->server;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * returns contents of $_REQUEST
153
-     *
154
-     * @return array
155
-     */
156
-    public function requestParams()
157
-    {
158
-        return $this->request;
159
-    }
160
-
161
-
162
-
163
-    /**
164
-     * @param      $key
165
-     * @param      $value
166
-     * @param bool $override_ee
167
-     * @return    void
168
-     */
169
-    public function setRequestParam($key, $value, $override_ee = false)
170
-    {
171
-        // don't allow "ee" to be overwritten unless explicitly instructed to do so
172
-        if (
173
-            $key !== 'ee'
174
-            || ($key === 'ee' && empty($this->request['ee']))
175
-            || ($key === 'ee' && ! empty($this->request['ee']) && $override_ee)
176
-        ) {
177
-            $this->request[ $key ] = $value;
178
-        }
179
-    }
180
-
181
-
182
-
183
-    /**
184
-     * returns   the value for a request param if the given key exists
185
-     *
186
-     * @param       $key
187
-     * @param null  $default
188
-     * @return mixed
189
-     */
190
-    public function getRequestParam($key, $default = null)
191
-    {
192
-        return $this->requestParameterDrillDown($key, $default, 'get');
193
-    }
194
-
195
-
196
-
197
-    /**
198
-     * check if param exists
199
-     *
200
-     * @param       $key
201
-     * @return bool
202
-     */
203
-    public function requestParamIsSet($key)
204
-    {
205
-        return $this->requestParameterDrillDown($key);
206
-    }
207
-
208
-
209
-    /**
210
-     * check if a request parameter exists whose key that matches the supplied wildcard pattern
211
-     * and return the value for the first match found
212
-     * wildcards can be either of the following:
213
-     *      ? to represent a single character of any type
214
-     *      * to represent one or more characters of any type
215
-     *
216
-     * @param string     $pattern
217
-     * @param null|mixed $default
218
-     * @return false|int
219
-     */
220
-    public function getMatch($pattern, $default = null)
221
-    {
222
-        return $this->requestParameterDrillDown($pattern, $default, 'match');
223
-    }
224
-
225
-
226
-    /**
227
-     * check if a request parameter exists whose key matches the supplied wildcard pattern
228
-     * wildcards can be either of the following:
229
-     *      ? to represent a single character of any type
230
-     *      * to represent one or more characters of any type
231
-     * returns true if a match is found or false if not
232
-     *
233
-     * @param string $pattern
234
-     * @return false|int
235
-     */
236
-    public function matches($pattern)
237
-    {
238
-        return $this->requestParameterDrillDown($pattern, null, 'match') !== null;
239
-    }
240
-
241
-
242
-    /**
243
-     * @see https://stackoverflow.com/questions/6163055/php-string-matching-with-wildcard
244
-     * @param string $pattern               A string including wildcards to be converted to a regex pattern
245
-     *                                      and used to search through the current request's parameter keys
246
-     * @param array  $request_params        The array of request parameters to search through
247
-     * @param mixed  $default               [optional] The value to be returned if no match is found.
248
-     *                                      Default is null
249
-     * @param string $return                [optional] Controls what kind of value is returned.
250
-     *                                      Options are:
251
-     *                                      'bool' will return true or false if match is found or not
252
-     *                                      'key' will return the first key found that matches the supplied pattern
253
-     *                                      'value' will return the value for the first request parameter
254
-     *                                      whose key matches the supplied pattern
255
-     *                                      Default is 'value'
256
-     * @return boolean|string
257
-     */
258
-    private function match($pattern, array $request_params, $default = null, $return = 'value')
259
-    {
260
-        $return = in_array($return, array('bool', 'key', 'value'), true)
261
-            ? $return
262
-            : 'is_set';
263
-        // replace wildcard chars with regex chars
264
-        $pattern = str_replace(
265
-            array("\*", "\?"),
266
-            array('.*', '.'),
267
-            preg_quote($pattern, '/')
268
-        );
269
-        foreach ($request_params as $key => $request_param) {
270
-            if (preg_match('/^' . $pattern . '$/is', $key)) {
271
-                // return value for request param
272
-                if ($return === 'value') {
273
-                    return $request_params[ $key ];
274
-                }
275
-                // or actual key or true just to indicate it was found
276
-                return $return === 'key' ? $key : true;
277
-            }
278
-        }
279
-        // match not found so return default value or false
280
-        return $return === 'value' ? $default : false;
281
-    }
282
-
283
-
284
-    /**
285
-     * the supplied key can be a simple string to represent a "top-level" request parameter
286
-     * or represent a key for a request parameter that is nested deeper within the request parameter array,
287
-     * by using square brackets to surround keys for deeper array elements.
288
-     * For example :
289
-     * if the supplied $key was: "first[second][third]"
290
-     * then this will attempt to drill down into the request parameter array to find a value.
291
-     * Given the following request parameters:
292
-     *  array(
293
-     *      'first' => array(
294
-     *          'second' => array(
295
-     *              'third' => 'has a value'
296
-     *          )
297
-     *      )
298
-     *  )
299
-     * would return true if default parameters were set
300
-     *
301
-     * @param string $callback
302
-     * @param        $key
303
-     * @param null   $default
304
-     * @param array  $request_params
305
-     * @return bool|mixed|null
306
-     */
307
-    private function requestParameterDrillDown(
308
-        $key,
309
-        $default = null,
310
-        $callback = 'is_set',
311
-        array $request_params = array()
312
-    ) {
313
-        $callback       = in_array($callback, array('is_set', 'get', 'match'), true)
314
-            ? $callback
315
-            : 'is_set';
316
-        $request_params = ! empty($request_params)
317
-            ? $request_params
318
-            : $this->request;
319
-        // does incoming key represent an array like 'first[second][third]'  ?
320
-        if (strpos($key, '[') !== false) {
321
-            // turn it into an actual array
322
-            $key  = str_replace(']', '', $key);
323
-            $keys = explode('[', $key);
324
-            $key  = array_shift($keys);
325
-            if ($callback === 'match') {
326
-                $real_key = $this->match($key, $request_params, $default, 'key');
327
-                $key      = $real_key ? $real_key : $key;
328
-            }
329
-            // check if top level key exists
330
-            if (isset($request_params[ $key ])) {
331
-                // build a new key to pass along like: 'second[third]'
332
-                // or just 'second' depending on depth of keys
333
-                $key_string = array_shift($keys);
334
-                if (! empty($keys)) {
335
-                    $key_string .= '[' . implode('][', $keys) . ']';
336
-                }
337
-                return $this->requestParameterDrillDown(
338
-                    $key_string,
339
-                    $default,
340
-                    $callback,
341
-                    $request_params[ $key ]
342
-                );
343
-            }
344
-        }
345
-        if ($callback === 'is_set') {
346
-            return isset($request_params[ $key ]);
347
-        }
348
-        if ($callback === 'match') {
349
-            return $this->match($key, $request_params, $default);
350
-        }
351
-        return isset($request_params[ $key ])
352
-            ? $request_params[ $key ]
353
-            : $default;
354
-    }
355
-
356
-
357
-    /**
358
-     * remove param
359
-     *
360
-     * @param      $key
361
-     * @param bool $unset_from_global_too
362
-     */
363
-    public function unSetRequestParam($key, $unset_from_global_too = false)
364
-    {
365
-        unset($this->request[ $key ]);
366
-        if ($unset_from_global_too) {
367
-            unset($_REQUEST[ $key ]);
368
-        }
369
-    }
370
-
371
-
372
-
373
-    /**
374
-     * @return string
375
-     */
376
-    public function ipAddress()
377
-    {
378
-        return $this->ip_address;
379
-    }
380
-
381
-
382
-    /**
383
-     * attempt to get IP address of current visitor from server
384
-     * plz see: http://stackoverflow.com/a/2031935/1475279
385
-     *
386
-     * @access public
387
-     * @return string
388
-     */
389
-    private function visitorIp()
390
-    {
391
-        $visitor_ip  = '0.0.0.0';
392
-        $server_keys = array(
393
-            'HTTP_CLIENT_IP',
394
-            'HTTP_X_FORWARDED_FOR',
395
-            'HTTP_X_FORWARDED',
396
-            'HTTP_X_CLUSTER_CLIENT_IP',
397
-            'HTTP_FORWARDED_FOR',
398
-            'HTTP_FORWARDED',
399
-            'REMOTE_ADDR',
400
-        );
401
-        foreach ($server_keys as $key) {
402
-            if (isset($this->server[ $key ])) {
403
-                foreach (array_map('trim', explode(',', $this->server[ $key ])) as $ip) {
404
-                    if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
405
-                        $visitor_ip = $ip;
406
-                    }
407
-                }
408
-            }
409
-        }
410
-        return $visitor_ip;
411
-    }
412
-
413
-
414
-    /**
415
-     * @return string
416
-     */
417
-    public function requestUri()
418
-    {
419
-        $request_uri = filter_input(
420
-            INPUT_SERVER,
421
-            'REQUEST_URI',
422
-            FILTER_SANITIZE_URL,
423
-            FILTER_NULL_ON_FAILURE
424
-        );
425
-        if (empty($request_uri)) {
426
-            // fallback sanitization if the above fails
427
-            $request_uri = wp_sanitize_redirect($this->server['REQUEST_URI']);
428
-        }
429
-        return $request_uri;
430
-    }
431
-
432
-
433
-    /**
434
-     * @return string
435
-     */
436
-    public function userAgent()
437
-    {
438
-        return $this->user_agent;
439
-    }
440
-
441
-
442
-    /**
443
-     * @param string $user_agent
444
-     */
445
-    public function setUserAgent($user_agent = '')
446
-    {
447
-        if ($user_agent === '' || ! is_string($user_agent)) {
448
-            $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? (string) esc_attr($_SERVER['HTTP_USER_AGENT']) : '';
449
-        }
450
-        $this->user_agent = $user_agent;
451
-    }
452
-
453
-
454
-    /**
455
-     * @return bool
456
-     */
457
-    public function isBot()
458
-    {
459
-        return $this->is_bot;
460
-    }
461
-
462
-
463
-    /**
464
-     * @param bool $is_bot
465
-     */
466
-    public function setIsBot($is_bot)
467
-    {
468
-        $this->is_bot = filter_var($is_bot, FILTER_VALIDATE_BOOLEAN);
469
-    }
470
-
471
-
472
-    /**
473
-     * @return bool
474
-     */
475
-    public function isActivation()
476
-    {
477
-        return $this->request_type->isActivation();
478
-    }
479
-
480
-
481
-    /**
482
-     * @param $is_activation
483
-     * @return bool
484
-     */
485
-    public function setIsActivation($is_activation)
486
-    {
487
-        return $this->request_type->setIsActivation($is_activation);
488
-    }
489
-
490
-
491
-    /**
492
-     * @return bool
493
-     */
494
-    public function isAdmin()
495
-    {
496
-        return $this->request_type->isAdmin();
497
-    }
498
-
499
-
500
-    /**
501
-     * @return bool
502
-     */
503
-    public function isAdminAjax()
504
-    {
505
-        return $this->request_type->isAdminAjax();
506
-    }
507
-
508
-
509
-    /**
510
-     * @return bool
511
-     */
512
-    public function isAjax()
513
-    {
514
-        return $this->request_type->isAjax();
515
-    }
516
-
517
-
518
-    /**
519
-     * @return bool
520
-     */
521
-    public function isEeAjax()
522
-    {
523
-        return $this->request_type->isEeAjax();
524
-    }
525
-
526
-
527
-    /**
528
-     * @return bool
529
-     */
530
-    public function isOtherAjax()
531
-    {
532
-        return $this->request_type->isOtherAjax();
533
-    }
534
-
535
-
536
-    /**
537
-     * @return bool
538
-     */
539
-    public function isApi()
540
-    {
541
-        return $this->request_type->isApi();
542
-    }
543
-
544
-
545
-    /**
546
-     * @return bool
547
-     */
548
-    public function isCli()
549
-    {
550
-        return $this->request_type->isCli();
551
-    }
552
-
553
-
554
-    /**
555
-     * @return bool
556
-     */
557
-    public function isCron()
558
-    {
559
-        return $this->request_type->isCron();
560
-    }
561
-
562
-
563
-    /**
564
-     * @return bool
565
-     */
566
-    public function isFeed()
567
-    {
568
-        return $this->request_type->isFeed();
569
-    }
570
-
571
-
572
-    /**
573
-     * @return bool
574
-     */
575
-    public function isFrontend()
576
-    {
577
-        return $this->request_type->isFrontend();
578
-    }
579
-
580
-
581
-    /**
582
-     * @return bool
583
-     */
584
-    public function isFrontAjax()
585
-    {
586
-        return $this->request_type->isFrontAjax();
587
-    }
588
-
589
-
590
-
591
-    /**
592
-     * @return bool
593
-     */
594
-    public function isIframe()
595
-    {
596
-        return $this->request_type->isIframe();
597
-    }
598
-
599
-
600
-    /**
601
-     * @return string
602
-     */
603
-    public function slug()
604
-    {
605
-        return $this->request_type->slug();
606
-    }
23
+	/**
24
+	 * $_GET parameters
25
+	 *
26
+	 * @var array $get
27
+	 */
28
+	private $get;
29
+
30
+	/**
31
+	 * $_POST parameters
32
+	 *
33
+	 * @var array $post
34
+	 */
35
+	private $post;
36
+
37
+	/**
38
+	 * $_COOKIE parameters
39
+	 *
40
+	 * @var array $cookie
41
+	 */
42
+	private $cookie;
43
+
44
+	/**
45
+	 * $_SERVER parameters
46
+	 *
47
+	 * @var array $server
48
+	 */
49
+	private $server;
50
+
51
+	/**
52
+	 * $_REQUEST parameters
53
+	 *
54
+	 * @var array $request
55
+	 */
56
+	private $request;
57
+
58
+	/**
59
+	 * @var RequestTypeContextCheckerInterface
60
+	 */
61
+	private $request_type;
62
+
63
+	/**
64
+	 * IP address for request
65
+	 *
66
+	 * @var string $ip_address
67
+	 */
68
+	private $ip_address;
69
+
70
+	/**
71
+	 * @var string $user_agent
72
+	 */
73
+	private $user_agent;
74
+
75
+	/**
76
+	 * true if current user appears to be some kind of bot
77
+	 *
78
+	 * @var bool $is_bot
79
+	 */
80
+	private $is_bot;
81
+
82
+
83
+
84
+	/**
85
+	 * @param array                              $get
86
+	 * @param array                              $post
87
+	 * @param array                              $cookie
88
+	 * @param array                              $server
89
+	 */
90
+	public function __construct(array $get, array $post, array $cookie, array $server)
91
+	{
92
+		// grab request vars
93
+		$this->get        = $get;
94
+		$this->post       = $post;
95
+		$this->cookie     = $cookie;
96
+		$this->server     = $server;
97
+		$this->request    = array_merge($this->get, $this->post);
98
+		$this->ip_address = $this->visitorIp();
99
+	}
100
+
101
+
102
+	/**
103
+	 * @param RequestTypeContextCheckerInterface $type
104
+	 */
105
+	public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type)
106
+	{
107
+		$this->request_type = $type;
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * @return array
114
+	 */
115
+	public function getParams()
116
+	{
117
+		return $this->get;
118
+	}
119
+
120
+
121
+
122
+	/**
123
+	 * @return array
124
+	 */
125
+	public function postParams()
126
+	{
127
+		return $this->post;
128
+	}
129
+
130
+
131
+
132
+	/**
133
+	 * @return array
134
+	 */
135
+	public function cookieParams()
136
+	{
137
+		return $this->cookie;
138
+	}
139
+
140
+
141
+	/**
142
+	 * @return array
143
+	 */
144
+	public function serverParams()
145
+	{
146
+		return $this->server;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * returns contents of $_REQUEST
153
+	 *
154
+	 * @return array
155
+	 */
156
+	public function requestParams()
157
+	{
158
+		return $this->request;
159
+	}
160
+
161
+
162
+
163
+	/**
164
+	 * @param      $key
165
+	 * @param      $value
166
+	 * @param bool $override_ee
167
+	 * @return    void
168
+	 */
169
+	public function setRequestParam($key, $value, $override_ee = false)
170
+	{
171
+		// don't allow "ee" to be overwritten unless explicitly instructed to do so
172
+		if (
173
+			$key !== 'ee'
174
+			|| ($key === 'ee' && empty($this->request['ee']))
175
+			|| ($key === 'ee' && ! empty($this->request['ee']) && $override_ee)
176
+		) {
177
+			$this->request[ $key ] = $value;
178
+		}
179
+	}
180
+
181
+
182
+
183
+	/**
184
+	 * returns   the value for a request param if the given key exists
185
+	 *
186
+	 * @param       $key
187
+	 * @param null  $default
188
+	 * @return mixed
189
+	 */
190
+	public function getRequestParam($key, $default = null)
191
+	{
192
+		return $this->requestParameterDrillDown($key, $default, 'get');
193
+	}
194
+
195
+
196
+
197
+	/**
198
+	 * check if param exists
199
+	 *
200
+	 * @param       $key
201
+	 * @return bool
202
+	 */
203
+	public function requestParamIsSet($key)
204
+	{
205
+		return $this->requestParameterDrillDown($key);
206
+	}
207
+
208
+
209
+	/**
210
+	 * check if a request parameter exists whose key that matches the supplied wildcard pattern
211
+	 * and return the value for the first match found
212
+	 * wildcards can be either of the following:
213
+	 *      ? to represent a single character of any type
214
+	 *      * to represent one or more characters of any type
215
+	 *
216
+	 * @param string     $pattern
217
+	 * @param null|mixed $default
218
+	 * @return false|int
219
+	 */
220
+	public function getMatch($pattern, $default = null)
221
+	{
222
+		return $this->requestParameterDrillDown($pattern, $default, 'match');
223
+	}
224
+
225
+
226
+	/**
227
+	 * check if a request parameter exists whose key matches the supplied wildcard pattern
228
+	 * wildcards can be either of the following:
229
+	 *      ? to represent a single character of any type
230
+	 *      * to represent one or more characters of any type
231
+	 * returns true if a match is found or false if not
232
+	 *
233
+	 * @param string $pattern
234
+	 * @return false|int
235
+	 */
236
+	public function matches($pattern)
237
+	{
238
+		return $this->requestParameterDrillDown($pattern, null, 'match') !== null;
239
+	}
240
+
241
+
242
+	/**
243
+	 * @see https://stackoverflow.com/questions/6163055/php-string-matching-with-wildcard
244
+	 * @param string $pattern               A string including wildcards to be converted to a regex pattern
245
+	 *                                      and used to search through the current request's parameter keys
246
+	 * @param array  $request_params        The array of request parameters to search through
247
+	 * @param mixed  $default               [optional] The value to be returned if no match is found.
248
+	 *                                      Default is null
249
+	 * @param string $return                [optional] Controls what kind of value is returned.
250
+	 *                                      Options are:
251
+	 *                                      'bool' will return true or false if match is found or not
252
+	 *                                      'key' will return the first key found that matches the supplied pattern
253
+	 *                                      'value' will return the value for the first request parameter
254
+	 *                                      whose key matches the supplied pattern
255
+	 *                                      Default is 'value'
256
+	 * @return boolean|string
257
+	 */
258
+	private function match($pattern, array $request_params, $default = null, $return = 'value')
259
+	{
260
+		$return = in_array($return, array('bool', 'key', 'value'), true)
261
+			? $return
262
+			: 'is_set';
263
+		// replace wildcard chars with regex chars
264
+		$pattern = str_replace(
265
+			array("\*", "\?"),
266
+			array('.*', '.'),
267
+			preg_quote($pattern, '/')
268
+		);
269
+		foreach ($request_params as $key => $request_param) {
270
+			if (preg_match('/^' . $pattern . '$/is', $key)) {
271
+				// return value for request param
272
+				if ($return === 'value') {
273
+					return $request_params[ $key ];
274
+				}
275
+				// or actual key or true just to indicate it was found
276
+				return $return === 'key' ? $key : true;
277
+			}
278
+		}
279
+		// match not found so return default value or false
280
+		return $return === 'value' ? $default : false;
281
+	}
282
+
283
+
284
+	/**
285
+	 * the supplied key can be a simple string to represent a "top-level" request parameter
286
+	 * or represent a key for a request parameter that is nested deeper within the request parameter array,
287
+	 * by using square brackets to surround keys for deeper array elements.
288
+	 * For example :
289
+	 * if the supplied $key was: "first[second][third]"
290
+	 * then this will attempt to drill down into the request parameter array to find a value.
291
+	 * Given the following request parameters:
292
+	 *  array(
293
+	 *      'first' => array(
294
+	 *          'second' => array(
295
+	 *              'third' => 'has a value'
296
+	 *          )
297
+	 *      )
298
+	 *  )
299
+	 * would return true if default parameters were set
300
+	 *
301
+	 * @param string $callback
302
+	 * @param        $key
303
+	 * @param null   $default
304
+	 * @param array  $request_params
305
+	 * @return bool|mixed|null
306
+	 */
307
+	private function requestParameterDrillDown(
308
+		$key,
309
+		$default = null,
310
+		$callback = 'is_set',
311
+		array $request_params = array()
312
+	) {
313
+		$callback       = in_array($callback, array('is_set', 'get', 'match'), true)
314
+			? $callback
315
+			: 'is_set';
316
+		$request_params = ! empty($request_params)
317
+			? $request_params
318
+			: $this->request;
319
+		// does incoming key represent an array like 'first[second][third]'  ?
320
+		if (strpos($key, '[') !== false) {
321
+			// turn it into an actual array
322
+			$key  = str_replace(']', '', $key);
323
+			$keys = explode('[', $key);
324
+			$key  = array_shift($keys);
325
+			if ($callback === 'match') {
326
+				$real_key = $this->match($key, $request_params, $default, 'key');
327
+				$key      = $real_key ? $real_key : $key;
328
+			}
329
+			// check if top level key exists
330
+			if (isset($request_params[ $key ])) {
331
+				// build a new key to pass along like: 'second[third]'
332
+				// or just 'second' depending on depth of keys
333
+				$key_string = array_shift($keys);
334
+				if (! empty($keys)) {
335
+					$key_string .= '[' . implode('][', $keys) . ']';
336
+				}
337
+				return $this->requestParameterDrillDown(
338
+					$key_string,
339
+					$default,
340
+					$callback,
341
+					$request_params[ $key ]
342
+				);
343
+			}
344
+		}
345
+		if ($callback === 'is_set') {
346
+			return isset($request_params[ $key ]);
347
+		}
348
+		if ($callback === 'match') {
349
+			return $this->match($key, $request_params, $default);
350
+		}
351
+		return isset($request_params[ $key ])
352
+			? $request_params[ $key ]
353
+			: $default;
354
+	}
355
+
356
+
357
+	/**
358
+	 * remove param
359
+	 *
360
+	 * @param      $key
361
+	 * @param bool $unset_from_global_too
362
+	 */
363
+	public function unSetRequestParam($key, $unset_from_global_too = false)
364
+	{
365
+		unset($this->request[ $key ]);
366
+		if ($unset_from_global_too) {
367
+			unset($_REQUEST[ $key ]);
368
+		}
369
+	}
370
+
371
+
372
+
373
+	/**
374
+	 * @return string
375
+	 */
376
+	public function ipAddress()
377
+	{
378
+		return $this->ip_address;
379
+	}
380
+
381
+
382
+	/**
383
+	 * attempt to get IP address of current visitor from server
384
+	 * plz see: http://stackoverflow.com/a/2031935/1475279
385
+	 *
386
+	 * @access public
387
+	 * @return string
388
+	 */
389
+	private function visitorIp()
390
+	{
391
+		$visitor_ip  = '0.0.0.0';
392
+		$server_keys = array(
393
+			'HTTP_CLIENT_IP',
394
+			'HTTP_X_FORWARDED_FOR',
395
+			'HTTP_X_FORWARDED',
396
+			'HTTP_X_CLUSTER_CLIENT_IP',
397
+			'HTTP_FORWARDED_FOR',
398
+			'HTTP_FORWARDED',
399
+			'REMOTE_ADDR',
400
+		);
401
+		foreach ($server_keys as $key) {
402
+			if (isset($this->server[ $key ])) {
403
+				foreach (array_map('trim', explode(',', $this->server[ $key ])) as $ip) {
404
+					if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
405
+						$visitor_ip = $ip;
406
+					}
407
+				}
408
+			}
409
+		}
410
+		return $visitor_ip;
411
+	}
412
+
413
+
414
+	/**
415
+	 * @return string
416
+	 */
417
+	public function requestUri()
418
+	{
419
+		$request_uri = filter_input(
420
+			INPUT_SERVER,
421
+			'REQUEST_URI',
422
+			FILTER_SANITIZE_URL,
423
+			FILTER_NULL_ON_FAILURE
424
+		);
425
+		if (empty($request_uri)) {
426
+			// fallback sanitization if the above fails
427
+			$request_uri = wp_sanitize_redirect($this->server['REQUEST_URI']);
428
+		}
429
+		return $request_uri;
430
+	}
431
+
432
+
433
+	/**
434
+	 * @return string
435
+	 */
436
+	public function userAgent()
437
+	{
438
+		return $this->user_agent;
439
+	}
440
+
441
+
442
+	/**
443
+	 * @param string $user_agent
444
+	 */
445
+	public function setUserAgent($user_agent = '')
446
+	{
447
+		if ($user_agent === '' || ! is_string($user_agent)) {
448
+			$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? (string) esc_attr($_SERVER['HTTP_USER_AGENT']) : '';
449
+		}
450
+		$this->user_agent = $user_agent;
451
+	}
452
+
453
+
454
+	/**
455
+	 * @return bool
456
+	 */
457
+	public function isBot()
458
+	{
459
+		return $this->is_bot;
460
+	}
461
+
462
+
463
+	/**
464
+	 * @param bool $is_bot
465
+	 */
466
+	public function setIsBot($is_bot)
467
+	{
468
+		$this->is_bot = filter_var($is_bot, FILTER_VALIDATE_BOOLEAN);
469
+	}
470
+
471
+
472
+	/**
473
+	 * @return bool
474
+	 */
475
+	public function isActivation()
476
+	{
477
+		return $this->request_type->isActivation();
478
+	}
479
+
480
+
481
+	/**
482
+	 * @param $is_activation
483
+	 * @return bool
484
+	 */
485
+	public function setIsActivation($is_activation)
486
+	{
487
+		return $this->request_type->setIsActivation($is_activation);
488
+	}
489
+
490
+
491
+	/**
492
+	 * @return bool
493
+	 */
494
+	public function isAdmin()
495
+	{
496
+		return $this->request_type->isAdmin();
497
+	}
498
+
499
+
500
+	/**
501
+	 * @return bool
502
+	 */
503
+	public function isAdminAjax()
504
+	{
505
+		return $this->request_type->isAdminAjax();
506
+	}
507
+
508
+
509
+	/**
510
+	 * @return bool
511
+	 */
512
+	public function isAjax()
513
+	{
514
+		return $this->request_type->isAjax();
515
+	}
516
+
517
+
518
+	/**
519
+	 * @return bool
520
+	 */
521
+	public function isEeAjax()
522
+	{
523
+		return $this->request_type->isEeAjax();
524
+	}
525
+
526
+
527
+	/**
528
+	 * @return bool
529
+	 */
530
+	public function isOtherAjax()
531
+	{
532
+		return $this->request_type->isOtherAjax();
533
+	}
534
+
535
+
536
+	/**
537
+	 * @return bool
538
+	 */
539
+	public function isApi()
540
+	{
541
+		return $this->request_type->isApi();
542
+	}
543
+
544
+
545
+	/**
546
+	 * @return bool
547
+	 */
548
+	public function isCli()
549
+	{
550
+		return $this->request_type->isCli();
551
+	}
552
+
553
+
554
+	/**
555
+	 * @return bool
556
+	 */
557
+	public function isCron()
558
+	{
559
+		return $this->request_type->isCron();
560
+	}
561
+
562
+
563
+	/**
564
+	 * @return bool
565
+	 */
566
+	public function isFeed()
567
+	{
568
+		return $this->request_type->isFeed();
569
+	}
570
+
571
+
572
+	/**
573
+	 * @return bool
574
+	 */
575
+	public function isFrontend()
576
+	{
577
+		return $this->request_type->isFrontend();
578
+	}
579
+
580
+
581
+	/**
582
+	 * @return bool
583
+	 */
584
+	public function isFrontAjax()
585
+	{
586
+		return $this->request_type->isFrontAjax();
587
+	}
588
+
589
+
590
+
591
+	/**
592
+	 * @return bool
593
+	 */
594
+	public function isIframe()
595
+	{
596
+		return $this->request_type->isIframe();
597
+	}
598
+
599
+
600
+	/**
601
+	 * @return string
602
+	 */
603
+	public function slug()
604
+	{
605
+		return $this->request_type->slug();
606
+	}
607 607
 
608 608
 
609 609
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
             || ($key === 'ee' && empty($this->request['ee']))
175 175
             || ($key === 'ee' && ! empty($this->request['ee']) && $override_ee)
176 176
         ) {
177
-            $this->request[ $key ] = $value;
177
+            $this->request[$key] = $value;
178 178
         }
179 179
     }
180 180
 
@@ -267,10 +267,10 @@  discard block
 block discarded – undo
267 267
             preg_quote($pattern, '/')
268 268
         );
269 269
         foreach ($request_params as $key => $request_param) {
270
-            if (preg_match('/^' . $pattern . '$/is', $key)) {
270
+            if (preg_match('/^'.$pattern.'$/is', $key)) {
271 271
                 // return value for request param
272 272
                 if ($return === 'value') {
273
-                    return $request_params[ $key ];
273
+                    return $request_params[$key];
274 274
                 }
275 275
                 // or actual key or true just to indicate it was found
276 276
                 return $return === 'key' ? $key : true;
@@ -327,29 +327,29 @@  discard block
 block discarded – undo
327 327
                 $key      = $real_key ? $real_key : $key;
328 328
             }
329 329
             // check if top level key exists
330
-            if (isset($request_params[ $key ])) {
330
+            if (isset($request_params[$key])) {
331 331
                 // build a new key to pass along like: 'second[third]'
332 332
                 // or just 'second' depending on depth of keys
333 333
                 $key_string = array_shift($keys);
334
-                if (! empty($keys)) {
335
-                    $key_string .= '[' . implode('][', $keys) . ']';
334
+                if ( ! empty($keys)) {
335
+                    $key_string .= '['.implode('][', $keys).']';
336 336
                 }
337 337
                 return $this->requestParameterDrillDown(
338 338
                     $key_string,
339 339
                     $default,
340 340
                     $callback,
341
-                    $request_params[ $key ]
341
+                    $request_params[$key]
342 342
                 );
343 343
             }
344 344
         }
345 345
         if ($callback === 'is_set') {
346
-            return isset($request_params[ $key ]);
346
+            return isset($request_params[$key]);
347 347
         }
348 348
         if ($callback === 'match') {
349 349
             return $this->match($key, $request_params, $default);
350 350
         }
351
-        return isset($request_params[ $key ])
352
-            ? $request_params[ $key ]
351
+        return isset($request_params[$key])
352
+            ? $request_params[$key]
353 353
             : $default;
354 354
     }
355 355
 
@@ -362,9 +362,9 @@  discard block
 block discarded – undo
362 362
      */
363 363
     public function unSetRequestParam($key, $unset_from_global_too = false)
364 364
     {
365
-        unset($this->request[ $key ]);
365
+        unset($this->request[$key]);
366 366
         if ($unset_from_global_too) {
367
-            unset($_REQUEST[ $key ]);
367
+            unset($_REQUEST[$key]);
368 368
         }
369 369
     }
370 370
 
@@ -399,8 +399,8 @@  discard block
 block discarded – undo
399 399
             'REMOTE_ADDR',
400 400
         );
401 401
         foreach ($server_keys as $key) {
402
-            if (isset($this->server[ $key ])) {
403
-                foreach (array_map('trim', explode(',', $this->server[ $key ])) as $ip) {
402
+            if (isset($this->server[$key])) {
403
+                foreach (array_map('trim', explode(',', $this->server[$key])) as $ip) {
404 404
                     if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
405 405
                         $visitor_ip = $ip;
406 406
                     }
Please login to merge, or discard this patch.
modules/single_page_checkout/inc/EE_SPCO_JSON_Response.php 2 patches
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -1,16 +1,16 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) { exit('No direct script access allowed'); }
2 2
  /**
3
- *
4
- * Class EE_SPCO_JSON_Response
5
- *
6
- * Description
7
- *
8
- * @package         Event Espresso
9
- * @subpackage    core
10
- * @author				Brent Christensen
11
- *
12
- *
13
- */
3
+  *
4
+  * Class EE_SPCO_JSON_Response
5
+  *
6
+  * Description
7
+  *
8
+  * @package         Event Espresso
9
+  * @subpackage    core
10
+  * @author				Brent Christensen
11
+  *
12
+  *
13
+  */
14 14
 class EE_SPCO_JSON_Response {
15 15
 
16 16
 	/**
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 
85 85
 	/**
86 86
 	 *    class constructor
87
-   */
87
+	 */
88 88
 	public function __construct(  ) {
89 89
 	}
90 90
 
@@ -271,10 +271,10 @@  discard block
 block discarded – undo
271 271
 	}
272 272
 
273 273
 
274
-    /**
275
-     * @param float $payment_amount
276
-     * @throws EE_Error
277
-     */
274
+	/**
275
+	 * @param float $payment_amount
276
+	 * @throws EE_Error
277
+	 */
278 278
 	public function set_payment_amount( $payment_amount ) {
279 279
 		$this->_payment_amount = (float)$payment_amount;
280 280
 	}
@@ -408,11 +408,11 @@  discard block
 block discarded – undo
408 408
 	}
409 409
 
410 410
 
411
-    public function echoAndExit()
412
-    {
413
-        echo $this;
414
-        exit();
415
-    }
411
+	public function echoAndExit()
412
+	{
413
+		echo $this;
414
+		exit();
415
+	}
416 416
 
417 417
 }
418 418
 // End of file EE_SPCO_JSON_Response.php
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -104,71 +104,71 @@  discard block
 block discarded – undo
104 104
 	public function __toString() {
105 105
 		$JSON_response = array();
106 106
 		// grab notices
107
-		$notices = EE_Error::get_notices( FALSE );
108
-		$this->set_attention( isset( $notices['attention'] ) ? $notices['attention'] : '' );
109
-		$this->set_errors( isset( $notices['errors'] ) ? $notices['errors'] : '' );
110
-		$this->set_success( isset( $notices['success'] ) ? $notices['success'] : '' );
107
+		$notices = EE_Error::get_notices(FALSE);
108
+		$this->set_attention(isset($notices['attention']) ? $notices['attention'] : '');
109
+		$this->set_errors(isset($notices['errors']) ? $notices['errors'] : '');
110
+		$this->set_success(isset($notices['success']) ? $notices['success'] : '');
111 111
 		// add notices to JSON response, but only if they exist
112
-		if ( $this->attention() ) {
112
+		if ($this->attention()) {
113 113
 			$JSON_response['attention'] = $this->attention();
114 114
 		}
115
-		if ( $this->errors() ) {
115
+		if ($this->errors()) {
116 116
 			$JSON_response['errors'] = $this->errors();
117 117
 		}
118
-		if ( $this->unexpected_errors() ) {
118
+		if ($this->unexpected_errors()) {
119 119
 			$JSON_response['unexpected_errors'] = $this->unexpected_errors();
120 120
 		}
121
-		if ( $this->success() ) {
121
+		if ($this->success()) {
122 122
 			$JSON_response['success'] = $this->success();
123 123
 		}
124 124
 		// but if NO notices are set... at least set the "success" as a key so that the JS knows everything worked
125
-		if ( ! isset( $JSON_response[ 'attention' ] ) && ! isset( $JSON_response[ 'errors' ] ) && ! isset( $JSON_response[ 'success' ] ) ) {
125
+		if ( ! isset($JSON_response['attention']) && ! isset($JSON_response['errors']) && ! isset($JSON_response['success'])) {
126 126
 			$JSON_response['success'] = null;
127 127
 		}
128 128
 		// set redirect_url, IF it exists
129
-		if ( $this->redirect_url() ) {
129
+		if ($this->redirect_url()) {
130 130
 			$JSON_response['redirect_url'] = $this->redirect_url();
131 131
 		}
132 132
 		// set registration_time_limit, IF it exists
133
-		if ( $this->registration_time_limit() ) {
133
+		if ($this->registration_time_limit()) {
134 134
 			$JSON_response['registration_time_limit'] = $this->registration_time_limit();
135 135
 		}
136 136
 		// set payment_amount, IF it exists
137
-		if ( $this->payment_amount() !== null ) {
138
-			$JSON_response[ 'payment_amount' ] = $this->payment_amount();
137
+		if ($this->payment_amount() !== null) {
138
+			$JSON_response['payment_amount'] = $this->payment_amount();
139 139
 		}
140 140
 		// grab generic return data
141 141
 		$return_data = $this->return_data();
142 142
 		// add billing form validation rules
143
-		if ( $this->validation_rules() ) {
143
+		if ($this->validation_rules()) {
144 144
 			$return_data['validation_rules'] = $this->validation_rules();
145 145
 		}
146 146
 		// set reg_step_html, IF it exists
147
-		if ( $this->reg_step_html() ) {
147
+		if ($this->reg_step_html()) {
148 148
 			$return_data['reg_step_html'] = $this->reg_step_html();
149 149
 		}
150 150
 		// set method of payment, IF it exists
151
-		if ( $this->method_of_payment() ) {
151
+		if ($this->method_of_payment()) {
152 152
 			$return_data['method_of_payment'] = $this->method_of_payment();
153 153
 		}
154 154
 		// set "plz_select_method_of_payment" message, IF it exists
155
-		if ( $this->plz_select_method_of_payment() ) {
155
+		if ($this->plz_select_method_of_payment()) {
156 156
 			$return_data['plz_select_method_of_payment'] = $this->plz_select_method_of_payment();
157 157
 		}
158 158
 		// set redirect_form, IF it exists
159
-		if ( $this->redirect_form() ) {
159
+		if ($this->redirect_form()) {
160 160
 			$return_data['redirect_form'] = $this->redirect_form();
161 161
 		}
162 162
 		// and finally, add return_data array to main JSON response array, IF it contains anything
163 163
 		// why did we add some of the above properties to the return data array?
164 164
 		// because it is easier and cleaner in the Javascript to deal with this way
165
-		if ( ! empty( $return_data )) {
165
+		if ( ! empty($return_data)) {
166 166
 			$JSON_response['return_data'] = $return_data;
167 167
 		}
168 168
 		// filter final array
169
-		$JSON_response = apply_filters( 'FHEE__EE_SPCO_JSON_Response___toString__JSON_response', $JSON_response );
169
+		$JSON_response = apply_filters('FHEE__EE_SPCO_JSON_Response___toString__JSON_response', $JSON_response);
170 170
 		// return encoded array
171
-		return (string) wp_json_encode( $JSON_response );
171
+		return (string) wp_json_encode($JSON_response);
172 172
 	}
173 173
 
174 174
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 	/**
177 177
 	 * @param string $attention
178 178
 	 */
179
-	public function set_attention( $attention ) {
179
+	public function set_attention($attention) {
180 180
 		$this->_attention = $attention;
181 181
 	}
182 182
 
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 	/**
195 195
 	 * @param string $errors
196 196
 	 */
197
-	public function set_errors( $errors ) {
197
+	public function set_errors($errors) {
198 198
 		$this->_errors = $errors;
199 199
 	}
200 200
 
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
 	/**
222 222
 	 * @param string $unexpected_errors
223 223
 	 */
224
-	public function set_unexpected_errors( $unexpected_errors ) {
224
+	public function set_unexpected_errors($unexpected_errors) {
225 225
 		$this->_unexpected_errors = $unexpected_errors;
226 226
 	}
227 227
 
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 	/**
231 231
 	 * @param string $success
232 232
 	 */
233
-	public function set_success( $success ) {
233
+	public function set_success($success) {
234 234
 		$this->_success = $success;
235 235
 	}
236 236
 
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 	/**
249 249
 	 * @param string $method_of_payment
250 250
 	 */
251
-	public function set_method_of_payment( $method_of_payment ) {
251
+	public function set_method_of_payment($method_of_payment) {
252 252
 		$this->_method_of_payment = $method_of_payment;
253 253
 	}
254 254
 
@@ -275,8 +275,8 @@  discard block
 block discarded – undo
275 275
      * @param float $payment_amount
276 276
      * @throws EE_Error
277 277
      */
278
-	public function set_payment_amount( $payment_amount ) {
279
-		$this->_payment_amount = (float)$payment_amount;
278
+	public function set_payment_amount($payment_amount) {
279
+		$this->_payment_amount = (float) $payment_amount;
280 280
 	}
281 281
 
282 282
 
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 	/**
285 285
 	 * @param string $next_step_html
286 286
 	 */
287
-	public function set_reg_step_html( $next_step_html ) {
287
+	public function set_reg_step_html($next_step_html) {
288 288
 		$this->_reg_step_html = $next_step_html;
289 289
 	}
290 290
 
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
 	/**
303 303
 	 * @param string $redirect_form
304 304
 	 */
305
-	public function set_redirect_form( $redirect_form ) {
305
+	public function set_redirect_form($redirect_form) {
306 306
 		$this->_redirect_form = $redirect_form;
307 307
 	}
308 308
 
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
 	 * @return string
313 313
 	 */
314 314
 	public function redirect_form() {
315
-		return ! empty( $this->_redirect_form ) ? $this->_redirect_form : FALSE;
315
+		return ! empty($this->_redirect_form) ? $this->_redirect_form : FALSE;
316 316
 	}
317 317
 
318 318
 
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
 	/**
321 321
 	 * @param string $plz_select_method_of_payment
322 322
 	 */
323
-	public function set_plz_select_method_of_payment( $plz_select_method_of_payment ) {
323
+	public function set_plz_select_method_of_payment($plz_select_method_of_payment) {
324 324
 		$this->_plz_select_method_of_payment = $plz_select_method_of_payment;
325 325
 	}
326 326
 
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
 	/**
339 339
 	 * @param string $redirect_url
340 340
 	 */
341
-	public function set_redirect_url( $redirect_url ) {
341
+	public function set_redirect_url($redirect_url) {
342 342
 		$this->_redirect_url = $redirect_url;
343 343
 	}
344 344
 
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 	/**
366 366
 	 * @param string $registration_time_limit
367 367
 	 */
368
-	public function set_registration_time_limit( $registration_time_limit ) {
368
+	public function set_registration_time_limit($registration_time_limit) {
369 369
 		$this->_registration_time_limit = $registration_time_limit;
370 370
 	}
371 371
 
@@ -374,8 +374,8 @@  discard block
 block discarded – undo
374 374
 	/**
375 375
 	 * @param array $return_data
376 376
 	 */
377
-	public function set_return_data( $return_data ) {
378
-		$this->_return_data = array_merge( $this->_return_data, $return_data );
377
+	public function set_return_data($return_data) {
378
+		$this->_return_data = array_merge($this->_return_data, $return_data);
379 379
 	}
380 380
 
381 381
 
@@ -393,8 +393,8 @@  discard block
 block discarded – undo
393 393
 	 * @param array $validation_rules
394 394
 	 */
395 395
 	public function add_validation_rules(array $validation_rules = array()) {
396
-		if ( is_array( $validation_rules ) && ! empty( $validation_rules )) {
397
-			$this->_validation_rules = array_merge( $this->_validation_rules, $validation_rules );
396
+		if (is_array($validation_rules) && ! empty($validation_rules)) {
397
+			$this->_validation_rules = array_merge($this->_validation_rules, $validation_rules);
398 398
 		}
399 399
 	}
400 400
 
@@ -404,7 +404,7 @@  discard block
 block discarded – undo
404 404
 	 * @return array | bool
405 405
 	 */
406 406
 	public function validation_rules() {
407
-		return ! empty( $this->_validation_rules ) ? $this->_validation_rules : FALSE;
407
+		return ! empty($this->_validation_rules) ? $this->_validation_rules : FALSE;
408 408
 	}
409 409
 
410 410
 
Please login to merge, or discard this patch.
modules/ticket_selector/ProcessTicketSelector.php 2 patches
Indentation   +574 added lines, -574 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
 use InvalidArgumentException;
16 16
 
17 17
 if (! defined('EVENT_ESPRESSO_VERSION')) {
18
-    exit('No direct script access allowed');
18
+	exit('No direct script access allowed');
19 19
 }
20 20
 
21 21
 
@@ -32,597 +32,597 @@  discard block
 block discarded – undo
32 32
 class ProcessTicketSelector
33 33
 {
34 34
 
35
-    /**
36
-     * array of datetimes and the spaces available for them
37
-     *
38
-     * @var array[][]
39
-     */
40
-    private static $_available_spaces = array();
35
+	/**
36
+	 * array of datetimes and the spaces available for them
37
+	 *
38
+	 * @var array[][]
39
+	 */
40
+	private static $_available_spaces = array();
41 41
 
42 42
 
43
-    /**
44
-     * cancelTicketSelections
45
-     *
46
-     * @return        string
47
-     * @throws EE_Error
48
-     * @throws InvalidArgumentException
49
-     * @throws InvalidInterfaceException
50
-     * @throws InvalidDataTypeException
51
-     */
52
-    public function cancelTicketSelections()
53
-    {
54
-        // check nonce
55
-        if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
56
-            return false;
57
-        }
58
-        EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
59
-        if (EE_Registry::instance()->REQ->is_set('event_id')) {
60
-            wp_safe_redirect(
61
-                EEH_Event_View::event_link_url(
62
-                    EE_Registry::instance()->REQ->get('event_id')
63
-                )
64
-            );
65
-        } else {
66
-            wp_safe_redirect(
67
-                site_url('/' . EE_Registry::instance()->CFG->core->event_cpt_slug . '/')
68
-            );
69
-        }
70
-        exit();
71
-    }
43
+	/**
44
+	 * cancelTicketSelections
45
+	 *
46
+	 * @return        string
47
+	 * @throws EE_Error
48
+	 * @throws InvalidArgumentException
49
+	 * @throws InvalidInterfaceException
50
+	 * @throws InvalidDataTypeException
51
+	 */
52
+	public function cancelTicketSelections()
53
+	{
54
+		// check nonce
55
+		if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
56
+			return false;
57
+		}
58
+		EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
59
+		if (EE_Registry::instance()->REQ->is_set('event_id')) {
60
+			wp_safe_redirect(
61
+				EEH_Event_View::event_link_url(
62
+					EE_Registry::instance()->REQ->get('event_id')
63
+				)
64
+			);
65
+		} else {
66
+			wp_safe_redirect(
67
+				site_url('/' . EE_Registry::instance()->CFG->core->event_cpt_slug . '/')
68
+			);
69
+		}
70
+		exit();
71
+	}
72 72
 
73 73
 
74
-    /**
75
-     * processTicketSelectorNonce
76
-     *
77
-     * @param  string $nonce_name
78
-     * @param string  $id
79
-     * @return bool
80
-     * @throws InvalidArgumentException
81
-     * @throws InvalidInterfaceException
82
-     * @throws InvalidDataTypeException
83
-     */
84
-    private function processTicketSelectorNonce($nonce_name, $id = '')
85
-    {
86
-        $nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
87
-        if (
88
-            ! is_admin()
89
-            && (
90
-                ! EE_Registry::instance()->REQ->is_set($nonce_name_with_id)
91
-                || ! wp_verify_nonce(
92
-                    EE_Registry::instance()->REQ->get($nonce_name_with_id),
93
-                    $nonce_name
94
-                )
95
-            )
96
-        ) {
97
-            EE_Error::add_error(
98
-                sprintf(
99
-                    __(
100
-                        'We\'re sorry but your request failed to pass a security check.%sPlease click the back button on your browser and try again.',
101
-                        'event_espresso'
102
-                    ),
103
-                    '<br/>'
104
-                ),
105
-                __FILE__,
106
-                __FUNCTION__,
107
-                __LINE__
108
-            );
109
-            return false;
110
-        }
111
-        return true;
112
-    }
74
+	/**
75
+	 * processTicketSelectorNonce
76
+	 *
77
+	 * @param  string $nonce_name
78
+	 * @param string  $id
79
+	 * @return bool
80
+	 * @throws InvalidArgumentException
81
+	 * @throws InvalidInterfaceException
82
+	 * @throws InvalidDataTypeException
83
+	 */
84
+	private function processTicketSelectorNonce($nonce_name, $id = '')
85
+	{
86
+		$nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
87
+		if (
88
+			! is_admin()
89
+			&& (
90
+				! EE_Registry::instance()->REQ->is_set($nonce_name_with_id)
91
+				|| ! wp_verify_nonce(
92
+					EE_Registry::instance()->REQ->get($nonce_name_with_id),
93
+					$nonce_name
94
+				)
95
+			)
96
+		) {
97
+			EE_Error::add_error(
98
+				sprintf(
99
+					__(
100
+						'We\'re sorry but your request failed to pass a security check.%sPlease click the back button on your browser and try again.',
101
+						'event_espresso'
102
+					),
103
+					'<br/>'
104
+				),
105
+				__FILE__,
106
+				__FUNCTION__,
107
+				__LINE__
108
+			);
109
+			return false;
110
+		}
111
+		return true;
112
+	}
113 113
 
114 114
 
115
-    /**
116
-     * process_ticket_selections
117
-     *
118
-     * @return array|bool
119
-     * @throws \ReflectionException
120
-     * @throws InvalidArgumentException
121
-     * @throws InvalidInterfaceException
122
-     * @throws InvalidDataTypeException
123
-     * @throws EE_Error
124
-     */
125
-    public function processTicketSelections()
126
-    {
127
-        do_action('EED_Ticket_Selector__process_ticket_selections__before');
128
-        $request = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\request\Request');
129
-        if($request->isBot()) {
130
-            wp_safe_redirect(
131
-                apply_filters(
132
-                    'FHEE__EE_Ticket_Selector__process_ticket_selections__bot_redirect_url',
133
-                    site_url()
134
-                )
135
-            );
136
-            exit();
137
-        }
138
-        // do we have an event id?
139
-        if (! EE_Registry::instance()->REQ->is_set('tkt-slctr-event-id')) {
140
-            // $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
141
-            EE_Error::add_error(
142
-                sprintf(
143
-                    __(
144
-                        'An event id was not provided or was not received.%sPlease click the back button on your browser and try again.',
145
-                        'event_espresso'
146
-                    ),
147
-                    '<br/>'
148
-                ),
149
-                __FILE__,
150
-                __FUNCTION__,
151
-                __LINE__
152
-            );
153
-        }
154
-        //if event id is valid
155
-        $id = absint(EE_Registry::instance()->REQ->get('tkt-slctr-event-id'));
156
-        //		d( \EE_Registry::instance()->REQ );
157
-        self::$_available_spaces = array(
158
-            'tickets'   => array(),
159
-            'datetimes' => array(),
160
-        );
161
-        //we should really only have 1 registration in the works now (ie, no MER) so clear any previous items in the cart.
162
-        // When MER happens this will probably need to be tweaked, possibly wrapped in a conditional checking for some constant defined in MER etc.
163
-        EE_Registry::instance()->load_core('Session');
164
-        // unless otherwise requested, clear the session
165
-        if (apply_filters('FHEE__EE_Ticket_Selector__process_ticket_selections__clear_session', true)) {
166
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
167
-        }
168
-        //d( \EE_Registry::instance()->SSN );
169
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
170
-        // validate/sanitize data
171
-        $valid = $this->validatePostData($id);
172
-        //EEH_Debug_Tools::printr( $_REQUEST, '$_REQUEST', __FILE__, __LINE__ );
173
-        //EEH_Debug_Tools::printr( $valid, '$valid', __FILE__, __LINE__ );
174
-        //EEH_Debug_Tools::printr( $valid[ 'total_tickets' ], 'total_tickets', __FILE__, __LINE__ );
175
-        //EEH_Debug_Tools::printr( $valid[ 'max_atndz' ], 'max_atndz', __FILE__, __LINE__ );
176
-        //check total tickets ordered vs max number of attendees that can register
177
-        if ($valid['total_tickets'] > $valid['max_atndz']) {
178
-            // ordering too many tickets !!!
179
-            $total_tickets_string = _n(
180
-                'You have attempted to purchase %s ticket.',
181
-                'You have attempted to purchase %s tickets.',
182
-                $valid['total_tickets'],
183
-                'event_espresso'
184
-            );
185
-            $limit_error_1        = sprintf($total_tickets_string, $valid['total_tickets']);
186
-            // dev only message
187
-            $max_atndz_string = _n(
188
-                'The registration limit for this event is %s ticket per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
189
-                'The registration limit for this event is %s tickets per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
190
-                $valid['max_atndz'],
191
-                'event_espresso'
192
-            );
193
-            $limit_error_2    = sprintf($max_atndz_string, $valid['max_atndz'], $valid['max_atndz']);
194
-            EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
195
-        } else {
196
-            // all data appears to be valid
197
-            $tckts_slctd   = false;
198
-            $tickets_added = 0;
199
-            $valid         = apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data',
200
-                $valid);
201
-            if ($valid['total_tickets'] > 0) {
202
-                // load cart
203
-                EE_Registry::instance()->load_core('Cart');
204
-                // cycle thru the number of data rows sent from the event listing
205
-                for ($x = 0; $x < $valid['rows']; $x++) {
206
-                    // does this row actually contain a ticket quantity?
207
-                    if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
208
-                        // YES we have a ticket quantity
209
-                        $tckts_slctd = true;
210
-                        //						d( $valid['ticket_obj'][$x] );
211
-                        if ($valid['ticket_obj'][ $x ] instanceof EE_Ticket) {
212
-                            // then add ticket to cart
213
-                            $tickets_added += $this->addTicketToCart(
214
-                                $valid['ticket_obj'][ $x ],
215
-                                $valid['qty'][ $x ]
216
-                            );
217
-                            if (EE_Error::has_error()) {
218
-                                break;
219
-                            }
220
-                        } else {
221
-                            // nothing added to cart retrieved
222
-                            EE_Error::add_error(
223
-                                sprintf(
224
-                                    __(
225
-                                        'A valid ticket could not be retrieved for the event.%sPlease click the back button on your browser and try again.',
226
-                                        'event_espresso'
227
-                                    ),
228
-                                    '<br/>'
229
-                                ),
230
-                                __FILE__, __FUNCTION__, __LINE__
231
-                            );
232
-                        }
233
-                    }
234
-                }
235
-            }
236
-            do_action(
237
-                'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
238
-                EE_Registry::instance()->CART,
239
-                $this
240
-            );
241
-            //d( \EE_Registry::instance()->CART );
242
-            //die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
243
-            if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tckts_slctd)) {
244
-                if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
245
-                    do_action(
246
-                        'FHEE__EE_Ticket_Selector__process_ticket_selections__before_redirecting_to_checkout',
247
-                        EE_Registry::instance()->CART,
248
-                        $this
249
-                    );
250
-                    EE_Registry::instance()->CART->recalculate_all_cart_totals();
251
-                    EE_Registry::instance()->CART->save_cart(false);
252
-                    // exit('KILL REDIRECT AFTER CART UPDATE'); // <<<<<<<<  OR HERE TO KILL REDIRECT AFTER CART UPDATE
253
-                    // just return TRUE for registrations being made from admin
254
-                    if (is_admin()) {
255
-                        return true;
256
-                    }
257
-                    EE_Error::get_notices(false, true);
258
-                    EEH_URL::safeRedirectAndExit(
259
-                        apply_filters(
260
-                            'FHEE__EE_Ticket_Selector__process_ticket_selections__success_redirect_url',
261
-                            EE_Registry::instance()->CFG->core->reg_page_url()
262
-                        )
263
-                    );
264
-                } else {
265
-                    if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
266
-                        // nothing added to cart
267
-                        EE_Error::add_attention(__('No tickets were added for the event', 'event_espresso'),
268
-                            __FILE__, __FUNCTION__, __LINE__);
269
-                    }
270
-                }
271
-            } else {
272
-                // no ticket quantities were selected
273
-                EE_Error::add_error(__('You need to select a ticket quantity before you can proceed.',
274
-                    'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
275
-            }
276
-        }
277
-        //die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL BEFORE REDIRECT
278
-        // at this point, just return if registration is being made from admin
279
-        if (is_admin()) {
280
-            return false;
281
-        }
282
-        if ($valid['return_url']) {
283
-            EEH_URL::safeRedirectAndExit($valid['return_url']);
284
-        }
285
-        if ($id) {
286
-            EEH_URL::safeRedirectAndExit(get_permalink($id));
287
-        }
288
-        echo EE_Error::get_notices();
289
-        return false;
290
-    }
115
+	/**
116
+	 * process_ticket_selections
117
+	 *
118
+	 * @return array|bool
119
+	 * @throws \ReflectionException
120
+	 * @throws InvalidArgumentException
121
+	 * @throws InvalidInterfaceException
122
+	 * @throws InvalidDataTypeException
123
+	 * @throws EE_Error
124
+	 */
125
+	public function processTicketSelections()
126
+	{
127
+		do_action('EED_Ticket_Selector__process_ticket_selections__before');
128
+		$request = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\request\Request');
129
+		if($request->isBot()) {
130
+			wp_safe_redirect(
131
+				apply_filters(
132
+					'FHEE__EE_Ticket_Selector__process_ticket_selections__bot_redirect_url',
133
+					site_url()
134
+				)
135
+			);
136
+			exit();
137
+		}
138
+		// do we have an event id?
139
+		if (! EE_Registry::instance()->REQ->is_set('tkt-slctr-event-id')) {
140
+			// $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
141
+			EE_Error::add_error(
142
+				sprintf(
143
+					__(
144
+						'An event id was not provided or was not received.%sPlease click the back button on your browser and try again.',
145
+						'event_espresso'
146
+					),
147
+					'<br/>'
148
+				),
149
+				__FILE__,
150
+				__FUNCTION__,
151
+				__LINE__
152
+			);
153
+		}
154
+		//if event id is valid
155
+		$id = absint(EE_Registry::instance()->REQ->get('tkt-slctr-event-id'));
156
+		//		d( \EE_Registry::instance()->REQ );
157
+		self::$_available_spaces = array(
158
+			'tickets'   => array(),
159
+			'datetimes' => array(),
160
+		);
161
+		//we should really only have 1 registration in the works now (ie, no MER) so clear any previous items in the cart.
162
+		// When MER happens this will probably need to be tweaked, possibly wrapped in a conditional checking for some constant defined in MER etc.
163
+		EE_Registry::instance()->load_core('Session');
164
+		// unless otherwise requested, clear the session
165
+		if (apply_filters('FHEE__EE_Ticket_Selector__process_ticket_selections__clear_session', true)) {
166
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
167
+		}
168
+		//d( \EE_Registry::instance()->SSN );
169
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
170
+		// validate/sanitize data
171
+		$valid = $this->validatePostData($id);
172
+		//EEH_Debug_Tools::printr( $_REQUEST, '$_REQUEST', __FILE__, __LINE__ );
173
+		//EEH_Debug_Tools::printr( $valid, '$valid', __FILE__, __LINE__ );
174
+		//EEH_Debug_Tools::printr( $valid[ 'total_tickets' ], 'total_tickets', __FILE__, __LINE__ );
175
+		//EEH_Debug_Tools::printr( $valid[ 'max_atndz' ], 'max_atndz', __FILE__, __LINE__ );
176
+		//check total tickets ordered vs max number of attendees that can register
177
+		if ($valid['total_tickets'] > $valid['max_atndz']) {
178
+			// ordering too many tickets !!!
179
+			$total_tickets_string = _n(
180
+				'You have attempted to purchase %s ticket.',
181
+				'You have attempted to purchase %s tickets.',
182
+				$valid['total_tickets'],
183
+				'event_espresso'
184
+			);
185
+			$limit_error_1        = sprintf($total_tickets_string, $valid['total_tickets']);
186
+			// dev only message
187
+			$max_atndz_string = _n(
188
+				'The registration limit for this event is %s ticket per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
189
+				'The registration limit for this event is %s tickets per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
190
+				$valid['max_atndz'],
191
+				'event_espresso'
192
+			);
193
+			$limit_error_2    = sprintf($max_atndz_string, $valid['max_atndz'], $valid['max_atndz']);
194
+			EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
195
+		} else {
196
+			// all data appears to be valid
197
+			$tckts_slctd   = false;
198
+			$tickets_added = 0;
199
+			$valid         = apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data',
200
+				$valid);
201
+			if ($valid['total_tickets'] > 0) {
202
+				// load cart
203
+				EE_Registry::instance()->load_core('Cart');
204
+				// cycle thru the number of data rows sent from the event listing
205
+				for ($x = 0; $x < $valid['rows']; $x++) {
206
+					// does this row actually contain a ticket quantity?
207
+					if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
208
+						// YES we have a ticket quantity
209
+						$tckts_slctd = true;
210
+						//						d( $valid['ticket_obj'][$x] );
211
+						if ($valid['ticket_obj'][ $x ] instanceof EE_Ticket) {
212
+							// then add ticket to cart
213
+							$tickets_added += $this->addTicketToCart(
214
+								$valid['ticket_obj'][ $x ],
215
+								$valid['qty'][ $x ]
216
+							);
217
+							if (EE_Error::has_error()) {
218
+								break;
219
+							}
220
+						} else {
221
+							// nothing added to cart retrieved
222
+							EE_Error::add_error(
223
+								sprintf(
224
+									__(
225
+										'A valid ticket could not be retrieved for the event.%sPlease click the back button on your browser and try again.',
226
+										'event_espresso'
227
+									),
228
+									'<br/>'
229
+								),
230
+								__FILE__, __FUNCTION__, __LINE__
231
+							);
232
+						}
233
+					}
234
+				}
235
+			}
236
+			do_action(
237
+				'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
238
+				EE_Registry::instance()->CART,
239
+				$this
240
+			);
241
+			//d( \EE_Registry::instance()->CART );
242
+			//die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
243
+			if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tckts_slctd)) {
244
+				if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
245
+					do_action(
246
+						'FHEE__EE_Ticket_Selector__process_ticket_selections__before_redirecting_to_checkout',
247
+						EE_Registry::instance()->CART,
248
+						$this
249
+					);
250
+					EE_Registry::instance()->CART->recalculate_all_cart_totals();
251
+					EE_Registry::instance()->CART->save_cart(false);
252
+					// exit('KILL REDIRECT AFTER CART UPDATE'); // <<<<<<<<  OR HERE TO KILL REDIRECT AFTER CART UPDATE
253
+					// just return TRUE for registrations being made from admin
254
+					if (is_admin()) {
255
+						return true;
256
+					}
257
+					EE_Error::get_notices(false, true);
258
+					EEH_URL::safeRedirectAndExit(
259
+						apply_filters(
260
+							'FHEE__EE_Ticket_Selector__process_ticket_selections__success_redirect_url',
261
+							EE_Registry::instance()->CFG->core->reg_page_url()
262
+						)
263
+					);
264
+				} else {
265
+					if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
266
+						// nothing added to cart
267
+						EE_Error::add_attention(__('No tickets were added for the event', 'event_espresso'),
268
+							__FILE__, __FUNCTION__, __LINE__);
269
+					}
270
+				}
271
+			} else {
272
+				// no ticket quantities were selected
273
+				EE_Error::add_error(__('You need to select a ticket quantity before you can proceed.',
274
+					'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
275
+			}
276
+		}
277
+		//die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL BEFORE REDIRECT
278
+		// at this point, just return if registration is being made from admin
279
+		if (is_admin()) {
280
+			return false;
281
+		}
282
+		if ($valid['return_url']) {
283
+			EEH_URL::safeRedirectAndExit($valid['return_url']);
284
+		}
285
+		if ($id) {
286
+			EEH_URL::safeRedirectAndExit(get_permalink($id));
287
+		}
288
+		echo EE_Error::get_notices();
289
+		return false;
290
+	}
291 291
 
292 292
 
293
-    /**
294
-     * validate_post_data
295
-     *
296
-     * @param int $id
297
-     * @return array|FALSE
298
-     * @throws \ReflectionException
299
-     * @throws InvalidArgumentException
300
-     * @throws InvalidInterfaceException
301
-     * @throws InvalidDataTypeException
302
-     * @throws EE_Error
303
-     */
304
-    private function validatePostData($id = 0)
305
-    {
306
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
307
-        if (! $id) {
308
-            EE_Error::add_error(
309
-                __('The event id provided was not valid.', 'event_espresso'),
310
-                __FILE__,
311
-                __FUNCTION__,
312
-                __LINE__
313
-            );
314
-            return false;
315
-        }
316
-        // start with an empty array()
317
-        $valid_data = array();
318
-        // grab valid id
319
-        $valid_data['id'] = $id;
320
-        // array of other form names
321
-        $inputs_to_clean = array(
322
-            'event_id'   => 'tkt-slctr-event-id',
323
-            'max_atndz'  => 'tkt-slctr-max-atndz-',
324
-            'rows'       => 'tkt-slctr-rows-',
325
-            'qty'        => 'tkt-slctr-qty-',
326
-            'ticket_id'  => 'tkt-slctr-ticket-id-',
327
-            'return_url' => 'tkt-slctr-return-url-',
328
-        );
329
-        // let's track the total number of tickets ordered.'
330
-        $valid_data['total_tickets'] = 0;
331
-        // cycle through $inputs_to_clean array
332
-        foreach ($inputs_to_clean as $what => $input_to_clean) {
333
-            // check for POST data
334
-            if (EE_Registry::instance()->REQ->is_set($input_to_clean . $id)) {
335
-                // grab value
336
-                $input_value = EE_Registry::instance()->REQ->get($input_to_clean . $id);
337
-                switch ($what) {
338
-                    // integers
339
-                    case 'event_id':
340
-                        $valid_data[ $what ] = absint($input_value);
341
-                        // get event via the event id we put in the form
342
-                        $valid_data['event'] = EE_Registry::instance()
343
-                                                           ->load_model('Event')
344
-                                                           ->get_one_by_ID($valid_data['event_id']);
345
-                        break;
346
-                    case 'rows':
347
-                    case 'max_atndz':
348
-                        $valid_data[ $what ] = absint($input_value);
349
-                        break;
350
-                    // arrays of integers
351
-                    case 'qty':
352
-                        /** @var array $row_qty */
353
-                        $row_qty = $input_value;
354
-                        // if qty is coming from a radio button input, then we need to assemble an array of rows
355
-                        if (! is_array($row_qty)) {
356
-                            // get number of rows
357
-                            $rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-' . $id)
358
-                                ? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-' . $id))
359
-                                : 1;
360
-                            // explode ints by the dash
361
-                            $row_qty = explode('-', $row_qty);
362
-                            $row     = isset($row_qty[0]) ? absint($row_qty[0]) : 1;
363
-                            $qty     = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
364
-                            $row_qty = array($row => $qty);
365
-                            for ($x = 1; $x <= $rows; $x++) {
366
-                                if (! isset($row_qty[ $x ])) {
367
-                                    $row_qty[ $x ] = 0;
368
-                                }
369
-                            }
370
-                        }
371
-                        ksort($row_qty);
372
-                        // cycle thru values
373
-                        foreach ($row_qty as $qty) {
374
-                            $qty = absint($qty);
375
-                            // sanitize as integers
376
-                            $valid_data[ $what ][]       = $qty;
377
-                            $valid_data['total_tickets'] += $qty;
378
-                        }
379
-                        break;
380
-                    // array of integers
381
-                    case 'ticket_id':
382
-                        $value_array = array();
383
-                        // cycle thru values
384
-                        foreach ((array) $input_value as $key => $value) {
385
-                            // allow only numbers, letters,  spaces, commas and dashes
386
-                            $value_array[ $key ] = wp_strip_all_tags($value);
387
-                            // get ticket via the ticket id we put in the form
388
-                            $ticket_obj                       = EE_Registry::instance()
389
-                                                                            ->load_model('Ticket')
390
-                                                                            ->get_one_by_ID($value);
391
-                            $valid_data['ticket_obj'][ $key ] = $ticket_obj;
392
-                        }
393
-                        $valid_data[ $what ] = $value_array;
394
-                        break;
395
-                    case 'return_url' :
396
-                        // grab and sanitize return-url
397
-                        $input_value = esc_url_raw($input_value);
398
-                        // was the request coming from an iframe ? if so, then:
399
-                        if (strpos($input_value, 'event_list=iframe')) {
400
-                            // get anchor fragment
401
-                            $input_value = explode('#', $input_value);
402
-                            $input_value = end($input_value);
403
-                            // use event list url instead, but append anchor
404
-                            $input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
405
-                        }
406
-                        $valid_data[ $what ] = $input_value;
407
-                        break;
408
-                }    // end switch $what
409
-            }
410
-        }    // end foreach $inputs_to_clean
411
-        return $valid_data;
412
-    }
293
+	/**
294
+	 * validate_post_data
295
+	 *
296
+	 * @param int $id
297
+	 * @return array|FALSE
298
+	 * @throws \ReflectionException
299
+	 * @throws InvalidArgumentException
300
+	 * @throws InvalidInterfaceException
301
+	 * @throws InvalidDataTypeException
302
+	 * @throws EE_Error
303
+	 */
304
+	private function validatePostData($id = 0)
305
+	{
306
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
307
+		if (! $id) {
308
+			EE_Error::add_error(
309
+				__('The event id provided was not valid.', 'event_espresso'),
310
+				__FILE__,
311
+				__FUNCTION__,
312
+				__LINE__
313
+			);
314
+			return false;
315
+		}
316
+		// start with an empty array()
317
+		$valid_data = array();
318
+		// grab valid id
319
+		$valid_data['id'] = $id;
320
+		// array of other form names
321
+		$inputs_to_clean = array(
322
+			'event_id'   => 'tkt-slctr-event-id',
323
+			'max_atndz'  => 'tkt-slctr-max-atndz-',
324
+			'rows'       => 'tkt-slctr-rows-',
325
+			'qty'        => 'tkt-slctr-qty-',
326
+			'ticket_id'  => 'tkt-slctr-ticket-id-',
327
+			'return_url' => 'tkt-slctr-return-url-',
328
+		);
329
+		// let's track the total number of tickets ordered.'
330
+		$valid_data['total_tickets'] = 0;
331
+		// cycle through $inputs_to_clean array
332
+		foreach ($inputs_to_clean as $what => $input_to_clean) {
333
+			// check for POST data
334
+			if (EE_Registry::instance()->REQ->is_set($input_to_clean . $id)) {
335
+				// grab value
336
+				$input_value = EE_Registry::instance()->REQ->get($input_to_clean . $id);
337
+				switch ($what) {
338
+					// integers
339
+					case 'event_id':
340
+						$valid_data[ $what ] = absint($input_value);
341
+						// get event via the event id we put in the form
342
+						$valid_data['event'] = EE_Registry::instance()
343
+														   ->load_model('Event')
344
+														   ->get_one_by_ID($valid_data['event_id']);
345
+						break;
346
+					case 'rows':
347
+					case 'max_atndz':
348
+						$valid_data[ $what ] = absint($input_value);
349
+						break;
350
+					// arrays of integers
351
+					case 'qty':
352
+						/** @var array $row_qty */
353
+						$row_qty = $input_value;
354
+						// if qty is coming from a radio button input, then we need to assemble an array of rows
355
+						if (! is_array($row_qty)) {
356
+							// get number of rows
357
+							$rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-' . $id)
358
+								? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-' . $id))
359
+								: 1;
360
+							// explode ints by the dash
361
+							$row_qty = explode('-', $row_qty);
362
+							$row     = isset($row_qty[0]) ? absint($row_qty[0]) : 1;
363
+							$qty     = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
364
+							$row_qty = array($row => $qty);
365
+							for ($x = 1; $x <= $rows; $x++) {
366
+								if (! isset($row_qty[ $x ])) {
367
+									$row_qty[ $x ] = 0;
368
+								}
369
+							}
370
+						}
371
+						ksort($row_qty);
372
+						// cycle thru values
373
+						foreach ($row_qty as $qty) {
374
+							$qty = absint($qty);
375
+							// sanitize as integers
376
+							$valid_data[ $what ][]       = $qty;
377
+							$valid_data['total_tickets'] += $qty;
378
+						}
379
+						break;
380
+					// array of integers
381
+					case 'ticket_id':
382
+						$value_array = array();
383
+						// cycle thru values
384
+						foreach ((array) $input_value as $key => $value) {
385
+							// allow only numbers, letters,  spaces, commas and dashes
386
+							$value_array[ $key ] = wp_strip_all_tags($value);
387
+							// get ticket via the ticket id we put in the form
388
+							$ticket_obj                       = EE_Registry::instance()
389
+																			->load_model('Ticket')
390
+																			->get_one_by_ID($value);
391
+							$valid_data['ticket_obj'][ $key ] = $ticket_obj;
392
+						}
393
+						$valid_data[ $what ] = $value_array;
394
+						break;
395
+					case 'return_url' :
396
+						// grab and sanitize return-url
397
+						$input_value = esc_url_raw($input_value);
398
+						// was the request coming from an iframe ? if so, then:
399
+						if (strpos($input_value, 'event_list=iframe')) {
400
+							// get anchor fragment
401
+							$input_value = explode('#', $input_value);
402
+							$input_value = end($input_value);
403
+							// use event list url instead, but append anchor
404
+							$input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
405
+						}
406
+						$valid_data[ $what ] = $input_value;
407
+						break;
408
+				}    // end switch $what
409
+			}
410
+		}    // end foreach $inputs_to_clean
411
+		return $valid_data;
412
+	}
413 413
 
414 414
 
415
-    /**
416
-     * adds a ticket to the cart
417
-     *
418
-     * @param EE_Ticket $ticket
419
-     * @param int        $qty
420
-     * @return TRUE on success, FALSE on fail
421
-     * @throws InvalidArgumentException
422
-     * @throws InvalidInterfaceException
423
-     * @throws InvalidDataTypeException
424
-     * @throws EE_Error
425
-     */
426
-    private function addTicketToCart(EE_Ticket $ticket = null, $qty = 1)
427
-    {
428
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
429
-        // get the number of spaces left for this datetime ticket
430
-        $available_spaces = $this->ticketDatetimeAvailability($ticket);
431
-        // compare available spaces against the number of tickets being purchased
432
-        if ($available_spaces >= $qty) {
433
-            // allow addons to prevent a ticket from being added to cart
434
-            if (
435
-            ! apply_filters(
436
-                'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart',
437
-                true,
438
-                $ticket,
439
-                $qty,
440
-                $available_spaces
441
-            )
442
-            ) {
443
-                return false;
444
-            }
445
-            $qty = absint(apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty', $qty, $ticket));
446
-            // add event to cart
447
-            if (EE_Registry::instance()->CART->add_ticket_to_cart($ticket, $qty)) {
448
-                $this->recalculateTicketDatetimeAvailability($ticket, $qty);
449
-                return true;
450
-            }
451
-            return false;
452
-        }
453
-        // tickets can not be purchased but let's find the exact number left
454
-        // for the last ticket selected PRIOR to subtracting tickets
455
-        $available_spaces = $this->ticketDatetimeAvailability($ticket, true);
456
-        // greedy greedy greedy eh?
457
-        if ($available_spaces > 0) {
458
-            if (
459
-            apply_filters(
460
-                'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_display_availability_error',
461
-                true,
462
-                $ticket,
463
-                $qty,
464
-                $available_spaces
465
-            )
466
-            ) {
467
-                $this->displayAvailabilityError($available_spaces);
468
-            }
469
-        } else {
470
-            EE_Error::add_error(
471
-                __(
472
-                    'We\'re sorry, but there are no available spaces left for this event at this particular date and time.',
473
-                    'event_espresso'
474
-                ),
475
-                __FILE__, __FUNCTION__, __LINE__
476
-            );
477
-        }
478
-        return false;
479
-    }
415
+	/**
416
+	 * adds a ticket to the cart
417
+	 *
418
+	 * @param EE_Ticket $ticket
419
+	 * @param int        $qty
420
+	 * @return TRUE on success, FALSE on fail
421
+	 * @throws InvalidArgumentException
422
+	 * @throws InvalidInterfaceException
423
+	 * @throws InvalidDataTypeException
424
+	 * @throws EE_Error
425
+	 */
426
+	private function addTicketToCart(EE_Ticket $ticket = null, $qty = 1)
427
+	{
428
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
429
+		// get the number of spaces left for this datetime ticket
430
+		$available_spaces = $this->ticketDatetimeAvailability($ticket);
431
+		// compare available spaces against the number of tickets being purchased
432
+		if ($available_spaces >= $qty) {
433
+			// allow addons to prevent a ticket from being added to cart
434
+			if (
435
+			! apply_filters(
436
+				'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart',
437
+				true,
438
+				$ticket,
439
+				$qty,
440
+				$available_spaces
441
+			)
442
+			) {
443
+				return false;
444
+			}
445
+			$qty = absint(apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty', $qty, $ticket));
446
+			// add event to cart
447
+			if (EE_Registry::instance()->CART->add_ticket_to_cart($ticket, $qty)) {
448
+				$this->recalculateTicketDatetimeAvailability($ticket, $qty);
449
+				return true;
450
+			}
451
+			return false;
452
+		}
453
+		// tickets can not be purchased but let's find the exact number left
454
+		// for the last ticket selected PRIOR to subtracting tickets
455
+		$available_spaces = $this->ticketDatetimeAvailability($ticket, true);
456
+		// greedy greedy greedy eh?
457
+		if ($available_spaces > 0) {
458
+			if (
459
+			apply_filters(
460
+				'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_display_availability_error',
461
+				true,
462
+				$ticket,
463
+				$qty,
464
+				$available_spaces
465
+			)
466
+			) {
467
+				$this->displayAvailabilityError($available_spaces);
468
+			}
469
+		} else {
470
+			EE_Error::add_error(
471
+				__(
472
+					'We\'re sorry, but there are no available spaces left for this event at this particular date and time.',
473
+					'event_espresso'
474
+				),
475
+				__FILE__, __FUNCTION__, __LINE__
476
+			);
477
+		}
478
+		return false;
479
+	}
480 480
 
481 481
 
482
-    /**
483
-     * @param int $available_spaces
484
-     * @throws InvalidArgumentException
485
-     * @throws InvalidInterfaceException
486
-     * @throws InvalidDataTypeException
487
-     * @throws EE_Error
488
-     */
489
-    private function displayAvailabilityError($available_spaces = 1)
490
-    {
491
-        // add error messaging - we're using the _n function that will generate
492
-        // the appropriate singular or plural message based on the number of $available_spaces
493
-        if (EE_Registry::instance()->CART->all_ticket_quantity_count()) {
494
-            $msg = sprintf(
495
-                _n(
496
-                    'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
497
-                    'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
498
-                    $available_spaces,
499
-                    'event_espresso'
500
-                ),
501
-                $available_spaces,
502
-                '<br />'
503
-            );
504
-        } else {
505
-            $msg = sprintf(
506
-                _n(
507
-                    'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
508
-                    'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
509
-                    $available_spaces,
510
-                    'event_espresso'
511
-                ),
512
-                $available_spaces,
513
-                '<br />'
514
-            );
515
-        }
516
-        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
517
-    }
482
+	/**
483
+	 * @param int $available_spaces
484
+	 * @throws InvalidArgumentException
485
+	 * @throws InvalidInterfaceException
486
+	 * @throws InvalidDataTypeException
487
+	 * @throws EE_Error
488
+	 */
489
+	private function displayAvailabilityError($available_spaces = 1)
490
+	{
491
+		// add error messaging - we're using the _n function that will generate
492
+		// the appropriate singular or plural message based on the number of $available_spaces
493
+		if (EE_Registry::instance()->CART->all_ticket_quantity_count()) {
494
+			$msg = sprintf(
495
+				_n(
496
+					'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
497
+					'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
498
+					$available_spaces,
499
+					'event_espresso'
500
+				),
501
+				$available_spaces,
502
+				'<br />'
503
+			);
504
+		} else {
505
+			$msg = sprintf(
506
+				_n(
507
+					'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
508
+					'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
509
+					$available_spaces,
510
+					'event_espresso'
511
+				),
512
+				$available_spaces,
513
+				'<br />'
514
+			);
515
+		}
516
+		EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
517
+	}
518 518
 
519 519
 
520
-    /**
521
-     * ticketDatetimeAvailability
522
-     * creates an array of tickets plus all of the datetimes available to each ticket
523
-     * and tracks the spaces remaining for each of those datetimes
524
-     *
525
-     * @param EE_Ticket $ticket - selected ticket
526
-     * @param bool      $get_original_ticket_spaces
527
-     * @return int
528
-     * @throws InvalidArgumentException
529
-     * @throws InvalidInterfaceException
530
-     * @throws InvalidDataTypeException
531
-     * @throws EE_Error
532
-     */
533
-    private function ticketDatetimeAvailability(EE_Ticket $ticket, $get_original_ticket_spaces = false)
534
-    {
535
-        // if the $_available_spaces array has not been set up yet...
536
-        if (! isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
537
-            $this->setInitialTicketDatetimeAvailability($ticket);
538
-        }
539
-        $available_spaces = $ticket->qty() - $ticket->sold();
540
-        if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
541
-            // loop thru tickets, which will ALSO include individual ticket records AND a total
542
-            foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
543
-                // if we want the original datetime availability BEFORE we started subtracting tickets ?
544
-                if ($get_original_ticket_spaces) {
545
-                    // then grab the available spaces from the "tickets" array
546
-                    // and compare with the above to get the lowest number
547
-                    $available_spaces = min(
548
-                        $available_spaces,
549
-                        self::$_available_spaces['tickets'][ $ticket->ID() ][ $DTD_ID ]
550
-                    );
551
-                } else {
552
-                    // we want the updated ticket availability as stored in the "datetimes" array
553
-                    $available_spaces = min($available_spaces, self::$_available_spaces['datetimes'][ $DTD_ID ]);
554
-                }
555
-            }
556
-        }
557
-        return $available_spaces;
558
-    }
520
+	/**
521
+	 * ticketDatetimeAvailability
522
+	 * creates an array of tickets plus all of the datetimes available to each ticket
523
+	 * and tracks the spaces remaining for each of those datetimes
524
+	 *
525
+	 * @param EE_Ticket $ticket - selected ticket
526
+	 * @param bool      $get_original_ticket_spaces
527
+	 * @return int
528
+	 * @throws InvalidArgumentException
529
+	 * @throws InvalidInterfaceException
530
+	 * @throws InvalidDataTypeException
531
+	 * @throws EE_Error
532
+	 */
533
+	private function ticketDatetimeAvailability(EE_Ticket $ticket, $get_original_ticket_spaces = false)
534
+	{
535
+		// if the $_available_spaces array has not been set up yet...
536
+		if (! isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
537
+			$this->setInitialTicketDatetimeAvailability($ticket);
538
+		}
539
+		$available_spaces = $ticket->qty() - $ticket->sold();
540
+		if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
541
+			// loop thru tickets, which will ALSO include individual ticket records AND a total
542
+			foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
543
+				// if we want the original datetime availability BEFORE we started subtracting tickets ?
544
+				if ($get_original_ticket_spaces) {
545
+					// then grab the available spaces from the "tickets" array
546
+					// and compare with the above to get the lowest number
547
+					$available_spaces = min(
548
+						$available_spaces,
549
+						self::$_available_spaces['tickets'][ $ticket->ID() ][ $DTD_ID ]
550
+					);
551
+				} else {
552
+					// we want the updated ticket availability as stored in the "datetimes" array
553
+					$available_spaces = min($available_spaces, self::$_available_spaces['datetimes'][ $DTD_ID ]);
554
+				}
555
+			}
556
+		}
557
+		return $available_spaces;
558
+	}
559 559
 
560 560
 
561
-    /**
562
-     * @param EE_Ticket $ticket
563
-     * @return void
564
-     * @throws InvalidArgumentException
565
-     * @throws InvalidInterfaceException
566
-     * @throws InvalidDataTypeException
567
-     * @throws EE_Error
568
-     */
569
-    private function setInitialTicketDatetimeAvailability(EE_Ticket $ticket)
570
-    {
571
-        // first, get all of the datetimes that are available to this ticket
572
-        $datetimes = $ticket->get_many_related(
573
-            'Datetime',
574
-            array(
575
-                array(
576
-                    'DTT_EVT_end' => array(
577
-                        '>=',
578
-                        EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
579
-                    ),
580
-                ),
581
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
582
-            )
583
-        );
584
-        if (! empty($datetimes)) {
585
-            // now loop thru all of the datetimes
586
-            foreach ($datetimes as $datetime) {
587
-                if ($datetime instanceof EE_Datetime) {
588
-                    // the number of spaces available for the datetime without considering individual ticket quantities
589
-                    $spaces_remaining = $datetime->spaces_remaining();
590
-                    // save the total available spaces ( the lesser of the ticket qty minus the number of tickets sold
591
-                    // or the datetime spaces remaining) to this ticket using the datetime ID as the key
592
-                    self::$_available_spaces['tickets'][ $ticket->ID() ][ $datetime->ID() ] = min(
593
-                        $ticket->qty() - $ticket->sold(),
594
-                        $spaces_remaining
595
-                    );
596
-                    // if the remaining spaces for this datetime is already set,
597
-                    // then compare that against the datetime spaces remaining, and take the lowest number,
598
-                    // else just take the datetime spaces remaining, and assign to the datetimes array
599
-                    self::$_available_spaces['datetimes'][ $datetime->ID() ] = isset(
600
-                        self::$_available_spaces['datetimes'][ $datetime->ID() ]
601
-                    )
602
-                        ? min(self::$_available_spaces['datetimes'][ $datetime->ID() ], $spaces_remaining)
603
-                        : $spaces_remaining;
604
-                }
605
-            }
606
-        }
607
-    }
561
+	/**
562
+	 * @param EE_Ticket $ticket
563
+	 * @return void
564
+	 * @throws InvalidArgumentException
565
+	 * @throws InvalidInterfaceException
566
+	 * @throws InvalidDataTypeException
567
+	 * @throws EE_Error
568
+	 */
569
+	private function setInitialTicketDatetimeAvailability(EE_Ticket $ticket)
570
+	{
571
+		// first, get all of the datetimes that are available to this ticket
572
+		$datetimes = $ticket->get_many_related(
573
+			'Datetime',
574
+			array(
575
+				array(
576
+					'DTT_EVT_end' => array(
577
+						'>=',
578
+						EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
579
+					),
580
+				),
581
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
582
+			)
583
+		);
584
+		if (! empty($datetimes)) {
585
+			// now loop thru all of the datetimes
586
+			foreach ($datetimes as $datetime) {
587
+				if ($datetime instanceof EE_Datetime) {
588
+					// the number of spaces available for the datetime without considering individual ticket quantities
589
+					$spaces_remaining = $datetime->spaces_remaining();
590
+					// save the total available spaces ( the lesser of the ticket qty minus the number of tickets sold
591
+					// or the datetime spaces remaining) to this ticket using the datetime ID as the key
592
+					self::$_available_spaces['tickets'][ $ticket->ID() ][ $datetime->ID() ] = min(
593
+						$ticket->qty() - $ticket->sold(),
594
+						$spaces_remaining
595
+					);
596
+					// if the remaining spaces for this datetime is already set,
597
+					// then compare that against the datetime spaces remaining, and take the lowest number,
598
+					// else just take the datetime spaces remaining, and assign to the datetimes array
599
+					self::$_available_spaces['datetimes'][ $datetime->ID() ] = isset(
600
+						self::$_available_spaces['datetimes'][ $datetime->ID() ]
601
+					)
602
+						? min(self::$_available_spaces['datetimes'][ $datetime->ID() ], $spaces_remaining)
603
+						: $spaces_remaining;
604
+				}
605
+			}
606
+		}
607
+	}
608 608
 
609 609
 
610
-    /**
611
-     * @param    EE_Ticket $ticket
612
-     * @param    int        $qty
613
-     * @return    void
614
-     * @throws EE_Error
615
-     */
616
-    private function recalculateTicketDatetimeAvailability(EE_Ticket $ticket, $qty = 0)
617
-    {
618
-        if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
619
-            // loop thru tickets, which will ALSO include individual ticket records AND a total
620
-            foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
621
-                // subtract the qty of selected tickets from each datetime's available spaces this ticket has access to,
622
-                self::$_available_spaces['datetimes'][ $DTD_ID ] -= $qty;
623
-            }
624
-        }
625
-    }
610
+	/**
611
+	 * @param    EE_Ticket $ticket
612
+	 * @param    int        $qty
613
+	 * @return    void
614
+	 * @throws EE_Error
615
+	 */
616
+	private function recalculateTicketDatetimeAvailability(EE_Ticket $ticket, $qty = 0)
617
+	{
618
+		if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
619
+			// loop thru tickets, which will ALSO include individual ticket records AND a total
620
+			foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
621
+				// subtract the qty of selected tickets from each datetime's available spaces this ticket has access to,
622
+				self::$_available_spaces['datetimes'][ $DTD_ID ] -= $qty;
623
+			}
624
+		}
625
+	}
626 626
 }
627 627
 // End of file ProcessTicketSelector.php
628 628
 // Location: /ProcessTicketSelector.php
Please login to merge, or discard this patch.
Spacing   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -14,7 +14,7 @@  discard block
 block discarded – undo
14 14
 use EventEspresso\core\services\loaders\LoaderFactory;
15 15
 use InvalidArgumentException;
16 16
 
17
-if (! defined('EVENT_ESPRESSO_VERSION')) {
17
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
18 18
     exit('No direct script access allowed');
19 19
 }
20 20
 
@@ -52,7 +52,7 @@  discard block
 block discarded – undo
52 52
     public function cancelTicketSelections()
53 53
     {
54 54
         // check nonce
55
-        if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
55
+        if ( ! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
56 56
             return false;
57 57
         }
58 58
         EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
             );
65 65
         } else {
66 66
             wp_safe_redirect(
67
-                site_url('/' . EE_Registry::instance()->CFG->core->event_cpt_slug . '/')
67
+                site_url('/'.EE_Registry::instance()->CFG->core->event_cpt_slug.'/')
68 68
             );
69 69
         }
70 70
         exit();
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
     {
127 127
         do_action('EED_Ticket_Selector__process_ticket_selections__before');
128 128
         $request = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\request\Request');
129
-        if($request->isBot()) {
129
+        if ($request->isBot()) {
130 130
             wp_safe_redirect(
131 131
                 apply_filters(
132 132
                     'FHEE__EE_Ticket_Selector__process_ticket_selections__bot_redirect_url',
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
             exit();
137 137
         }
138 138
         // do we have an event id?
139
-        if (! EE_Registry::instance()->REQ->is_set('tkt-slctr-event-id')) {
139
+        if ( ! EE_Registry::instance()->REQ->is_set('tkt-slctr-event-id')) {
140 140
             // $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
141 141
             EE_Error::add_error(
142 142
                 sprintf(
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
                 $valid['total_tickets'],
183 183
                 'event_espresso'
184 184
             );
185
-            $limit_error_1        = sprintf($total_tickets_string, $valid['total_tickets']);
185
+            $limit_error_1 = sprintf($total_tickets_string, $valid['total_tickets']);
186 186
             // dev only message
187 187
             $max_atndz_string = _n(
188 188
                 'The registration limit for this event is %s ticket per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
@@ -190,8 +190,8 @@  discard block
 block discarded – undo
190 190
                 $valid['max_atndz'],
191 191
                 'event_espresso'
192 192
             );
193
-            $limit_error_2    = sprintf($max_atndz_string, $valid['max_atndz'], $valid['max_atndz']);
194
-            EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
193
+            $limit_error_2 = sprintf($max_atndz_string, $valid['max_atndz'], $valid['max_atndz']);
194
+            EE_Error::add_error($limit_error_1.'<br/>'.$limit_error_2, __FILE__, __FUNCTION__, __LINE__);
195 195
         } else {
196 196
             // all data appears to be valid
197 197
             $tckts_slctd   = false;
@@ -204,15 +204,15 @@  discard block
 block discarded – undo
204 204
                 // cycle thru the number of data rows sent from the event listing
205 205
                 for ($x = 0; $x < $valid['rows']; $x++) {
206 206
                     // does this row actually contain a ticket quantity?
207
-                    if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
207
+                    if (isset($valid['qty'][$x]) && $valid['qty'][$x] > 0) {
208 208
                         // YES we have a ticket quantity
209 209
                         $tckts_slctd = true;
210 210
                         //						d( $valid['ticket_obj'][$x] );
211
-                        if ($valid['ticket_obj'][ $x ] instanceof EE_Ticket) {
211
+                        if ($valid['ticket_obj'][$x] instanceof EE_Ticket) {
212 212
                             // then add ticket to cart
213 213
                             $tickets_added += $this->addTicketToCart(
214
-                                $valid['ticket_obj'][ $x ],
215
-                                $valid['qty'][ $x ]
214
+                                $valid['ticket_obj'][$x],
215
+                                $valid['qty'][$x]
216 216
                             );
217 217
                             if (EE_Error::has_error()) {
218 218
                                 break;
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
                         )
263 263
                     );
264 264
                 } else {
265
-                    if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
265
+                    if ( ! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
266 266
                         // nothing added to cart
267 267
                         EE_Error::add_attention(__('No tickets were added for the event', 'event_espresso'),
268 268
                             __FILE__, __FUNCTION__, __LINE__);
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
     private function validatePostData($id = 0)
305 305
     {
306 306
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
307
-        if (! $id) {
307
+        if ( ! $id) {
308 308
             EE_Error::add_error(
309 309
                 __('The event id provided was not valid.', 'event_espresso'),
310 310
                 __FILE__,
@@ -331,13 +331,13 @@  discard block
 block discarded – undo
331 331
         // cycle through $inputs_to_clean array
332 332
         foreach ($inputs_to_clean as $what => $input_to_clean) {
333 333
             // check for POST data
334
-            if (EE_Registry::instance()->REQ->is_set($input_to_clean . $id)) {
334
+            if (EE_Registry::instance()->REQ->is_set($input_to_clean.$id)) {
335 335
                 // grab value
336
-                $input_value = EE_Registry::instance()->REQ->get($input_to_clean . $id);
336
+                $input_value = EE_Registry::instance()->REQ->get($input_to_clean.$id);
337 337
                 switch ($what) {
338 338
                     // integers
339 339
                     case 'event_id':
340
-                        $valid_data[ $what ] = absint($input_value);
340
+                        $valid_data[$what] = absint($input_value);
341 341
                         // get event via the event id we put in the form
342 342
                         $valid_data['event'] = EE_Registry::instance()
343 343
                                                            ->load_model('Event')
@@ -345,17 +345,17 @@  discard block
 block discarded – undo
345 345
                         break;
346 346
                     case 'rows':
347 347
                     case 'max_atndz':
348
-                        $valid_data[ $what ] = absint($input_value);
348
+                        $valid_data[$what] = absint($input_value);
349 349
                         break;
350 350
                     // arrays of integers
351 351
                     case 'qty':
352 352
                         /** @var array $row_qty */
353 353
                         $row_qty = $input_value;
354 354
                         // if qty is coming from a radio button input, then we need to assemble an array of rows
355
-                        if (! is_array($row_qty)) {
355
+                        if ( ! is_array($row_qty)) {
356 356
                             // get number of rows
357
-                            $rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-' . $id)
358
-                                ? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-' . $id))
357
+                            $rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-'.$id)
358
+                                ? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-'.$id))
359 359
                                 : 1;
360 360
                             // explode ints by the dash
361 361
                             $row_qty = explode('-', $row_qty);
@@ -363,8 +363,8 @@  discard block
 block discarded – undo
363 363
                             $qty     = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
364 364
                             $row_qty = array($row => $qty);
365 365
                             for ($x = 1; $x <= $rows; $x++) {
366
-                                if (! isset($row_qty[ $x ])) {
367
-                                    $row_qty[ $x ] = 0;
366
+                                if ( ! isset($row_qty[$x])) {
367
+                                    $row_qty[$x] = 0;
368 368
                                 }
369 369
                             }
370 370
                         }
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
                         foreach ($row_qty as $qty) {
374 374
                             $qty = absint($qty);
375 375
                             // sanitize as integers
376
-                            $valid_data[ $what ][]       = $qty;
376
+                            $valid_data[$what][] = $qty;
377 377
                             $valid_data['total_tickets'] += $qty;
378 378
                         }
379 379
                         break;
@@ -383,14 +383,14 @@  discard block
 block discarded – undo
383 383
                         // cycle thru values
384 384
                         foreach ((array) $input_value as $key => $value) {
385 385
                             // allow only numbers, letters,  spaces, commas and dashes
386
-                            $value_array[ $key ] = wp_strip_all_tags($value);
386
+                            $value_array[$key] = wp_strip_all_tags($value);
387 387
                             // get ticket via the ticket id we put in the form
388 388
                             $ticket_obj                       = EE_Registry::instance()
389 389
                                                                             ->load_model('Ticket')
390 390
                                                                             ->get_one_by_ID($value);
391
-                            $valid_data['ticket_obj'][ $key ] = $ticket_obj;
391
+                            $valid_data['ticket_obj'][$key] = $ticket_obj;
392 392
                         }
393
-                        $valid_data[ $what ] = $value_array;
393
+                        $valid_data[$what] = $value_array;
394 394
                         break;
395 395
                     case 'return_url' :
396 396
                         // grab and sanitize return-url
@@ -401,9 +401,9 @@  discard block
 block discarded – undo
401 401
                             $input_value = explode('#', $input_value);
402 402
                             $input_value = end($input_value);
403 403
                             // use event list url instead, but append anchor
404
-                            $input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
404
+                            $input_value = EEH_Event_View::event_archive_url().'#'.$input_value;
405 405
                         }
406
-                        $valid_data[ $what ] = $input_value;
406
+                        $valid_data[$what] = $input_value;
407 407
                         break;
408 408
                 }    // end switch $what
409 409
             }
@@ -533,24 +533,24 @@  discard block
 block discarded – undo
533 533
     private function ticketDatetimeAvailability(EE_Ticket $ticket, $get_original_ticket_spaces = false)
534 534
     {
535 535
         // if the $_available_spaces array has not been set up yet...
536
-        if (! isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
536
+        if ( ! isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
537 537
             $this->setInitialTicketDatetimeAvailability($ticket);
538 538
         }
539 539
         $available_spaces = $ticket->qty() - $ticket->sold();
540
-        if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
540
+        if (isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
541 541
             // loop thru tickets, which will ALSO include individual ticket records AND a total
542
-            foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
542
+            foreach (self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
543 543
                 // if we want the original datetime availability BEFORE we started subtracting tickets ?
544 544
                 if ($get_original_ticket_spaces) {
545 545
                     // then grab the available spaces from the "tickets" array
546 546
                     // and compare with the above to get the lowest number
547 547
                     $available_spaces = min(
548 548
                         $available_spaces,
549
-                        self::$_available_spaces['tickets'][ $ticket->ID() ][ $DTD_ID ]
549
+                        self::$_available_spaces['tickets'][$ticket->ID()][$DTD_ID]
550 550
                     );
551 551
                 } else {
552 552
                     // we want the updated ticket availability as stored in the "datetimes" array
553
-                    $available_spaces = min($available_spaces, self::$_available_spaces['datetimes'][ $DTD_ID ]);
553
+                    $available_spaces = min($available_spaces, self::$_available_spaces['datetimes'][$DTD_ID]);
554 554
                 }
555 555
             }
556 556
         }
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
                 'order_by' => array('DTT_EVT_start' => 'ASC'),
582 582
             )
583 583
         );
584
-        if (! empty($datetimes)) {
584
+        if ( ! empty($datetimes)) {
585 585
             // now loop thru all of the datetimes
586 586
             foreach ($datetimes as $datetime) {
587 587
                 if ($datetime instanceof EE_Datetime) {
@@ -589,17 +589,17 @@  discard block
 block discarded – undo
589 589
                     $spaces_remaining = $datetime->spaces_remaining();
590 590
                     // save the total available spaces ( the lesser of the ticket qty minus the number of tickets sold
591 591
                     // or the datetime spaces remaining) to this ticket using the datetime ID as the key
592
-                    self::$_available_spaces['tickets'][ $ticket->ID() ][ $datetime->ID() ] = min(
592
+                    self::$_available_spaces['tickets'][$ticket->ID()][$datetime->ID()] = min(
593 593
                         $ticket->qty() - $ticket->sold(),
594 594
                         $spaces_remaining
595 595
                     );
596 596
                     // if the remaining spaces for this datetime is already set,
597 597
                     // then compare that against the datetime spaces remaining, and take the lowest number,
598 598
                     // else just take the datetime spaces remaining, and assign to the datetimes array
599
-                    self::$_available_spaces['datetimes'][ $datetime->ID() ] = isset(
600
-                        self::$_available_spaces['datetimes'][ $datetime->ID() ]
599
+                    self::$_available_spaces['datetimes'][$datetime->ID()] = isset(
600
+                        self::$_available_spaces['datetimes'][$datetime->ID()]
601 601
                     )
602
-                        ? min(self::$_available_spaces['datetimes'][ $datetime->ID() ], $spaces_remaining)
602
+                        ? min(self::$_available_spaces['datetimes'][$datetime->ID()], $spaces_remaining)
603 603
                         : $spaces_remaining;
604 604
                 }
605 605
             }
@@ -615,11 +615,11 @@  discard block
 block discarded – undo
615 615
      */
616 616
     private function recalculateTicketDatetimeAvailability(EE_Ticket $ticket, $qty = 0)
617 617
     {
618
-        if (isset(self::$_available_spaces['tickets'][ $ticket->ID() ])) {
618
+        if (isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
619 619
             // loop thru tickets, which will ALSO include individual ticket records AND a total
620
-            foreach (self::$_available_spaces['tickets'][ $ticket->ID() ] as $DTD_ID => $spaces) {
620
+            foreach (self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
621 621
                 // subtract the qty of selected tickets from each datetime's available spaces this ticket has access to,
622
-                self::$_available_spaces['datetimes'][ $DTD_ID ] -= $qty;
622
+                self::$_available_spaces['datetimes'][$DTD_ID] -= $qty;
623 623
             }
624 624
         }
625 625
     }
Please login to merge, or discard this patch.
core/libraries/form_sections/base/EE_Form_Section_Proper.form.php 2 patches
Spacing   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -111,8 +111,8 @@  discard block
 block discarded – undo
111 111
             //AND we are going to make sure they're in that specified order
112 112
             $reordered_subsections = array();
113 113
             foreach ($options_array['include'] as $input_name) {
114
-                if (isset($this->_subsections[ $input_name ])) {
115
-                    $reordered_subsections[ $input_name ] = $this->_subsections[ $input_name ];
114
+                if (isset($this->_subsections[$input_name])) {
115
+                    $reordered_subsections[$input_name] = $this->_subsections[$input_name];
116 116
                 }
117 117
             }
118 118
             $this->_subsections = $reordered_subsections;
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
         if (isset($options_array['layout_strategy'])) {
125 125
             $this->_layout_strategy = $options_array['layout_strategy'];
126 126
         }
127
-        if (! $this->_layout_strategy) {
127
+        if ( ! $this->_layout_strategy) {
128 128
             $this->_layout_strategy = is_admin() ? new EE_Admin_Two_Column_Layout() : new EE_Two_Column_Layout();
129 129
         }
130 130
         $this->_layout_strategy->_construct_finalize($this);
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
                 $req_data,
278 278
                 $this
279 279
             );
280
-            $this->cached_request_data = (array)$req_data;
280
+            $this->cached_request_data = (array) $req_data;
281 281
         }
282 282
         return $this->cached_request_data;
283 283
     }
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
         if ($validate) {
314 314
             $this->_validate();
315 315
             //if it's invalid, we're going to want to re-display so remember what they submitted
316
-            if (! $this->is_valid()) {
316
+            if ( ! $this->is_valid()) {
317 317
                 $this->store_submitted_form_data_in_session();
318 318
             }
319 319
         }
@@ -426,11 +426,11 @@  discard block
 block discarded – undo
426 426
     public function populate_defaults($default_data)
427 427
     {
428 428
         foreach ($this->subsections(false) as $subsection_name => $subsection) {
429
-            if (isset($default_data[ $subsection_name ])) {
429
+            if (isset($default_data[$subsection_name])) {
430 430
                 if ($subsection instanceof EE_Form_Input_Base) {
431
-                    $subsection->set_default($default_data[ $subsection_name ]);
431
+                    $subsection->set_default($default_data[$subsection_name]);
432 432
                 } elseif ($subsection instanceof EE_Form_Section_Proper) {
433
-                    $subsection->populate_defaults($default_data[ $subsection_name ]);
433
+                    $subsection->populate_defaults($default_data[$subsection_name]);
434 434
                 }
435 435
             }
436 436
         }
@@ -445,7 +445,7 @@  discard block
 block discarded – undo
445 445
      */
446 446
     public function subsection_exists($name)
447 447
     {
448
-        return isset($this->_subsections[ $name ]) ? true : false;
448
+        return isset($this->_subsections[$name]) ? true : false;
449 449
     }
450 450
 
451 451
 
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
         if ($require_construction_to_be_finalized) {
468 468
             $this->ensure_construct_finalized_called();
469 469
         }
470
-        return $this->subsection_exists($name) ? $this->_subsections[ $name ] : null;
470
+        return $this->subsection_exists($name) ? $this->_subsections[$name] : null;
471 471
     }
472 472
 
473 473
 
@@ -482,7 +482,7 @@  discard block
 block discarded – undo
482 482
         $validatable_subsections = array();
483 483
         foreach ($this->subsections() as $name => $obj) {
484 484
             if ($obj instanceof EE_Form_Section_Validatable) {
485
-                $validatable_subsections[ $name ] = $obj;
485
+                $validatable_subsections[$name] = $obj;
486 486
             }
487 487
         }
488 488
         return $validatable_subsections;
@@ -509,7 +509,7 @@  discard block
 block discarded – undo
509 509
             $name,
510 510
             $require_construction_to_be_finalized
511 511
         );
512
-        if (! $subsection instanceof EE_Form_Input_Base) {
512
+        if ( ! $subsection instanceof EE_Form_Input_Base) {
513 513
             throw new EE_Error(
514 514
                 sprintf(
515 515
                     esc_html__(
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
             $name,
547 547
             $require_construction_to_be_finalized
548 548
         );
549
-        if (! $subsection instanceof EE_Form_Section_Proper) {
549
+        if ( ! $subsection instanceof EE_Form_Section_Proper) {
550 550
             throw new EE_Error(
551 551
                 sprintf(
552 552
                     esc_html__(
@@ -585,8 +585,8 @@  discard block
 block discarded – undo
585 585
      */
586 586
     public function is_valid()
587 587
     {
588
-        if($this->is_valid === null) {
589
-            if (! $this->has_received_submission()) {
588
+        if ($this->is_valid === null) {
589
+            if ( ! $this->has_received_submission()) {
590 590
                 throw new EE_Error(
591 591
                     sprintf(
592 592
                         esc_html__(
@@ -596,14 +596,14 @@  discard block
 block discarded – undo
596 596
                     )
597 597
                 );
598 598
             }
599
-            if (! parent::is_valid()) {
599
+            if ( ! parent::is_valid()) {
600 600
                 $this->is_valid = false;
601 601
             } else {
602 602
                 // ok so no general errors to this entire form section.
603 603
                 // so let's check the subsections, but only set errors if that hasn't been done yet
604 604
                 $this->is_valid = true;
605 605
                 foreach ($this->get_validatable_subsections() as $subsection) {
606
-                    if (! $subsection->is_valid()) {
606
+                    if ( ! $subsection->is_valid()) {
607 607
                         $this->is_valid = false;
608 608
                     }
609 609
                 }
@@ -620,7 +620,7 @@  discard block
 block discarded – undo
620 620
      */
621 621
     protected function _set_default_name_if_empty()
622 622
     {
623
-        if (! $this->_name) {
623
+        if ( ! $this->_name) {
624 624
             $classname    = get_class($this);
625 625
             $default_name = str_replace('EE_', '', $classname);
626 626
             $this->_name  = $default_name;
@@ -710,7 +710,7 @@  discard block
 block discarded – undo
710 710
     {
711 711
         wp_register_script(
712 712
             'ee_form_section_validation',
713
-            EE_GLOBAL_ASSETS_URL . 'scripts' . DS . 'form_section_validation.js',
713
+            EE_GLOBAL_ASSETS_URL.'scripts'.DS.'form_section_validation.js',
714 714
             array('jquery-validate', 'jquery-ui-datepicker', 'jquery-validate-extra-methods'),
715 715
             EVENT_ESPRESSO_VERSION,
716 716
             true
@@ -754,13 +754,13 @@  discard block
 block discarded – undo
754 754
         // we only want to localize vars ONCE for the entire form,
755 755
         // so if the form section doesn't have a parent, then it must be the top dog
756 756
         if ($return_for_subsection || ! $this->parent_section()) {
757
-            EE_Form_Section_Proper::$_js_localization['form_data'][ $this->html_id() ] = array(
757
+            EE_Form_Section_Proper::$_js_localization['form_data'][$this->html_id()] = array(
758 758
                 'form_section_id'  => $this->html_id(true),
759 759
                 'validation_rules' => $this->get_jquery_validation_rules(),
760 760
                 'other_data'       => $this->get_other_js_data(),
761 761
                 'errors'           => $this->subsection_validation_errors_by_html_name(),
762 762
             );
763
-            EE_Form_Section_Proper::$_scripts_localized                                = true;
763
+            EE_Form_Section_Proper::$_scripts_localized = true;
764 764
         }
765 765
     }
766 766
 
@@ -795,7 +795,7 @@  discard block
 block discarded – undo
795 795
         $inputs = array();
796 796
         foreach ($this->subsections() as $subsection) {
797 797
             if ($subsection instanceof EE_Form_Input_Base) {
798
-                $inputs[ $subsection->html_name() ] = $subsection;
798
+                $inputs[$subsection->html_name()] = $subsection;
799 799
             } elseif ($subsection instanceof EE_Form_Section_Proper) {
800 800
                 $inputs += $subsection->inputs_in_subsections();
801 801
             }
@@ -818,7 +818,7 @@  discard block
 block discarded – undo
818 818
         $errors = array();
819 819
         foreach ($inputs as $form_input) {
820 820
             if ($form_input instanceof EE_Form_Input_Base && $form_input->get_validation_errors()) {
821
-                $errors[ $form_input->html_name() ] = $form_input->get_validation_error_string();
821
+                $errors[$form_input->html_name()] = $form_input->get_validation_error_string();
822 822
             }
823 823
         }
824 824
         return $errors;
@@ -841,7 +841,7 @@  discard block
 block discarded – undo
841 841
         $email_validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
842 842
             ? EE_Registry::instance()->CFG->registration->email_validation_level
843 843
             : 'wp_default';
844
-        EE_Form_Section_Proper::$_js_localization['email_validation_level']   = $email_validation_level;
844
+        EE_Form_Section_Proper::$_js_localization['email_validation_level'] = $email_validation_level;
845 845
         wp_enqueue_script('ee_form_section_validation');
846 846
         wp_localize_script(
847 847
             'ee_form_section_validation',
@@ -858,7 +858,7 @@  discard block
 block discarded – undo
858 858
      */
859 859
     public function ensure_scripts_localized()
860 860
     {
861
-        if (! EE_Form_Section_Proper::$_scripts_localized) {
861
+        if ( ! EE_Form_Section_Proper::$_scripts_localized) {
862 862
             $this->_enqueue_and_localize_form_js();
863 863
         }
864 864
     }
@@ -954,8 +954,8 @@  discard block
 block discarded – undo
954 954
         //reset the cache of whether this form is valid or not- we're re-validating it now
955 955
         $this->is_valid = null;
956 956
         foreach ($this->get_validatable_subsections() as $subsection_name => $subsection) {
957
-            if (method_exists($this, '_validate_' . $subsection_name)) {
958
-                call_user_func_array(array($this, '_validate_' . $subsection_name), array($subsection));
957
+            if (method_exists($this, '_validate_'.$subsection_name)) {
958
+                call_user_func_array(array($this, '_validate_'.$subsection_name), array($subsection));
959 959
             }
960 960
             $subsection->_validate();
961 961
         }
@@ -973,9 +973,9 @@  discard block
 block discarded – undo
973 973
         $inputs = array();
974 974
         foreach ($this->subsections() as $subsection_name => $subsection) {
975 975
             if ($subsection instanceof EE_Form_Section_Proper) {
976
-                $inputs[ $subsection_name ] = $subsection->valid_data();
976
+                $inputs[$subsection_name] = $subsection->valid_data();
977 977
             } elseif ($subsection instanceof EE_Form_Input_Base) {
978
-                $inputs[ $subsection_name ] = $subsection->normalized_value();
978
+                $inputs[$subsection_name] = $subsection->normalized_value();
979 979
             }
980 980
         }
981 981
         return $inputs;
@@ -993,7 +993,7 @@  discard block
 block discarded – undo
993 993
         $inputs = array();
994 994
         foreach ($this->subsections() as $subsection_name => $subsection) {
995 995
             if ($subsection instanceof EE_Form_Input_Base) {
996
-                $inputs[ $subsection_name ] = $subsection;
996
+                $inputs[$subsection_name] = $subsection;
997 997
             }
998 998
         }
999 999
         return $inputs;
@@ -1011,7 +1011,7 @@  discard block
 block discarded – undo
1011 1011
         $form_sections = array();
1012 1012
         foreach ($this->subsections() as $name => $obj) {
1013 1013
             if ($obj instanceof EE_Form_Section_Proper) {
1014
-                $form_sections[ $name ] = $obj;
1014
+                $form_sections[$name] = $obj;
1015 1015
             }
1016 1016
         }
1017 1017
         return $form_sections;
@@ -1118,7 +1118,7 @@  discard block
 block discarded – undo
1118 1118
         $input_values = array();
1119 1119
         foreach ($this->subsections() as $subsection_name => $subsection) {
1120 1120
             if ($subsection instanceof EE_Form_Input_Base) {
1121
-                $input_values[ $subsection_name ] = $pretty
1121
+                $input_values[$subsection_name] = $pretty
1122 1122
                     ? $subsection->pretty_value()
1123 1123
                     : $subsection->normalized_value();
1124 1124
             } elseif ($subsection instanceof EE_Form_Section_Proper && $include_subform_inputs) {
@@ -1130,7 +1130,7 @@  discard block
 block discarded – undo
1130 1130
                 if ($flatten) {
1131 1131
                     $input_values = array_merge($input_values, $subform_input_values);
1132 1132
                 } else {
1133
-                    $input_values[ $subsection_name ] = $subform_input_values;
1133
+                    $input_values[$subsection_name] = $subform_input_values;
1134 1134
                 }
1135 1135
             }
1136 1136
         }
@@ -1158,7 +1158,7 @@  discard block
 block discarded – undo
1158 1158
             if ($subsection instanceof EE_Form_Input_Base) {
1159 1159
                 // is this input part of an array of inputs?
1160 1160
                 if (strpos($subsection->html_name(), '[') !== false) {
1161
-                    $full_input_name  = EEH_Array::convert_array_values_to_keys(
1161
+                    $full_input_name = EEH_Array::convert_array_values_to_keys(
1162 1162
                         explode(
1163 1163
                             '[',
1164 1164
                             str_replace(']', '', $subsection->html_name())
@@ -1167,7 +1167,7 @@  discard block
 block discarded – undo
1167 1167
                     );
1168 1168
                     $submitted_values = array_replace_recursive($submitted_values, $full_input_name);
1169 1169
                 } else {
1170
-                    $submitted_values[ $subsection->html_name() ] = $subsection->raw_value();
1170
+                    $submitted_values[$subsection->html_name()] = $subsection->raw_value();
1171 1171
                 }
1172 1172
             } elseif ($subsection instanceof EE_Form_Section_Proper && $include_subforms) {
1173 1173
                 $subform_input_values = $subsection->submitted_values($include_subforms);
@@ -1202,7 +1202,7 @@  discard block
 block discarded – undo
1202 1202
     public function exclude(array $inputs_to_exclude = array())
1203 1203
     {
1204 1204
         foreach ($inputs_to_exclude as $input_to_exclude_name) {
1205
-            unset($this->_subsections[ $input_to_exclude_name ]);
1205
+            unset($this->_subsections[$input_to_exclude_name]);
1206 1206
         }
1207 1207
     }
1208 1208
 
@@ -1244,7 +1244,7 @@  discard block
 block discarded – undo
1244 1244
     public function add_subsections($new_subsections, $subsection_name_to_target = null, $add_before = true)
1245 1245
     {
1246 1246
         foreach ($new_subsections as $subsection_name => $subsection) {
1247
-            if (! $subsection instanceof EE_Form_Section_Base) {
1247
+            if ( ! $subsection instanceof EE_Form_Section_Base) {
1248 1248
                 EE_Error::add_error(
1249 1249
                     sprintf(
1250 1250
                         esc_html__(
@@ -1256,7 +1256,7 @@  discard block
 block discarded – undo
1256 1256
                         $this->name()
1257 1257
                     )
1258 1258
                 );
1259
-                unset($new_subsections[ $subsection_name ]);
1259
+                unset($new_subsections[$subsection_name]);
1260 1260
             }
1261 1261
         }
1262 1262
         $this->_subsections = EEH_Array::insert_into_array(
@@ -1280,7 +1280,7 @@  discard block
 block discarded – undo
1280 1280
      */
1281 1281
     public function has_subsection($subsection_name, $recursive = false)
1282 1282
     {
1283
-        foreach ($this->_subsections as $name => $subsection) {if(
1283
+        foreach ($this->_subsections as $name => $subsection) {if (
1284 1284
                 $name === $subsection_name
1285 1285
                 || (
1286 1286
                     $recursive
@@ -1371,7 +1371,7 @@  discard block
 block discarded – undo
1371 1371
     public function html_name_prefix()
1372 1372
     {
1373 1373
         if ($this->parent_section() instanceof EE_Form_Section_Proper) {
1374
-            return $this->parent_section()->html_name_prefix() . '[' . $this->name() . ']';
1374
+            return $this->parent_section()->html_name_prefix().'['.$this->name().']';
1375 1375
         }
1376 1376
         return $this->name();
1377 1377
     }
@@ -1411,7 +1411,7 @@  discard block
 block discarded – undo
1411 1411
      */
1412 1412
     public function ensure_construct_finalized_called()
1413 1413
     {
1414
-        if (! $this->_construction_finalized) {
1414
+        if ( ! $this->_construction_finalized) {
1415 1415
             $this->_construct_finalize($this->_parent_section, $this->_name);
1416 1416
         }
1417 1417
     }
@@ -1484,7 +1484,7 @@  discard block
 block discarded – undo
1484 1484
                 $form_section = $validation_error->get_form_section();
1485 1485
                 if ($form_section instanceof EE_Form_Input_Base) {
1486 1486
                    $label = $validation_error->get_form_section()->html_label_text();
1487
-                } elseif($form_section instanceof EE_Form_Section_Validatable) {
1487
+                } elseif ($form_section instanceof EE_Form_Section_Validatable) {
1488 1488
                     $label = $validation_error->get_form_section()->name();
1489 1489
                 } else {
1490 1490
                     $label = esc_html__('Unknown', 'event_espresso');
Please login to merge, or discard this patch.
Indentation   +1524 added lines, -1524 removed lines patch added patch discarded remove patch
@@ -14,1529 +14,1529 @@
 block discarded – undo
14 14
 class EE_Form_Section_Proper extends EE_Form_Section_Validatable
15 15
 {
16 16
 
17
-    const SUBMITTED_FORM_DATA_SSN_KEY = 'submitted_form_data';
18
-
19
-    /**
20
-     * Subsections
21
-     *
22
-     * @var EE_Form_Section_Validatable[]
23
-     */
24
-    protected $_subsections = array();
25
-
26
-    /**
27
-     * Strategy for laying out the form
28
-     *
29
-     * @var EE_Form_Section_Layout_Base
30
-     */
31
-    protected $_layout_strategy;
32
-
33
-    /**
34
-     * Whether or not this form has received and validated a form submission yet
35
-     *
36
-     * @var boolean
37
-     */
38
-    protected $_received_submission = false;
39
-
40
-    /**
41
-     * message displayed to users upon successful form submission
42
-     *
43
-     * @var string
44
-     */
45
-    protected $_form_submission_success_message = '';
46
-
47
-    /**
48
-     * message displayed to users upon unsuccessful form submission
49
-     *
50
-     * @var string
51
-     */
52
-    protected $_form_submission_error_message = '';
53
-
54
-    /**
55
-     * @var array like $_REQUEST
56
-     */
57
-    protected $cached_request_data;
58
-
59
-    /**
60
-     * Stores whether this form (and its sub-sections) were found to be valid or not.
61
-     * Starts off as null, but once the form is validated, it set to either true or false
62
-     * @var boolean|null
63
-     */
64
-    protected $is_valid;
65
-
66
-    /**
67
-     * Stores all the data that will localized for form validation
68
-     *
69
-     * @var array
70
-     */
71
-    static protected $_js_localization = array();
72
-
73
-    /**
74
-     * whether or not the form's localized validation JS vars have been set
75
-     *
76
-     * @type boolean
77
-     */
78
-    static protected $_scripts_localized = false;
79
-
80
-
81
-    /**
82
-     * when constructing a proper form section, calls _construct_finalize on children
83
-     * so that they know who their parent is, and what name they've been given.
84
-     *
85
-     * @param array[] $options_array   {
86
-     * @type          $subsections     EE_Form_Section_Validatable[] where keys are the section's name
87
-     * @type          $include         string[] numerically-indexed where values are section names to be included,
88
-     *                                 and in that order. This is handy if you want
89
-     *                                 the subsections to be ordered differently than the default, and if you override
90
-     *                                 which fields are shown
91
-     * @type          $exclude         string[] values are subsections to be excluded. This is handy if you want
92
-     *                                 to remove certain default subsections (note: if you specify BOTH 'include' AND
93
-     *                                 'exclude', the inclusions will be applied first, and the exclusions will exclude
94
-     *                                 items from that list of inclusions)
95
-     * @type          $layout_strategy EE_Form_Section_Layout_Base strategy for laying out the form
96
-     *                                 } @see EE_Form_Section_Validatable::__construct()
97
-     * @throws EE_Error
98
-     */
99
-    public function __construct($options_array = array())
100
-    {
101
-        $options_array = (array) apply_filters(
102
-            'FHEE__EE_Form_Section_Proper___construct__options_array',
103
-            $options_array,
104
-            $this
105
-        );
106
-        //call parent first, as it may be setting the name
107
-        parent::__construct($options_array);
108
-        //if they've included subsections in the constructor, add them now
109
-        if (isset($options_array['include'])) {
110
-            //we are going to make sure we ONLY have those subsections to include
111
-            //AND we are going to make sure they're in that specified order
112
-            $reordered_subsections = array();
113
-            foreach ($options_array['include'] as $input_name) {
114
-                if (isset($this->_subsections[ $input_name ])) {
115
-                    $reordered_subsections[ $input_name ] = $this->_subsections[ $input_name ];
116
-                }
117
-            }
118
-            $this->_subsections = $reordered_subsections;
119
-        }
120
-        if (isset($options_array['exclude'])) {
121
-            $exclude            = $options_array['exclude'];
122
-            $this->_subsections = array_diff_key($this->_subsections, array_flip($exclude));
123
-        }
124
-        if (isset($options_array['layout_strategy'])) {
125
-            $this->_layout_strategy = $options_array['layout_strategy'];
126
-        }
127
-        if (! $this->_layout_strategy) {
128
-            $this->_layout_strategy = is_admin() ? new EE_Admin_Two_Column_Layout() : new EE_Two_Column_Layout();
129
-        }
130
-        $this->_layout_strategy->_construct_finalize($this);
131
-        //ok so we are definitely going to want the forms JS,
132
-        //so enqueue it or remember to enqueue it during wp_enqueue_scripts
133
-        if (did_action('wp_enqueue_scripts') || did_action('admin_enqueue_scripts')) {
134
-            //ok so they've constructed this object after when they should have.
135
-            //just enqueue the generic form scripts and initialize the form immediately in the JS
136
-            EE_Form_Section_Proper::wp_enqueue_scripts(true);
137
-        } else {
138
-            add_action('wp_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
139
-            add_action('admin_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
140
-        }
141
-        add_action('wp_footer', array($this, 'ensure_scripts_localized'), 1);
142
-        /**
143
-         * Gives other plugins a chance to hook in before construct finalize is called.
144
-         * The form probably doesn't yet have a parent form section.
145
-         * Since 4.9.32, when this action was introduced, this is the best place to add a subsection onto a form,
146
-         * assuming you don't care what the form section's name, HTML ID, or HTML name etc are.
147
-         * Also see AHEE__EE_Form_Section_Proper___construct_finalize__end
148
-         *
149
-         * @since 4.9.32
150
-         * @param EE_Form_Section_Proper $this          before __construct is done, but all of its logic,
151
-         *                                              except maybe calling _construct_finalize has been done
152
-         * @param array                  $options_array options passed into the constructor
153
-         */
154
-        do_action(
155
-            'AHEE__EE_Form_Input_Base___construct__before_construct_finalize_called',
156
-            $this,
157
-            $options_array
158
-        );
159
-        if (isset($options_array['name'])) {
160
-            $this->_construct_finalize(null, $options_array['name']);
161
-        }
162
-    }
163
-
164
-
165
-    /**
166
-     * Finishes construction given the parent form section and this form section's name
167
-     *
168
-     * @param EE_Form_Section_Proper $parent_form_section
169
-     * @param string                 $name
170
-     * @throws EE_Error
171
-     */
172
-    public function _construct_finalize($parent_form_section, $name)
173
-    {
174
-        parent::_construct_finalize($parent_form_section, $name);
175
-        $this->_set_default_name_if_empty();
176
-        $this->_set_default_html_id_if_empty();
177
-        foreach ($this->_subsections as $subsection_name => $subsection) {
178
-            if ($subsection instanceof EE_Form_Section_Base) {
179
-                $subsection->_construct_finalize($this, $subsection_name);
180
-            } else {
181
-                throw new EE_Error(
182
-                    sprintf(
183
-                        esc_html__(
184
-                            'Subsection "%s" is not an instanceof EE_Form_Section_Base on form "%s". It is a "%s"',
185
-                            'event_espresso'
186
-                        ),
187
-                        $subsection_name,
188
-                        get_class($this),
189
-                        $subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
190
-                    )
191
-                );
192
-            }
193
-        }
194
-        /**
195
-         * Action performed just after form has been given a name (and HTML ID etc) and is fully constructed.
196
-         * If you have code that should modify the form and needs it and its subsections to have a name, HTML ID
197
-         * (or other attributes derived from the name like the HTML label id, etc), this is where it should be done.
198
-         * This might only happen just before displaying the form, or just before it receives form submission data.
199
-         * If you need to modify the form or its subsections before _construct_finalize is called on it (and we've
200
-         * ensured it has a name, HTML IDs, etc
201
-         *
202
-         * @param EE_Form_Section_Proper      $this
203
-         * @param EE_Form_Section_Proper|null $parent_form_section
204
-         * @param string                      $name
205
-         */
206
-        do_action(
207
-            'AHEE__EE_Form_Section_Proper___construct_finalize__end',
208
-            $this,
209
-            $parent_form_section,
210
-            $name
211
-        );
212
-    }
213
-
214
-
215
-    /**
216
-     * Gets the layout strategy for this form section
217
-     *
218
-     * @return EE_Form_Section_Layout_Base
219
-     */
220
-    public function get_layout_strategy()
221
-    {
222
-        return $this->_layout_strategy;
223
-    }
224
-
225
-
226
-    /**
227
-     * Gets the HTML for a single input for this form section according
228
-     * to the layout strategy
229
-     *
230
-     * @param EE_Form_Input_Base $input
231
-     * @return string
232
-     */
233
-    public function get_html_for_input($input)
234
-    {
235
-        return $this->_layout_strategy->layout_input($input);
236
-    }
237
-
238
-
239
-    /**
240
-     * was_submitted - checks if form inputs are present in request data
241
-     * Basically an alias for form_data_present_in() (which is used by both
242
-     * proper form sections and form inputs)
243
-     *
244
-     * @param null $form_data
245
-     * @return boolean
246
-     * @throws EE_Error
247
-     */
248
-    public function was_submitted($form_data = null)
249
-    {
250
-        return $this->form_data_present_in($form_data);
251
-    }
252
-
253
-    /**
254
-     * Gets the cached request data; but if there is none, or $req_data was set with
255
-     * something different, refresh the cache, and then return it
256
-     * @param null $req_data
257
-     * @return array
258
-     */
259
-    protected function getCachedRequest($req_data = null)
260
-    {
261
-        if ($this->cached_request_data === null
262
-            || (
263
-                $req_data !== null &&
264
-                $req_data !== $this->cached_request_data
265
-            )
266
-        ) {
267
-            $req_data = apply_filters(
268
-                'FHEE__EE_Form_Section_Proper__receive_form_submission__req_data',
269
-                $req_data,
270
-                $this
271
-            );
272
-            if ($req_data === null) {
273
-                $req_data = array_merge($_GET, $_POST);
274
-            }
275
-            $req_data = apply_filters(
276
-                'FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
277
-                $req_data,
278
-                $this
279
-            );
280
-            $this->cached_request_data = (array)$req_data;
281
-        }
282
-        return $this->cached_request_data;
283
-    }
284
-
285
-
286
-    /**
287
-     * After the form section is initially created, call this to sanitize the data in the submission
288
-     * which relates to this form section, validate it, and set it as properties on the form.
289
-     *
290
-     * @param array|null $req_data should usually be $_POST (the default).
291
-     *                             However, you CAN supply a different array.
292
-     *                             Consider using set_defaults() instead however.
293
-     *                             (If you rendered the form in the page using echo $form_x->get_html()
294
-     *                             the inputs will have the correct name in the request data for this function
295
-     *                             to find them and populate the form with them.
296
-     *                             If you have a flat form (with only input subsections),
297
-     *                             you can supply a flat array where keys
298
-     *                             are the form input names and values are their values)
299
-     * @param boolean    $validate whether or not to perform validation on this data. Default is,
300
-     *                             of course, to validate that data, and set errors on the invalid values.
301
-     *                             But if the data has already been validated
302
-     *                             (eg you validated the data then stored it in the DB)
303
-     *                             you may want to skip this step.
304
-     * @throws InvalidArgumentException
305
-     * @throws InvalidInterfaceException
306
-     * @throws InvalidDataTypeException
307
-     * @throws EE_Error
308
-     */
309
-    public function receive_form_submission($req_data = null, $validate = true)
310
-    {
311
-        $req_data = $this->getCachedRequest($req_data);
312
-        $this->_normalize($req_data);
313
-        if ($validate) {
314
-            $this->_validate();
315
-            //if it's invalid, we're going to want to re-display so remember what they submitted
316
-            if (! $this->is_valid()) {
317
-                $this->store_submitted_form_data_in_session();
318
-            }
319
-        }
320
-        if ($this->submission_error_message() === '' && ! $this->is_valid()) {
321
-            $this->set_submission_error_message();
322
-        }
323
-        do_action(
324
-            'AHEE__EE_Form_Section_Proper__receive_form_submission__end',
325
-            $req_data,
326
-            $this,
327
-            $validate
328
-        );
329
-    }
330
-
331
-
332
-    /**
333
-     * caches the originally submitted input values in the session
334
-     * so that they can be used to repopulate the form if it failed validation
335
-     *
336
-     * @return boolean whether or not the data was successfully stored in the session
337
-     * @throws InvalidArgumentException
338
-     * @throws InvalidInterfaceException
339
-     * @throws InvalidDataTypeException
340
-     * @throws EE_Error
341
-     */
342
-    protected function store_submitted_form_data_in_session()
343
-    {
344
-        return EE_Registry::instance()->SSN->set_session_data(
345
-            array(
346
-                EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY => $this->submitted_values(true),
347
-            )
348
-        );
349
-    }
350
-
351
-
352
-    /**
353
-     * retrieves the originally submitted input values in the session
354
-     * so that they can be used to repopulate the form if it failed validation
355
-     *
356
-     * @return array
357
-     * @throws InvalidArgumentException
358
-     * @throws InvalidInterfaceException
359
-     * @throws InvalidDataTypeException
360
-     */
361
-    protected function get_submitted_form_data_from_session()
362
-    {
363
-        $session = EE_Registry::instance()->SSN;
364
-        if ($session instanceof EE_Session) {
365
-            return $session->get_session_data(
366
-                EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY
367
-            );
368
-        }
369
-        return array();
370
-    }
371
-
372
-
373
-    /**
374
-     * flushed the originally submitted input values from the session
375
-     *
376
-     * @return boolean whether or not the data was successfully removed from the session
377
-     * @throws InvalidArgumentException
378
-     * @throws InvalidInterfaceException
379
-     * @throws InvalidDataTypeException
380
-     */
381
-    protected function flush_submitted_form_data_from_session()
382
-    {
383
-        return EE_Registry::instance()->SSN->reset_data(
384
-            array(EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY)
385
-        );
386
-    }
387
-
388
-
389
-    /**
390
-     * Populates this form and its subsections with data from the session.
391
-     * (Wrapper for EE_Form_Section_Proper::receive_form_submission, so it shows
392
-     * validation errors when displaying too)
393
-     * Returns true if the form was populated from the session, false otherwise
394
-     *
395
-     * @return boolean
396
-     * @throws InvalidArgumentException
397
-     * @throws InvalidInterfaceException
398
-     * @throws InvalidDataTypeException
399
-     * @throws EE_Error
400
-     */
401
-    public function populate_from_session()
402
-    {
403
-        $form_data_in_session = $this->get_submitted_form_data_from_session();
404
-        if (empty($form_data_in_session)) {
405
-            return false;
406
-        }
407
-        $this->receive_form_submission($form_data_in_session);
408
-        $this->flush_submitted_form_data_from_session();
409
-        if ($this->form_data_present_in($form_data_in_session)) {
410
-            return true;
411
-        }
412
-        return false;
413
-    }
414
-
415
-
416
-    /**
417
-     * Populates the default data for the form, given an array where keys are
418
-     * the input names, and values are their values (preferably normalized to be their
419
-     * proper PHP types, not all strings... although that should be ok too).
420
-     * Proper subsections are sub-arrays, the key being the subsection's name, and
421
-     * the value being an array formatted in teh same way
422
-     *
423
-     * @param array $default_data
424
-     * @throws EE_Error
425
-     */
426
-    public function populate_defaults($default_data)
427
-    {
428
-        foreach ($this->subsections(false) as $subsection_name => $subsection) {
429
-            if (isset($default_data[ $subsection_name ])) {
430
-                if ($subsection instanceof EE_Form_Input_Base) {
431
-                    $subsection->set_default($default_data[ $subsection_name ]);
432
-                } elseif ($subsection instanceof EE_Form_Section_Proper) {
433
-                    $subsection->populate_defaults($default_data[ $subsection_name ]);
434
-                }
435
-            }
436
-        }
437
-    }
438
-
439
-
440
-    /**
441
-     * returns true if subsection exists
442
-     *
443
-     * @param string $name
444
-     * @return boolean
445
-     */
446
-    public function subsection_exists($name)
447
-    {
448
-        return isset($this->_subsections[ $name ]) ? true : false;
449
-    }
450
-
451
-
452
-    /**
453
-     * Gets the subsection specified by its name
454
-     *
455
-     * @param string  $name
456
-     * @param boolean $require_construction_to_be_finalized most client code should leave this as TRUE
457
-     *                                                      so that the inputs will be properly configured.
458
-     *                                                      However, some client code may be ok
459
-     *                                                      with construction finalize being called later
460
-     *                                                      (realizing that the subsections' html names
461
-     *                                                      might not be set yet, etc.)
462
-     * @return EE_Form_Section_Base
463
-     * @throws EE_Error
464
-     */
465
-    public function get_subsection($name, $require_construction_to_be_finalized = true)
466
-    {
467
-        if ($require_construction_to_be_finalized) {
468
-            $this->ensure_construct_finalized_called();
469
-        }
470
-        return $this->subsection_exists($name) ? $this->_subsections[ $name ] : null;
471
-    }
472
-
473
-
474
-    /**
475
-     * Gets all the validatable subsections of this form section
476
-     *
477
-     * @return EE_Form_Section_Validatable[]
478
-     * @throws EE_Error
479
-     */
480
-    public function get_validatable_subsections()
481
-    {
482
-        $validatable_subsections = array();
483
-        foreach ($this->subsections() as $name => $obj) {
484
-            if ($obj instanceof EE_Form_Section_Validatable) {
485
-                $validatable_subsections[ $name ] = $obj;
486
-            }
487
-        }
488
-        return $validatable_subsections;
489
-    }
490
-
491
-
492
-    /**
493
-     * Gets an input by the given name. If not found, or if its not an EE_FOrm_Input_Base child,
494
-     * throw an EE_Error.
495
-     *
496
-     * @param string  $name
497
-     * @param boolean $require_construction_to_be_finalized most client code should
498
-     *                                                      leave this as TRUE so that the inputs will be properly
499
-     *                                                      configured. However, some client code may be ok with
500
-     *                                                      construction finalize being called later
501
-     *                                                      (realizing that the subsections' html names might not be
502
-     *                                                      set yet, etc.)
503
-     * @return EE_Form_Input_Base
504
-     * @throws EE_Error
505
-     */
506
-    public function get_input($name, $require_construction_to_be_finalized = true)
507
-    {
508
-        $subsection = $this->get_subsection(
509
-            $name,
510
-            $require_construction_to_be_finalized
511
-        );
512
-        if (! $subsection instanceof EE_Form_Input_Base) {
513
-            throw new EE_Error(
514
-                sprintf(
515
-                    esc_html__(
516
-                        "Subsection '%s' is not an instanceof EE_Form_Input_Base on form '%s'. It is a '%s'",
517
-                        'event_espresso'
518
-                    ),
519
-                    $name,
520
-                    get_class($this),
521
-                    $subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
522
-                )
523
-            );
524
-        }
525
-        return $subsection;
526
-    }
527
-
528
-
529
-    /**
530
-     * Like get_input(), gets the proper subsection of the form given the name,
531
-     * otherwise throws an EE_Error
532
-     *
533
-     * @param string  $name
534
-     * @param boolean $require_construction_to_be_finalized most client code should
535
-     *                                                      leave this as TRUE so that the inputs will be properly
536
-     *                                                      configured. However, some client code may be ok with
537
-     *                                                      construction finalize being called later
538
-     *                                                      (realizing that the subsections' html names might not be
539
-     *                                                      set yet, etc.)
540
-     * @return EE_Form_Section_Proper
541
-     * @throws EE_Error
542
-     */
543
-    public function get_proper_subsection($name, $require_construction_to_be_finalized = true)
544
-    {
545
-        $subsection = $this->get_subsection(
546
-            $name,
547
-            $require_construction_to_be_finalized
548
-        );
549
-        if (! $subsection instanceof EE_Form_Section_Proper) {
550
-            throw new EE_Error(
551
-                sprintf(
552
-                    esc_html__(
553
-                        "Subsection '%'s is not an instanceof EE_Form_Section_Proper on form '%s'",
554
-                        'event_espresso'
555
-                    ),
556
-                    $name,
557
-                    get_class($this)
558
-                )
559
-            );
560
-        }
561
-        return $subsection;
562
-    }
563
-
564
-
565
-    /**
566
-     * Gets the value of the specified input. Should be called after receive_form_submission()
567
-     * or populate_defaults() on the form, where the normalized value on the input is set.
568
-     *
569
-     * @param string $name
570
-     * @return mixed depending on the input's type and its normalization strategy
571
-     * @throws EE_Error
572
-     */
573
-    public function get_input_value($name)
574
-    {
575
-        $input = $this->get_input($name);
576
-        return $input->normalized_value();
577
-    }
578
-
579
-
580
-    /**
581
-     * Checks if this form section itself is valid, and then checks its subsections
582
-     *
583
-     * @throws EE_Error
584
-     * @return boolean
585
-     */
586
-    public function is_valid()
587
-    {
588
-        if($this->is_valid === null) {
589
-            if (! $this->has_received_submission()) {
590
-                throw new EE_Error(
591
-                    sprintf(
592
-                        esc_html__(
593
-                            'You cannot check if a form is valid before receiving the form submission using receive_form_submission',
594
-                            'event_espresso'
595
-                        )
596
-                    )
597
-                );
598
-            }
599
-            if (! parent::is_valid()) {
600
-                $this->is_valid = false;
601
-            } else {
602
-                // ok so no general errors to this entire form section.
603
-                // so let's check the subsections, but only set errors if that hasn't been done yet
604
-                $this->is_valid = true;
605
-                foreach ($this->get_validatable_subsections() as $subsection) {
606
-                    if (! $subsection->is_valid()) {
607
-                        $this->is_valid = false;
608
-                    }
609
-                }
610
-            }
611
-        }
612
-        return $this->is_valid;
613
-    }
614
-
615
-
616
-    /**
617
-     * gets the default name of this form section if none is specified
618
-     *
619
-     * @return void
620
-     */
621
-    protected function _set_default_name_if_empty()
622
-    {
623
-        if (! $this->_name) {
624
-            $classname    = get_class($this);
625
-            $default_name = str_replace('EE_', '', $classname);
626
-            $this->_name  = $default_name;
627
-        }
628
-    }
629
-
630
-
631
-    /**
632
-     * Returns the HTML for the form, except for the form opening and closing tags
633
-     * (as the form section doesn't know where you necessarily want to send the information to),
634
-     * and except for a submit button. Enqueues JS and CSS; if called early enough we will
635
-     * try to enqueue them in the header, otherwise they'll be enqueued in the footer.
636
-     * Not doing_it_wrong because theoretically this CAN be used properly,
637
-     * provided its used during "wp_enqueue_scripts", or it doesn't need to enqueue
638
-     * any CSS.
639
-     *
640
-     * @throws InvalidArgumentException
641
-     * @throws InvalidInterfaceException
642
-     * @throws InvalidDataTypeException
643
-     * @throws EE_Error
644
-     */
645
-    public function get_html_and_js()
646
-    {
647
-        $this->enqueue_js();
648
-        return $this->get_html();
649
-    }
650
-
651
-
652
-    /**
653
-     * returns HTML for displaying this form section. recursively calls display_section() on all subsections
654
-     *
655
-     * @param bool $display_previously_submitted_data
656
-     * @return string
657
-     * @throws InvalidArgumentException
658
-     * @throws InvalidInterfaceException
659
-     * @throws InvalidDataTypeException
660
-     * @throws EE_Error
661
-     * @throws EE_Error
662
-     * @throws EE_Error
663
-     */
664
-    public function get_html($display_previously_submitted_data = true)
665
-    {
666
-        $this->ensure_construct_finalized_called();
667
-        if ($display_previously_submitted_data) {
668
-            $this->populate_from_session();
669
-        }
670
-        return $this->_form_html_filter
671
-            ? $this->_form_html_filter->filterHtml($this->_layout_strategy->layout_form(), $this)
672
-            : $this->_layout_strategy->layout_form();
673
-    }
674
-
675
-
676
-    /**
677
-     * enqueues JS and CSS for the form.
678
-     * It is preferred to call this before wp_enqueue_scripts so the
679
-     * scripts and styles can be put in the header, but if called later
680
-     * they will be put in the footer (which is OK for JS, but in HTML4 CSS should
681
-     * only be in the header; but in HTML5 its ok in the body.
682
-     * See http://stackoverflow.com/questions/4957446/load-external-css-file-in-body-tag.
683
-     * So if your form enqueues CSS, it's preferred to call this before wp_enqueue_scripts.)
684
-     *
685
-     * @return void
686
-     * @throws EE_Error
687
-     */
688
-    public function enqueue_js()
689
-    {
690
-        $this->_enqueue_and_localize_form_js();
691
-        foreach ($this->subsections() as $subsection) {
692
-            $subsection->enqueue_js();
693
-        }
694
-    }
695
-
696
-
697
-    /**
698
-     * adds a filter so that jquery validate gets enqueued in EE_System::wp_enqueue_scripts().
699
-     * This must be done BEFORE wp_enqueue_scripts() gets called, which is on
700
-     * the wp_enqueue_scripts hook.
701
-     * However, registering the form js and localizing it can happen when we
702
-     * actually output the form (which is preferred, seeing how teh form's fields
703
-     * could change until it's actually outputted)
704
-     *
705
-     * @param boolean $init_form_validation_automatically whether or not we want the form validation
706
-     *                                                    to be triggered automatically or not
707
-     * @return void
708
-     */
709
-    public static function wp_enqueue_scripts($init_form_validation_automatically = true)
710
-    {
711
-        wp_register_script(
712
-            'ee_form_section_validation',
713
-            EE_GLOBAL_ASSETS_URL . 'scripts' . DS . 'form_section_validation.js',
714
-            array('jquery-validate', 'jquery-ui-datepicker', 'jquery-validate-extra-methods'),
715
-            EVENT_ESPRESSO_VERSION,
716
-            true
717
-        );
718
-        wp_localize_script(
719
-            'ee_form_section_validation',
720
-            'ee_form_section_validation_init',
721
-            array('init' => $init_form_validation_automatically ? '1' : '0')
722
-        );
723
-    }
724
-
725
-
726
-    /**
727
-     * gets the variables used by form_section_validation.js.
728
-     * This needs to be called AFTER we've called $this->_enqueue_jquery_validate_script,
729
-     * but before the wordpress hook wp_loaded
730
-     *
731
-     * @throws EE_Error
732
-     */
733
-    public function _enqueue_and_localize_form_js()
734
-    {
735
-        $this->ensure_construct_finalized_called();
736
-        //actually, we don't want to localize just yet. There may be other forms on the page.
737
-        //so we need to add our form section data to a static variable accessible by all form sections
738
-        //and localize it just before the footer
739
-        $this->localize_validation_rules();
740
-        add_action('wp_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'), 2);
741
-        add_action('admin_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'));
742
-    }
743
-
744
-
745
-    /**
746
-     * add our form section data to a static variable accessible by all form sections
747
-     *
748
-     * @param bool $return_for_subsection
749
-     * @return void
750
-     * @throws EE_Error
751
-     */
752
-    public function localize_validation_rules($return_for_subsection = false)
753
-    {
754
-        // we only want to localize vars ONCE for the entire form,
755
-        // so if the form section doesn't have a parent, then it must be the top dog
756
-        if ($return_for_subsection || ! $this->parent_section()) {
757
-            EE_Form_Section_Proper::$_js_localization['form_data'][ $this->html_id() ] = array(
758
-                'form_section_id'  => $this->html_id(true),
759
-                'validation_rules' => $this->get_jquery_validation_rules(),
760
-                'other_data'       => $this->get_other_js_data(),
761
-                'errors'           => $this->subsection_validation_errors_by_html_name(),
762
-            );
763
-            EE_Form_Section_Proper::$_scripts_localized                                = true;
764
-        }
765
-    }
766
-
767
-
768
-    /**
769
-     * Gets an array of extra data that will be useful for client-side javascript.
770
-     * This is primarily data added by inputs and forms in addition to any
771
-     * scripts they might enqueue
772
-     *
773
-     * @param array $form_other_js_data
774
-     * @return array
775
-     * @throws EE_Error
776
-     */
777
-    public function get_other_js_data($form_other_js_data = array())
778
-    {
779
-        foreach ($this->subsections() as $subsection) {
780
-            $form_other_js_data = $subsection->get_other_js_data($form_other_js_data);
781
-        }
782
-        return $form_other_js_data;
783
-    }
784
-
785
-
786
-    /**
787
-     * Gets a flat array of inputs for this form section and its subsections.
788
-     * Keys are their form names, and values are the inputs themselves
789
-     *
790
-     * @return EE_Form_Input_Base
791
-     * @throws EE_Error
792
-     */
793
-    public function inputs_in_subsections()
794
-    {
795
-        $inputs = array();
796
-        foreach ($this->subsections() as $subsection) {
797
-            if ($subsection instanceof EE_Form_Input_Base) {
798
-                $inputs[ $subsection->html_name() ] = $subsection;
799
-            } elseif ($subsection instanceof EE_Form_Section_Proper) {
800
-                $inputs += $subsection->inputs_in_subsections();
801
-            }
802
-        }
803
-        return $inputs;
804
-    }
805
-
806
-
807
-    /**
808
-     * Gets a flat array of all the validation errors.
809
-     * Keys are html names (because those should be unique)
810
-     * and values are a string of all their validation errors
811
-     *
812
-     * @return string[]
813
-     * @throws EE_Error
814
-     */
815
-    public function subsection_validation_errors_by_html_name()
816
-    {
817
-        $inputs = $this->inputs();
818
-        $errors = array();
819
-        foreach ($inputs as $form_input) {
820
-            if ($form_input instanceof EE_Form_Input_Base && $form_input->get_validation_errors()) {
821
-                $errors[ $form_input->html_name() ] = $form_input->get_validation_error_string();
822
-            }
823
-        }
824
-        return $errors;
825
-    }
826
-
827
-
828
-    /**
829
-     * passes all the form data required by the JS to the JS, and enqueues the few required JS files.
830
-     * Should be setup by each form during the _enqueues_and_localize_form_js
831
-     *
832
-     * @throws InvalidArgumentException
833
-     * @throws InvalidInterfaceException
834
-     * @throws InvalidDataTypeException
835
-     */
836
-    public static function localize_script_for_all_forms()
837
-    {
838
-        //allow inputs and stuff to hook in their JS and stuff here
839
-        do_action('AHEE__EE_Form_Section_Proper__localize_script_for_all_forms__begin');
840
-        EE_Form_Section_Proper::$_js_localization['localized_error_messages'] = EE_Form_Section_Proper::_get_localized_error_messages();
841
-        $email_validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
842
-            ? EE_Registry::instance()->CFG->registration->email_validation_level
843
-            : 'wp_default';
844
-        EE_Form_Section_Proper::$_js_localization['email_validation_level']   = $email_validation_level;
845
-        wp_enqueue_script('ee_form_section_validation');
846
-        wp_localize_script(
847
-            'ee_form_section_validation',
848
-            'ee_form_section_vars',
849
-            EE_Form_Section_Proper::$_js_localization
850
-        );
851
-    }
852
-
853
-
854
-    /**
855
-     * ensure_scripts_localized
856
-     *
857
-     * @throws EE_Error
858
-     */
859
-    public function ensure_scripts_localized()
860
-    {
861
-        if (! EE_Form_Section_Proper::$_scripts_localized) {
862
-            $this->_enqueue_and_localize_form_js();
863
-        }
864
-    }
865
-
866
-
867
-    /**
868
-     * Gets the hard-coded validation error messages to be used in the JS. The convention
869
-     * is that the key here should be the same as the custom validation rule put in the JS file
870
-     *
871
-     * @return array keys are custom validation rules, and values are internationalized strings
872
-     */
873
-    private static function _get_localized_error_messages()
874
-    {
875
-        return array(
876
-            'validUrl' => esc_html__('This is not a valid absolute URL. Eg, http://domain.com/monkey.jpg', 'event_espresso'),
877
-            'regex'    => esc_html__('Please check your input', 'event_espresso'),
878
-        );
879
-    }
880
-
881
-
882
-    /**
883
-     * @return array
884
-     */
885
-    public static function js_localization()
886
-    {
887
-        return self::$_js_localization;
888
-    }
889
-
890
-
891
-    /**
892
-     * @return void
893
-     */
894
-    public static function reset_js_localization()
895
-    {
896
-        self::$_js_localization = array();
897
-    }
898
-
899
-
900
-    /**
901
-     * Gets the JS to put inside the jquery validation rules for subsection of this form section.
902
-     * See parent function for more...
903
-     *
904
-     * @return array
905
-     * @throws EE_Error
906
-     */
907
-    public function get_jquery_validation_rules()
908
-    {
909
-        $jquery_validation_rules = array();
910
-        foreach ($this->get_validatable_subsections() as $subsection) {
911
-            $jquery_validation_rules = array_merge(
912
-                $jquery_validation_rules,
913
-                $subsection->get_jquery_validation_rules()
914
-            );
915
-        }
916
-        return $jquery_validation_rules;
917
-    }
918
-
919
-
920
-    /**
921
-     * Sanitizes all the data and sets the sanitized value of each field
922
-     *
923
-     * @param array $req_data like $_POST
924
-     * @return void
925
-     * @throws EE_Error
926
-     */
927
-    protected function _normalize($req_data)
928
-    {
929
-        $this->_received_submission = true;
930
-        $this->_validation_errors   = array();
931
-        foreach ($this->get_validatable_subsections() as $subsection) {
932
-            try {
933
-                $subsection->_normalize($req_data);
934
-            } catch (EE_Validation_Error $e) {
935
-                $subsection->add_validation_error($e);
936
-            }
937
-        }
938
-    }
939
-
940
-
941
-    /**
942
-     * Performs validation on this form section and its subsections.
943
-     * For each subsection,
944
-     * calls _validate_{subsection_name} on THIS form (if the function exists)
945
-     * and passes it the subsection, then calls _validate on that subsection.
946
-     * If you need to perform validation on the form as a whole (considering multiple)
947
-     * you would be best to override this _validate method,
948
-     * calling parent::_validate() first.
949
-     *
950
-     * @throws EE_Error
951
-     */
952
-    protected function _validate()
953
-    {
954
-        //reset the cache of whether this form is valid or not- we're re-validating it now
955
-        $this->is_valid = null;
956
-        foreach ($this->get_validatable_subsections() as $subsection_name => $subsection) {
957
-            if (method_exists($this, '_validate_' . $subsection_name)) {
958
-                call_user_func_array(array($this, '_validate_' . $subsection_name), array($subsection));
959
-            }
960
-            $subsection->_validate();
961
-        }
962
-    }
963
-
964
-
965
-    /**
966
-     * Gets all the validated inputs for the form section
967
-     *
968
-     * @return array
969
-     * @throws EE_Error
970
-     */
971
-    public function valid_data()
972
-    {
973
-        $inputs = array();
974
-        foreach ($this->subsections() as $subsection_name => $subsection) {
975
-            if ($subsection instanceof EE_Form_Section_Proper) {
976
-                $inputs[ $subsection_name ] = $subsection->valid_data();
977
-            } elseif ($subsection instanceof EE_Form_Input_Base) {
978
-                $inputs[ $subsection_name ] = $subsection->normalized_value();
979
-            }
980
-        }
981
-        return $inputs;
982
-    }
983
-
984
-
985
-    /**
986
-     * Gets all the inputs on this form section
987
-     *
988
-     * @return EE_Form_Input_Base[]
989
-     * @throws EE_Error
990
-     */
991
-    public function inputs()
992
-    {
993
-        $inputs = array();
994
-        foreach ($this->subsections() as $subsection_name => $subsection) {
995
-            if ($subsection instanceof EE_Form_Input_Base) {
996
-                $inputs[ $subsection_name ] = $subsection;
997
-            }
998
-        }
999
-        return $inputs;
1000
-    }
1001
-
1002
-
1003
-    /**
1004
-     * Gets all the subsections which are a proper form
1005
-     *
1006
-     * @return EE_Form_Section_Proper[]
1007
-     * @throws EE_Error
1008
-     */
1009
-    public function subforms()
1010
-    {
1011
-        $form_sections = array();
1012
-        foreach ($this->subsections() as $name => $obj) {
1013
-            if ($obj instanceof EE_Form_Section_Proper) {
1014
-                $form_sections[ $name ] = $obj;
1015
-            }
1016
-        }
1017
-        return $form_sections;
1018
-    }
1019
-
1020
-
1021
-    /**
1022
-     * Gets all the subsections (inputs, proper subsections, or html-only sections).
1023
-     * Consider using inputs() or subforms()
1024
-     * if you only want form inputs or proper form sections.
1025
-     *
1026
-     * @param boolean $require_construction_to_be_finalized most client code should
1027
-     *                                                      leave this as TRUE so that the inputs will be properly
1028
-     *                                                      configured. However, some client code may be ok with
1029
-     *                                                      construction finalize being called later
1030
-     *                                                      (realizing that the subsections' html names might not be
1031
-     *                                                      set yet, etc.)
1032
-     * @return EE_Form_Section_Proper[]
1033
-     * @throws EE_Error
1034
-     */
1035
-    public function subsections($require_construction_to_be_finalized = true)
1036
-    {
1037
-        if ($require_construction_to_be_finalized) {
1038
-            $this->ensure_construct_finalized_called();
1039
-        }
1040
-        return $this->_subsections;
1041
-    }
1042
-
1043
-
1044
-    /**
1045
-     * Returns whether this form has any subforms or inputs
1046
-     * @return bool
1047
-     */
1048
-    public function hasSubsections()
1049
-    {
1050
-        return ! empty($this->_subsections);
1051
-    }
1052
-
1053
-
1054
-    /**
1055
-     * Returns a simple array where keys are input names, and values are their normalized
1056
-     * values. (Similar to calling get_input_value on inputs)
1057
-     *
1058
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1059
-     *                                        or just this forms' direct children inputs
1060
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1061
-     *                                        or allow multidimensional array
1062
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array
1063
-     *                                        with array keys being input names
1064
-     *                                        (regardless of whether they are from a subsection or not),
1065
-     *                                        and if $flatten is FALSE it can be a multidimensional array
1066
-     *                                        where keys are always subsection names and values are either
1067
-     *                                        the input's normalized value, or an array like the top-level array
1068
-     * @throws EE_Error
1069
-     */
1070
-    public function input_values($include_subform_inputs = false, $flatten = false)
1071
-    {
1072
-        return $this->_input_values(false, $include_subform_inputs, $flatten);
1073
-    }
1074
-
1075
-
1076
-    /**
1077
-     * Similar to EE_Form_Section_Proper::input_values(), except this returns the 'display_value'
1078
-     * of each input. On some inputs (especially radio boxes or checkboxes), the value stored
1079
-     * is not necessarily the value we want to display to users. This creates an array
1080
-     * where keys are the input names, and values are their display values
1081
-     *
1082
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1083
-     *                                        or just this forms' direct children inputs
1084
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1085
-     *                                        or allow multidimensional array
1086
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array
1087
-     *                                        with array keys being input names
1088
-     *                                        (regardless of whether they are from a subsection or not),
1089
-     *                                        and if $flatten is FALSE it can be a multidimensional array
1090
-     *                                        where keys are always subsection names and values are either
1091
-     *                                        the input's normalized value, or an array like the top-level array
1092
-     * @throws EE_Error
1093
-     */
1094
-    public function input_pretty_values($include_subform_inputs = false, $flatten = false)
1095
-    {
1096
-        return $this->_input_values(true, $include_subform_inputs, $flatten);
1097
-    }
1098
-
1099
-
1100
-    /**
1101
-     * Gets the input values from the form
1102
-     *
1103
-     * @param boolean $pretty                 Whether to retrieve the pretty value,
1104
-     *                                        or just the normalized value
1105
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1106
-     *                                        or just this forms' direct children inputs
1107
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1108
-     *                                        or allow multidimensional array
1109
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array with array keys being
1110
-     *                                        input names (regardless of whether they are from a subsection or not),
1111
-     *                                        and if $flatten is FALSE it can be a multidimensional array
1112
-     *                                        where keys are always subsection names and values are either
1113
-     *                                        the input's normalized value, or an array like the top-level array
1114
-     * @throws EE_Error
1115
-     */
1116
-    public function _input_values($pretty = false, $include_subform_inputs = false, $flatten = false)
1117
-    {
1118
-        $input_values = array();
1119
-        foreach ($this->subsections() as $subsection_name => $subsection) {
1120
-            if ($subsection instanceof EE_Form_Input_Base) {
1121
-                $input_values[ $subsection_name ] = $pretty
1122
-                    ? $subsection->pretty_value()
1123
-                    : $subsection->normalized_value();
1124
-            } elseif ($subsection instanceof EE_Form_Section_Proper && $include_subform_inputs) {
1125
-                $subform_input_values = $subsection->_input_values(
1126
-                    $pretty,
1127
-                    $include_subform_inputs,
1128
-                    $flatten
1129
-                );
1130
-                if ($flatten) {
1131
-                    $input_values = array_merge($input_values, $subform_input_values);
1132
-                } else {
1133
-                    $input_values[ $subsection_name ] = $subform_input_values;
1134
-                }
1135
-            }
1136
-        }
1137
-        return $input_values;
1138
-    }
1139
-
1140
-
1141
-    /**
1142
-     * Gets the originally submitted input values from the form
1143
-     *
1144
-     * @param boolean $include_subforms  Whether to include inputs from subforms,
1145
-     *                                   or just this forms' direct children inputs
1146
-     * @return array                     if $flatten is TRUE it will always be a 1-dimensional array
1147
-     *                                   with array keys being input names
1148
-     *                                   (regardless of whether they are from a subsection or not),
1149
-     *                                   and if $flatten is FALSE it can be a multidimensional array
1150
-     *                                   where keys are always subsection names and values are either
1151
-     *                                   the input's normalized value, or an array like the top-level array
1152
-     * @throws EE_Error
1153
-     */
1154
-    public function submitted_values($include_subforms = false)
1155
-    {
1156
-        $submitted_values = array();
1157
-        foreach ($this->subsections() as $subsection) {
1158
-            if ($subsection instanceof EE_Form_Input_Base) {
1159
-                // is this input part of an array of inputs?
1160
-                if (strpos($subsection->html_name(), '[') !== false) {
1161
-                    $full_input_name  = EEH_Array::convert_array_values_to_keys(
1162
-                        explode(
1163
-                            '[',
1164
-                            str_replace(']', '', $subsection->html_name())
1165
-                        ),
1166
-                        $subsection->raw_value()
1167
-                    );
1168
-                    $submitted_values = array_replace_recursive($submitted_values, $full_input_name);
1169
-                } else {
1170
-                    $submitted_values[ $subsection->html_name() ] = $subsection->raw_value();
1171
-                }
1172
-            } elseif ($subsection instanceof EE_Form_Section_Proper && $include_subforms) {
1173
-                $subform_input_values = $subsection->submitted_values($include_subforms);
1174
-                $submitted_values     = array_replace_recursive($submitted_values, $subform_input_values);
1175
-            }
1176
-        }
1177
-        return $submitted_values;
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * Indicates whether or not this form has received a submission yet
1183
-     * (ie, had receive_form_submission called on it yet)
1184
-     *
1185
-     * @return boolean
1186
-     * @throws EE_Error
1187
-     */
1188
-    public function has_received_submission()
1189
-    {
1190
-        $this->ensure_construct_finalized_called();
1191
-        return $this->_received_submission;
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * Equivalent to passing 'exclude' in the constructor's options array.
1197
-     * Removes the listed inputs from the form
1198
-     *
1199
-     * @param array $inputs_to_exclude values are the input names
1200
-     * @return void
1201
-     */
1202
-    public function exclude(array $inputs_to_exclude = array())
1203
-    {
1204
-        foreach ($inputs_to_exclude as $input_to_exclude_name) {
1205
-            unset($this->_subsections[ $input_to_exclude_name ]);
1206
-        }
1207
-    }
1208
-
1209
-
1210
-    /**
1211
-     * Changes these inputs' display strategy to be EE_Hidden_Display_Strategy.
1212
-     * @param array $inputs_to_hide
1213
-     * @throws EE_Error
1214
-     */
1215
-    public function hide(array $inputs_to_hide = array())
1216
-    {
1217
-        foreach ($inputs_to_hide as $input_to_hide) {
1218
-            $input = $this->get_input($input_to_hide);
1219
-            $input->set_display_strategy(new EE_Hidden_Display_Strategy());
1220
-        }
1221
-    }
1222
-
1223
-
1224
-    /**
1225
-     * add_subsections
1226
-     * Adds the listed subsections to the form section.
1227
-     * If $subsection_name_to_target is provided,
1228
-     * then new subsections are added before or after that subsection,
1229
-     * otherwise to the start or end of the entire subsections array.
1230
-     *
1231
-     * @param EE_Form_Section_Base[] $new_subsections           array of new form subsections
1232
-     *                                                          where keys are their names
1233
-     * @param string                 $subsection_name_to_target an existing for section that $new_subsections
1234
-     *                                                          should be added before or after
1235
-     *                                                          IF $subsection_name_to_target is null,
1236
-     *                                                          then $new_subsections will be added to
1237
-     *                                                          the beginning or end of the entire subsections array
1238
-     * @param boolean                $add_before                whether to add $new_subsections, before or after
1239
-     *                                                          $subsection_name_to_target,
1240
-     *                                                          or if $subsection_name_to_target is null,
1241
-     *                                                          before or after entire subsections array
1242
-     * @return void
1243
-     * @throws EE_Error
1244
-     */
1245
-    public function add_subsections($new_subsections, $subsection_name_to_target = null, $add_before = true)
1246
-    {
1247
-        foreach ($new_subsections as $subsection_name => $subsection) {
1248
-            if (! $subsection instanceof EE_Form_Section_Base) {
1249
-                EE_Error::add_error(
1250
-                    sprintf(
1251
-                        esc_html__(
1252
-                            "Trying to add a %s as a subsection (it was named '%s') to the form section '%s'. It was removed.",
1253
-                            'event_espresso'
1254
-                        ),
1255
-                        get_class($subsection),
1256
-                        $subsection_name,
1257
-                        $this->name()
1258
-                    )
1259
-                );
1260
-                unset($new_subsections[ $subsection_name ]);
1261
-            }
1262
-        }
1263
-        $this->_subsections = EEH_Array::insert_into_array(
1264
-            $this->_subsections,
1265
-            $new_subsections,
1266
-            $subsection_name_to_target,
1267
-            $add_before
1268
-        );
1269
-        if ($this->_construction_finalized) {
1270
-            foreach ($this->_subsections as $name => $subsection) {
1271
-                $subsection->_construct_finalize($this, $name);
1272
-            }
1273
-        }
1274
-    }
1275
-
1276
-
1277
-    /**
1278
-     * @param string $subsection_name
1279
-     * @param bool   $recursive
1280
-     * @return bool
1281
-     */
1282
-    public function has_subsection($subsection_name, $recursive = false)
1283
-    {
1284
-        foreach ($this->_subsections as $name => $subsection) {if(
1285
-                $name === $subsection_name
1286
-                || (
1287
-                    $recursive
1288
-                    && $subsection instanceof EE_Form_Section_Proper
1289
-                    && $subsection->has_subsection($subsection_name, $recursive)
1290
-                )
1291
-            ) {
1292
-                return true;
1293
-            }
1294
-        }
1295
-        return false;
1296
-    }
1297
-
1298
-
1299
-
1300
-    /**
1301
-     * Just gets all validatable subsections to clean their sensitive data
1302
-     *
1303
-     * @throws EE_Error
1304
-     */
1305
-    public function clean_sensitive_data()
1306
-    {
1307
-        foreach ($this->get_validatable_subsections() as $subsection) {
1308
-            $subsection->clean_sensitive_data();
1309
-        }
1310
-    }
1311
-
1312
-
1313
-    /**
1314
-     * Sets the submission error message (aka validation error message for this form section and all sub-sections)
1315
-     * @param string                           $form_submission_error_message
1316
-     * @param EE_Form_Section_Validatable $form_section unused
1317
-     * @throws EE_Error
1318
-     */
1319
-    public function set_submission_error_message(
1320
-        $form_submission_error_message = ''
1321
-    ) {
1322
-        $this->_form_submission_error_message = ! empty($form_submission_error_message)
1323
-            ? $form_submission_error_message
1324
-            : $this->getAllValidationErrorsString();
1325
-    }
1326
-
1327
-
1328
-    /**
1329
-     * Returns the cached error message. A default value is set for this during _validate(),
1330
-     * (called during receive_form_submission) but it can be explicitly set using
1331
-     * set_submission_error_message
1332
-     *
1333
-     * @return string
1334
-     */
1335
-    public function submission_error_message()
1336
-    {
1337
-        return $this->_form_submission_error_message;
1338
-    }
1339
-
1340
-
1341
-    /**
1342
-     * Sets a message to display if the data submitted to the form was valid.
1343
-     * @param string $form_submission_success_message
1344
-     */
1345
-    public function set_submission_success_message($form_submission_success_message = '')
1346
-    {
1347
-        $this->_form_submission_success_message = ! empty($form_submission_success_message)
1348
-            ? $form_submission_success_message
1349
-            : esc_html__('Form submitted successfully', 'event_espresso');
1350
-    }
1351
-
1352
-
1353
-    /**
1354
-     * Gets a message appropriate for display when the form is correctly submitted
1355
-     * @return string
1356
-     */
1357
-    public function submission_success_message()
1358
-    {
1359
-        return $this->_form_submission_success_message;
1360
-    }
1361
-
1362
-
1363
-    /**
1364
-     * Returns the prefix that should be used on child of this form section for
1365
-     * their html names. If this form section itself has a parent, prepends ITS
1366
-     * prefix onto this form section's prefix. Used primarily by
1367
-     * EE_Form_Input_Base::_set_default_html_name_if_empty
1368
-     *
1369
-     * @return string
1370
-     * @throws EE_Error
1371
-     */
1372
-    public function html_name_prefix()
1373
-    {
1374
-        if ($this->parent_section() instanceof EE_Form_Section_Proper) {
1375
-            return $this->parent_section()->html_name_prefix() . '[' . $this->name() . ']';
1376
-        }
1377
-        return $this->name();
1378
-    }
1379
-
1380
-
1381
-    /**
1382
-     * Gets the name, but first checks _construct_finalize has been called. If not,
1383
-     * calls it (assumes there is no parent and that we want the name to be whatever
1384
-     * was set, which is probably nothing, or the classname)
1385
-     *
1386
-     * @return string
1387
-     * @throws EE_Error
1388
-     */
1389
-    public function name()
1390
-    {
1391
-        $this->ensure_construct_finalized_called();
1392
-        return parent::name();
1393
-    }
1394
-
1395
-
1396
-    /**
1397
-     * @return EE_Form_Section_Proper
1398
-     * @throws EE_Error
1399
-     */
1400
-    public function parent_section()
1401
-    {
1402
-        $this->ensure_construct_finalized_called();
1403
-        return parent::parent_section();
1404
-    }
1405
-
1406
-
1407
-    /**
1408
-     * make sure construction finalized was called, otherwise children might not be ready
1409
-     *
1410
-     * @return void
1411
-     * @throws EE_Error
1412
-     */
1413
-    public function ensure_construct_finalized_called()
1414
-    {
1415
-        if (! $this->_construction_finalized) {
1416
-            $this->_construct_finalize($this->_parent_section, $this->_name);
1417
-        }
1418
-    }
1419
-
1420
-
1421
-    /**
1422
-     * Checks if any of this form section's inputs, or any of its children's inputs,
1423
-     * are in teh form data. If any are found, returns true. Else false
1424
-     *
1425
-     * @param array $req_data
1426
-     * @return boolean
1427
-     * @throws EE_Error
1428
-     */
1429
-    public function form_data_present_in($req_data = null)
1430
-    {
1431
-        $req_data = $this->getCachedRequest($req_data);
1432
-        foreach ($this->subsections() as $subsection) {
1433
-            if ($subsection instanceof EE_Form_Input_Base) {
1434
-                if ($subsection->form_data_present_in($req_data)) {
1435
-                    return true;
1436
-                }
1437
-            } elseif ($subsection instanceof EE_Form_Section_Proper) {
1438
-                if ($subsection->form_data_present_in($req_data)) {
1439
-                    return true;
1440
-                }
1441
-            }
1442
-        }
1443
-        return false;
1444
-    }
1445
-
1446
-
1447
-    /**
1448
-     * Gets validation errors for this form section and subsections
1449
-     * Similar to EE_Form_Section_Validatable::get_validation_errors() except this
1450
-     * gets the validation errors for ALL subsection
1451
-     *
1452
-     * @return EE_Validation_Error[]
1453
-     * @throws EE_Error
1454
-     */
1455
-    public function get_validation_errors_accumulated()
1456
-    {
1457
-        $validation_errors = $this->get_validation_errors();
1458
-        foreach ($this->get_validatable_subsections() as $subsection) {
1459
-            if ($subsection instanceof EE_Form_Section_Proper) {
1460
-                $validation_errors_on_this_subsection = $subsection->get_validation_errors_accumulated();
1461
-            } else {
1462
-                $validation_errors_on_this_subsection = $subsection->get_validation_errors();
1463
-            }
1464
-            if ($validation_errors_on_this_subsection) {
1465
-                $validation_errors = array_merge($validation_errors, $validation_errors_on_this_subsection);
1466
-            }
1467
-        }
1468
-        return $validation_errors;
1469
-    }
1470
-
1471
-    /**
1472
-     * Fetch validation errors from children and grandchildren and puts them in a single string.
1473
-     * This traverses the form section tree to generate this, but you probably want to instead use
1474
-     * get_form_submission_error_message() which is usually this message cached (or a custom validation error message)
1475
-     *
1476
-     * @return string
1477
-     * @since $VID:$
1478
-     */
1479
-    protected function getAllValidationErrorsString()
1480
-    {
1481
-        $submission_error_messages = array();
1482
-        // bad, bad, bad registrant
1483
-        foreach ($this->get_validation_errors_accumulated() as $validation_error) {
1484
-            if ($validation_error instanceof EE_Validation_Error) {
1485
-                $form_section = $validation_error->get_form_section();
1486
-                if ($form_section instanceof EE_Form_Input_Base) {
1487
-                   $label = $validation_error->get_form_section()->html_label_text();
1488
-                } elseif($form_section instanceof EE_Form_Section_Validatable) {
1489
-                    $label = $validation_error->get_form_section()->name();
1490
-                } else {
1491
-                    $label = esc_html__('Unknown', 'event_espresso');
1492
-                }
1493
-                $submission_error_messages[] = sprintf(
1494
-                    __('%s : %s', 'event_espresso'),
1495
-                    $label,
1496
-                    $validation_error->getMessage()
1497
-                );
1498
-            }
1499
-        }
1500
-        return implode('<br', $submission_error_messages);
1501
-    }
1502
-
1503
-
1504
-    /**
1505
-     * This isn't just the name of an input, it's a path pointing to an input. The
1506
-     * path is similar to a folder path: slash (/) means to descend into a subsection,
1507
-     * dot-dot-slash (../) means to ascend into the parent section.
1508
-     * After a series of slashes and dot-dot-slashes, there should be the name of an input,
1509
-     * which will be returned.
1510
-     * Eg, if you want the related input to be conditional on a sibling input name 'foobar'
1511
-     * just use 'foobar'. If you want it to be conditional on an aunt/uncle input name
1512
-     * 'baz', use '../baz'. If you want it to be conditional on a cousin input,
1513
-     * the child of 'baz_section' named 'baz_child', use '../baz_section/baz_child'.
1514
-     * Etc
1515
-     *
1516
-     * @param string|false $form_section_path we accept false also because substr( '../', '../' ) = false
1517
-     * @return EE_Form_Section_Base
1518
-     * @throws EE_Error
1519
-     */
1520
-    public function find_section_from_path($form_section_path)
1521
-    {
1522
-        //check if we can find the input from purely going straight up the tree
1523
-        $input = parent::find_section_from_path($form_section_path);
1524
-        if ($input instanceof EE_Form_Section_Base) {
1525
-            return $input;
1526
-        }
1527
-        $next_slash_pos = strpos($form_section_path, '/');
1528
-        if ($next_slash_pos !== false) {
1529
-            $child_section_name = substr($form_section_path, 0, $next_slash_pos);
1530
-            $subpath            = substr($form_section_path, $next_slash_pos + 1);
1531
-        } else {
1532
-            $child_section_name = $form_section_path;
1533
-            $subpath            = '';
1534
-        }
1535
-        $child_section = $this->get_subsection($child_section_name);
1536
-        if ($child_section instanceof EE_Form_Section_Base) {
1537
-            return $child_section->find_section_from_path($subpath);
1538
-        }
1539
-        return null;
1540
-    }
17
+	const SUBMITTED_FORM_DATA_SSN_KEY = 'submitted_form_data';
18
+
19
+	/**
20
+	 * Subsections
21
+	 *
22
+	 * @var EE_Form_Section_Validatable[]
23
+	 */
24
+	protected $_subsections = array();
25
+
26
+	/**
27
+	 * Strategy for laying out the form
28
+	 *
29
+	 * @var EE_Form_Section_Layout_Base
30
+	 */
31
+	protected $_layout_strategy;
32
+
33
+	/**
34
+	 * Whether or not this form has received and validated a form submission yet
35
+	 *
36
+	 * @var boolean
37
+	 */
38
+	protected $_received_submission = false;
39
+
40
+	/**
41
+	 * message displayed to users upon successful form submission
42
+	 *
43
+	 * @var string
44
+	 */
45
+	protected $_form_submission_success_message = '';
46
+
47
+	/**
48
+	 * message displayed to users upon unsuccessful form submission
49
+	 *
50
+	 * @var string
51
+	 */
52
+	protected $_form_submission_error_message = '';
53
+
54
+	/**
55
+	 * @var array like $_REQUEST
56
+	 */
57
+	protected $cached_request_data;
58
+
59
+	/**
60
+	 * Stores whether this form (and its sub-sections) were found to be valid or not.
61
+	 * Starts off as null, but once the form is validated, it set to either true or false
62
+	 * @var boolean|null
63
+	 */
64
+	protected $is_valid;
65
+
66
+	/**
67
+	 * Stores all the data that will localized for form validation
68
+	 *
69
+	 * @var array
70
+	 */
71
+	static protected $_js_localization = array();
72
+
73
+	/**
74
+	 * whether or not the form's localized validation JS vars have been set
75
+	 *
76
+	 * @type boolean
77
+	 */
78
+	static protected $_scripts_localized = false;
79
+
80
+
81
+	/**
82
+	 * when constructing a proper form section, calls _construct_finalize on children
83
+	 * so that they know who their parent is, and what name they've been given.
84
+	 *
85
+	 * @param array[] $options_array   {
86
+	 * @type          $subsections     EE_Form_Section_Validatable[] where keys are the section's name
87
+	 * @type          $include         string[] numerically-indexed where values are section names to be included,
88
+	 *                                 and in that order. This is handy if you want
89
+	 *                                 the subsections to be ordered differently than the default, and if you override
90
+	 *                                 which fields are shown
91
+	 * @type          $exclude         string[] values are subsections to be excluded. This is handy if you want
92
+	 *                                 to remove certain default subsections (note: if you specify BOTH 'include' AND
93
+	 *                                 'exclude', the inclusions will be applied first, and the exclusions will exclude
94
+	 *                                 items from that list of inclusions)
95
+	 * @type          $layout_strategy EE_Form_Section_Layout_Base strategy for laying out the form
96
+	 *                                 } @see EE_Form_Section_Validatable::__construct()
97
+	 * @throws EE_Error
98
+	 */
99
+	public function __construct($options_array = array())
100
+	{
101
+		$options_array = (array) apply_filters(
102
+			'FHEE__EE_Form_Section_Proper___construct__options_array',
103
+			$options_array,
104
+			$this
105
+		);
106
+		//call parent first, as it may be setting the name
107
+		parent::__construct($options_array);
108
+		//if they've included subsections in the constructor, add them now
109
+		if (isset($options_array['include'])) {
110
+			//we are going to make sure we ONLY have those subsections to include
111
+			//AND we are going to make sure they're in that specified order
112
+			$reordered_subsections = array();
113
+			foreach ($options_array['include'] as $input_name) {
114
+				if (isset($this->_subsections[ $input_name ])) {
115
+					$reordered_subsections[ $input_name ] = $this->_subsections[ $input_name ];
116
+				}
117
+			}
118
+			$this->_subsections = $reordered_subsections;
119
+		}
120
+		if (isset($options_array['exclude'])) {
121
+			$exclude            = $options_array['exclude'];
122
+			$this->_subsections = array_diff_key($this->_subsections, array_flip($exclude));
123
+		}
124
+		if (isset($options_array['layout_strategy'])) {
125
+			$this->_layout_strategy = $options_array['layout_strategy'];
126
+		}
127
+		if (! $this->_layout_strategy) {
128
+			$this->_layout_strategy = is_admin() ? new EE_Admin_Two_Column_Layout() : new EE_Two_Column_Layout();
129
+		}
130
+		$this->_layout_strategy->_construct_finalize($this);
131
+		//ok so we are definitely going to want the forms JS,
132
+		//so enqueue it or remember to enqueue it during wp_enqueue_scripts
133
+		if (did_action('wp_enqueue_scripts') || did_action('admin_enqueue_scripts')) {
134
+			//ok so they've constructed this object after when they should have.
135
+			//just enqueue the generic form scripts and initialize the form immediately in the JS
136
+			EE_Form_Section_Proper::wp_enqueue_scripts(true);
137
+		} else {
138
+			add_action('wp_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
139
+			add_action('admin_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
140
+		}
141
+		add_action('wp_footer', array($this, 'ensure_scripts_localized'), 1);
142
+		/**
143
+		 * Gives other plugins a chance to hook in before construct finalize is called.
144
+		 * The form probably doesn't yet have a parent form section.
145
+		 * Since 4.9.32, when this action was introduced, this is the best place to add a subsection onto a form,
146
+		 * assuming you don't care what the form section's name, HTML ID, or HTML name etc are.
147
+		 * Also see AHEE__EE_Form_Section_Proper___construct_finalize__end
148
+		 *
149
+		 * @since 4.9.32
150
+		 * @param EE_Form_Section_Proper $this          before __construct is done, but all of its logic,
151
+		 *                                              except maybe calling _construct_finalize has been done
152
+		 * @param array                  $options_array options passed into the constructor
153
+		 */
154
+		do_action(
155
+			'AHEE__EE_Form_Input_Base___construct__before_construct_finalize_called',
156
+			$this,
157
+			$options_array
158
+		);
159
+		if (isset($options_array['name'])) {
160
+			$this->_construct_finalize(null, $options_array['name']);
161
+		}
162
+	}
163
+
164
+
165
+	/**
166
+	 * Finishes construction given the parent form section and this form section's name
167
+	 *
168
+	 * @param EE_Form_Section_Proper $parent_form_section
169
+	 * @param string                 $name
170
+	 * @throws EE_Error
171
+	 */
172
+	public function _construct_finalize($parent_form_section, $name)
173
+	{
174
+		parent::_construct_finalize($parent_form_section, $name);
175
+		$this->_set_default_name_if_empty();
176
+		$this->_set_default_html_id_if_empty();
177
+		foreach ($this->_subsections as $subsection_name => $subsection) {
178
+			if ($subsection instanceof EE_Form_Section_Base) {
179
+				$subsection->_construct_finalize($this, $subsection_name);
180
+			} else {
181
+				throw new EE_Error(
182
+					sprintf(
183
+						esc_html__(
184
+							'Subsection "%s" is not an instanceof EE_Form_Section_Base on form "%s". It is a "%s"',
185
+							'event_espresso'
186
+						),
187
+						$subsection_name,
188
+						get_class($this),
189
+						$subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
190
+					)
191
+				);
192
+			}
193
+		}
194
+		/**
195
+		 * Action performed just after form has been given a name (and HTML ID etc) and is fully constructed.
196
+		 * If you have code that should modify the form and needs it and its subsections to have a name, HTML ID
197
+		 * (or other attributes derived from the name like the HTML label id, etc), this is where it should be done.
198
+		 * This might only happen just before displaying the form, or just before it receives form submission data.
199
+		 * If you need to modify the form or its subsections before _construct_finalize is called on it (and we've
200
+		 * ensured it has a name, HTML IDs, etc
201
+		 *
202
+		 * @param EE_Form_Section_Proper      $this
203
+		 * @param EE_Form_Section_Proper|null $parent_form_section
204
+		 * @param string                      $name
205
+		 */
206
+		do_action(
207
+			'AHEE__EE_Form_Section_Proper___construct_finalize__end',
208
+			$this,
209
+			$parent_form_section,
210
+			$name
211
+		);
212
+	}
213
+
214
+
215
+	/**
216
+	 * Gets the layout strategy for this form section
217
+	 *
218
+	 * @return EE_Form_Section_Layout_Base
219
+	 */
220
+	public function get_layout_strategy()
221
+	{
222
+		return $this->_layout_strategy;
223
+	}
224
+
225
+
226
+	/**
227
+	 * Gets the HTML for a single input for this form section according
228
+	 * to the layout strategy
229
+	 *
230
+	 * @param EE_Form_Input_Base $input
231
+	 * @return string
232
+	 */
233
+	public function get_html_for_input($input)
234
+	{
235
+		return $this->_layout_strategy->layout_input($input);
236
+	}
237
+
238
+
239
+	/**
240
+	 * was_submitted - checks if form inputs are present in request data
241
+	 * Basically an alias for form_data_present_in() (which is used by both
242
+	 * proper form sections and form inputs)
243
+	 *
244
+	 * @param null $form_data
245
+	 * @return boolean
246
+	 * @throws EE_Error
247
+	 */
248
+	public function was_submitted($form_data = null)
249
+	{
250
+		return $this->form_data_present_in($form_data);
251
+	}
252
+
253
+	/**
254
+	 * Gets the cached request data; but if there is none, or $req_data was set with
255
+	 * something different, refresh the cache, and then return it
256
+	 * @param null $req_data
257
+	 * @return array
258
+	 */
259
+	protected function getCachedRequest($req_data = null)
260
+	{
261
+		if ($this->cached_request_data === null
262
+			|| (
263
+				$req_data !== null &&
264
+				$req_data !== $this->cached_request_data
265
+			)
266
+		) {
267
+			$req_data = apply_filters(
268
+				'FHEE__EE_Form_Section_Proper__receive_form_submission__req_data',
269
+				$req_data,
270
+				$this
271
+			);
272
+			if ($req_data === null) {
273
+				$req_data = array_merge($_GET, $_POST);
274
+			}
275
+			$req_data = apply_filters(
276
+				'FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
277
+				$req_data,
278
+				$this
279
+			);
280
+			$this->cached_request_data = (array)$req_data;
281
+		}
282
+		return $this->cached_request_data;
283
+	}
284
+
285
+
286
+	/**
287
+	 * After the form section is initially created, call this to sanitize the data in the submission
288
+	 * which relates to this form section, validate it, and set it as properties on the form.
289
+	 *
290
+	 * @param array|null $req_data should usually be $_POST (the default).
291
+	 *                             However, you CAN supply a different array.
292
+	 *                             Consider using set_defaults() instead however.
293
+	 *                             (If you rendered the form in the page using echo $form_x->get_html()
294
+	 *                             the inputs will have the correct name in the request data for this function
295
+	 *                             to find them and populate the form with them.
296
+	 *                             If you have a flat form (with only input subsections),
297
+	 *                             you can supply a flat array where keys
298
+	 *                             are the form input names and values are their values)
299
+	 * @param boolean    $validate whether or not to perform validation on this data. Default is,
300
+	 *                             of course, to validate that data, and set errors on the invalid values.
301
+	 *                             But if the data has already been validated
302
+	 *                             (eg you validated the data then stored it in the DB)
303
+	 *                             you may want to skip this step.
304
+	 * @throws InvalidArgumentException
305
+	 * @throws InvalidInterfaceException
306
+	 * @throws InvalidDataTypeException
307
+	 * @throws EE_Error
308
+	 */
309
+	public function receive_form_submission($req_data = null, $validate = true)
310
+	{
311
+		$req_data = $this->getCachedRequest($req_data);
312
+		$this->_normalize($req_data);
313
+		if ($validate) {
314
+			$this->_validate();
315
+			//if it's invalid, we're going to want to re-display so remember what they submitted
316
+			if (! $this->is_valid()) {
317
+				$this->store_submitted_form_data_in_session();
318
+			}
319
+		}
320
+		if ($this->submission_error_message() === '' && ! $this->is_valid()) {
321
+			$this->set_submission_error_message();
322
+		}
323
+		do_action(
324
+			'AHEE__EE_Form_Section_Proper__receive_form_submission__end',
325
+			$req_data,
326
+			$this,
327
+			$validate
328
+		);
329
+	}
330
+
331
+
332
+	/**
333
+	 * caches the originally submitted input values in the session
334
+	 * so that they can be used to repopulate the form if it failed validation
335
+	 *
336
+	 * @return boolean whether or not the data was successfully stored in the session
337
+	 * @throws InvalidArgumentException
338
+	 * @throws InvalidInterfaceException
339
+	 * @throws InvalidDataTypeException
340
+	 * @throws EE_Error
341
+	 */
342
+	protected function store_submitted_form_data_in_session()
343
+	{
344
+		return EE_Registry::instance()->SSN->set_session_data(
345
+			array(
346
+				EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY => $this->submitted_values(true),
347
+			)
348
+		);
349
+	}
350
+
351
+
352
+	/**
353
+	 * retrieves the originally submitted input values in the session
354
+	 * so that they can be used to repopulate the form if it failed validation
355
+	 *
356
+	 * @return array
357
+	 * @throws InvalidArgumentException
358
+	 * @throws InvalidInterfaceException
359
+	 * @throws InvalidDataTypeException
360
+	 */
361
+	protected function get_submitted_form_data_from_session()
362
+	{
363
+		$session = EE_Registry::instance()->SSN;
364
+		if ($session instanceof EE_Session) {
365
+			return $session->get_session_data(
366
+				EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY
367
+			);
368
+		}
369
+		return array();
370
+	}
371
+
372
+
373
+	/**
374
+	 * flushed the originally submitted input values from the session
375
+	 *
376
+	 * @return boolean whether or not the data was successfully removed from the session
377
+	 * @throws InvalidArgumentException
378
+	 * @throws InvalidInterfaceException
379
+	 * @throws InvalidDataTypeException
380
+	 */
381
+	protected function flush_submitted_form_data_from_session()
382
+	{
383
+		return EE_Registry::instance()->SSN->reset_data(
384
+			array(EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY)
385
+		);
386
+	}
387
+
388
+
389
+	/**
390
+	 * Populates this form and its subsections with data from the session.
391
+	 * (Wrapper for EE_Form_Section_Proper::receive_form_submission, so it shows
392
+	 * validation errors when displaying too)
393
+	 * Returns true if the form was populated from the session, false otherwise
394
+	 *
395
+	 * @return boolean
396
+	 * @throws InvalidArgumentException
397
+	 * @throws InvalidInterfaceException
398
+	 * @throws InvalidDataTypeException
399
+	 * @throws EE_Error
400
+	 */
401
+	public function populate_from_session()
402
+	{
403
+		$form_data_in_session = $this->get_submitted_form_data_from_session();
404
+		if (empty($form_data_in_session)) {
405
+			return false;
406
+		}
407
+		$this->receive_form_submission($form_data_in_session);
408
+		$this->flush_submitted_form_data_from_session();
409
+		if ($this->form_data_present_in($form_data_in_session)) {
410
+			return true;
411
+		}
412
+		return false;
413
+	}
414
+
415
+
416
+	/**
417
+	 * Populates the default data for the form, given an array where keys are
418
+	 * the input names, and values are their values (preferably normalized to be their
419
+	 * proper PHP types, not all strings... although that should be ok too).
420
+	 * Proper subsections are sub-arrays, the key being the subsection's name, and
421
+	 * the value being an array formatted in teh same way
422
+	 *
423
+	 * @param array $default_data
424
+	 * @throws EE_Error
425
+	 */
426
+	public function populate_defaults($default_data)
427
+	{
428
+		foreach ($this->subsections(false) as $subsection_name => $subsection) {
429
+			if (isset($default_data[ $subsection_name ])) {
430
+				if ($subsection instanceof EE_Form_Input_Base) {
431
+					$subsection->set_default($default_data[ $subsection_name ]);
432
+				} elseif ($subsection instanceof EE_Form_Section_Proper) {
433
+					$subsection->populate_defaults($default_data[ $subsection_name ]);
434
+				}
435
+			}
436
+		}
437
+	}
438
+
439
+
440
+	/**
441
+	 * returns true if subsection exists
442
+	 *
443
+	 * @param string $name
444
+	 * @return boolean
445
+	 */
446
+	public function subsection_exists($name)
447
+	{
448
+		return isset($this->_subsections[ $name ]) ? true : false;
449
+	}
450
+
451
+
452
+	/**
453
+	 * Gets the subsection specified by its name
454
+	 *
455
+	 * @param string  $name
456
+	 * @param boolean $require_construction_to_be_finalized most client code should leave this as TRUE
457
+	 *                                                      so that the inputs will be properly configured.
458
+	 *                                                      However, some client code may be ok
459
+	 *                                                      with construction finalize being called later
460
+	 *                                                      (realizing that the subsections' html names
461
+	 *                                                      might not be set yet, etc.)
462
+	 * @return EE_Form_Section_Base
463
+	 * @throws EE_Error
464
+	 */
465
+	public function get_subsection($name, $require_construction_to_be_finalized = true)
466
+	{
467
+		if ($require_construction_to_be_finalized) {
468
+			$this->ensure_construct_finalized_called();
469
+		}
470
+		return $this->subsection_exists($name) ? $this->_subsections[ $name ] : null;
471
+	}
472
+
473
+
474
+	/**
475
+	 * Gets all the validatable subsections of this form section
476
+	 *
477
+	 * @return EE_Form_Section_Validatable[]
478
+	 * @throws EE_Error
479
+	 */
480
+	public function get_validatable_subsections()
481
+	{
482
+		$validatable_subsections = array();
483
+		foreach ($this->subsections() as $name => $obj) {
484
+			if ($obj instanceof EE_Form_Section_Validatable) {
485
+				$validatable_subsections[ $name ] = $obj;
486
+			}
487
+		}
488
+		return $validatable_subsections;
489
+	}
490
+
491
+
492
+	/**
493
+	 * Gets an input by the given name. If not found, or if its not an EE_FOrm_Input_Base child,
494
+	 * throw an EE_Error.
495
+	 *
496
+	 * @param string  $name
497
+	 * @param boolean $require_construction_to_be_finalized most client code should
498
+	 *                                                      leave this as TRUE so that the inputs will be properly
499
+	 *                                                      configured. However, some client code may be ok with
500
+	 *                                                      construction finalize being called later
501
+	 *                                                      (realizing that the subsections' html names might not be
502
+	 *                                                      set yet, etc.)
503
+	 * @return EE_Form_Input_Base
504
+	 * @throws EE_Error
505
+	 */
506
+	public function get_input($name, $require_construction_to_be_finalized = true)
507
+	{
508
+		$subsection = $this->get_subsection(
509
+			$name,
510
+			$require_construction_to_be_finalized
511
+		);
512
+		if (! $subsection instanceof EE_Form_Input_Base) {
513
+			throw new EE_Error(
514
+				sprintf(
515
+					esc_html__(
516
+						"Subsection '%s' is not an instanceof EE_Form_Input_Base on form '%s'. It is a '%s'",
517
+						'event_espresso'
518
+					),
519
+					$name,
520
+					get_class($this),
521
+					$subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
522
+				)
523
+			);
524
+		}
525
+		return $subsection;
526
+	}
527
+
528
+
529
+	/**
530
+	 * Like get_input(), gets the proper subsection of the form given the name,
531
+	 * otherwise throws an EE_Error
532
+	 *
533
+	 * @param string  $name
534
+	 * @param boolean $require_construction_to_be_finalized most client code should
535
+	 *                                                      leave this as TRUE so that the inputs will be properly
536
+	 *                                                      configured. However, some client code may be ok with
537
+	 *                                                      construction finalize being called later
538
+	 *                                                      (realizing that the subsections' html names might not be
539
+	 *                                                      set yet, etc.)
540
+	 * @return EE_Form_Section_Proper
541
+	 * @throws EE_Error
542
+	 */
543
+	public function get_proper_subsection($name, $require_construction_to_be_finalized = true)
544
+	{
545
+		$subsection = $this->get_subsection(
546
+			$name,
547
+			$require_construction_to_be_finalized
548
+		);
549
+		if (! $subsection instanceof EE_Form_Section_Proper) {
550
+			throw new EE_Error(
551
+				sprintf(
552
+					esc_html__(
553
+						"Subsection '%'s is not an instanceof EE_Form_Section_Proper on form '%s'",
554
+						'event_espresso'
555
+					),
556
+					$name,
557
+					get_class($this)
558
+				)
559
+			);
560
+		}
561
+		return $subsection;
562
+	}
563
+
564
+
565
+	/**
566
+	 * Gets the value of the specified input. Should be called after receive_form_submission()
567
+	 * or populate_defaults() on the form, where the normalized value on the input is set.
568
+	 *
569
+	 * @param string $name
570
+	 * @return mixed depending on the input's type and its normalization strategy
571
+	 * @throws EE_Error
572
+	 */
573
+	public function get_input_value($name)
574
+	{
575
+		$input = $this->get_input($name);
576
+		return $input->normalized_value();
577
+	}
578
+
579
+
580
+	/**
581
+	 * Checks if this form section itself is valid, and then checks its subsections
582
+	 *
583
+	 * @throws EE_Error
584
+	 * @return boolean
585
+	 */
586
+	public function is_valid()
587
+	{
588
+		if($this->is_valid === null) {
589
+			if (! $this->has_received_submission()) {
590
+				throw new EE_Error(
591
+					sprintf(
592
+						esc_html__(
593
+							'You cannot check if a form is valid before receiving the form submission using receive_form_submission',
594
+							'event_espresso'
595
+						)
596
+					)
597
+				);
598
+			}
599
+			if (! parent::is_valid()) {
600
+				$this->is_valid = false;
601
+			} else {
602
+				// ok so no general errors to this entire form section.
603
+				// so let's check the subsections, but only set errors if that hasn't been done yet
604
+				$this->is_valid = true;
605
+				foreach ($this->get_validatable_subsections() as $subsection) {
606
+					if (! $subsection->is_valid()) {
607
+						$this->is_valid = false;
608
+					}
609
+				}
610
+			}
611
+		}
612
+		return $this->is_valid;
613
+	}
614
+
615
+
616
+	/**
617
+	 * gets the default name of this form section if none is specified
618
+	 *
619
+	 * @return void
620
+	 */
621
+	protected function _set_default_name_if_empty()
622
+	{
623
+		if (! $this->_name) {
624
+			$classname    = get_class($this);
625
+			$default_name = str_replace('EE_', '', $classname);
626
+			$this->_name  = $default_name;
627
+		}
628
+	}
629
+
630
+
631
+	/**
632
+	 * Returns the HTML for the form, except for the form opening and closing tags
633
+	 * (as the form section doesn't know where you necessarily want to send the information to),
634
+	 * and except for a submit button. Enqueues JS and CSS; if called early enough we will
635
+	 * try to enqueue them in the header, otherwise they'll be enqueued in the footer.
636
+	 * Not doing_it_wrong because theoretically this CAN be used properly,
637
+	 * provided its used during "wp_enqueue_scripts", or it doesn't need to enqueue
638
+	 * any CSS.
639
+	 *
640
+	 * @throws InvalidArgumentException
641
+	 * @throws InvalidInterfaceException
642
+	 * @throws InvalidDataTypeException
643
+	 * @throws EE_Error
644
+	 */
645
+	public function get_html_and_js()
646
+	{
647
+		$this->enqueue_js();
648
+		return $this->get_html();
649
+	}
650
+
651
+
652
+	/**
653
+	 * returns HTML for displaying this form section. recursively calls display_section() on all subsections
654
+	 *
655
+	 * @param bool $display_previously_submitted_data
656
+	 * @return string
657
+	 * @throws InvalidArgumentException
658
+	 * @throws InvalidInterfaceException
659
+	 * @throws InvalidDataTypeException
660
+	 * @throws EE_Error
661
+	 * @throws EE_Error
662
+	 * @throws EE_Error
663
+	 */
664
+	public function get_html($display_previously_submitted_data = true)
665
+	{
666
+		$this->ensure_construct_finalized_called();
667
+		if ($display_previously_submitted_data) {
668
+			$this->populate_from_session();
669
+		}
670
+		return $this->_form_html_filter
671
+			? $this->_form_html_filter->filterHtml($this->_layout_strategy->layout_form(), $this)
672
+			: $this->_layout_strategy->layout_form();
673
+	}
674
+
675
+
676
+	/**
677
+	 * enqueues JS and CSS for the form.
678
+	 * It is preferred to call this before wp_enqueue_scripts so the
679
+	 * scripts and styles can be put in the header, but if called later
680
+	 * they will be put in the footer (which is OK for JS, but in HTML4 CSS should
681
+	 * only be in the header; but in HTML5 its ok in the body.
682
+	 * See http://stackoverflow.com/questions/4957446/load-external-css-file-in-body-tag.
683
+	 * So if your form enqueues CSS, it's preferred to call this before wp_enqueue_scripts.)
684
+	 *
685
+	 * @return void
686
+	 * @throws EE_Error
687
+	 */
688
+	public function enqueue_js()
689
+	{
690
+		$this->_enqueue_and_localize_form_js();
691
+		foreach ($this->subsections() as $subsection) {
692
+			$subsection->enqueue_js();
693
+		}
694
+	}
695
+
696
+
697
+	/**
698
+	 * adds a filter so that jquery validate gets enqueued in EE_System::wp_enqueue_scripts().
699
+	 * This must be done BEFORE wp_enqueue_scripts() gets called, which is on
700
+	 * the wp_enqueue_scripts hook.
701
+	 * However, registering the form js and localizing it can happen when we
702
+	 * actually output the form (which is preferred, seeing how teh form's fields
703
+	 * could change until it's actually outputted)
704
+	 *
705
+	 * @param boolean $init_form_validation_automatically whether or not we want the form validation
706
+	 *                                                    to be triggered automatically or not
707
+	 * @return void
708
+	 */
709
+	public static function wp_enqueue_scripts($init_form_validation_automatically = true)
710
+	{
711
+		wp_register_script(
712
+			'ee_form_section_validation',
713
+			EE_GLOBAL_ASSETS_URL . 'scripts' . DS . 'form_section_validation.js',
714
+			array('jquery-validate', 'jquery-ui-datepicker', 'jquery-validate-extra-methods'),
715
+			EVENT_ESPRESSO_VERSION,
716
+			true
717
+		);
718
+		wp_localize_script(
719
+			'ee_form_section_validation',
720
+			'ee_form_section_validation_init',
721
+			array('init' => $init_form_validation_automatically ? '1' : '0')
722
+		);
723
+	}
724
+
725
+
726
+	/**
727
+	 * gets the variables used by form_section_validation.js.
728
+	 * This needs to be called AFTER we've called $this->_enqueue_jquery_validate_script,
729
+	 * but before the wordpress hook wp_loaded
730
+	 *
731
+	 * @throws EE_Error
732
+	 */
733
+	public function _enqueue_and_localize_form_js()
734
+	{
735
+		$this->ensure_construct_finalized_called();
736
+		//actually, we don't want to localize just yet. There may be other forms on the page.
737
+		//so we need to add our form section data to a static variable accessible by all form sections
738
+		//and localize it just before the footer
739
+		$this->localize_validation_rules();
740
+		add_action('wp_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'), 2);
741
+		add_action('admin_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'));
742
+	}
743
+
744
+
745
+	/**
746
+	 * add our form section data to a static variable accessible by all form sections
747
+	 *
748
+	 * @param bool $return_for_subsection
749
+	 * @return void
750
+	 * @throws EE_Error
751
+	 */
752
+	public function localize_validation_rules($return_for_subsection = false)
753
+	{
754
+		// we only want to localize vars ONCE for the entire form,
755
+		// so if the form section doesn't have a parent, then it must be the top dog
756
+		if ($return_for_subsection || ! $this->parent_section()) {
757
+			EE_Form_Section_Proper::$_js_localization['form_data'][ $this->html_id() ] = array(
758
+				'form_section_id'  => $this->html_id(true),
759
+				'validation_rules' => $this->get_jquery_validation_rules(),
760
+				'other_data'       => $this->get_other_js_data(),
761
+				'errors'           => $this->subsection_validation_errors_by_html_name(),
762
+			);
763
+			EE_Form_Section_Proper::$_scripts_localized                                = true;
764
+		}
765
+	}
766
+
767
+
768
+	/**
769
+	 * Gets an array of extra data that will be useful for client-side javascript.
770
+	 * This is primarily data added by inputs and forms in addition to any
771
+	 * scripts they might enqueue
772
+	 *
773
+	 * @param array $form_other_js_data
774
+	 * @return array
775
+	 * @throws EE_Error
776
+	 */
777
+	public function get_other_js_data($form_other_js_data = array())
778
+	{
779
+		foreach ($this->subsections() as $subsection) {
780
+			$form_other_js_data = $subsection->get_other_js_data($form_other_js_data);
781
+		}
782
+		return $form_other_js_data;
783
+	}
784
+
785
+
786
+	/**
787
+	 * Gets a flat array of inputs for this form section and its subsections.
788
+	 * Keys are their form names, and values are the inputs themselves
789
+	 *
790
+	 * @return EE_Form_Input_Base
791
+	 * @throws EE_Error
792
+	 */
793
+	public function inputs_in_subsections()
794
+	{
795
+		$inputs = array();
796
+		foreach ($this->subsections() as $subsection) {
797
+			if ($subsection instanceof EE_Form_Input_Base) {
798
+				$inputs[ $subsection->html_name() ] = $subsection;
799
+			} elseif ($subsection instanceof EE_Form_Section_Proper) {
800
+				$inputs += $subsection->inputs_in_subsections();
801
+			}
802
+		}
803
+		return $inputs;
804
+	}
805
+
806
+
807
+	/**
808
+	 * Gets a flat array of all the validation errors.
809
+	 * Keys are html names (because those should be unique)
810
+	 * and values are a string of all their validation errors
811
+	 *
812
+	 * @return string[]
813
+	 * @throws EE_Error
814
+	 */
815
+	public function subsection_validation_errors_by_html_name()
816
+	{
817
+		$inputs = $this->inputs();
818
+		$errors = array();
819
+		foreach ($inputs as $form_input) {
820
+			if ($form_input instanceof EE_Form_Input_Base && $form_input->get_validation_errors()) {
821
+				$errors[ $form_input->html_name() ] = $form_input->get_validation_error_string();
822
+			}
823
+		}
824
+		return $errors;
825
+	}
826
+
827
+
828
+	/**
829
+	 * passes all the form data required by the JS to the JS, and enqueues the few required JS files.
830
+	 * Should be setup by each form during the _enqueues_and_localize_form_js
831
+	 *
832
+	 * @throws InvalidArgumentException
833
+	 * @throws InvalidInterfaceException
834
+	 * @throws InvalidDataTypeException
835
+	 */
836
+	public static function localize_script_for_all_forms()
837
+	{
838
+		//allow inputs and stuff to hook in their JS and stuff here
839
+		do_action('AHEE__EE_Form_Section_Proper__localize_script_for_all_forms__begin');
840
+		EE_Form_Section_Proper::$_js_localization['localized_error_messages'] = EE_Form_Section_Proper::_get_localized_error_messages();
841
+		$email_validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
842
+			? EE_Registry::instance()->CFG->registration->email_validation_level
843
+			: 'wp_default';
844
+		EE_Form_Section_Proper::$_js_localization['email_validation_level']   = $email_validation_level;
845
+		wp_enqueue_script('ee_form_section_validation');
846
+		wp_localize_script(
847
+			'ee_form_section_validation',
848
+			'ee_form_section_vars',
849
+			EE_Form_Section_Proper::$_js_localization
850
+		);
851
+	}
852
+
853
+
854
+	/**
855
+	 * ensure_scripts_localized
856
+	 *
857
+	 * @throws EE_Error
858
+	 */
859
+	public function ensure_scripts_localized()
860
+	{
861
+		if (! EE_Form_Section_Proper::$_scripts_localized) {
862
+			$this->_enqueue_and_localize_form_js();
863
+		}
864
+	}
865
+
866
+
867
+	/**
868
+	 * Gets the hard-coded validation error messages to be used in the JS. The convention
869
+	 * is that the key here should be the same as the custom validation rule put in the JS file
870
+	 *
871
+	 * @return array keys are custom validation rules, and values are internationalized strings
872
+	 */
873
+	private static function _get_localized_error_messages()
874
+	{
875
+		return array(
876
+			'validUrl' => esc_html__('This is not a valid absolute URL. Eg, http://domain.com/monkey.jpg', 'event_espresso'),
877
+			'regex'    => esc_html__('Please check your input', 'event_espresso'),
878
+		);
879
+	}
880
+
881
+
882
+	/**
883
+	 * @return array
884
+	 */
885
+	public static function js_localization()
886
+	{
887
+		return self::$_js_localization;
888
+	}
889
+
890
+
891
+	/**
892
+	 * @return void
893
+	 */
894
+	public static function reset_js_localization()
895
+	{
896
+		self::$_js_localization = array();
897
+	}
898
+
899
+
900
+	/**
901
+	 * Gets the JS to put inside the jquery validation rules for subsection of this form section.
902
+	 * See parent function for more...
903
+	 *
904
+	 * @return array
905
+	 * @throws EE_Error
906
+	 */
907
+	public function get_jquery_validation_rules()
908
+	{
909
+		$jquery_validation_rules = array();
910
+		foreach ($this->get_validatable_subsections() as $subsection) {
911
+			$jquery_validation_rules = array_merge(
912
+				$jquery_validation_rules,
913
+				$subsection->get_jquery_validation_rules()
914
+			);
915
+		}
916
+		return $jquery_validation_rules;
917
+	}
918
+
919
+
920
+	/**
921
+	 * Sanitizes all the data and sets the sanitized value of each field
922
+	 *
923
+	 * @param array $req_data like $_POST
924
+	 * @return void
925
+	 * @throws EE_Error
926
+	 */
927
+	protected function _normalize($req_data)
928
+	{
929
+		$this->_received_submission = true;
930
+		$this->_validation_errors   = array();
931
+		foreach ($this->get_validatable_subsections() as $subsection) {
932
+			try {
933
+				$subsection->_normalize($req_data);
934
+			} catch (EE_Validation_Error $e) {
935
+				$subsection->add_validation_error($e);
936
+			}
937
+		}
938
+	}
939
+
940
+
941
+	/**
942
+	 * Performs validation on this form section and its subsections.
943
+	 * For each subsection,
944
+	 * calls _validate_{subsection_name} on THIS form (if the function exists)
945
+	 * and passes it the subsection, then calls _validate on that subsection.
946
+	 * If you need to perform validation on the form as a whole (considering multiple)
947
+	 * you would be best to override this _validate method,
948
+	 * calling parent::_validate() first.
949
+	 *
950
+	 * @throws EE_Error
951
+	 */
952
+	protected function _validate()
953
+	{
954
+		//reset the cache of whether this form is valid or not- we're re-validating it now
955
+		$this->is_valid = null;
956
+		foreach ($this->get_validatable_subsections() as $subsection_name => $subsection) {
957
+			if (method_exists($this, '_validate_' . $subsection_name)) {
958
+				call_user_func_array(array($this, '_validate_' . $subsection_name), array($subsection));
959
+			}
960
+			$subsection->_validate();
961
+		}
962
+	}
963
+
964
+
965
+	/**
966
+	 * Gets all the validated inputs for the form section
967
+	 *
968
+	 * @return array
969
+	 * @throws EE_Error
970
+	 */
971
+	public function valid_data()
972
+	{
973
+		$inputs = array();
974
+		foreach ($this->subsections() as $subsection_name => $subsection) {
975
+			if ($subsection instanceof EE_Form_Section_Proper) {
976
+				$inputs[ $subsection_name ] = $subsection->valid_data();
977
+			} elseif ($subsection instanceof EE_Form_Input_Base) {
978
+				$inputs[ $subsection_name ] = $subsection->normalized_value();
979
+			}
980
+		}
981
+		return $inputs;
982
+	}
983
+
984
+
985
+	/**
986
+	 * Gets all the inputs on this form section
987
+	 *
988
+	 * @return EE_Form_Input_Base[]
989
+	 * @throws EE_Error
990
+	 */
991
+	public function inputs()
992
+	{
993
+		$inputs = array();
994
+		foreach ($this->subsections() as $subsection_name => $subsection) {
995
+			if ($subsection instanceof EE_Form_Input_Base) {
996
+				$inputs[ $subsection_name ] = $subsection;
997
+			}
998
+		}
999
+		return $inputs;
1000
+	}
1001
+
1002
+
1003
+	/**
1004
+	 * Gets all the subsections which are a proper form
1005
+	 *
1006
+	 * @return EE_Form_Section_Proper[]
1007
+	 * @throws EE_Error
1008
+	 */
1009
+	public function subforms()
1010
+	{
1011
+		$form_sections = array();
1012
+		foreach ($this->subsections() as $name => $obj) {
1013
+			if ($obj instanceof EE_Form_Section_Proper) {
1014
+				$form_sections[ $name ] = $obj;
1015
+			}
1016
+		}
1017
+		return $form_sections;
1018
+	}
1019
+
1020
+
1021
+	/**
1022
+	 * Gets all the subsections (inputs, proper subsections, or html-only sections).
1023
+	 * Consider using inputs() or subforms()
1024
+	 * if you only want form inputs or proper form sections.
1025
+	 *
1026
+	 * @param boolean $require_construction_to_be_finalized most client code should
1027
+	 *                                                      leave this as TRUE so that the inputs will be properly
1028
+	 *                                                      configured. However, some client code may be ok with
1029
+	 *                                                      construction finalize being called later
1030
+	 *                                                      (realizing that the subsections' html names might not be
1031
+	 *                                                      set yet, etc.)
1032
+	 * @return EE_Form_Section_Proper[]
1033
+	 * @throws EE_Error
1034
+	 */
1035
+	public function subsections($require_construction_to_be_finalized = true)
1036
+	{
1037
+		if ($require_construction_to_be_finalized) {
1038
+			$this->ensure_construct_finalized_called();
1039
+		}
1040
+		return $this->_subsections;
1041
+	}
1042
+
1043
+
1044
+	/**
1045
+	 * Returns whether this form has any subforms or inputs
1046
+	 * @return bool
1047
+	 */
1048
+	public function hasSubsections()
1049
+	{
1050
+		return ! empty($this->_subsections);
1051
+	}
1052
+
1053
+
1054
+	/**
1055
+	 * Returns a simple array where keys are input names, and values are their normalized
1056
+	 * values. (Similar to calling get_input_value on inputs)
1057
+	 *
1058
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1059
+	 *                                        or just this forms' direct children inputs
1060
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1061
+	 *                                        or allow multidimensional array
1062
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array
1063
+	 *                                        with array keys being input names
1064
+	 *                                        (regardless of whether they are from a subsection or not),
1065
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
1066
+	 *                                        where keys are always subsection names and values are either
1067
+	 *                                        the input's normalized value, or an array like the top-level array
1068
+	 * @throws EE_Error
1069
+	 */
1070
+	public function input_values($include_subform_inputs = false, $flatten = false)
1071
+	{
1072
+		return $this->_input_values(false, $include_subform_inputs, $flatten);
1073
+	}
1074
+
1075
+
1076
+	/**
1077
+	 * Similar to EE_Form_Section_Proper::input_values(), except this returns the 'display_value'
1078
+	 * of each input. On some inputs (especially radio boxes or checkboxes), the value stored
1079
+	 * is not necessarily the value we want to display to users. This creates an array
1080
+	 * where keys are the input names, and values are their display values
1081
+	 *
1082
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1083
+	 *                                        or just this forms' direct children inputs
1084
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1085
+	 *                                        or allow multidimensional array
1086
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array
1087
+	 *                                        with array keys being input names
1088
+	 *                                        (regardless of whether they are from a subsection or not),
1089
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
1090
+	 *                                        where keys are always subsection names and values are either
1091
+	 *                                        the input's normalized value, or an array like the top-level array
1092
+	 * @throws EE_Error
1093
+	 */
1094
+	public function input_pretty_values($include_subform_inputs = false, $flatten = false)
1095
+	{
1096
+		return $this->_input_values(true, $include_subform_inputs, $flatten);
1097
+	}
1098
+
1099
+
1100
+	/**
1101
+	 * Gets the input values from the form
1102
+	 *
1103
+	 * @param boolean $pretty                 Whether to retrieve the pretty value,
1104
+	 *                                        or just the normalized value
1105
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1106
+	 *                                        or just this forms' direct children inputs
1107
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1108
+	 *                                        or allow multidimensional array
1109
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array with array keys being
1110
+	 *                                        input names (regardless of whether they are from a subsection or not),
1111
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
1112
+	 *                                        where keys are always subsection names and values are either
1113
+	 *                                        the input's normalized value, or an array like the top-level array
1114
+	 * @throws EE_Error
1115
+	 */
1116
+	public function _input_values($pretty = false, $include_subform_inputs = false, $flatten = false)
1117
+	{
1118
+		$input_values = array();
1119
+		foreach ($this->subsections() as $subsection_name => $subsection) {
1120
+			if ($subsection instanceof EE_Form_Input_Base) {
1121
+				$input_values[ $subsection_name ] = $pretty
1122
+					? $subsection->pretty_value()
1123
+					: $subsection->normalized_value();
1124
+			} elseif ($subsection instanceof EE_Form_Section_Proper && $include_subform_inputs) {
1125
+				$subform_input_values = $subsection->_input_values(
1126
+					$pretty,
1127
+					$include_subform_inputs,
1128
+					$flatten
1129
+				);
1130
+				if ($flatten) {
1131
+					$input_values = array_merge($input_values, $subform_input_values);
1132
+				} else {
1133
+					$input_values[ $subsection_name ] = $subform_input_values;
1134
+				}
1135
+			}
1136
+		}
1137
+		return $input_values;
1138
+	}
1139
+
1140
+
1141
+	/**
1142
+	 * Gets the originally submitted input values from the form
1143
+	 *
1144
+	 * @param boolean $include_subforms  Whether to include inputs from subforms,
1145
+	 *                                   or just this forms' direct children inputs
1146
+	 * @return array                     if $flatten is TRUE it will always be a 1-dimensional array
1147
+	 *                                   with array keys being input names
1148
+	 *                                   (regardless of whether they are from a subsection or not),
1149
+	 *                                   and if $flatten is FALSE it can be a multidimensional array
1150
+	 *                                   where keys are always subsection names and values are either
1151
+	 *                                   the input's normalized value, or an array like the top-level array
1152
+	 * @throws EE_Error
1153
+	 */
1154
+	public function submitted_values($include_subforms = false)
1155
+	{
1156
+		$submitted_values = array();
1157
+		foreach ($this->subsections() as $subsection) {
1158
+			if ($subsection instanceof EE_Form_Input_Base) {
1159
+				// is this input part of an array of inputs?
1160
+				if (strpos($subsection->html_name(), '[') !== false) {
1161
+					$full_input_name  = EEH_Array::convert_array_values_to_keys(
1162
+						explode(
1163
+							'[',
1164
+							str_replace(']', '', $subsection->html_name())
1165
+						),
1166
+						$subsection->raw_value()
1167
+					);
1168
+					$submitted_values = array_replace_recursive($submitted_values, $full_input_name);
1169
+				} else {
1170
+					$submitted_values[ $subsection->html_name() ] = $subsection->raw_value();
1171
+				}
1172
+			} elseif ($subsection instanceof EE_Form_Section_Proper && $include_subforms) {
1173
+				$subform_input_values = $subsection->submitted_values($include_subforms);
1174
+				$submitted_values     = array_replace_recursive($submitted_values, $subform_input_values);
1175
+			}
1176
+		}
1177
+		return $submitted_values;
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * Indicates whether or not this form has received a submission yet
1183
+	 * (ie, had receive_form_submission called on it yet)
1184
+	 *
1185
+	 * @return boolean
1186
+	 * @throws EE_Error
1187
+	 */
1188
+	public function has_received_submission()
1189
+	{
1190
+		$this->ensure_construct_finalized_called();
1191
+		return $this->_received_submission;
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * Equivalent to passing 'exclude' in the constructor's options array.
1197
+	 * Removes the listed inputs from the form
1198
+	 *
1199
+	 * @param array $inputs_to_exclude values are the input names
1200
+	 * @return void
1201
+	 */
1202
+	public function exclude(array $inputs_to_exclude = array())
1203
+	{
1204
+		foreach ($inputs_to_exclude as $input_to_exclude_name) {
1205
+			unset($this->_subsections[ $input_to_exclude_name ]);
1206
+		}
1207
+	}
1208
+
1209
+
1210
+	/**
1211
+	 * Changes these inputs' display strategy to be EE_Hidden_Display_Strategy.
1212
+	 * @param array $inputs_to_hide
1213
+	 * @throws EE_Error
1214
+	 */
1215
+	public function hide(array $inputs_to_hide = array())
1216
+	{
1217
+		foreach ($inputs_to_hide as $input_to_hide) {
1218
+			$input = $this->get_input($input_to_hide);
1219
+			$input->set_display_strategy(new EE_Hidden_Display_Strategy());
1220
+		}
1221
+	}
1222
+
1223
+
1224
+	/**
1225
+	 * add_subsections
1226
+	 * Adds the listed subsections to the form section.
1227
+	 * If $subsection_name_to_target is provided,
1228
+	 * then new subsections are added before or after that subsection,
1229
+	 * otherwise to the start or end of the entire subsections array.
1230
+	 *
1231
+	 * @param EE_Form_Section_Base[] $new_subsections           array of new form subsections
1232
+	 *                                                          where keys are their names
1233
+	 * @param string                 $subsection_name_to_target an existing for section that $new_subsections
1234
+	 *                                                          should be added before or after
1235
+	 *                                                          IF $subsection_name_to_target is null,
1236
+	 *                                                          then $new_subsections will be added to
1237
+	 *                                                          the beginning or end of the entire subsections array
1238
+	 * @param boolean                $add_before                whether to add $new_subsections, before or after
1239
+	 *                                                          $subsection_name_to_target,
1240
+	 *                                                          or if $subsection_name_to_target is null,
1241
+	 *                                                          before or after entire subsections array
1242
+	 * @return void
1243
+	 * @throws EE_Error
1244
+	 */
1245
+	public function add_subsections($new_subsections, $subsection_name_to_target = null, $add_before = true)
1246
+	{
1247
+		foreach ($new_subsections as $subsection_name => $subsection) {
1248
+			if (! $subsection instanceof EE_Form_Section_Base) {
1249
+				EE_Error::add_error(
1250
+					sprintf(
1251
+						esc_html__(
1252
+							"Trying to add a %s as a subsection (it was named '%s') to the form section '%s'. It was removed.",
1253
+							'event_espresso'
1254
+						),
1255
+						get_class($subsection),
1256
+						$subsection_name,
1257
+						$this->name()
1258
+					)
1259
+				);
1260
+				unset($new_subsections[ $subsection_name ]);
1261
+			}
1262
+		}
1263
+		$this->_subsections = EEH_Array::insert_into_array(
1264
+			$this->_subsections,
1265
+			$new_subsections,
1266
+			$subsection_name_to_target,
1267
+			$add_before
1268
+		);
1269
+		if ($this->_construction_finalized) {
1270
+			foreach ($this->_subsections as $name => $subsection) {
1271
+				$subsection->_construct_finalize($this, $name);
1272
+			}
1273
+		}
1274
+	}
1275
+
1276
+
1277
+	/**
1278
+	 * @param string $subsection_name
1279
+	 * @param bool   $recursive
1280
+	 * @return bool
1281
+	 */
1282
+	public function has_subsection($subsection_name, $recursive = false)
1283
+	{
1284
+		foreach ($this->_subsections as $name => $subsection) {if(
1285
+				$name === $subsection_name
1286
+				|| (
1287
+					$recursive
1288
+					&& $subsection instanceof EE_Form_Section_Proper
1289
+					&& $subsection->has_subsection($subsection_name, $recursive)
1290
+				)
1291
+			) {
1292
+				return true;
1293
+			}
1294
+		}
1295
+		return false;
1296
+	}
1297
+
1298
+
1299
+
1300
+	/**
1301
+	 * Just gets all validatable subsections to clean their sensitive data
1302
+	 *
1303
+	 * @throws EE_Error
1304
+	 */
1305
+	public function clean_sensitive_data()
1306
+	{
1307
+		foreach ($this->get_validatable_subsections() as $subsection) {
1308
+			$subsection->clean_sensitive_data();
1309
+		}
1310
+	}
1311
+
1312
+
1313
+	/**
1314
+	 * Sets the submission error message (aka validation error message for this form section and all sub-sections)
1315
+	 * @param string                           $form_submission_error_message
1316
+	 * @param EE_Form_Section_Validatable $form_section unused
1317
+	 * @throws EE_Error
1318
+	 */
1319
+	public function set_submission_error_message(
1320
+		$form_submission_error_message = ''
1321
+	) {
1322
+		$this->_form_submission_error_message = ! empty($form_submission_error_message)
1323
+			? $form_submission_error_message
1324
+			: $this->getAllValidationErrorsString();
1325
+	}
1326
+
1327
+
1328
+	/**
1329
+	 * Returns the cached error message. A default value is set for this during _validate(),
1330
+	 * (called during receive_form_submission) but it can be explicitly set using
1331
+	 * set_submission_error_message
1332
+	 *
1333
+	 * @return string
1334
+	 */
1335
+	public function submission_error_message()
1336
+	{
1337
+		return $this->_form_submission_error_message;
1338
+	}
1339
+
1340
+
1341
+	/**
1342
+	 * Sets a message to display if the data submitted to the form was valid.
1343
+	 * @param string $form_submission_success_message
1344
+	 */
1345
+	public function set_submission_success_message($form_submission_success_message = '')
1346
+	{
1347
+		$this->_form_submission_success_message = ! empty($form_submission_success_message)
1348
+			? $form_submission_success_message
1349
+			: esc_html__('Form submitted successfully', 'event_espresso');
1350
+	}
1351
+
1352
+
1353
+	/**
1354
+	 * Gets a message appropriate for display when the form is correctly submitted
1355
+	 * @return string
1356
+	 */
1357
+	public function submission_success_message()
1358
+	{
1359
+		return $this->_form_submission_success_message;
1360
+	}
1361
+
1362
+
1363
+	/**
1364
+	 * Returns the prefix that should be used on child of this form section for
1365
+	 * their html names. If this form section itself has a parent, prepends ITS
1366
+	 * prefix onto this form section's prefix. Used primarily by
1367
+	 * EE_Form_Input_Base::_set_default_html_name_if_empty
1368
+	 *
1369
+	 * @return string
1370
+	 * @throws EE_Error
1371
+	 */
1372
+	public function html_name_prefix()
1373
+	{
1374
+		if ($this->parent_section() instanceof EE_Form_Section_Proper) {
1375
+			return $this->parent_section()->html_name_prefix() . '[' . $this->name() . ']';
1376
+		}
1377
+		return $this->name();
1378
+	}
1379
+
1380
+
1381
+	/**
1382
+	 * Gets the name, but first checks _construct_finalize has been called. If not,
1383
+	 * calls it (assumes there is no parent and that we want the name to be whatever
1384
+	 * was set, which is probably nothing, or the classname)
1385
+	 *
1386
+	 * @return string
1387
+	 * @throws EE_Error
1388
+	 */
1389
+	public function name()
1390
+	{
1391
+		$this->ensure_construct_finalized_called();
1392
+		return parent::name();
1393
+	}
1394
+
1395
+
1396
+	/**
1397
+	 * @return EE_Form_Section_Proper
1398
+	 * @throws EE_Error
1399
+	 */
1400
+	public function parent_section()
1401
+	{
1402
+		$this->ensure_construct_finalized_called();
1403
+		return parent::parent_section();
1404
+	}
1405
+
1406
+
1407
+	/**
1408
+	 * make sure construction finalized was called, otherwise children might not be ready
1409
+	 *
1410
+	 * @return void
1411
+	 * @throws EE_Error
1412
+	 */
1413
+	public function ensure_construct_finalized_called()
1414
+	{
1415
+		if (! $this->_construction_finalized) {
1416
+			$this->_construct_finalize($this->_parent_section, $this->_name);
1417
+		}
1418
+	}
1419
+
1420
+
1421
+	/**
1422
+	 * Checks if any of this form section's inputs, or any of its children's inputs,
1423
+	 * are in teh form data. If any are found, returns true. Else false
1424
+	 *
1425
+	 * @param array $req_data
1426
+	 * @return boolean
1427
+	 * @throws EE_Error
1428
+	 */
1429
+	public function form_data_present_in($req_data = null)
1430
+	{
1431
+		$req_data = $this->getCachedRequest($req_data);
1432
+		foreach ($this->subsections() as $subsection) {
1433
+			if ($subsection instanceof EE_Form_Input_Base) {
1434
+				if ($subsection->form_data_present_in($req_data)) {
1435
+					return true;
1436
+				}
1437
+			} elseif ($subsection instanceof EE_Form_Section_Proper) {
1438
+				if ($subsection->form_data_present_in($req_data)) {
1439
+					return true;
1440
+				}
1441
+			}
1442
+		}
1443
+		return false;
1444
+	}
1445
+
1446
+
1447
+	/**
1448
+	 * Gets validation errors for this form section and subsections
1449
+	 * Similar to EE_Form_Section_Validatable::get_validation_errors() except this
1450
+	 * gets the validation errors for ALL subsection
1451
+	 *
1452
+	 * @return EE_Validation_Error[]
1453
+	 * @throws EE_Error
1454
+	 */
1455
+	public function get_validation_errors_accumulated()
1456
+	{
1457
+		$validation_errors = $this->get_validation_errors();
1458
+		foreach ($this->get_validatable_subsections() as $subsection) {
1459
+			if ($subsection instanceof EE_Form_Section_Proper) {
1460
+				$validation_errors_on_this_subsection = $subsection->get_validation_errors_accumulated();
1461
+			} else {
1462
+				$validation_errors_on_this_subsection = $subsection->get_validation_errors();
1463
+			}
1464
+			if ($validation_errors_on_this_subsection) {
1465
+				$validation_errors = array_merge($validation_errors, $validation_errors_on_this_subsection);
1466
+			}
1467
+		}
1468
+		return $validation_errors;
1469
+	}
1470
+
1471
+	/**
1472
+	 * Fetch validation errors from children and grandchildren and puts them in a single string.
1473
+	 * This traverses the form section tree to generate this, but you probably want to instead use
1474
+	 * get_form_submission_error_message() which is usually this message cached (or a custom validation error message)
1475
+	 *
1476
+	 * @return string
1477
+	 * @since $VID:$
1478
+	 */
1479
+	protected function getAllValidationErrorsString()
1480
+	{
1481
+		$submission_error_messages = array();
1482
+		// bad, bad, bad registrant
1483
+		foreach ($this->get_validation_errors_accumulated() as $validation_error) {
1484
+			if ($validation_error instanceof EE_Validation_Error) {
1485
+				$form_section = $validation_error->get_form_section();
1486
+				if ($form_section instanceof EE_Form_Input_Base) {
1487
+				   $label = $validation_error->get_form_section()->html_label_text();
1488
+				} elseif($form_section instanceof EE_Form_Section_Validatable) {
1489
+					$label = $validation_error->get_form_section()->name();
1490
+				} else {
1491
+					$label = esc_html__('Unknown', 'event_espresso');
1492
+				}
1493
+				$submission_error_messages[] = sprintf(
1494
+					__('%s : %s', 'event_espresso'),
1495
+					$label,
1496
+					$validation_error->getMessage()
1497
+				);
1498
+			}
1499
+		}
1500
+		return implode('<br', $submission_error_messages);
1501
+	}
1502
+
1503
+
1504
+	/**
1505
+	 * This isn't just the name of an input, it's a path pointing to an input. The
1506
+	 * path is similar to a folder path: slash (/) means to descend into a subsection,
1507
+	 * dot-dot-slash (../) means to ascend into the parent section.
1508
+	 * After a series of slashes and dot-dot-slashes, there should be the name of an input,
1509
+	 * which will be returned.
1510
+	 * Eg, if you want the related input to be conditional on a sibling input name 'foobar'
1511
+	 * just use 'foobar'. If you want it to be conditional on an aunt/uncle input name
1512
+	 * 'baz', use '../baz'. If you want it to be conditional on a cousin input,
1513
+	 * the child of 'baz_section' named 'baz_child', use '../baz_section/baz_child'.
1514
+	 * Etc
1515
+	 *
1516
+	 * @param string|false $form_section_path we accept false also because substr( '../', '../' ) = false
1517
+	 * @return EE_Form_Section_Base
1518
+	 * @throws EE_Error
1519
+	 */
1520
+	public function find_section_from_path($form_section_path)
1521
+	{
1522
+		//check if we can find the input from purely going straight up the tree
1523
+		$input = parent::find_section_from_path($form_section_path);
1524
+		if ($input instanceof EE_Form_Section_Base) {
1525
+			return $input;
1526
+		}
1527
+		$next_slash_pos = strpos($form_section_path, '/');
1528
+		if ($next_slash_pos !== false) {
1529
+			$child_section_name = substr($form_section_path, 0, $next_slash_pos);
1530
+			$subpath            = substr($form_section_path, $next_slash_pos + 1);
1531
+		} else {
1532
+			$child_section_name = $form_section_path;
1533
+			$subpath            = '';
1534
+		}
1535
+		$child_section = $this->get_subsection($child_section_name);
1536
+		if ($child_section instanceof EE_Form_Section_Base) {
1537
+			return $child_section->find_section_from_path($subpath);
1538
+		}
1539
+		return null;
1540
+	}
1541 1541
 }
1542 1542
 
Please login to merge, or discard this patch.
core/services/request/RequestInterface.php 1 patch
Indentation   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -20,139 +20,139 @@
 block discarded – undo
20 20
 interface RequestInterface extends RequestTypeContextCheckerInterface
21 21
 {
22 22
 
23
-    /**
24
-     * @param RequestTypeContextCheckerInterface $type
25
-     */
26
-    public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type);
27
-
28
-    /**
29
-     * @return array
30
-     */
31
-    public function getParams();
32
-
33
-
34
-    /**
35
-     * @return array
36
-     */
37
-    public function postParams();
38
-
39
-
40
-    /**
41
-     * @return array
42
-     */
43
-    public function cookieParams();
44
-
45
-
46
-    /**
47
-     * @return array
48
-     */
49
-    public function serverParams();
50
-
51
-
52
-    /**
53
-     * returns contents of $_REQUEST
54
-     *
55
-     * @return array
56
-     */
57
-    public function requestParams();
23
+	/**
24
+	 * @param RequestTypeContextCheckerInterface $type
25
+	 */
26
+	public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type);
27
+
28
+	/**
29
+	 * @return array
30
+	 */
31
+	public function getParams();
32
+
33
+
34
+	/**
35
+	 * @return array
36
+	 */
37
+	public function postParams();
38
+
39
+
40
+	/**
41
+	 * @return array
42
+	 */
43
+	public function cookieParams();
44
+
45
+
46
+	/**
47
+	 * @return array
48
+	 */
49
+	public function serverParams();
50
+
51
+
52
+	/**
53
+	 * returns contents of $_REQUEST
54
+	 *
55
+	 * @return array
56
+	 */
57
+	public function requestParams();
58 58
 
59 59
 
60
-    /**
61
-     * @param string $key
62
-     * @param string $value
63
-     * @param bool   $override_ee
64
-     * @return    void
65
-     */
66
-    public function setRequestParam($key, $value, $override_ee = false);
60
+	/**
61
+	 * @param string $key
62
+	 * @param string $value
63
+	 * @param bool   $override_ee
64
+	 * @return    void
65
+	 */
66
+	public function setRequestParam($key, $value, $override_ee = false);
67 67
 
68 68
 
69
-    /**
70
-     * returns the value for a request param if the given key exists
71
-     *
72
-     * @param string $key
73
-     * @param null   $default
74
-     * @return mixed
75
-     */
76
-    public function getRequestParam($key, $default = null);
69
+	/**
70
+	 * returns the value for a request param if the given key exists
71
+	 *
72
+	 * @param string $key
73
+	 * @param null   $default
74
+	 * @return mixed
75
+	 */
76
+	public function getRequestParam($key, $default = null);
77 77
 
78 78
 
79
-    /**
80
-     * check if param exists
81
-     *
82
-     * @param string $key
83
-     * @return bool
84
-     */
85
-    public function requestParamIsSet($key);
79
+	/**
80
+	 * check if param exists
81
+	 *
82
+	 * @param string $key
83
+	 * @return bool
84
+	 */
85
+	public function requestParamIsSet($key);
86 86
 
87 87
 
88
-    /**
89
-     * check if a request parameter exists whose key that matches the supplied wildcard pattern
90
-     * and return the value for the first match found
91
-     * wildcards can be either of the following:
92
-     *      ? to represent a single character of any type
93
-     *      * to represent one or more characters of any type
94
-     *
95
-     * @param string     $pattern
96
-     * @param null|mixed $default
97
-     * @return false|int
98
-     */
99
-    public function getMatch($pattern, $default = null);
88
+	/**
89
+	 * check if a request parameter exists whose key that matches the supplied wildcard pattern
90
+	 * and return the value for the first match found
91
+	 * wildcards can be either of the following:
92
+	 *      ? to represent a single character of any type
93
+	 *      * to represent one or more characters of any type
94
+	 *
95
+	 * @param string     $pattern
96
+	 * @param null|mixed $default
97
+	 * @return false|int
98
+	 */
99
+	public function getMatch($pattern, $default = null);
100 100
 
101 101
 
102
-    /**
103
-     * check if a request parameter exists whose key matches the supplied wildcard pattern
104
-     * wildcards can be either of the following:
105
-     *      ? to represent a single character of any type
106
-     *      * to represent one or more characters of any type
107
-     * returns true if a match is found or false if not
108
-     *
109
-     * @param string $pattern
110
-     * @return false|int
111
-     */
112
-    public function matches($pattern);
102
+	/**
103
+	 * check if a request parameter exists whose key matches the supplied wildcard pattern
104
+	 * wildcards can be either of the following:
105
+	 *      ? to represent a single character of any type
106
+	 *      * to represent one or more characters of any type
107
+	 * returns true if a match is found or false if not
108
+	 *
109
+	 * @param string $pattern
110
+	 * @return false|int
111
+	 */
112
+	public function matches($pattern);
113 113
 
114 114
 
115
-    /**
116
-     * remove param
117
-     *
118
-     * @param string $key
119
-     * @param bool   $unset_from_global_too
120
-     */
121
-    public function unSetRequestParam($key, $unset_from_global_too = false);
115
+	/**
116
+	 * remove param
117
+	 *
118
+	 * @param string $key
119
+	 * @param bool   $unset_from_global_too
120
+	 */
121
+	public function unSetRequestParam($key, $unset_from_global_too = false);
122 122
 
123 123
 
124
-    /**
125
-     * @return string
126
-     */
127
-    public function ipAddress();
124
+	/**
125
+	 * @return string
126
+	 */
127
+	public function ipAddress();
128 128
 
129 129
 
130
-    /**
131
-     * @return string
132
-     */
133
-    public function requestUri();
134
-
130
+	/**
131
+	 * @return string
132
+	 */
133
+	public function requestUri();
134
+
135 135
 
136
-    /**
137
-     * @return string
138
-     */
139
-    public function userAgent();
140
-
141
-
142
-    /**
143
-     * @param string $user_agent
144
-     */
145
-    public function setUserAgent($user_agent = '');
146
-
147
-
148
-    /**
149
-     * @return bool
150
-     */
151
-    public function isBot();
152
-
153
-
154
-    /**
155
-     * @param bool $is_bot
156
-     */
157
-    public function setIsBot($is_bot);
136
+	/**
137
+	 * @return string
138
+	 */
139
+	public function userAgent();
140
+
141
+
142
+	/**
143
+	 * @param string $user_agent
144
+	 */
145
+	public function setUserAgent($user_agent = '');
146
+
147
+
148
+	/**
149
+	 * @return bool
150
+	 */
151
+	public function isBot();
152
+
153
+
154
+	/**
155
+	 * @param bool $is_bot
156
+	 */
157
+	public function setIsBot($is_bot);
158 158
 }
Please login to merge, or discard this patch.
core/EE_Error.core.php 2 patches
Spacing   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -102,14 +102,14 @@  discard block
 block discarded – undo
102 102
             default :
103 103
                 $to = get_option('admin_email');
104 104
         }
105
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
105
+        $subject = $type.' '.$message.' in '.EVENT_ESPRESSO_VERSION.' on '.site_url();
106 106
         $msg = EE_Error::_format_error($type, $message, $file, $line);
107 107
         if (function_exists('wp_mail')) {
108 108
             add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
109 109
             wp_mail($to, $subject, $msg);
110 110
         }
111 111
         echo '<div id="message" class="espresso-notices error"><p>';
112
-        echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
112
+        echo $type.': '.$message.'<br />'.$file.' line '.$line;
113 113
         echo '<br /></p></div>';
114 114
     }
115 115
 
@@ -334,7 +334,7 @@  discard block
 block discarded – undo
334 334
 	}
335 335
 </style>
336 336
 <div id="ee-error-message" class="error">';
337
-        if (! WP_DEBUG) {
337
+        if ( ! WP_DEBUG) {
338 338
             $output .= '
339 339
 	<p>';
340 340
         }
@@ -393,14 +393,14 @@  discard block
 block discarded – undo
393 393
                     $class_dsply = ! empty($class) ? $class : '&nbsp;';
394 394
                     $type_dsply = ! empty($type) ? $type : '&nbsp;';
395 395
                     $function_dsply = ! empty($function) ? $function : '&nbsp;';
396
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
396
+                    $args_dsply = ! empty($args) ? '( '.$args.' )' : '';
397 397
                     $trace_details .= '
398 398
 					<tr>
399
-						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
400
-						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
401
-						<td align="left" class="' . $zebra . '">' . $file_dsply . '</td>
402
-						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
403
-						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
399
+						<td align="right" class="' . $zebra.'">'.$nmbr_dsply.'</td>
400
+						<td align="right" class="' . $zebra.'">'.$line_dsply.'</td>
401
+						<td align="left" class="' . $zebra.'">'.$file_dsply.'</td>
402
+						<td align="left" class="' . $zebra.'">'.$class_dsply.'</td>
403
+						<td align="left" class="' . $zebra.'">'.$type_dsply.$function_dsply.$args_dsply.'</td>
404 404
 					</tr>';
405 405
                 }
406 406
                 $trace_details .= '
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
             }
410 410
             $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
411 411
             // add generic non-identifying messages for non-privileged users
412
-            if (! WP_DEBUG) {
412
+            if ( ! WP_DEBUG) {
413 413
                 $output .= '<span class="ee-error-user-msg-spn">'
414 414
                            . trim($ex['msg'])
415 415
                            . '</span> &nbsp; <sup>'
@@ -451,14 +451,14 @@  discard block
 block discarded – undo
451 451
                            . '-dv" class="ee-error-trace-dv" style="display: none;">
452 452
 				'
453 453
                            . $trace_details;
454
-                if (! empty($class)) {
454
+                if ( ! empty($class)) {
455 455
                     $output .= '
456 456
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
457 457
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
458 458
 						<h3>Class Details</h3>';
459 459
                     $a = new ReflectionClass($class);
460 460
                     $output .= '
461
-						<pre>' . $a . '</pre>
461
+						<pre>' . $a.'</pre>
462 462
 					</div>
463 463
 				</div>';
464 464
                 }
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
         }
472 472
         // remove last linebreak
473 473
         $output = substr($output, 0, -6);
474
-        if (! WP_DEBUG) {
474
+        if ( ! WP_DEBUG) {
475 475
             $output .= '
476 476
 	</p>';
477 477
         }
@@ -498,20 +498,20 @@  discard block
 block discarded – undo
498 498
     private function _convert_args_to_string($arguments = array(), $array = false)
499 499
     {
500 500
         $arg_string = '';
501
-        if (! empty($arguments)) {
501
+        if ( ! empty($arguments)) {
502 502
             $args = array();
503 503
             foreach ($arguments as $arg) {
504
-                if (! empty($arg)) {
504
+                if ( ! empty($arg)) {
505 505
                     if (is_string($arg)) {
506
-                        $args[] = " '" . $arg . "'";
506
+                        $args[] = " '".$arg."'";
507 507
                     } elseif (is_array($arg)) {
508
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
508
+                        $args[] = 'ARRAY('.$this->_convert_args_to_string($arg, true);
509 509
                     } elseif ($arg === null) {
510 510
                         $args[] = ' NULL';
511 511
                     } elseif (is_bool($arg)) {
512 512
                         $args[] = ($arg) ? ' TRUE' : ' FALSE';
513 513
                     } elseif (is_object($arg)) {
514
-                        $args[] = ' OBJECT ' . get_class($arg);
514
+                        $args[] = ' OBJECT '.get_class($arg);
515 515
                     } elseif (is_resource($arg)) {
516 516
                         $args[] = get_resource_type($arg);
517 517
                     } else {
@@ -614,7 +614,7 @@  discard block
 block discarded – undo
614 614
     {
615 615
         if (empty($msg)) {
616 616
             EE_Error::doing_it_wrong(
617
-                'EE_Error::add_' . $type . '()',
617
+                'EE_Error::add_'.$type.'()',
618 618
                 sprintf(
619 619
                     __('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
620 620
                         'event_espresso'),
@@ -650,11 +650,11 @@  discard block
 block discarded – undo
650 650
         do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
651 651
         $msg = WP_DEBUG ? $dev_msg : $user_msg;
652 652
         // add notice if message exists
653
-        if (! empty($msg)) {
653
+        if ( ! empty($msg)) {
654 654
             // get error code
655 655
             $notice_code = EE_Error::generate_error_code($file, $func, $line);
656 656
             if (WP_DEBUG && $type === 'errors') {
657
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
657
+                $msg .= '<br/><span class="tiny-text">'.$notice_code.'</span>';
658 658
             }
659 659
             // add notice. Index by code if it's not blank
660 660
             if ($notice_code) {
@@ -868,13 +868,13 @@  discard block
 block discarded – undo
868 868
         if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
869 869
             // combine messages
870 870
             $success_messages .= implode(self::$_espresso_notices['success'], '<br />');
871
-            $print_scripts    = true;
871
+            $print_scripts = true;
872 872
         }
873 873
         // check for attention messages
874 874
         if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
875 875
             // combine messages
876 876
             $attention_messages .= implode(self::$_espresso_notices['attention'], '<br />');
877
-            $print_scripts      = true;
877
+            $print_scripts = true;
878 878
         }
879 879
         // check for error messages
880 880
         if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
@@ -883,7 +883,7 @@  discard block
 block discarded – undo
883 883
                 : __('An error has occurred:<br />', 'event_espresso');
884 884
             // combine messages
885 885
             $error_messages .= implode(self::$_espresso_notices['errors'], '<br />');
886
-            $print_scripts  = true;
886
+            $print_scripts = true;
887 887
         }
888 888
         if ($format_output) {
889 889
             $notices = EE_Error::formatNoticesOutput(
@@ -924,16 +924,16 @@  discard block
 block discarded – undo
924 924
         $print_scripts = false;
925 925
         // grab any notices that have been previously saved
926 926
         $notices = EE_Error::getStoredNotices();
927
-        if (! empty($notices)) {
927
+        if ( ! empty($notices)) {
928 928
             foreach ($notices as $type => $notice) {
929 929
                 if (is_array($notice) && ! empty($notice)) {
930 930
                     // make sure that existing notice type is an array
931
-                    self::$_espresso_notices[ $type ] = is_array(self::$_espresso_notices[ $type ])
932
-                                                        && ! empty(self::$_espresso_notices[ $type ])
933
-                        ? self::$_espresso_notices[ $type ]
931
+                    self::$_espresso_notices[$type] = is_array(self::$_espresso_notices[$type])
932
+                                                        && ! empty(self::$_espresso_notices[$type])
933
+                        ? self::$_espresso_notices[$type]
934 934
                         : array();
935 935
                     // add newly created notices to existing ones
936
-                    self::$_espresso_notices[ $type ] += $notice;
936
+                    self::$_espresso_notices[$type] += $notice;
937 937
                     $print_scripts = true;
938 938
                 }
939 939
             }
@@ -960,10 +960,10 @@  discard block
 block discarded – undo
960 960
             $css_id    = is_admin() ? 'message' : 'espresso-notices-success';
961 961
             $css_class = is_admin() ? 'updated fade' : 'success fade-away';
962 962
             //showMessage( $success_messages );
963
-            $notices .= '<div id="' . $css_id . '" '
964
-                        . 'class="espresso-notices ' . $css_class . '" '
963
+            $notices .= '<div id="'.$css_id.'" '
964
+                        . 'class="espresso-notices '.$css_class.'" '
965 965
                         . 'style="display:none;">'
966
-                        . '<p>' . $success_messages . '</p>'
966
+                        . '<p>'.$success_messages.'</p>'
967 967
                         . $close
968 968
                         . '</div>';
969 969
         }
@@ -971,10 +971,10 @@  discard block
 block discarded – undo
971 971
             $css_id    = is_admin() ? 'message' : 'espresso-notices-attention';
972 972
             $css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
973 973
             //showMessage( $error_messages, TRUE );
974
-            $notices .= '<div id="' . $css_id . '" '
975
-                        . 'class="espresso-notices ' . $css_class . '" '
974
+            $notices .= '<div id="'.$css_id.'" '
975
+                        . 'class="espresso-notices '.$css_class.'" '
976 976
                         . 'style="display:none;">'
977
-                        . '<p>' . $attention_messages . '</p>'
977
+                        . '<p>'.$attention_messages.'</p>'
978 978
                         . $close
979 979
                         . '</div>';
980 980
         }
@@ -982,10 +982,10 @@  discard block
 block discarded – undo
982 982
             $css_id    = is_admin() ? 'message' : 'espresso-notices-error';
983 983
             $css_class = is_admin() ? 'error' : 'error fade-away';
984 984
             //showMessage( $error_messages, TRUE );
985
-            $notices .= '<div id="' . $css_id . '" '
986
-                        . 'class="espresso-notices ' . $css_class . '" '
985
+            $notices .= '<div id="'.$css_id.'" '
986
+                        . 'class="espresso-notices '.$css_class.'" '
987 987
                         . 'style="display:none;">'
988
-                        . '<p>' . $error_messages . '</p>'
988
+                        . '<p>'.$error_messages.'</p>'
989 989
                         . $close
990 990
                         . '</div>';
991 991
         }
@@ -1003,7 +1003,7 @@  discard block
 block discarded – undo
1003 1003
      */
1004 1004
     private static function _print_scripts($force_print = false)
1005 1005
     {
1006
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
1006
+        if ( ! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
1007 1007
             if (wp_script_is('ee_error_js', 'enqueued')) {
1008 1008
                 return '';
1009 1009
             }
@@ -1017,12 +1017,12 @@  discard block
 block discarded – undo
1017 1017
             return '
1018 1018
 <script>
1019 1019
 /* <![CDATA[ */
1020
-var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
1020
+var ee_settings = {"wp_debug":"' . WP_DEBUG.'"};
1021 1021
 /* ]]> */
1022 1022
 </script>
1023
-<script src="' . includes_url() . 'js/jquery/jquery.js" type="text/javascript"></script>
1024
-<script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
1025
-<script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
1023
+<script src="' . includes_url().'js/jquery/jquery.js" type="text/javascript"></script>
1024
+<script src="' . EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js'.'?ver='.espresso_version().'" type="text/javascript"></script>
1025
+<script src="' . EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js'.'?ver='.espresso_version().'" type="text/javascript"></script>
1026 1026
 ';
1027 1027
         }
1028 1028
         return '';
@@ -1053,8 +1053,8 @@  discard block
 block discarded – undo
1053 1053
     {
1054 1054
         $file       = explode('.', basename($file));
1055 1055
         $error_code = ! empty($file[0]) ? $file[0] : '';
1056
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
1057
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
1056
+        $error_code .= ! empty($func) ? ' - '.$func : '';
1057
+        $error_code .= ! empty($line) ? ' - '.$line : '';
1058 1058
         return $error_code;
1059 1059
     }
1060 1060
 
@@ -1074,18 +1074,18 @@  discard block
 block discarded – undo
1074 1074
         if (empty($ex)) {
1075 1075
             return;
1076 1076
         }
1077
-        if (! $time) {
1077
+        if ( ! $time) {
1078 1078
             $time = time();
1079 1079
         }
1080 1080
         $exception_log = '----------------------------------------------------------------------------------------'
1081 1081
                          . PHP_EOL;
1082
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1083
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1084
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1085
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1086
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1087
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
1088
-        $exception_log .= $ex['string'] . PHP_EOL;
1082
+        $exception_log .= '['.date('Y-m-d H:i:s', $time).']  Exception Details'.PHP_EOL;
1083
+        $exception_log .= 'Message: '.$ex['msg'].PHP_EOL;
1084
+        $exception_log .= 'Code: '.$ex['code'].PHP_EOL;
1085
+        $exception_log .= 'File: '.$ex['file'].PHP_EOL;
1086
+        $exception_log .= 'Line No: '.$ex['line'].PHP_EOL;
1087
+        $exception_log .= 'Stack trace: '.PHP_EOL;
1088
+        $exception_log .= $ex['string'].PHP_EOL;
1089 1089
         $exception_log .= '----------------------------------------------------------------------------------------'
1090 1090
                           . PHP_EOL;
1091 1091
         try {
@@ -1258,14 +1258,14 @@  discard block
 block discarded – undo
1258 1258
     // js for error handling
1259 1259
     wp_register_script(
1260 1260
         'espresso_core',
1261
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1261
+        EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
1262 1262
         array('jquery'),
1263 1263
         EVENT_ESPRESSO_VERSION,
1264 1264
         false
1265 1265
     );
1266 1266
     wp_register_script(
1267 1267
         'ee_error_js',
1268
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1268
+        EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js',
1269 1269
         array('espresso_core'),
1270 1270
         EVENT_ESPRESSO_VERSION,
1271 1271
         false
Please login to merge, or discard this patch.
Indentation   +1142 added lines, -1142 removed lines patch added patch discarded remove patch
@@ -11,8 +11,8 @@  discard block
 block discarded – undo
11 11
 // if you're a dev and want to receive all errors via email
12 12
 // add this to your wp-config.php: define( 'EE_ERROR_EMAILS', TRUE );
13 13
 if (defined('WP_DEBUG') && WP_DEBUG === true && defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS === true) {
14
-    set_error_handler(array('EE_Error', 'error_handler'));
15
-    register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
14
+	set_error_handler(array('EE_Error', 'error_handler'));
15
+	register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
16 16
 }
17 17
 
18 18
 
@@ -27,258 +27,258 @@  discard block
 block discarded – undo
27 27
 class EE_Error extends Exception
28 28
 {
29 29
 
30
-    const OPTIONS_KEY_NOTICES = 'ee_notices';
31
-
32
-
33
-    /**
34
-     * name of the file to log exceptions to
35
-     *
36
-     * @var string
37
-     */
38
-    private static $_exception_log_file = 'espresso_error_log.txt';
39
-
40
-    /**
41
-     *    stores details for all exception
42
-     *
43
-     * @var array
44
-     */
45
-    private static $_all_exceptions = array();
46
-
47
-    /**
48
-     *    tracks number of errors
49
-     *
50
-     * @var int
51
-     */
52
-    private static $_error_count = 0;
53
-
54
-    /**
55
-     * @var array $_espresso_notices
56
-     */
57
-    private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
58
-
59
-
60
-
61
-    /**
62
-     * @override default exception handling
63
-     * @param string         $message
64
-     * @param int            $code
65
-     * @param Exception|null $previous
66
-     */
67
-    public function __construct($message, $code = 0, Exception $previous = null)
68
-    {
69
-        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
70
-            parent::__construct($message, $code);
71
-        } else {
72
-            parent::__construct($message, $code, $previous);
73
-        }
74
-    }
75
-
76
-
77
-    /**
78
-     *    error_handler
79
-     *
80
-     * @param $code
81
-     * @param $message
82
-     * @param $file
83
-     * @param $line
84
-     * @return void
85
-     */
86
-    public static function error_handler($code, $message, $file, $line)
87
-    {
88
-        $type = EE_Error::error_type($code);
89
-        $site = site_url();
90
-        switch ($site) {
91
-            case 'http://ee4.eventespresso.com/' :
92
-            case 'http://ee4decaf.eventespresso.com/' :
93
-            case 'http://ee4hf.eventespresso.com/' :
94
-            case 'http://ee4a.eventespresso.com/' :
95
-            case 'http://ee4ad.eventespresso.com/' :
96
-            case 'http://ee4b.eventespresso.com/' :
97
-            case 'http://ee4bd.eventespresso.com/' :
98
-            case 'http://ee4d.eventespresso.com/' :
99
-            case 'http://ee4dd.eventespresso.com/' :
100
-                $to = '[email protected]';
101
-                break;
102
-            default :
103
-                $to = get_option('admin_email');
104
-        }
105
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
106
-        $msg = EE_Error::_format_error($type, $message, $file, $line);
107
-        if (function_exists('wp_mail')) {
108
-            add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
109
-            wp_mail($to, $subject, $msg);
110
-        }
111
-        echo '<div id="message" class="espresso-notices error"><p>';
112
-        echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
113
-        echo '<br /></p></div>';
114
-    }
115
-
116
-
117
-
118
-    /**
119
-     * error_type
120
-     * http://www.php.net/manual/en/errorfunc.constants.php#109430
121
-     *
122
-     * @param $code
123
-     * @return string
124
-     */
125
-    public static function error_type($code)
126
-    {
127
-        switch ($code) {
128
-            case E_ERROR: // 1 //
129
-                return 'E_ERROR';
130
-            case E_WARNING: // 2 //
131
-                return 'E_WARNING';
132
-            case E_PARSE: // 4 //
133
-                return 'E_PARSE';
134
-            case E_NOTICE: // 8 //
135
-                return 'E_NOTICE';
136
-            case E_CORE_ERROR: // 16 //
137
-                return 'E_CORE_ERROR';
138
-            case E_CORE_WARNING: // 32 //
139
-                return 'E_CORE_WARNING';
140
-            case E_COMPILE_ERROR: // 64 //
141
-                return 'E_COMPILE_ERROR';
142
-            case E_COMPILE_WARNING: // 128 //
143
-                return 'E_COMPILE_WARNING';
144
-            case E_USER_ERROR: // 256 //
145
-                return 'E_USER_ERROR';
146
-            case E_USER_WARNING: // 512 //
147
-                return 'E_USER_WARNING';
148
-            case E_USER_NOTICE: // 1024 //
149
-                return 'E_USER_NOTICE';
150
-            case E_STRICT: // 2048 //
151
-                return 'E_STRICT';
152
-            case E_RECOVERABLE_ERROR: // 4096 //
153
-                return 'E_RECOVERABLE_ERROR';
154
-            case E_DEPRECATED: // 8192 //
155
-                return 'E_DEPRECATED';
156
-            case E_USER_DEPRECATED: // 16384 //
157
-                return 'E_USER_DEPRECATED';
158
-            case E_ALL: // 16384 //
159
-                return 'E_ALL';
160
-        }
161
-        return '';
162
-    }
163
-
164
-
165
-
166
-    /**
167
-     *    fatal_error_handler
168
-     *
169
-     * @return void
170
-     */
171
-    public static function fatal_error_handler()
172
-    {
173
-        $last_error = error_get_last();
174
-        if ($last_error['type'] === E_ERROR) {
175
-            EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
176
-        }
177
-    }
178
-
179
-
180
-
181
-    /**
182
-     * _format_error
183
-     *
184
-     * @param $code
185
-     * @param $message
186
-     * @param $file
187
-     * @param $line
188
-     * @return string
189
-     */
190
-    private static function _format_error($code, $message, $file, $line)
191
-    {
192
-        $html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
193
-        $html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
194
-        $html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
195
-        $html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
196
-        $html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
197
-        $html .= '</tbody></table>';
198
-        return $html;
199
-    }
200
-
201
-
202
-
203
-    /**
204
-     * set_content_type
205
-     *
206
-     * @param $content_type
207
-     * @return string
208
-     */
209
-    public static function set_content_type($content_type)
210
-    {
211
-        return 'text/html';
212
-    }
213
-
214
-
215
-
216
-    /**
217
-     * @return void
218
-     * @throws EE_Error
219
-     * @throws ReflectionException
220
-     */
221
-    public function get_error()
222
-    {
223
-        if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
224
-            throw $this;
225
-        }
226
-        // get separate user and developer messages if they exist
227
-        $msg = explode('||', $this->getMessage());
228
-        $user_msg = $msg[0];
229
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
230
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
231
-        // add details to _all_exceptions array
232
-        $x_time = time();
233
-        self::$_all_exceptions[$x_time]['name'] = get_class($this);
234
-        self::$_all_exceptions[$x_time]['file'] = $this->getFile();
235
-        self::$_all_exceptions[$x_time]['line'] = $this->getLine();
236
-        self::$_all_exceptions[$x_time]['msg'] = $msg;
237
-        self::$_all_exceptions[$x_time]['code'] = $this->getCode();
238
-        self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
239
-        self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
240
-        self::$_error_count++;
241
-        //add_action( 'shutdown', array( $this, 'display_errors' ));
242
-        $this->display_errors();
243
-    }
244
-
245
-
246
-    /**
247
-     * @param bool   $check_stored
248
-     * @param string $type_to_check
249
-     * @return bool
250
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
251
-     * @throws \InvalidArgumentException
252
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
253
-     * @throws InvalidInterfaceException
254
-     */
255
-    public static function has_error($check_stored = false, $type_to_check = 'errors')
256
-    {
257
-        $has_error = isset(self::$_espresso_notices[$type_to_check])
258
-                     && ! empty(self::$_espresso_notices[$type_to_check])
259
-            ? true
260
-            : false;
261
-        if ($check_stored && ! $has_error) {
262
-            $notices = EE_Error::getStoredNotices();
263
-            foreach ($notices as $type => $notice) {
264
-                if ($type === $type_to_check && $notice) {
265
-                    return true;
266
-                }
267
-            }
268
-        }
269
-        return $has_error;
270
-    }
271
-
272
-
273
-
274
-    /**
275
-     * @echo string
276
-     * @throws \ReflectionException
277
-     */
278
-    public function display_errors()
279
-    {
280
-        $trace_details = '';
281
-        $output = '
30
+	const OPTIONS_KEY_NOTICES = 'ee_notices';
31
+
32
+
33
+	/**
34
+	 * name of the file to log exceptions to
35
+	 *
36
+	 * @var string
37
+	 */
38
+	private static $_exception_log_file = 'espresso_error_log.txt';
39
+
40
+	/**
41
+	 *    stores details for all exception
42
+	 *
43
+	 * @var array
44
+	 */
45
+	private static $_all_exceptions = array();
46
+
47
+	/**
48
+	 *    tracks number of errors
49
+	 *
50
+	 * @var int
51
+	 */
52
+	private static $_error_count = 0;
53
+
54
+	/**
55
+	 * @var array $_espresso_notices
56
+	 */
57
+	private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
58
+
59
+
60
+
61
+	/**
62
+	 * @override default exception handling
63
+	 * @param string         $message
64
+	 * @param int            $code
65
+	 * @param Exception|null $previous
66
+	 */
67
+	public function __construct($message, $code = 0, Exception $previous = null)
68
+	{
69
+		if (version_compare(PHP_VERSION, '5.3.0', '<')) {
70
+			parent::__construct($message, $code);
71
+		} else {
72
+			parent::__construct($message, $code, $previous);
73
+		}
74
+	}
75
+
76
+
77
+	/**
78
+	 *    error_handler
79
+	 *
80
+	 * @param $code
81
+	 * @param $message
82
+	 * @param $file
83
+	 * @param $line
84
+	 * @return void
85
+	 */
86
+	public static function error_handler($code, $message, $file, $line)
87
+	{
88
+		$type = EE_Error::error_type($code);
89
+		$site = site_url();
90
+		switch ($site) {
91
+			case 'http://ee4.eventespresso.com/' :
92
+			case 'http://ee4decaf.eventespresso.com/' :
93
+			case 'http://ee4hf.eventespresso.com/' :
94
+			case 'http://ee4a.eventespresso.com/' :
95
+			case 'http://ee4ad.eventespresso.com/' :
96
+			case 'http://ee4b.eventespresso.com/' :
97
+			case 'http://ee4bd.eventespresso.com/' :
98
+			case 'http://ee4d.eventespresso.com/' :
99
+			case 'http://ee4dd.eventespresso.com/' :
100
+				$to = '[email protected]';
101
+				break;
102
+			default :
103
+				$to = get_option('admin_email');
104
+		}
105
+		$subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
106
+		$msg = EE_Error::_format_error($type, $message, $file, $line);
107
+		if (function_exists('wp_mail')) {
108
+			add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
109
+			wp_mail($to, $subject, $msg);
110
+		}
111
+		echo '<div id="message" class="espresso-notices error"><p>';
112
+		echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
113
+		echo '<br /></p></div>';
114
+	}
115
+
116
+
117
+
118
+	/**
119
+	 * error_type
120
+	 * http://www.php.net/manual/en/errorfunc.constants.php#109430
121
+	 *
122
+	 * @param $code
123
+	 * @return string
124
+	 */
125
+	public static function error_type($code)
126
+	{
127
+		switch ($code) {
128
+			case E_ERROR: // 1 //
129
+				return 'E_ERROR';
130
+			case E_WARNING: // 2 //
131
+				return 'E_WARNING';
132
+			case E_PARSE: // 4 //
133
+				return 'E_PARSE';
134
+			case E_NOTICE: // 8 //
135
+				return 'E_NOTICE';
136
+			case E_CORE_ERROR: // 16 //
137
+				return 'E_CORE_ERROR';
138
+			case E_CORE_WARNING: // 32 //
139
+				return 'E_CORE_WARNING';
140
+			case E_COMPILE_ERROR: // 64 //
141
+				return 'E_COMPILE_ERROR';
142
+			case E_COMPILE_WARNING: // 128 //
143
+				return 'E_COMPILE_WARNING';
144
+			case E_USER_ERROR: // 256 //
145
+				return 'E_USER_ERROR';
146
+			case E_USER_WARNING: // 512 //
147
+				return 'E_USER_WARNING';
148
+			case E_USER_NOTICE: // 1024 //
149
+				return 'E_USER_NOTICE';
150
+			case E_STRICT: // 2048 //
151
+				return 'E_STRICT';
152
+			case E_RECOVERABLE_ERROR: // 4096 //
153
+				return 'E_RECOVERABLE_ERROR';
154
+			case E_DEPRECATED: // 8192 //
155
+				return 'E_DEPRECATED';
156
+			case E_USER_DEPRECATED: // 16384 //
157
+				return 'E_USER_DEPRECATED';
158
+			case E_ALL: // 16384 //
159
+				return 'E_ALL';
160
+		}
161
+		return '';
162
+	}
163
+
164
+
165
+
166
+	/**
167
+	 *    fatal_error_handler
168
+	 *
169
+	 * @return void
170
+	 */
171
+	public static function fatal_error_handler()
172
+	{
173
+		$last_error = error_get_last();
174
+		if ($last_error['type'] === E_ERROR) {
175
+			EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
176
+		}
177
+	}
178
+
179
+
180
+
181
+	/**
182
+	 * _format_error
183
+	 *
184
+	 * @param $code
185
+	 * @param $message
186
+	 * @param $file
187
+	 * @param $line
188
+	 * @return string
189
+	 */
190
+	private static function _format_error($code, $message, $file, $line)
191
+	{
192
+		$html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
193
+		$html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
194
+		$html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
195
+		$html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
196
+		$html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
197
+		$html .= '</tbody></table>';
198
+		return $html;
199
+	}
200
+
201
+
202
+
203
+	/**
204
+	 * set_content_type
205
+	 *
206
+	 * @param $content_type
207
+	 * @return string
208
+	 */
209
+	public static function set_content_type($content_type)
210
+	{
211
+		return 'text/html';
212
+	}
213
+
214
+
215
+
216
+	/**
217
+	 * @return void
218
+	 * @throws EE_Error
219
+	 * @throws ReflectionException
220
+	 */
221
+	public function get_error()
222
+	{
223
+		if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
224
+			throw $this;
225
+		}
226
+		// get separate user and developer messages if they exist
227
+		$msg = explode('||', $this->getMessage());
228
+		$user_msg = $msg[0];
229
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
230
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
231
+		// add details to _all_exceptions array
232
+		$x_time = time();
233
+		self::$_all_exceptions[$x_time]['name'] = get_class($this);
234
+		self::$_all_exceptions[$x_time]['file'] = $this->getFile();
235
+		self::$_all_exceptions[$x_time]['line'] = $this->getLine();
236
+		self::$_all_exceptions[$x_time]['msg'] = $msg;
237
+		self::$_all_exceptions[$x_time]['code'] = $this->getCode();
238
+		self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
239
+		self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
240
+		self::$_error_count++;
241
+		//add_action( 'shutdown', array( $this, 'display_errors' ));
242
+		$this->display_errors();
243
+	}
244
+
245
+
246
+	/**
247
+	 * @param bool   $check_stored
248
+	 * @param string $type_to_check
249
+	 * @return bool
250
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
251
+	 * @throws \InvalidArgumentException
252
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
253
+	 * @throws InvalidInterfaceException
254
+	 */
255
+	public static function has_error($check_stored = false, $type_to_check = 'errors')
256
+	{
257
+		$has_error = isset(self::$_espresso_notices[$type_to_check])
258
+					 && ! empty(self::$_espresso_notices[$type_to_check])
259
+			? true
260
+			: false;
261
+		if ($check_stored && ! $has_error) {
262
+			$notices = EE_Error::getStoredNotices();
263
+			foreach ($notices as $type => $notice) {
264
+				if ($type === $type_to_check && $notice) {
265
+					return true;
266
+				}
267
+			}
268
+		}
269
+		return $has_error;
270
+	}
271
+
272
+
273
+
274
+	/**
275
+	 * @echo string
276
+	 * @throws \ReflectionException
277
+	 */
278
+	public function display_errors()
279
+	{
280
+		$trace_details = '';
281
+		$output = '
282 282
 <style type="text/css">
283 283
 	#ee-error-message {
284 284
 		max-width:90% !important;
@@ -334,21 +334,21 @@  discard block
 block discarded – undo
334 334
 	}
335 335
 </style>
336 336
 <div id="ee-error-message" class="error">';
337
-        if (! WP_DEBUG) {
338
-            $output .= '
337
+		if (! WP_DEBUG) {
338
+			$output .= '
339 339
 	<p>';
340
-        }
341
-        // cycle thru errors
342
-        foreach (self::$_all_exceptions as $time => $ex) {
343
-            $error_code = '';
344
-            // process trace info
345
-            if (empty($ex['trace'])) {
346
-                $trace_details .= __(
347
-                    'Sorry, but no trace information was available for this exception.',
348
-                    'event_espresso'
349
-                );
350
-            } else {
351
-                $trace_details .= '
340
+		}
341
+		// cycle thru errors
342
+		foreach (self::$_all_exceptions as $time => $ex) {
343
+			$error_code = '';
344
+			// process trace info
345
+			if (empty($ex['trace'])) {
346
+				$trace_details .= __(
347
+					'Sorry, but no trace information was available for this exception.',
348
+					'event_espresso'
349
+				);
350
+			} else {
351
+				$trace_details .= '
352 352
 			<div id="ee-trace-details">
353 353
 			<table width="100%" border="0" cellpadding="5" cellspacing="0">
354 354
 				<tr>
@@ -358,43 +358,43 @@  discard block
 block discarded – undo
358 358
 					<th scope="col" align="left">Class</th>
359 359
 					<th scope="col" align="left">Method( arguments )</th>
360 360
 				</tr>';
361
-                $last_on_stack = count($ex['trace']) - 1;
362
-                // reverse array so that stack is in proper chronological order
363
-                $sorted_trace = array_reverse($ex['trace']);
364
-                foreach ($sorted_trace as $nmbr => $trace) {
365
-                    $file = isset($trace['file']) ? $trace['file'] : '';
366
-                    $class = isset($trace['class']) ? $trace['class'] : '';
367
-                    $type = isset($trace['type']) ? $trace['type'] : '';
368
-                    $function = isset($trace['function']) ? $trace['function'] : '';
369
-                    $args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
370
-                    $line = isset($trace['line']) ? $trace['line'] : '';
371
-                    $zebra = ($nmbr % 2) ? ' odd' : '';
372
-                    if (empty($file) && ! empty($class)) {
373
-                        $a = new ReflectionClass($class);
374
-                        $file = $a->getFileName();
375
-                        if (empty($line) && ! empty($function)) {
376
-                            try {
377
-                                //if $function is a closure, this throws an exception
378
-                                $b = new ReflectionMethod($class, $function);
379
-                                $line = $b->getStartLine();
380
-                            } catch (Exception $closure_exception) {
381
-                                $line = 'unknown';
382
-                            }
383
-                        }
384
-                    }
385
-                    if ($nmbr === $last_on_stack) {
386
-                        $file = $ex['file'] !== '' ? $ex['file'] : $file;
387
-                        $line = $ex['line'] !== '' ? $ex['line'] : $line;
388
-                        $error_code = self::generate_error_code($file, $trace['function'], $line);
389
-                    }
390
-                    $nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
391
-                    $line_dsply = ! empty($line) ? $line : '&nbsp;';
392
-                    $file_dsply = ! empty($file) ? $file : '&nbsp;';
393
-                    $class_dsply = ! empty($class) ? $class : '&nbsp;';
394
-                    $type_dsply = ! empty($type) ? $type : '&nbsp;';
395
-                    $function_dsply = ! empty($function) ? $function : '&nbsp;';
396
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
397
-                    $trace_details .= '
361
+				$last_on_stack = count($ex['trace']) - 1;
362
+				// reverse array so that stack is in proper chronological order
363
+				$sorted_trace = array_reverse($ex['trace']);
364
+				foreach ($sorted_trace as $nmbr => $trace) {
365
+					$file = isset($trace['file']) ? $trace['file'] : '';
366
+					$class = isset($trace['class']) ? $trace['class'] : '';
367
+					$type = isset($trace['type']) ? $trace['type'] : '';
368
+					$function = isset($trace['function']) ? $trace['function'] : '';
369
+					$args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
370
+					$line = isset($trace['line']) ? $trace['line'] : '';
371
+					$zebra = ($nmbr % 2) ? ' odd' : '';
372
+					if (empty($file) && ! empty($class)) {
373
+						$a = new ReflectionClass($class);
374
+						$file = $a->getFileName();
375
+						if (empty($line) && ! empty($function)) {
376
+							try {
377
+								//if $function is a closure, this throws an exception
378
+								$b = new ReflectionMethod($class, $function);
379
+								$line = $b->getStartLine();
380
+							} catch (Exception $closure_exception) {
381
+								$line = 'unknown';
382
+							}
383
+						}
384
+					}
385
+					if ($nmbr === $last_on_stack) {
386
+						$file = $ex['file'] !== '' ? $ex['file'] : $file;
387
+						$line = $ex['line'] !== '' ? $ex['line'] : $line;
388
+						$error_code = self::generate_error_code($file, $trace['function'], $line);
389
+					}
390
+					$nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
391
+					$line_dsply = ! empty($line) ? $line : '&nbsp;';
392
+					$file_dsply = ! empty($file) ? $file : '&nbsp;';
393
+					$class_dsply = ! empty($class) ? $class : '&nbsp;';
394
+					$type_dsply = ! empty($type) ? $type : '&nbsp;';
395
+					$function_dsply = ! empty($function) ? $function : '&nbsp;';
396
+					$args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
397
+					$trace_details .= '
398 398
 					<tr>
399 399
 						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
400 400
 						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
@@ -402,633 +402,633 @@  discard block
 block discarded – undo
402 402
 						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
403 403
 						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
404 404
 					</tr>';
405
-                }
406
-                $trace_details .= '
405
+				}
406
+				$trace_details .= '
407 407
 			 </table>
408 408
 			</div>';
409
-            }
410
-            $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
411
-            // add generic non-identifying messages for non-privileged users
412
-            if (! WP_DEBUG) {
413
-                $output .= '<span class="ee-error-user-msg-spn">'
414
-                           . trim($ex['msg'])
415
-                           . '</span> &nbsp; <sup>'
416
-                           . $ex['code']
417
-                           . '</sup><br />';
418
-            } else {
419
-                // or helpful developer messages if debugging is on
420
-                $output .= '
409
+			}
410
+			$ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
411
+			// add generic non-identifying messages for non-privileged users
412
+			if (! WP_DEBUG) {
413
+				$output .= '<span class="ee-error-user-msg-spn">'
414
+						   . trim($ex['msg'])
415
+						   . '</span> &nbsp; <sup>'
416
+						   . $ex['code']
417
+						   . '</sup><br />';
418
+			} else {
419
+				// or helpful developer messages if debugging is on
420
+				$output .= '
421 421
 		<div class="ee-error-dev-msg-dv">
422 422
 			<p class="ee-error-dev-msg-pg">
423 423
 				<strong class="ee-error-dev-msg-str">An '
424
-                           . $ex['name']
425
-                           . ' exception was thrown!</strong>  &nbsp; <span>code: '
426
-                           . $ex['code']
427
-                           . '</span><br />
424
+						   . $ex['name']
425
+						   . ' exception was thrown!</strong>  &nbsp; <span>code: '
426
+						   . $ex['code']
427
+						   . '</span><br />
428 428
 				<span class="big-text">"'
429
-                           . trim($ex['msg'])
430
-                           . '"</span><br/>
429
+						   . trim($ex['msg'])
430
+						   . '"</span><br/>
431 431
 				<a id="display-ee-error-trace-'
432
-                           . self::$_error_count
433
-                           . $time
434
-                           . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
435
-                           . self::$_error_count
436
-                           . $time
437
-                           . '">
432
+						   . self::$_error_count
433
+						   . $time
434
+						   . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
435
+						   . self::$_error_count
436
+						   . $time
437
+						   . '">
438 438
 					'
439
-                           . __('click to view backtrace and class/method details', 'event_espresso')
440
-                           . '
439
+						   . __('click to view backtrace and class/method details', 'event_espresso')
440
+						   . '
441 441
 				</a><br />
442 442
 				<span class="small-text lt-grey-text">'
443
-                           . $ex['file']
444
-                           . ' &nbsp; ( line no: '
445
-                           . $ex['line']
446
-                           . ' )</span>
443
+						   . $ex['file']
444
+						   . ' &nbsp; ( line no: '
445
+						   . $ex['line']
446
+						   . ' )</span>
447 447
 			</p>
448 448
 			<div id="ee-error-trace-'
449
-                           . self::$_error_count
450
-                           . $time
451
-                           . '-dv" class="ee-error-trace-dv" style="display: none;">
449
+						   . self::$_error_count
450
+						   . $time
451
+						   . '-dv" class="ee-error-trace-dv" style="display: none;">
452 452
 				'
453
-                           . $trace_details;
454
-                if (! empty($class)) {
455
-                    $output .= '
453
+						   . $trace_details;
454
+				if (! empty($class)) {
455
+					$output .= '
456 456
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
457 457
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
458 458
 						<h3>Class Details</h3>';
459
-                    $a = new ReflectionClass($class);
460
-                    $output .= '
459
+					$a = new ReflectionClass($class);
460
+					$output .= '
461 461
 						<pre>' . $a . '</pre>
462 462
 					</div>
463 463
 				</div>';
464
-                }
465
-                $output .= '
464
+				}
465
+				$output .= '
466 466
 			</div>
467 467
 		</div>
468 468
 		<br />';
469
-            }
470
-            $this->write_to_error_log($time, $ex);
471
-        }
472
-        // remove last linebreak
473
-        $output = substr($output, 0, -6);
474
-        if (! WP_DEBUG) {
475
-            $output .= '
469
+			}
470
+			$this->write_to_error_log($time, $ex);
471
+		}
472
+		// remove last linebreak
473
+		$output = substr($output, 0, -6);
474
+		if (! WP_DEBUG) {
475
+			$output .= '
476 476
 	</p>';
477
-        }
478
-        $output .= '
477
+		}
478
+		$output .= '
479 479
 </div>';
480
-        $output .= self::_print_scripts(true);
481
-        if (defined('DOING_AJAX')) {
482
-            echo wp_json_encode(array('error' => $output));
483
-            exit();
484
-        }
485
-        echo $output;
486
-        die();
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     *    generate string from exception trace args
493
-     *
494
-     * @param array $arguments
495
-     * @param bool  $array
496
-     * @return string
497
-     */
498
-    private function _convert_args_to_string($arguments = array(), $array = false)
499
-    {
500
-        $arg_string = '';
501
-        if (! empty($arguments)) {
502
-            $args = array();
503
-            foreach ($arguments as $arg) {
504
-                if (! empty($arg)) {
505
-                    if (is_string($arg)) {
506
-                        $args[] = " '" . $arg . "'";
507
-                    } elseif (is_array($arg)) {
508
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
509
-                    } elseif ($arg === null) {
510
-                        $args[] = ' NULL';
511
-                    } elseif (is_bool($arg)) {
512
-                        $args[] = ($arg) ? ' TRUE' : ' FALSE';
513
-                    } elseif (is_object($arg)) {
514
-                        $args[] = ' OBJECT ' . get_class($arg);
515
-                    } elseif (is_resource($arg)) {
516
-                        $args[] = get_resource_type($arg);
517
-                    } else {
518
-                        $args[] = $arg;
519
-                    }
520
-                }
521
-            }
522
-            $arg_string = implode(', ', $args);
523
-        }
524
-        if ($array) {
525
-            $arg_string .= ' )';
526
-        }
527
-        return $arg_string;
528
-    }
529
-
530
-
531
-
532
-    /**
533
-     *    add error message
534
-     *
535
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
536
-     *                            separate messages for user || dev
537
-     * @param        string $file the file that the error occurred in - just use __FILE__
538
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
539
-     * @param        string $line the line number where the error occurred - just use __LINE__
540
-     * @return        void
541
-     */
542
-    public static function add_error($msg = null, $file = null, $func = null, $line = null)
543
-    {
544
-        self::_add_notice('errors', $msg, $file, $func, $line);
545
-        self::$_error_count++;
546
-    }
547
-
548
-
549
-
550
-    /**
551
-     * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
552
-     * adds an error
553
-     *
554
-     * @param string $msg
555
-     * @param string $file
556
-     * @param string $func
557
-     * @param string $line
558
-     * @throws EE_Error
559
-     */
560
-    public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
561
-    {
562
-        if (WP_DEBUG) {
563
-            throw new EE_Error($msg);
564
-        }
565
-        EE_Error::add_error($msg, $file, $func, $line);
566
-    }
567
-
568
-
569
-
570
-    /**
571
-     *    add success message
572
-     *
573
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
574
-     *                            separate messages for user || dev
575
-     * @param        string $file the file that the error occurred in - just use __FILE__
576
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
577
-     * @param        string $line the line number where the error occurred - just use __LINE__
578
-     * @return        void
579
-     */
580
-    public static function add_success($msg = null, $file = null, $func = null, $line = null)
581
-    {
582
-        self::_add_notice('success', $msg, $file, $func, $line);
583
-    }
584
-
585
-
586
-
587
-    /**
588
-     *    add attention message
589
-     *
590
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
591
-     *                            separate messages for user || dev
592
-     * @param        string $file the file that the error occurred in - just use __FILE__
593
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
594
-     * @param        string $line the line number where the error occurred - just use __LINE__
595
-     * @return        void
596
-     */
597
-    public static function add_attention($msg = null, $file = null, $func = null, $line = null)
598
-    {
599
-        self::_add_notice('attention', $msg, $file, $func, $line);
600
-    }
601
-
602
-
603
-
604
-    /**
605
-     * @param string $type whether the message is for a success or error notification
606
-     * @param string $msg the message to display to users or developers
607
-     *                    - adding a double pipe || (OR) creates separate messages for user || dev
608
-     * @param string $file the file that the error occurred in - just use __FILE__
609
-     * @param string $func the function/method that the error occurred in - just use __FUNCTION__
610
-     * @param string $line the line number where the error occurred - just use __LINE__
611
-     * @return void
612
-     */
613
-    private static function _add_notice($type = 'success', $msg = '', $file = '', $func = '', $line = '')
614
-    {
615
-        if (empty($msg)) {
616
-            EE_Error::doing_it_wrong(
617
-                'EE_Error::add_' . $type . '()',
618
-                sprintf(
619
-                    __('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
620
-                        'event_espresso'),
621
-                    $type,
622
-                    $file,
623
-                    $line
624
-                ),
625
-                EVENT_ESPRESSO_VERSION
626
-            );
627
-        }
628
-        if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
629
-            EE_Error::doing_it_wrong(
630
-                'EE_Error::add_error()',
631
-                __('You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
632
-                    'event_espresso'),
633
-                EVENT_ESPRESSO_VERSION
634
-            );
635
-        }
636
-        // get separate user and developer messages if they exist
637
-        $msg      = explode('||', $msg);
638
-        $user_msg = $msg[0];
639
-        $dev_msg  = isset($msg[1]) ? $msg[1] : $msg[0];
640
-        /**
641
-         * Do an action so other code can be triggered when a notice is created
642
-         *
643
-         * @param string $type     can be 'errors', 'attention', or 'success'
644
-         * @param string $user_msg message displayed to user when WP_DEBUG is off
645
-         * @param string $user_msg message displayed to user when WP_DEBUG is on
646
-         * @param string $file     file where error was generated
647
-         * @param string $func     function where error was generated
648
-         * @param string $line     line where error was generated
649
-         */
650
-        do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
651
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
652
-        // add notice if message exists
653
-        if (! empty($msg)) {
654
-            // get error code
655
-            $notice_code = EE_Error::generate_error_code($file, $func, $line);
656
-            if (WP_DEBUG && $type === 'errors') {
657
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
658
-            }
659
-            // add notice. Index by code if it's not blank
660
-            if ($notice_code) {
661
-                self::$_espresso_notices[$type][$notice_code] = $msg;
662
-            } else {
663
-                self::$_espresso_notices[$type][] = $msg;
664
-            }
665
-            add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
666
-        }
667
-    }
668
-
669
-
670
-    /**
671
-     * in some case it may be necessary to overwrite the existing success messages
672
-     *
673
-     * @return        void
674
-     */
675
-    public static function overwrite_success()
676
-    {
677
-        self::$_espresso_notices['success'] = false;
678
-    }
679
-
680
-
681
-
682
-    /**
683
-     * in some case it may be necessary to overwrite the existing attention messages
684
-     *
685
-     * @return void
686
-     */
687
-    public static function overwrite_attention()
688
-    {
689
-        self::$_espresso_notices['attention'] = false;
690
-    }
691
-
692
-
693
-
694
-    /**
695
-     * in some case it may be necessary to overwrite the existing error messages
696
-     *
697
-     * @return void
698
-     */
699
-    public static function overwrite_errors()
700
-    {
701
-        self::$_espresso_notices['errors'] = false;
702
-    }
703
-
704
-
705
-
706
-    /**
707
-     * @return void
708
-     */
709
-    public static function reset_notices()
710
-    {
711
-        self::$_espresso_notices['success']   = false;
712
-        self::$_espresso_notices['attention'] = false;
713
-        self::$_espresso_notices['errors']    = false;
714
-    }
715
-
716
-
717
-
718
-    /**
719
-     * @return int
720
-     */
721
-    public static function has_notices()
722
-    {
723
-        $has_notices = 0;
724
-        // check for success messages
725
-        $has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])
726
-            ? 3
727
-            : $has_notices;
728
-        // check for attention messages
729
-        $has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])
730
-            ? 2
731
-            : $has_notices;
732
-        // check for error messages
733
-        $has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])
734
-            ? 1
735
-            : $has_notices;
736
-        return $has_notices;
737
-    }
738
-
739
-
740
-    /**
741
-     * This simply returns non formatted error notices as they were sent into the EE_Error object.
742
-     *
743
-     * @since 4.9.0
744
-     * @return array
745
-     */
746
-    public static function get_vanilla_notices()
747
-    {
748
-        return array(
749
-            'success'   => isset(self::$_espresso_notices['success'])
750
-                ? self::$_espresso_notices['success']
751
-                : array(),
752
-            'attention' => isset(self::$_espresso_notices['attention'])
753
-                ? self::$_espresso_notices['attention']
754
-                : array(),
755
-            'errors'    => isset(self::$_espresso_notices['errors'])
756
-                ? self::$_espresso_notices['errors']
757
-                : array(),
758
-        );
759
-    }
760
-
761
-
762
-    /**
763
-     * @return array
764
-     * @throws InvalidArgumentException
765
-     * @throws InvalidDataTypeException
766
-     * @throws InvalidInterfaceException
767
-     */
768
-    public static function getStoredNotices()
769
-    {
770
-        if ($user_id = get_current_user_id()) {
771
-            // get notices for logged in user
772
-            $notices = get_user_option(EE_Error::OPTIONS_KEY_NOTICES, $user_id);
773
-            return is_array($notices) ? $notices : array();
774
-        }
775
-        if (EE_Session::isLoadedAndActive()) {
776
-            // get notices for user currently engaged in a session
777
-            $session_data = EE_Session::instance()->get_session_data(EE_Error::OPTIONS_KEY_NOTICES);
778
-            return is_array($session_data) ? $session_data : array();
779
-        }
780
-        // get global notices and hope they apply to the current site visitor
781
-        $notices = get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
782
-        return is_array($notices) ? $notices : array();
783
-    }
784
-
785
-
786
-    /**
787
-     * @param array $notices
788
-     * @return bool
789
-     * @throws InvalidArgumentException
790
-     * @throws InvalidDataTypeException
791
-     * @throws InvalidInterfaceException
792
-     */
793
-    public static function storeNotices(array $notices)
794
-    {
795
-        if ($user_id = get_current_user_id()) {
796
-            // store notices for logged in user
797
-            return (bool) update_user_option(
798
-                $user_id,
799
-                EE_Error::OPTIONS_KEY_NOTICES,
800
-                $notices
801
-            );
802
-        }
803
-        if (EE_Session::isLoadedAndActive()) {
804
-            // store notices for user currently engaged in a session
805
-            return EE_Session::instance()->set_session_data(
806
-                array(EE_Error::OPTIONS_KEY_NOTICES => $notices)
807
-            );
808
-        }
809
-        // store global notices and hope they apply to the same site visitor on the next request
810
-        return update_option(EE_Error::OPTIONS_KEY_NOTICES, $notices);
811
-    }
812
-
813
-
814
-    /**
815
-     * @return bool|TRUE
816
-     * @throws InvalidArgumentException
817
-     * @throws InvalidDataTypeException
818
-     * @throws InvalidInterfaceException
819
-     */
820
-    public static function clearNotices()
821
-    {
822
-        if ($user_id = get_current_user_id()) {
823
-            // clear notices for logged in user
824
-            return (bool) update_user_option(
825
-                $user_id,
826
-                EE_Error::OPTIONS_KEY_NOTICES,
827
-                array()
828
-            );
829
-        }
830
-        if (EE_Session::isLoadedAndActive()) {
831
-            // clear notices for user currently engaged in a session
832
-            return EE_Session::instance()->reset_data(EE_Error::OPTIONS_KEY_NOTICES);
833
-        }
834
-        // clear global notices and hope none belonged to some for some other site visitor
835
-        return update_option(EE_Error::OPTIONS_KEY_NOTICES, array());
836
-    }
837
-
838
-
839
-    /**
840
-     * saves notices to the db for retrieval on next request
841
-     *
842
-     * @return void
843
-     * @throws InvalidArgumentException
844
-     * @throws InvalidDataTypeException
845
-     * @throws InvalidInterfaceException
846
-     */
847
-    public static function stashNoticesBeforeRedirect()
848
-    {
849
-        EE_Error::get_notices(false, true);
850
-    }
851
-
852
-
853
-    /**
854
-     * compile all error or success messages into one string
855
-     *
856
-     * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
857
-     * @param boolean $format_output            whether or not to format the messages for display in the WP admin
858
-     * @param boolean $save_to_transient        whether or not to save notices to the db for retrieval on next request
859
-     *                                          - ONLY do this just before redirecting
860
-     * @param boolean $remove_empty             whether or not to unset empty messages
861
-     * @return array
862
-     * @throws InvalidArgumentException
863
-     * @throws InvalidDataTypeException
864
-     * @throws InvalidInterfaceException
865
-     */
866
-    public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
867
-    {
868
-        $success_messages   = '';
869
-        $attention_messages = '';
870
-        $error_messages     = '';
871
-        // either save notices to the db
872
-        if ($save_to_transient || isset($_REQUEST['activate-selected'])) {
873
-            self::$_espresso_notices = array_merge(
874
-                EE_Error::getStoredNotices(),
875
-                self::$_espresso_notices
876
-            );
877
-            EE_Error::storeNotices(self::$_espresso_notices);
878
-            return array();
879
-        }
880
-        $print_scripts = EE_Error::combineExistingAndNewNotices();
881
-        // check for success messages
882
-        if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
883
-            // combine messages
884
-            $success_messages .= implode(self::$_espresso_notices['success'], '<br />');
885
-            $print_scripts    = true;
886
-        }
887
-        // check for attention messages
888
-        if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
889
-            // combine messages
890
-            $attention_messages .= implode(self::$_espresso_notices['attention'], '<br />');
891
-            $print_scripts      = true;
892
-        }
893
-        // check for error messages
894
-        if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
895
-            $error_messages .= count(self::$_espresso_notices['errors']) > 1
896
-                ? __('The following errors have occurred:<br />', 'event_espresso')
897
-                : __('An error has occurred:<br />', 'event_espresso');
898
-            // combine messages
899
-            $error_messages .= implode(self::$_espresso_notices['errors'], '<br />');
900
-            $print_scripts  = true;
901
-        }
902
-        if ($format_output) {
903
-            $notices = EE_Error::formatNoticesOutput(
904
-                $success_messages,
905
-                $attention_messages,
906
-                $error_messages
907
-            );
908
-        } else {
909
-            $notices = array(
910
-                'success'   => $success_messages,
911
-                'attention' => $attention_messages,
912
-                'errors'    => $error_messages,
913
-            );
914
-            if ($remove_empty) {
915
-                // remove empty notices
916
-                foreach ($notices as $type => $notice) {
917
-                    if (empty($notice)) {
918
-                        unset($notices[$type]);
919
-                    }
920
-                }
921
-            }
922
-        }
923
-        if ($print_scripts) {
924
-            self::_print_scripts();
925
-        }
926
-        return $notices;
927
-    }
928
-
929
-
930
-    /**
931
-     * @return bool
932
-     * @throws InvalidArgumentException
933
-     * @throws InvalidDataTypeException
934
-     * @throws InvalidInterfaceException
935
-     */
936
-    private static function combineExistingAndNewNotices()
937
-    {
938
-        $print_scripts = false;
939
-        // grab any notices that have been previously saved
940
-        $notices = EE_Error::getStoredNotices();
941
-        if (! empty($notices)) {
942
-            foreach ($notices as $type => $notice) {
943
-                if (is_array($notice) && ! empty($notice)) {
944
-                    // make sure that existing notice type is an array
945
-                    self::$_espresso_notices[ $type ] = is_array(self::$_espresso_notices[ $type ])
946
-                                                        && ! empty(self::$_espresso_notices[ $type ])
947
-                        ? self::$_espresso_notices[ $type ]
948
-                        : array();
949
-                    // add newly created notices to existing ones
950
-                    self::$_espresso_notices[ $type ] += $notice;
951
-                    $print_scripts = true;
952
-                }
953
-            }
954
-            // now clear any stored notices
955
-            EE_Error::clearNotices();
956
-        }
957
-        return $print_scripts;
958
-    }
959
-
960
-
961
-    /**
962
-     * @param string $success_messages
963
-     * @param string $attention_messages
964
-     * @param string $error_messages
965
-     * @return string
966
-     */
967
-    private static function formatNoticesOutput($success_messages, $attention_messages, $error_messages)
968
-    {
969
-        $notices = '<div id="espresso-notices">';
970
-        $close   = is_admin()
971
-            ? ''
972
-            : '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"/></a>';
973
-        if ($success_messages !== '') {
974
-            $css_id    = is_admin() ? 'message' : 'espresso-notices-success';
975
-            $css_class = is_admin() ? 'updated fade' : 'success fade-away';
976
-            //showMessage( $success_messages );
977
-            $notices .= '<div id="' . $css_id . '" '
978
-                        . 'class="espresso-notices ' . $css_class . '" '
979
-                        . 'style="display:none;">'
980
-                        . '<p>' . $success_messages . '</p>'
981
-                        . $close
982
-                        . '</div>';
983
-        }
984
-        if ($attention_messages !== '') {
985
-            $css_id    = is_admin() ? 'message' : 'espresso-notices-attention';
986
-            $css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
987
-            //showMessage( $error_messages, TRUE );
988
-            $notices .= '<div id="' . $css_id . '" '
989
-                        . 'class="espresso-notices ' . $css_class . '" '
990
-                        . 'style="display:none;">'
991
-                        . '<p>' . $attention_messages . '</p>'
992
-                        . $close
993
-                        . '</div>';
994
-        }
995
-        if ($error_messages !== '') {
996
-            $css_id    = is_admin() ? 'message' : 'espresso-notices-error';
997
-            $css_class = is_admin() ? 'error' : 'error fade-away';
998
-            //showMessage( $error_messages, TRUE );
999
-            $notices .= '<div id="' . $css_id . '" '
1000
-                        . 'class="espresso-notices ' . $css_class . '" '
1001
-                        . 'style="display:none;">'
1002
-                        . '<p>' . $error_messages . '</p>'
1003
-                        . $close
1004
-                        . '</div>';
1005
-        }
1006
-        $notices .= '</div>';
1007
-        return $notices;
1008
-    }
1009
-
1010
-
1011
-
1012
-    /**
1013
-     * _print_scripts
1014
-     *
1015
-     * @param    bool $force_print
1016
-     * @return    string
1017
-     */
1018
-    private static function _print_scripts($force_print = false)
1019
-    {
1020
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
1021
-            if (wp_script_is('ee_error_js', 'enqueued')) {
1022
-                return '';
1023
-            }
1024
-            if (wp_script_is('ee_error_js', 'registered')) {
1025
-                wp_enqueue_style('espresso_default');
1026
-                wp_enqueue_style('espresso_custom_css');
1027
-                wp_enqueue_script('ee_error_js');
1028
-                wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
1029
-            }
1030
-        } else {
1031
-            return '
480
+		$output .= self::_print_scripts(true);
481
+		if (defined('DOING_AJAX')) {
482
+			echo wp_json_encode(array('error' => $output));
483
+			exit();
484
+		}
485
+		echo $output;
486
+		die();
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 *    generate string from exception trace args
493
+	 *
494
+	 * @param array $arguments
495
+	 * @param bool  $array
496
+	 * @return string
497
+	 */
498
+	private function _convert_args_to_string($arguments = array(), $array = false)
499
+	{
500
+		$arg_string = '';
501
+		if (! empty($arguments)) {
502
+			$args = array();
503
+			foreach ($arguments as $arg) {
504
+				if (! empty($arg)) {
505
+					if (is_string($arg)) {
506
+						$args[] = " '" . $arg . "'";
507
+					} elseif (is_array($arg)) {
508
+						$args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
509
+					} elseif ($arg === null) {
510
+						$args[] = ' NULL';
511
+					} elseif (is_bool($arg)) {
512
+						$args[] = ($arg) ? ' TRUE' : ' FALSE';
513
+					} elseif (is_object($arg)) {
514
+						$args[] = ' OBJECT ' . get_class($arg);
515
+					} elseif (is_resource($arg)) {
516
+						$args[] = get_resource_type($arg);
517
+					} else {
518
+						$args[] = $arg;
519
+					}
520
+				}
521
+			}
522
+			$arg_string = implode(', ', $args);
523
+		}
524
+		if ($array) {
525
+			$arg_string .= ' )';
526
+		}
527
+		return $arg_string;
528
+	}
529
+
530
+
531
+
532
+	/**
533
+	 *    add error message
534
+	 *
535
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
536
+	 *                            separate messages for user || dev
537
+	 * @param        string $file the file that the error occurred in - just use __FILE__
538
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
539
+	 * @param        string $line the line number where the error occurred - just use __LINE__
540
+	 * @return        void
541
+	 */
542
+	public static function add_error($msg = null, $file = null, $func = null, $line = null)
543
+	{
544
+		self::_add_notice('errors', $msg, $file, $func, $line);
545
+		self::$_error_count++;
546
+	}
547
+
548
+
549
+
550
+	/**
551
+	 * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
552
+	 * adds an error
553
+	 *
554
+	 * @param string $msg
555
+	 * @param string $file
556
+	 * @param string $func
557
+	 * @param string $line
558
+	 * @throws EE_Error
559
+	 */
560
+	public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
561
+	{
562
+		if (WP_DEBUG) {
563
+			throw new EE_Error($msg);
564
+		}
565
+		EE_Error::add_error($msg, $file, $func, $line);
566
+	}
567
+
568
+
569
+
570
+	/**
571
+	 *    add success message
572
+	 *
573
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
574
+	 *                            separate messages for user || dev
575
+	 * @param        string $file the file that the error occurred in - just use __FILE__
576
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
577
+	 * @param        string $line the line number where the error occurred - just use __LINE__
578
+	 * @return        void
579
+	 */
580
+	public static function add_success($msg = null, $file = null, $func = null, $line = null)
581
+	{
582
+		self::_add_notice('success', $msg, $file, $func, $line);
583
+	}
584
+
585
+
586
+
587
+	/**
588
+	 *    add attention message
589
+	 *
590
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
591
+	 *                            separate messages for user || dev
592
+	 * @param        string $file the file that the error occurred in - just use __FILE__
593
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
594
+	 * @param        string $line the line number where the error occurred - just use __LINE__
595
+	 * @return        void
596
+	 */
597
+	public static function add_attention($msg = null, $file = null, $func = null, $line = null)
598
+	{
599
+		self::_add_notice('attention', $msg, $file, $func, $line);
600
+	}
601
+
602
+
603
+
604
+	/**
605
+	 * @param string $type whether the message is for a success or error notification
606
+	 * @param string $msg the message to display to users or developers
607
+	 *                    - adding a double pipe || (OR) creates separate messages for user || dev
608
+	 * @param string $file the file that the error occurred in - just use __FILE__
609
+	 * @param string $func the function/method that the error occurred in - just use __FUNCTION__
610
+	 * @param string $line the line number where the error occurred - just use __LINE__
611
+	 * @return void
612
+	 */
613
+	private static function _add_notice($type = 'success', $msg = '', $file = '', $func = '', $line = '')
614
+	{
615
+		if (empty($msg)) {
616
+			EE_Error::doing_it_wrong(
617
+				'EE_Error::add_' . $type . '()',
618
+				sprintf(
619
+					__('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
620
+						'event_espresso'),
621
+					$type,
622
+					$file,
623
+					$line
624
+				),
625
+				EVENT_ESPRESSO_VERSION
626
+			);
627
+		}
628
+		if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
629
+			EE_Error::doing_it_wrong(
630
+				'EE_Error::add_error()',
631
+				__('You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
632
+					'event_espresso'),
633
+				EVENT_ESPRESSO_VERSION
634
+			);
635
+		}
636
+		// get separate user and developer messages if they exist
637
+		$msg      = explode('||', $msg);
638
+		$user_msg = $msg[0];
639
+		$dev_msg  = isset($msg[1]) ? $msg[1] : $msg[0];
640
+		/**
641
+		 * Do an action so other code can be triggered when a notice is created
642
+		 *
643
+		 * @param string $type     can be 'errors', 'attention', or 'success'
644
+		 * @param string $user_msg message displayed to user when WP_DEBUG is off
645
+		 * @param string $user_msg message displayed to user when WP_DEBUG is on
646
+		 * @param string $file     file where error was generated
647
+		 * @param string $func     function where error was generated
648
+		 * @param string $line     line where error was generated
649
+		 */
650
+		do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
651
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
652
+		// add notice if message exists
653
+		if (! empty($msg)) {
654
+			// get error code
655
+			$notice_code = EE_Error::generate_error_code($file, $func, $line);
656
+			if (WP_DEBUG && $type === 'errors') {
657
+				$msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
658
+			}
659
+			// add notice. Index by code if it's not blank
660
+			if ($notice_code) {
661
+				self::$_espresso_notices[$type][$notice_code] = $msg;
662
+			} else {
663
+				self::$_espresso_notices[$type][] = $msg;
664
+			}
665
+			add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
666
+		}
667
+	}
668
+
669
+
670
+	/**
671
+	 * in some case it may be necessary to overwrite the existing success messages
672
+	 *
673
+	 * @return        void
674
+	 */
675
+	public static function overwrite_success()
676
+	{
677
+		self::$_espresso_notices['success'] = false;
678
+	}
679
+
680
+
681
+
682
+	/**
683
+	 * in some case it may be necessary to overwrite the existing attention messages
684
+	 *
685
+	 * @return void
686
+	 */
687
+	public static function overwrite_attention()
688
+	{
689
+		self::$_espresso_notices['attention'] = false;
690
+	}
691
+
692
+
693
+
694
+	/**
695
+	 * in some case it may be necessary to overwrite the existing error messages
696
+	 *
697
+	 * @return void
698
+	 */
699
+	public static function overwrite_errors()
700
+	{
701
+		self::$_espresso_notices['errors'] = false;
702
+	}
703
+
704
+
705
+
706
+	/**
707
+	 * @return void
708
+	 */
709
+	public static function reset_notices()
710
+	{
711
+		self::$_espresso_notices['success']   = false;
712
+		self::$_espresso_notices['attention'] = false;
713
+		self::$_espresso_notices['errors']    = false;
714
+	}
715
+
716
+
717
+
718
+	/**
719
+	 * @return int
720
+	 */
721
+	public static function has_notices()
722
+	{
723
+		$has_notices = 0;
724
+		// check for success messages
725
+		$has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])
726
+			? 3
727
+			: $has_notices;
728
+		// check for attention messages
729
+		$has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])
730
+			? 2
731
+			: $has_notices;
732
+		// check for error messages
733
+		$has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])
734
+			? 1
735
+			: $has_notices;
736
+		return $has_notices;
737
+	}
738
+
739
+
740
+	/**
741
+	 * This simply returns non formatted error notices as they were sent into the EE_Error object.
742
+	 *
743
+	 * @since 4.9.0
744
+	 * @return array
745
+	 */
746
+	public static function get_vanilla_notices()
747
+	{
748
+		return array(
749
+			'success'   => isset(self::$_espresso_notices['success'])
750
+				? self::$_espresso_notices['success']
751
+				: array(),
752
+			'attention' => isset(self::$_espresso_notices['attention'])
753
+				? self::$_espresso_notices['attention']
754
+				: array(),
755
+			'errors'    => isset(self::$_espresso_notices['errors'])
756
+				? self::$_espresso_notices['errors']
757
+				: array(),
758
+		);
759
+	}
760
+
761
+
762
+	/**
763
+	 * @return array
764
+	 * @throws InvalidArgumentException
765
+	 * @throws InvalidDataTypeException
766
+	 * @throws InvalidInterfaceException
767
+	 */
768
+	public static function getStoredNotices()
769
+	{
770
+		if ($user_id = get_current_user_id()) {
771
+			// get notices for logged in user
772
+			$notices = get_user_option(EE_Error::OPTIONS_KEY_NOTICES, $user_id);
773
+			return is_array($notices) ? $notices : array();
774
+		}
775
+		if (EE_Session::isLoadedAndActive()) {
776
+			// get notices for user currently engaged in a session
777
+			$session_data = EE_Session::instance()->get_session_data(EE_Error::OPTIONS_KEY_NOTICES);
778
+			return is_array($session_data) ? $session_data : array();
779
+		}
780
+		// get global notices and hope they apply to the current site visitor
781
+		$notices = get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
782
+		return is_array($notices) ? $notices : array();
783
+	}
784
+
785
+
786
+	/**
787
+	 * @param array $notices
788
+	 * @return bool
789
+	 * @throws InvalidArgumentException
790
+	 * @throws InvalidDataTypeException
791
+	 * @throws InvalidInterfaceException
792
+	 */
793
+	public static function storeNotices(array $notices)
794
+	{
795
+		if ($user_id = get_current_user_id()) {
796
+			// store notices for logged in user
797
+			return (bool) update_user_option(
798
+				$user_id,
799
+				EE_Error::OPTIONS_KEY_NOTICES,
800
+				$notices
801
+			);
802
+		}
803
+		if (EE_Session::isLoadedAndActive()) {
804
+			// store notices for user currently engaged in a session
805
+			return EE_Session::instance()->set_session_data(
806
+				array(EE_Error::OPTIONS_KEY_NOTICES => $notices)
807
+			);
808
+		}
809
+		// store global notices and hope they apply to the same site visitor on the next request
810
+		return update_option(EE_Error::OPTIONS_KEY_NOTICES, $notices);
811
+	}
812
+
813
+
814
+	/**
815
+	 * @return bool|TRUE
816
+	 * @throws InvalidArgumentException
817
+	 * @throws InvalidDataTypeException
818
+	 * @throws InvalidInterfaceException
819
+	 */
820
+	public static function clearNotices()
821
+	{
822
+		if ($user_id = get_current_user_id()) {
823
+			// clear notices for logged in user
824
+			return (bool) update_user_option(
825
+				$user_id,
826
+				EE_Error::OPTIONS_KEY_NOTICES,
827
+				array()
828
+			);
829
+		}
830
+		if (EE_Session::isLoadedAndActive()) {
831
+			// clear notices for user currently engaged in a session
832
+			return EE_Session::instance()->reset_data(EE_Error::OPTIONS_KEY_NOTICES);
833
+		}
834
+		// clear global notices and hope none belonged to some for some other site visitor
835
+		return update_option(EE_Error::OPTIONS_KEY_NOTICES, array());
836
+	}
837
+
838
+
839
+	/**
840
+	 * saves notices to the db for retrieval on next request
841
+	 *
842
+	 * @return void
843
+	 * @throws InvalidArgumentException
844
+	 * @throws InvalidDataTypeException
845
+	 * @throws InvalidInterfaceException
846
+	 */
847
+	public static function stashNoticesBeforeRedirect()
848
+	{
849
+		EE_Error::get_notices(false, true);
850
+	}
851
+
852
+
853
+	/**
854
+	 * compile all error or success messages into one string
855
+	 *
856
+	 * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
857
+	 * @param boolean $format_output            whether or not to format the messages for display in the WP admin
858
+	 * @param boolean $save_to_transient        whether or not to save notices to the db for retrieval on next request
859
+	 *                                          - ONLY do this just before redirecting
860
+	 * @param boolean $remove_empty             whether or not to unset empty messages
861
+	 * @return array
862
+	 * @throws InvalidArgumentException
863
+	 * @throws InvalidDataTypeException
864
+	 * @throws InvalidInterfaceException
865
+	 */
866
+	public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
867
+	{
868
+		$success_messages   = '';
869
+		$attention_messages = '';
870
+		$error_messages     = '';
871
+		// either save notices to the db
872
+		if ($save_to_transient || isset($_REQUEST['activate-selected'])) {
873
+			self::$_espresso_notices = array_merge(
874
+				EE_Error::getStoredNotices(),
875
+				self::$_espresso_notices
876
+			);
877
+			EE_Error::storeNotices(self::$_espresso_notices);
878
+			return array();
879
+		}
880
+		$print_scripts = EE_Error::combineExistingAndNewNotices();
881
+		// check for success messages
882
+		if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
883
+			// combine messages
884
+			$success_messages .= implode(self::$_espresso_notices['success'], '<br />');
885
+			$print_scripts    = true;
886
+		}
887
+		// check for attention messages
888
+		if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
889
+			// combine messages
890
+			$attention_messages .= implode(self::$_espresso_notices['attention'], '<br />');
891
+			$print_scripts      = true;
892
+		}
893
+		// check for error messages
894
+		if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
895
+			$error_messages .= count(self::$_espresso_notices['errors']) > 1
896
+				? __('The following errors have occurred:<br />', 'event_espresso')
897
+				: __('An error has occurred:<br />', 'event_espresso');
898
+			// combine messages
899
+			$error_messages .= implode(self::$_espresso_notices['errors'], '<br />');
900
+			$print_scripts  = true;
901
+		}
902
+		if ($format_output) {
903
+			$notices = EE_Error::formatNoticesOutput(
904
+				$success_messages,
905
+				$attention_messages,
906
+				$error_messages
907
+			);
908
+		} else {
909
+			$notices = array(
910
+				'success'   => $success_messages,
911
+				'attention' => $attention_messages,
912
+				'errors'    => $error_messages,
913
+			);
914
+			if ($remove_empty) {
915
+				// remove empty notices
916
+				foreach ($notices as $type => $notice) {
917
+					if (empty($notice)) {
918
+						unset($notices[$type]);
919
+					}
920
+				}
921
+			}
922
+		}
923
+		if ($print_scripts) {
924
+			self::_print_scripts();
925
+		}
926
+		return $notices;
927
+	}
928
+
929
+
930
+	/**
931
+	 * @return bool
932
+	 * @throws InvalidArgumentException
933
+	 * @throws InvalidDataTypeException
934
+	 * @throws InvalidInterfaceException
935
+	 */
936
+	private static function combineExistingAndNewNotices()
937
+	{
938
+		$print_scripts = false;
939
+		// grab any notices that have been previously saved
940
+		$notices = EE_Error::getStoredNotices();
941
+		if (! empty($notices)) {
942
+			foreach ($notices as $type => $notice) {
943
+				if (is_array($notice) && ! empty($notice)) {
944
+					// make sure that existing notice type is an array
945
+					self::$_espresso_notices[ $type ] = is_array(self::$_espresso_notices[ $type ])
946
+														&& ! empty(self::$_espresso_notices[ $type ])
947
+						? self::$_espresso_notices[ $type ]
948
+						: array();
949
+					// add newly created notices to existing ones
950
+					self::$_espresso_notices[ $type ] += $notice;
951
+					$print_scripts = true;
952
+				}
953
+			}
954
+			// now clear any stored notices
955
+			EE_Error::clearNotices();
956
+		}
957
+		return $print_scripts;
958
+	}
959
+
960
+
961
+	/**
962
+	 * @param string $success_messages
963
+	 * @param string $attention_messages
964
+	 * @param string $error_messages
965
+	 * @return string
966
+	 */
967
+	private static function formatNoticesOutput($success_messages, $attention_messages, $error_messages)
968
+	{
969
+		$notices = '<div id="espresso-notices">';
970
+		$close   = is_admin()
971
+			? ''
972
+			: '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"/></a>';
973
+		if ($success_messages !== '') {
974
+			$css_id    = is_admin() ? 'message' : 'espresso-notices-success';
975
+			$css_class = is_admin() ? 'updated fade' : 'success fade-away';
976
+			//showMessage( $success_messages );
977
+			$notices .= '<div id="' . $css_id . '" '
978
+						. 'class="espresso-notices ' . $css_class . '" '
979
+						. 'style="display:none;">'
980
+						. '<p>' . $success_messages . '</p>'
981
+						. $close
982
+						. '</div>';
983
+		}
984
+		if ($attention_messages !== '') {
985
+			$css_id    = is_admin() ? 'message' : 'espresso-notices-attention';
986
+			$css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
987
+			//showMessage( $error_messages, TRUE );
988
+			$notices .= '<div id="' . $css_id . '" '
989
+						. 'class="espresso-notices ' . $css_class . '" '
990
+						. 'style="display:none;">'
991
+						. '<p>' . $attention_messages . '</p>'
992
+						. $close
993
+						. '</div>';
994
+		}
995
+		if ($error_messages !== '') {
996
+			$css_id    = is_admin() ? 'message' : 'espresso-notices-error';
997
+			$css_class = is_admin() ? 'error' : 'error fade-away';
998
+			//showMessage( $error_messages, TRUE );
999
+			$notices .= '<div id="' . $css_id . '" '
1000
+						. 'class="espresso-notices ' . $css_class . '" '
1001
+						. 'style="display:none;">'
1002
+						. '<p>' . $error_messages . '</p>'
1003
+						. $close
1004
+						. '</div>';
1005
+		}
1006
+		$notices .= '</div>';
1007
+		return $notices;
1008
+	}
1009
+
1010
+
1011
+
1012
+	/**
1013
+	 * _print_scripts
1014
+	 *
1015
+	 * @param    bool $force_print
1016
+	 * @return    string
1017
+	 */
1018
+	private static function _print_scripts($force_print = false)
1019
+	{
1020
+		if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
1021
+			if (wp_script_is('ee_error_js', 'enqueued')) {
1022
+				return '';
1023
+			}
1024
+			if (wp_script_is('ee_error_js', 'registered')) {
1025
+				wp_enqueue_style('espresso_default');
1026
+				wp_enqueue_style('espresso_custom_css');
1027
+				wp_enqueue_script('ee_error_js');
1028
+				wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
1029
+			}
1030
+		} else {
1031
+			return '
1032 1032
 <script>
1033 1033
 /* <![CDATA[ */
1034 1034
 var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
@@ -1038,223 +1038,223 @@  discard block
 block discarded – undo
1038 1038
 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
1039 1039
 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
1040 1040
 ';
1041
-        }
1042
-        return '';
1043
-    }
1044
-
1045
-
1046
-
1047
-    /**
1048
-     * @return void
1049
-     */
1050
-    public static function enqueue_error_scripts()
1051
-    {
1052
-        self::_print_scripts();
1053
-    }
1054
-
1055
-
1056
-
1057
-    /**
1058
-     * create error code from filepath, function name,
1059
-     * and line number where exception or error was thrown
1060
-     *
1061
-     * @param string $file
1062
-     * @param string $func
1063
-     * @param string $line
1064
-     * @return string
1065
-     */
1066
-    public static function generate_error_code($file = '', $func = '', $line = '')
1067
-    {
1068
-        $file       = explode('.', basename($file));
1069
-        $error_code = ! empty($file[0]) ? $file[0] : '';
1070
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
1071
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
1072
-        return $error_code;
1073
-    }
1074
-
1075
-
1076
-
1077
-    /**
1078
-     * write exception details to log file
1079
-     * Since 4.9.53.rc.006 this writes to the standard PHP log file, not EE's custom log file
1080
-     *
1081
-     * @param int   $time
1082
-     * @param array $ex
1083
-     * @param bool  $clear
1084
-     * @return void
1085
-     */
1086
-    public function write_to_error_log($time = 0, $ex = array(), $clear = false)
1087
-    {
1088
-        if (empty($ex)) {
1089
-            return;
1090
-        }
1091
-        if (! $time) {
1092
-            $time = time();
1093
-        }
1094
-        $exception_log = '----------------------------------------------------------------------------------------'
1095
-                         . PHP_EOL;
1096
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1097
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1098
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1099
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1100
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1101
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
1102
-        $exception_log .= $ex['string'] . PHP_EOL;
1103
-        $exception_log .= '----------------------------------------------------------------------------------------'
1104
-                          . PHP_EOL;
1105
-        try {
1106
-            error_log($exception_log);
1107
-        } catch (EE_Error $e) {
1108
-            EE_Error::add_error(sprintf(__('Event Espresso error logging could not be setup because: %s',
1109
-                'event_espresso'), $e->getMessage()));
1110
-        }
1111
-    }
1112
-
1113
-
1114
-
1115
-    /**
1116
-     * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1117
-     * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1118
-     * but the code execution is done in a manner that could lead to unexpected results
1119
-     * (i.e. running to early, or too late in WP or EE loading process).
1120
-     * A good test for knowing whether to use this method is:
1121
-     * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1122
-     * Yes -> use EE_Error::add_error() or throw new EE_Error()
1123
-     * 2. If this is loaded before something else, it won't break anything,
1124
-     * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1125
-     *
1126
-     * @uses   constant WP_DEBUG test if wp_debug is on or not
1127
-     * @param string $function      The function that was called
1128
-     * @param string $message       A message explaining what has been done incorrectly
1129
-     * @param string $version       The version of Event Espresso where the error was added
1130
-     * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1131
-     *                              for a deprecated function. This allows deprecation to occur during one version,
1132
-     *                              but not have any notices appear until a later version. This allows developers
1133
-     *                              extra time to update their code before notices appear.
1134
-     * @param int    $error_type
1135
-     */
1136
-    public static function doing_it_wrong(
1137
-        $function,
1138
-        $message,
1139
-        $version,
1140
-        $applies_when = '',
1141
-        $error_type = null
1142
-    ) {
1143
-        if (defined('WP_DEBUG') && WP_DEBUG) {
1144
-            EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1145
-        }
1146
-    }
1147
-
1148
-
1149
-
1150
-    /**
1151
-     * Like get_notices, but returns an array of all the notices of the given type.
1152
-     *
1153
-     * @return array {
1154
-     *  @type array $success   all the success messages
1155
-     *  @type array $errors    all the error messages
1156
-     *  @type array $attention all the attention messages
1157
-     * }
1158
-     */
1159
-    public static function get_raw_notices()
1160
-    {
1161
-        return self::$_espresso_notices;
1162
-    }
1163
-
1164
-
1165
-
1166
-    /**
1167
-     * @deprecated 4.9.27
1168
-     * @param string $pan_name     the name, or key of the Persistent Admin Notice to be stored
1169
-     * @param string $pan_message  the message to be stored persistently until dismissed
1170
-     * @param bool   $force_update allows one to enforce the reappearance of a persistent message.
1171
-     * @return void
1172
-     * @throws InvalidDataTypeException
1173
-     */
1174
-    public static function add_persistent_admin_notice($pan_name = '', $pan_message, $force_update = false)
1175
-    {
1176
-        new PersistentAdminNotice(
1177
-            $pan_name,
1178
-            $pan_message,
1179
-            $force_update
1180
-        );
1181
-        EE_Error::doing_it_wrong(
1182
-            __METHOD__,
1183
-            sprintf(
1184
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1185
-                '\EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
1186
-            ),
1187
-            '4.9.27'
1188
-        );
1189
-    }
1190
-
1191
-
1192
-
1193
-    /**
1194
-     * @deprecated 4.9.27
1195
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
1196
-     * @param bool   $purge
1197
-     * @param bool   $return
1198
-     * @throws DomainException
1199
-     * @throws InvalidInterfaceException
1200
-     * @throws InvalidDataTypeException
1201
-     * @throws ServiceNotFoundException
1202
-     * @throws InvalidArgumentException
1203
-     */
1204
-    public static function dismiss_persistent_admin_notice($pan_name = '', $purge = false, $return = false)
1205
-    {
1206
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
1207
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
1208
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1209
-        );
1210
-        $persistent_admin_notice_manager->dismissNotice($pan_name, $purge, $return);
1211
-        EE_Error::doing_it_wrong(
1212
-            __METHOD__,
1213
-            sprintf(
1214
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1215
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1216
-            ),
1217
-            '4.9.27'
1218
-        );
1219
-    }
1220
-
1221
-
1222
-
1223
-    /**
1224
-     * @deprecated 4.9.27
1225
-     * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
1226
-     * @param  string $pan_message the message to be stored persistently until dismissed
1227
-     * @param  string $return_url  URL to go back to after nag notice is dismissed
1228
-     */
1229
-    public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
1230
-    {
1231
-        EE_Error::doing_it_wrong(
1232
-            __METHOD__,
1233
-            sprintf(
1234
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1235
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1236
-            ),
1237
-            '4.9.27'
1238
-        );
1239
-    }
1240
-
1241
-
1242
-
1243
-    /**
1244
-     * @deprecated 4.9.27
1245
-     * @param string $return_url
1246
-     */
1247
-    public static function get_persistent_admin_notices($return_url = '')
1248
-    {
1249
-        EE_Error::doing_it_wrong(
1250
-            __METHOD__,
1251
-            sprintf(
1252
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1253
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1254
-            ),
1255
-            '4.9.27'
1256
-        );
1257
-    }
1041
+		}
1042
+		return '';
1043
+	}
1044
+
1045
+
1046
+
1047
+	/**
1048
+	 * @return void
1049
+	 */
1050
+	public static function enqueue_error_scripts()
1051
+	{
1052
+		self::_print_scripts();
1053
+	}
1054
+
1055
+
1056
+
1057
+	/**
1058
+	 * create error code from filepath, function name,
1059
+	 * and line number where exception or error was thrown
1060
+	 *
1061
+	 * @param string $file
1062
+	 * @param string $func
1063
+	 * @param string $line
1064
+	 * @return string
1065
+	 */
1066
+	public static function generate_error_code($file = '', $func = '', $line = '')
1067
+	{
1068
+		$file       = explode('.', basename($file));
1069
+		$error_code = ! empty($file[0]) ? $file[0] : '';
1070
+		$error_code .= ! empty($func) ? ' - ' . $func : '';
1071
+		$error_code .= ! empty($line) ? ' - ' . $line : '';
1072
+		return $error_code;
1073
+	}
1074
+
1075
+
1076
+
1077
+	/**
1078
+	 * write exception details to log file
1079
+	 * Since 4.9.53.rc.006 this writes to the standard PHP log file, not EE's custom log file
1080
+	 *
1081
+	 * @param int   $time
1082
+	 * @param array $ex
1083
+	 * @param bool  $clear
1084
+	 * @return void
1085
+	 */
1086
+	public function write_to_error_log($time = 0, $ex = array(), $clear = false)
1087
+	{
1088
+		if (empty($ex)) {
1089
+			return;
1090
+		}
1091
+		if (! $time) {
1092
+			$time = time();
1093
+		}
1094
+		$exception_log = '----------------------------------------------------------------------------------------'
1095
+						 . PHP_EOL;
1096
+		$exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1097
+		$exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1098
+		$exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1099
+		$exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1100
+		$exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1101
+		$exception_log .= 'Stack trace: ' . PHP_EOL;
1102
+		$exception_log .= $ex['string'] . PHP_EOL;
1103
+		$exception_log .= '----------------------------------------------------------------------------------------'
1104
+						  . PHP_EOL;
1105
+		try {
1106
+			error_log($exception_log);
1107
+		} catch (EE_Error $e) {
1108
+			EE_Error::add_error(sprintf(__('Event Espresso error logging could not be setup because: %s',
1109
+				'event_espresso'), $e->getMessage()));
1110
+		}
1111
+	}
1112
+
1113
+
1114
+
1115
+	/**
1116
+	 * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1117
+	 * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1118
+	 * but the code execution is done in a manner that could lead to unexpected results
1119
+	 * (i.e. running to early, or too late in WP or EE loading process).
1120
+	 * A good test for knowing whether to use this method is:
1121
+	 * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1122
+	 * Yes -> use EE_Error::add_error() or throw new EE_Error()
1123
+	 * 2. If this is loaded before something else, it won't break anything,
1124
+	 * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1125
+	 *
1126
+	 * @uses   constant WP_DEBUG test if wp_debug is on or not
1127
+	 * @param string $function      The function that was called
1128
+	 * @param string $message       A message explaining what has been done incorrectly
1129
+	 * @param string $version       The version of Event Espresso where the error was added
1130
+	 * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1131
+	 *                              for a deprecated function. This allows deprecation to occur during one version,
1132
+	 *                              but not have any notices appear until a later version. This allows developers
1133
+	 *                              extra time to update their code before notices appear.
1134
+	 * @param int    $error_type
1135
+	 */
1136
+	public static function doing_it_wrong(
1137
+		$function,
1138
+		$message,
1139
+		$version,
1140
+		$applies_when = '',
1141
+		$error_type = null
1142
+	) {
1143
+		if (defined('WP_DEBUG') && WP_DEBUG) {
1144
+			EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1145
+		}
1146
+	}
1147
+
1148
+
1149
+
1150
+	/**
1151
+	 * Like get_notices, but returns an array of all the notices of the given type.
1152
+	 *
1153
+	 * @return array {
1154
+	 *  @type array $success   all the success messages
1155
+	 *  @type array $errors    all the error messages
1156
+	 *  @type array $attention all the attention messages
1157
+	 * }
1158
+	 */
1159
+	public static function get_raw_notices()
1160
+	{
1161
+		return self::$_espresso_notices;
1162
+	}
1163
+
1164
+
1165
+
1166
+	/**
1167
+	 * @deprecated 4.9.27
1168
+	 * @param string $pan_name     the name, or key of the Persistent Admin Notice to be stored
1169
+	 * @param string $pan_message  the message to be stored persistently until dismissed
1170
+	 * @param bool   $force_update allows one to enforce the reappearance of a persistent message.
1171
+	 * @return void
1172
+	 * @throws InvalidDataTypeException
1173
+	 */
1174
+	public static function add_persistent_admin_notice($pan_name = '', $pan_message, $force_update = false)
1175
+	{
1176
+		new PersistentAdminNotice(
1177
+			$pan_name,
1178
+			$pan_message,
1179
+			$force_update
1180
+		);
1181
+		EE_Error::doing_it_wrong(
1182
+			__METHOD__,
1183
+			sprintf(
1184
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1185
+				'\EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
1186
+			),
1187
+			'4.9.27'
1188
+		);
1189
+	}
1190
+
1191
+
1192
+
1193
+	/**
1194
+	 * @deprecated 4.9.27
1195
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
1196
+	 * @param bool   $purge
1197
+	 * @param bool   $return
1198
+	 * @throws DomainException
1199
+	 * @throws InvalidInterfaceException
1200
+	 * @throws InvalidDataTypeException
1201
+	 * @throws ServiceNotFoundException
1202
+	 * @throws InvalidArgumentException
1203
+	 */
1204
+	public static function dismiss_persistent_admin_notice($pan_name = '', $purge = false, $return = false)
1205
+	{
1206
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
1207
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
1208
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1209
+		);
1210
+		$persistent_admin_notice_manager->dismissNotice($pan_name, $purge, $return);
1211
+		EE_Error::doing_it_wrong(
1212
+			__METHOD__,
1213
+			sprintf(
1214
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1215
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1216
+			),
1217
+			'4.9.27'
1218
+		);
1219
+	}
1220
+
1221
+
1222
+
1223
+	/**
1224
+	 * @deprecated 4.9.27
1225
+	 * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
1226
+	 * @param  string $pan_message the message to be stored persistently until dismissed
1227
+	 * @param  string $return_url  URL to go back to after nag notice is dismissed
1228
+	 */
1229
+	public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
1230
+	{
1231
+		EE_Error::doing_it_wrong(
1232
+			__METHOD__,
1233
+			sprintf(
1234
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1235
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1236
+			),
1237
+			'4.9.27'
1238
+		);
1239
+	}
1240
+
1241
+
1242
+
1243
+	/**
1244
+	 * @deprecated 4.9.27
1245
+	 * @param string $return_url
1246
+	 */
1247
+	public static function get_persistent_admin_notices($return_url = '')
1248
+	{
1249
+		EE_Error::doing_it_wrong(
1250
+			__METHOD__,
1251
+			sprintf(
1252
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1253
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1254
+			),
1255
+			'4.9.27'
1256
+		);
1257
+	}
1258 1258
 
1259 1259
 
1260 1260
 
@@ -1269,27 +1269,27 @@  discard block
 block discarded – undo
1269 1269
  */
1270 1270
 function espresso_error_enqueue_scripts()
1271 1271
 {
1272
-    // js for error handling
1273
-    wp_register_script(
1274
-        'espresso_core',
1275
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1276
-        array('jquery'),
1277
-        EVENT_ESPRESSO_VERSION,
1278
-        false
1279
-    );
1280
-    wp_register_script(
1281
-        'ee_error_js',
1282
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1283
-        array('espresso_core'),
1284
-        EVENT_ESPRESSO_VERSION,
1285
-        false
1286
-    );
1272
+	// js for error handling
1273
+	wp_register_script(
1274
+		'espresso_core',
1275
+		EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1276
+		array('jquery'),
1277
+		EVENT_ESPRESSO_VERSION,
1278
+		false
1279
+	);
1280
+	wp_register_script(
1281
+		'ee_error_js',
1282
+		EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1283
+		array('espresso_core'),
1284
+		EVENT_ESPRESSO_VERSION,
1285
+		false
1286
+	);
1287 1287
 }
1288 1288
 
1289 1289
 if (is_admin()) {
1290
-    add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1290
+	add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1291 1291
 } else {
1292
-    add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1292
+	add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1293 1293
 }
1294 1294
 
1295 1295
 
Please login to merge, or discard this patch.
core/libraries/messages/messenger/EE_Email_messenger.class.php 2 patches
Indentation   +645 added lines, -645 removed lines patch added patch discarded remove patch
@@ -8,649 +8,649 @@
 block discarded – undo
8 8
 class EE_Email_messenger extends EE_messenger
9 9
 {
10 10
 
11
-    /**
12
-     * To field for email
13
-     * @var string
14
-     */
15
-    protected $_to = '';
16
-
17
-
18
-    /**
19
-     * CC field for email.
20
-     * @var string
21
-     */
22
-    protected $_cc = '';
23
-
24
-    /**
25
-     * From field for email
26
-     * @var string
27
-     */
28
-    protected $_from = '';
29
-
30
-
31
-    /**
32
-     * Subject field for email
33
-     * @var string
34
-     */
35
-    protected $_subject = '';
36
-
37
-
38
-    /**
39
-     * Content field for email
40
-     * @var string
41
-     */
42
-    protected $_content = '';
43
-
44
-
45
-    /**
46
-     * constructor
47
-     *
48
-     * @access public
49
-     */
50
-    public function __construct()
51
-    {
52
-        //set name and description properties
53
-        $this->name                = 'email';
54
-        $this->description         = sprintf(
55
-            esc_html__(
56
-                'This messenger delivers messages via email using the built-in %s function included with WordPress',
57
-                'event_espresso'
58
-            ),
59
-            '<code>wp_mail</code>'
60
-        );
61
-        $this->label               = array(
62
-            'singular' => esc_html__('email', 'event_espresso'),
63
-            'plural'   => esc_html__('emails', 'event_espresso'),
64
-        );
65
-        $this->activate_on_install = true;
66
-
67
-        //we're using defaults so let's call parent constructor that will take care of setting up all the other
68
-        // properties
69
-        parent::__construct();
70
-    }
71
-
72
-
73
-    /**
74
-     * see abstract declaration in parent class for details.
75
-     */
76
-    protected function _set_admin_pages()
77
-    {
78
-        $this->admin_registered_pages = array(
79
-            'events_edit' => true,
80
-        );
81
-    }
82
-
83
-
84
-    /**
85
-     * see abstract declaration in parent class for details
86
-     */
87
-    protected function _set_valid_shortcodes()
88
-    {
89
-        //remember by leaving the other fields not set, those fields will inherit the valid shortcodes from the
90
-        // message type.
91
-        $this->_valid_shortcodes = array(
92
-            'to'   => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
93
-            'cc' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
94
-            'from' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
95
-        );
96
-    }
97
-
98
-
99
-    /**
100
-     * see abstract declaration in parent class for details
101
-     *
102
-     * @access protected
103
-     * @return void
104
-     */
105
-    protected function _set_validator_config()
106
-    {
107
-        $valid_shortcodes = $this->get_valid_shortcodes();
108
-
109
-        $this->_validator_config = array(
110
-            'to'            => array(
111
-                'shortcodes' => $valid_shortcodes['to'],
112
-                'type'       => 'email',
113
-            ),
114
-            'cc' => array(
115
-                'shortcodes' => $valid_shortcodes['to'],
116
-                'type' => 'email',
117
-            ),
118
-            'from'          => array(
119
-                'shortcodes' => $valid_shortcodes['from'],
120
-                'type'       => 'email',
121
-            ),
122
-            'subject'       => array(
123
-                'shortcodes' => array(
124
-                    'organization',
125
-                    'primary_registration_details',
126
-                    'event_author',
127
-                    'primary_registration_details',
128
-                    'recipient_details',
129
-                ),
130
-            ),
131
-            'content'       => array(
132
-                'shortcodes' => array(
133
-                    'event_list',
134
-                    'attendee_list',
135
-                    'ticket_list',
136
-                    'organization',
137
-                    'primary_registration_details',
138
-                    'primary_registration_list',
139
-                    'event_author',
140
-                    'recipient_details',
141
-                    'recipient_list',
142
-                    'transaction',
143
-                    'messenger',
144
-                ),
145
-            ),
146
-            'attendee_list' => array(
147
-                'shortcodes' => array('attendee', 'event_list', 'ticket_list'),
148
-                'required'   => array('[ATTENDEE_LIST]'),
149
-            ),
150
-            'event_list'    => array(
151
-                'shortcodes' => array(
152
-                    'event',
153
-                    'attendee_list',
154
-                    'ticket_list',
155
-                    'venue',
156
-                    'datetime_list',
157
-                    'attendee',
158
-                    'primary_registration_details',
159
-                    'primary_registration_list',
160
-                    'event_author',
161
-                    'recipient_details',
162
-                    'recipient_list',
163
-                ),
164
-                'required'   => array('[EVENT_LIST]'),
165
-            ),
166
-            'ticket_list'   => array(
167
-                'shortcodes' => array(
168
-                    'event_list',
169
-                    'attendee_list',
170
-                    'ticket',
171
-                    'datetime_list',
172
-                    'primary_registration_details',
173
-                    'recipient_details',
174
-                ),
175
-                'required'   => array('[TICKET_LIST]'),
176
-            ),
177
-            'datetime_list' => array(
178
-                'shortcodes' => array('datetime'),
179
-                'required'   => array('[DATETIME_LIST]'),
180
-            ),
181
-        );
182
-    }
183
-
184
-
185
-    /**
186
-     * @see   parent EE_messenger class for docs
187
-     * @since 4.5.0
188
-     */
189
-    public function do_secondary_messenger_hooks($sending_messenger_name)
190
-    {
191
-        if ($sending_messenger_name = 'html') {
192
-            add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
193
-        }
194
-    }
195
-
196
-
197
-    public function add_email_css(
198
-        $variation_path,
199
-        $messenger,
200
-        $message_type,
201
-        $type,
202
-        $variation,
203
-        $file_extension,
204
-        $url,
205
-        EE_Messages_Template_Pack $template_pack
206
-    ) {
207
-        //prevent recursion on this callback.
208
-        remove_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10);
209
-        $variation = $this->get_variation($template_pack, $message_type, $url, 'main', $variation, false);
210
-
211
-        add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
212
-        return $variation;
213
-    }
214
-
215
-
216
-    /**
217
-     * See parent for details
218
-     *
219
-     * @access protected
220
-     * @return void
221
-     */
222
-    protected function _set_test_settings_fields()
223
-    {
224
-        $this->_test_settings_fields = array(
225
-            'to'      => array(
226
-                'input'      => 'text',
227
-                'label'      => esc_html__('Send a test email to', 'event_espresso'),
228
-                'type'       => 'email',
229
-                'required'   => true,
230
-                'validation' => true,
231
-                'css_class'  => 'large-text',
232
-                'format'     => '%s',
233
-                'default'    => get_bloginfo('admin_email'),
234
-            ),
235
-            'subject' => array(
236
-                'input'      => 'hidden',
237
-                'label'      => '',
238
-                'type'       => 'string',
239
-                'required'   => false,
240
-                'validation' => false,
241
-                'format'     => '%s',
242
-                'value'      => sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name')),
243
-                'default'    => '',
244
-                'css_class'  => '',
245
-            ),
246
-        );
247
-    }
248
-
249
-
250
-    /**
251
-     * _set_template_fields
252
-     * This sets up the fields that a messenger requires for the message to go out.
253
-     *
254
-     * @access  protected
255
-     * @return void
256
-     */
257
-    protected function _set_template_fields()
258
-    {
259
-        // any extra template fields that are NOT used by the messenger but will get used by a messenger field for
260
-        // shortcode replacement get added to the 'extra' key in an associated array indexed by the messenger field
261
-        // they relate to.  This is important for the Messages_admin to know what fields to display to the user.
262
-        //  Also, notice that the "values" are equal to the field type that messages admin will use to know what
263
-        // kind of field to display. The values ALSO have one index labeled "shortcode".  the values in that array
264
-        // indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE]) is required in order for this extra field to be
265
-        // displayed.  If the required shortcode isn't part of the shortcodes array then the field is not needed and
266
-        // will not be displayed/parsed.
267
-        $this->_template_fields = array(
268
-            'to'      => array(
269
-                'input'      => 'text',
270
-                'label'      => esc_html_x(
271
-                    'To',
272
-                    'Label for the "To" field for email addresses',
273
-                    'event_espresso'
274
-                ),
275
-                'type'       => 'string',
276
-                'required'   => true,
277
-                'validation' => true,
278
-                'css_class'  => 'large-text',
279
-                'format'     => '%s',
280
-            ),
281
-            'cc'      => array(
282
-                'input'      => 'text',
283
-                'label'      => esc_html_x(
284
-                    'CC',
285
-                    'Label for the "Carbon Copy" field used for additional email addresses',
286
-                    'event_espresso'
287
-                ),
288
-                'type'       => 'string',
289
-                'required'   => false,
290
-                'validation' => true,
291
-                'css_class'  => 'large-text',
292
-                'format'     => '%s',
293
-            ),
294
-            'from'    => array(
295
-                'input'      => 'text',
296
-                'label'      => esc_html_x(
297
-                    'From',
298
-                    'Label for the "From" field for email addresses.',
299
-                    'event_espresso'
300
-                ),
301
-                'type'       => 'string',
302
-                'required'   => true,
303
-                'validation' => true,
304
-                'css_class'  => 'large-text',
305
-                'format'     => '%s',
306
-            ),
307
-            'subject' => array(
308
-                'input'      => 'text',
309
-                'label'      => esc_html_x(
310
-                    'Subject',
311
-                    'Label for the "Subject" field (short description of contents) for emails.',
312
-                    'event_espresso'
313
-                ),
314
-                'type'       => 'string',
315
-                'required'   => true,
316
-                'validation' => true,
317
-                'css_class'  => 'large-text',
318
-                'format'     => '%s',
319
-            ),
320
-            'content' => '',
321
-            //left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
322
-            'extra'   => array(
323
-                'content' => array(
324
-                    'main'          => array(
325
-                        'input'      => 'wp_editor',
326
-                        'label'      => esc_html__('Main Content', 'event_espresso'),
327
-                        'type'       => 'string',
328
-                        'required'   => true,
329
-                        'validation' => true,
330
-                        'format'     => '%s',
331
-                        'rows'       => '15',
332
-                    ),
333
-                    'event_list'    => array(
334
-                        'input'               => 'wp_editor',
335
-                        'label'               => '[EVENT_LIST]',
336
-                        'type'                => 'string',
337
-                        'required'            => true,
338
-                        'validation'          => true,
339
-                        'format'              => '%s',
340
-                        'rows'                => '15',
341
-                        'shortcodes_required' => array('[EVENT_LIST]'),
342
-                    ),
343
-                    'attendee_list' => array(
344
-                        'input'               => 'textarea',
345
-                        'label'               => '[ATTENDEE_LIST]',
346
-                        'type'                => 'string',
347
-                        'required'            => true,
348
-                        'validation'          => true,
349
-                        'format'              => '%s',
350
-                        'css_class'           => 'large-text',
351
-                        'rows'                => '5',
352
-                        'shortcodes_required' => array('[ATTENDEE_LIST]'),
353
-                    ),
354
-                    'ticket_list'   => array(
355
-                        'input'               => 'textarea',
356
-                        'label'               => '[TICKET_LIST]',
357
-                        'type'                => 'string',
358
-                        'required'            => true,
359
-                        'validation'          => true,
360
-                        'format'              => '%s',
361
-                        'css_class'           => 'large-text',
362
-                        'rows'                => '10',
363
-                        'shortcodes_required' => array('[TICKET_LIST]'),
364
-                    ),
365
-                    'datetime_list' => array(
366
-                        'input'               => 'textarea',
367
-                        'label'               => '[DATETIME_LIST]',
368
-                        'type'                => 'string',
369
-                        'required'            => true,
370
-                        'validation'          => true,
371
-                        'format'              => '%s',
372
-                        'css_class'           => 'large-text',
373
-                        'rows'                => '10',
374
-                        'shortcodes_required' => array('[DATETIME_LIST]'),
375
-                    ),
376
-                ),
377
-            ),
378
-        );
379
-    }
380
-
381
-
382
-    /**
383
-     * See definition of this class in parent
384
-     */
385
-    protected function _set_default_message_types()
386
-    {
387
-        $this->_default_message_types = array(
388
-            'payment',
389
-            'payment_refund',
390
-            'registration',
391
-            'not_approved_registration',
392
-            'pending_approval',
393
-        );
394
-    }
395
-
396
-
397
-    /**
398
-     * @see   definition of this class in parent
399
-     * @since 4.5.0
400
-     */
401
-    protected function _set_valid_message_types()
402
-    {
403
-        $this->_valid_message_types = array(
404
-            'payment',
405
-            'registration',
406
-            'not_approved_registration',
407
-            'declined_registration',
408
-            'cancelled_registration',
409
-            'pending_approval',
410
-            'registration_summary',
411
-            'payment_reminder',
412
-            'payment_declined',
413
-            'payment_refund',
414
-        );
415
-    }
416
-
417
-
418
-    /**
419
-     * setting up admin_settings_fields for messenger.
420
-     */
421
-    protected function _set_admin_settings_fields()
422
-    {
423
-    }
424
-
425
-    /**
426
-     * We just deliver the messages don't kill us!!
427
-     *
428
-     * @return bool|WP_Error true if message delivered, false if it didn't deliver OR bubble up any error object if
429
-     *              present.
430
-     * @throws EE_Error
431
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
432
-     */
433
-    protected function _send_message()
434
-    {
435
-        $success = wp_mail(
436
-            $this->_to,
437
-            //some old values for subject may be expecting HTML entities to be decoded in the subject
438
-            //and subjects aren't interpreted as HTML, so there should be no HTML in them
439
-            wp_strip_all_tags(wp_specialchars_decode($this->_subject, ENT_QUOTES)),
440
-            $this->_body(),
441
-            $this->_headers()
442
-        );
443
-        if (! $success) {
444
-            EE_Error::add_error(
445
-                sprintf(
446
-                    esc_html__(
447
-                        'The email did not send successfully.%3$sThe WordPress wp_mail function is used for sending mails but does not give any useful information when an email fails to send.%3$sIt is possible the "to" address (%1$s) or "from" address (%2$s) is invalid.%3$s',
448
-                        'event_espresso'
449
-                    ),
450
-                    $this->_to,
451
-                    $this->_from,
452
-                    '<br />'
453
-                ),
454
-                __FILE__,
455
-                __FUNCTION__,
456
-                __LINE__
457
-            );
458
-        }
459
-        return $success;
460
-    }
461
-
462
-
463
-    /**
464
-     * see parent for definition
465
-     *
466
-     * @return string html body of the message content and the related css.
467
-     * @throws EE_Error
468
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
469
-     */
470
-    protected function _preview()
471
-    {
472
-        return $this->_body(true);
473
-    }
474
-
475
-
476
-    /**
477
-     * Setup headers for email
478
-     *
479
-     * @access protected
480
-     * @return string formatted header for email
481
-     */
482
-    protected function _headers()
483
-    {
484
-        $this->_ensure_has_from_email_address();
485
-        $from    = $this->_from;
486
-        $headers = array(
487
-            'From:' . $from,
488
-            'Reply-To:' . $from,
489
-            'Content-Type:text/html; charset=utf-8',
490
-        );
491
-
492
-        /**
493
-         * Second condition added as a result of https://events.codebasehq.com/projects/event-espresso/tickets/11416 to
494
-         * cover back compat where there may be users who have saved cc values in their db for the newsletter message
495
-         * type which they are no longer able to change.
496
-         */
497
-        if (! empty($this->_cc) && ! $this->_incoming_message_type instanceof EE_Newsletter_message_type) {
498
-            $headers[] = 'cc: ' . $this->_cc;
499
-        }
500
-
501
-        //but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
502
-        // header.
503
-        add_filter('wp_mail_from', array($this, 'set_from_address'), 100);
504
-        add_filter('wp_mail_from_name', array($this, 'set_from_name'), 100);
505
-        return apply_filters('FHEE__EE_Email_messenger___headers', $headers, $this->_incoming_message_type, $this);
506
-    }
507
-
508
-
509
-    /**
510
-     * This simply ensures that the from address is not empty.  If it is, then we use whatever is set as the site email
511
-     * address for the from address to avoid problems with sending emails.
512
-     */
513
-    protected function _ensure_has_from_email_address()
514
-    {
515
-        if (empty($this->_from)) {
516
-            $this->_from = get_bloginfo('admin_email');
517
-        }
518
-    }
519
-
520
-
521
-    /**
522
-     * This simply parses whatever is set as the $_from address and determines if it is in the format {name} <{email}>
523
-     * or just {email} and returns an array with the "from_name" and "from_email" as the values. Note from_name *MAY*
524
-     * be empty
525
-     *
526
-     * @since 4.3.1
527
-     * @return array
528
-     */
529
-    private function _parse_from()
530
-    {
531
-        if (strpos($this->_from, '<') !== false) {
532
-            $from_name = substr($this->_from, 0, strpos($this->_from, '<') - 1);
533
-            $from_name = str_replace('"', '', $from_name);
534
-            $from_name = trim($from_name);
535
-
536
-            $from_email = substr($this->_from, strpos($this->_from, '<') + 1);
537
-            $from_email = str_replace('>', '', $from_email);
538
-            $from_email = trim($from_email);
539
-        } elseif (trim($this->_from) !== '') {
540
-            $from_name  = '';
541
-            $from_email = trim($this->_from);
542
-        } else {
543
-            $from_name = $from_email = '';
544
-        }
545
-        return array($from_name, $from_email);
546
-    }
547
-
548
-
549
-    /**
550
-     * Callback for the wp_mail_from filter.
551
-     *
552
-     * @since 4.3.1
553
-     * @param string $from_email What the original from_email is.
554
-     * @return string
555
-     */
556
-    public function set_from_address($from_email)
557
-    {
558
-        $parsed_from = $this->_parse_from();
559
-        //includes fallback if the parsing failed.
560
-        $from_email = is_array($parsed_from) && ! empty($parsed_from[1])
561
-            ? $parsed_from[1]
562
-            : get_bloginfo('admin_email');
563
-        return $from_email;
564
-    }
565
-
566
-
567
-    /**
568
-     * Callback fro the wp_mail_from_name filter.
569
-     *
570
-     * @since 4.3.1
571
-     * @param string $from_name The original from_name.
572
-     * @return string
573
-     */
574
-    public function set_from_name($from_name)
575
-    {
576
-        $parsed_from = $this->_parse_from();
577
-        if (is_array($parsed_from) && ! empty($parsed_from[0])) {
578
-            $from_name = $parsed_from[0];
579
-        }
580
-
581
-        //if from name is "WordPress" let's sub in the site name instead (more friendly!)
582
-        //but realize the default name is HTML entity-encoded
583
-        $from_name = $from_name == 'WordPress' ? wp_specialchars_decode(get_bloginfo(), ENT_QUOTES) : $from_name;
584
-
585
-        return $from_name;
586
-    }
587
-
588
-
589
-    /**
590
-     * setup body for email
591
-     *
592
-     * @param bool $preview will determine whether this is preview template or not.
593
-     * @return string formatted body for email.
594
-     * @throws EE_Error
595
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
596
-     */
597
-    protected function _body($preview = false)
598
-    {
599
-        //setup template args!
600
-        $this->_template_args = array(
601
-            'subject'   => $this->_subject,
602
-            'from'      => $this->_from,
603
-            'main_body' => wpautop($this->_content),
604
-        );
605
-        $body                 = $this->_get_main_template($preview);
606
-
607
-        /**
608
-         * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
609
-         *
610
-         * @type    bool $preview Indicates whether a preview is being generated or not.
611
-         * @return  bool    true  indicates to use the inliner, false bypasses it.
612
-         */
613
-        if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
614
-            //require CssToInlineStyles library and its dependencies via composer autoloader
615
-            require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
616
-
617
-            //now if this isn't a preview, let's setup the body so it has inline styles
618
-            if (! $preview || ($preview && defined('DOING_AJAX'))) {
619
-                $style = file_get_contents(
620
-                    $this->get_variation(
621
-                        $this->_tmp_pack,
622
-                        $this->_incoming_message_type->name,
623
-                        false,
624
-                        'main',
625
-                        $this->_variation
626
-                    ),
627
-                    true
628
-                );
629
-                $CSS   = new TijsVerkoyen\CssToInlineStyles\CssToInlineStyles($body, $style);
630
-                //for some reason the library has a bracket and new line at the beginning.  This takes care of that.
631
-                $body  = ltrim($CSS->convert(true), ">\n");
632
-                //see https://events.codebasehq.com/projects/event-espresso/tickets/8609
633
-                $body  = ltrim($body, "<?");
634
-            }
635
-
636
-        }
637
-        return $body;
638
-    }
639
-
640
-
641
-    /**
642
-     * This just returns any existing test settings that might be saved in the database
643
-     *
644
-     * @access public
645
-     * @return array
646
-     */
647
-    public function get_existing_test_settings()
648
-    {
649
-        $settings = parent::get_existing_test_settings();
650
-        //override subject if present because we always want it to be fresh.
651
-        if (is_array($settings) && ! empty($settings['subject'])) {
652
-            $settings['subject'] = sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name'));
653
-        }
654
-        return $settings;
655
-    }
11
+	/**
12
+	 * To field for email
13
+	 * @var string
14
+	 */
15
+	protected $_to = '';
16
+
17
+
18
+	/**
19
+	 * CC field for email.
20
+	 * @var string
21
+	 */
22
+	protected $_cc = '';
23
+
24
+	/**
25
+	 * From field for email
26
+	 * @var string
27
+	 */
28
+	protected $_from = '';
29
+
30
+
31
+	/**
32
+	 * Subject field for email
33
+	 * @var string
34
+	 */
35
+	protected $_subject = '';
36
+
37
+
38
+	/**
39
+	 * Content field for email
40
+	 * @var string
41
+	 */
42
+	protected $_content = '';
43
+
44
+
45
+	/**
46
+	 * constructor
47
+	 *
48
+	 * @access public
49
+	 */
50
+	public function __construct()
51
+	{
52
+		//set name and description properties
53
+		$this->name                = 'email';
54
+		$this->description         = sprintf(
55
+			esc_html__(
56
+				'This messenger delivers messages via email using the built-in %s function included with WordPress',
57
+				'event_espresso'
58
+			),
59
+			'<code>wp_mail</code>'
60
+		);
61
+		$this->label               = array(
62
+			'singular' => esc_html__('email', 'event_espresso'),
63
+			'plural'   => esc_html__('emails', 'event_espresso'),
64
+		);
65
+		$this->activate_on_install = true;
66
+
67
+		//we're using defaults so let's call parent constructor that will take care of setting up all the other
68
+		// properties
69
+		parent::__construct();
70
+	}
71
+
72
+
73
+	/**
74
+	 * see abstract declaration in parent class for details.
75
+	 */
76
+	protected function _set_admin_pages()
77
+	{
78
+		$this->admin_registered_pages = array(
79
+			'events_edit' => true,
80
+		);
81
+	}
82
+
83
+
84
+	/**
85
+	 * see abstract declaration in parent class for details
86
+	 */
87
+	protected function _set_valid_shortcodes()
88
+	{
89
+		//remember by leaving the other fields not set, those fields will inherit the valid shortcodes from the
90
+		// message type.
91
+		$this->_valid_shortcodes = array(
92
+			'to'   => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
93
+			'cc' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
94
+			'from' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
95
+		);
96
+	}
97
+
98
+
99
+	/**
100
+	 * see abstract declaration in parent class for details
101
+	 *
102
+	 * @access protected
103
+	 * @return void
104
+	 */
105
+	protected function _set_validator_config()
106
+	{
107
+		$valid_shortcodes = $this->get_valid_shortcodes();
108
+
109
+		$this->_validator_config = array(
110
+			'to'            => array(
111
+				'shortcodes' => $valid_shortcodes['to'],
112
+				'type'       => 'email',
113
+			),
114
+			'cc' => array(
115
+				'shortcodes' => $valid_shortcodes['to'],
116
+				'type' => 'email',
117
+			),
118
+			'from'          => array(
119
+				'shortcodes' => $valid_shortcodes['from'],
120
+				'type'       => 'email',
121
+			),
122
+			'subject'       => array(
123
+				'shortcodes' => array(
124
+					'organization',
125
+					'primary_registration_details',
126
+					'event_author',
127
+					'primary_registration_details',
128
+					'recipient_details',
129
+				),
130
+			),
131
+			'content'       => array(
132
+				'shortcodes' => array(
133
+					'event_list',
134
+					'attendee_list',
135
+					'ticket_list',
136
+					'organization',
137
+					'primary_registration_details',
138
+					'primary_registration_list',
139
+					'event_author',
140
+					'recipient_details',
141
+					'recipient_list',
142
+					'transaction',
143
+					'messenger',
144
+				),
145
+			),
146
+			'attendee_list' => array(
147
+				'shortcodes' => array('attendee', 'event_list', 'ticket_list'),
148
+				'required'   => array('[ATTENDEE_LIST]'),
149
+			),
150
+			'event_list'    => array(
151
+				'shortcodes' => array(
152
+					'event',
153
+					'attendee_list',
154
+					'ticket_list',
155
+					'venue',
156
+					'datetime_list',
157
+					'attendee',
158
+					'primary_registration_details',
159
+					'primary_registration_list',
160
+					'event_author',
161
+					'recipient_details',
162
+					'recipient_list',
163
+				),
164
+				'required'   => array('[EVENT_LIST]'),
165
+			),
166
+			'ticket_list'   => array(
167
+				'shortcodes' => array(
168
+					'event_list',
169
+					'attendee_list',
170
+					'ticket',
171
+					'datetime_list',
172
+					'primary_registration_details',
173
+					'recipient_details',
174
+				),
175
+				'required'   => array('[TICKET_LIST]'),
176
+			),
177
+			'datetime_list' => array(
178
+				'shortcodes' => array('datetime'),
179
+				'required'   => array('[DATETIME_LIST]'),
180
+			),
181
+		);
182
+	}
183
+
184
+
185
+	/**
186
+	 * @see   parent EE_messenger class for docs
187
+	 * @since 4.5.0
188
+	 */
189
+	public function do_secondary_messenger_hooks($sending_messenger_name)
190
+	{
191
+		if ($sending_messenger_name = 'html') {
192
+			add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
193
+		}
194
+	}
195
+
196
+
197
+	public function add_email_css(
198
+		$variation_path,
199
+		$messenger,
200
+		$message_type,
201
+		$type,
202
+		$variation,
203
+		$file_extension,
204
+		$url,
205
+		EE_Messages_Template_Pack $template_pack
206
+	) {
207
+		//prevent recursion on this callback.
208
+		remove_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10);
209
+		$variation = $this->get_variation($template_pack, $message_type, $url, 'main', $variation, false);
210
+
211
+		add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
212
+		return $variation;
213
+	}
214
+
215
+
216
+	/**
217
+	 * See parent for details
218
+	 *
219
+	 * @access protected
220
+	 * @return void
221
+	 */
222
+	protected function _set_test_settings_fields()
223
+	{
224
+		$this->_test_settings_fields = array(
225
+			'to'      => array(
226
+				'input'      => 'text',
227
+				'label'      => esc_html__('Send a test email to', 'event_espresso'),
228
+				'type'       => 'email',
229
+				'required'   => true,
230
+				'validation' => true,
231
+				'css_class'  => 'large-text',
232
+				'format'     => '%s',
233
+				'default'    => get_bloginfo('admin_email'),
234
+			),
235
+			'subject' => array(
236
+				'input'      => 'hidden',
237
+				'label'      => '',
238
+				'type'       => 'string',
239
+				'required'   => false,
240
+				'validation' => false,
241
+				'format'     => '%s',
242
+				'value'      => sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name')),
243
+				'default'    => '',
244
+				'css_class'  => '',
245
+			),
246
+		);
247
+	}
248
+
249
+
250
+	/**
251
+	 * _set_template_fields
252
+	 * This sets up the fields that a messenger requires for the message to go out.
253
+	 *
254
+	 * @access  protected
255
+	 * @return void
256
+	 */
257
+	protected function _set_template_fields()
258
+	{
259
+		// any extra template fields that are NOT used by the messenger but will get used by a messenger field for
260
+		// shortcode replacement get added to the 'extra' key in an associated array indexed by the messenger field
261
+		// they relate to.  This is important for the Messages_admin to know what fields to display to the user.
262
+		//  Also, notice that the "values" are equal to the field type that messages admin will use to know what
263
+		// kind of field to display. The values ALSO have one index labeled "shortcode".  the values in that array
264
+		// indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE]) is required in order for this extra field to be
265
+		// displayed.  If the required shortcode isn't part of the shortcodes array then the field is not needed and
266
+		// will not be displayed/parsed.
267
+		$this->_template_fields = array(
268
+			'to'      => array(
269
+				'input'      => 'text',
270
+				'label'      => esc_html_x(
271
+					'To',
272
+					'Label for the "To" field for email addresses',
273
+					'event_espresso'
274
+				),
275
+				'type'       => 'string',
276
+				'required'   => true,
277
+				'validation' => true,
278
+				'css_class'  => 'large-text',
279
+				'format'     => '%s',
280
+			),
281
+			'cc'      => array(
282
+				'input'      => 'text',
283
+				'label'      => esc_html_x(
284
+					'CC',
285
+					'Label for the "Carbon Copy" field used for additional email addresses',
286
+					'event_espresso'
287
+				),
288
+				'type'       => 'string',
289
+				'required'   => false,
290
+				'validation' => true,
291
+				'css_class'  => 'large-text',
292
+				'format'     => '%s',
293
+			),
294
+			'from'    => array(
295
+				'input'      => 'text',
296
+				'label'      => esc_html_x(
297
+					'From',
298
+					'Label for the "From" field for email addresses.',
299
+					'event_espresso'
300
+				),
301
+				'type'       => 'string',
302
+				'required'   => true,
303
+				'validation' => true,
304
+				'css_class'  => 'large-text',
305
+				'format'     => '%s',
306
+			),
307
+			'subject' => array(
308
+				'input'      => 'text',
309
+				'label'      => esc_html_x(
310
+					'Subject',
311
+					'Label for the "Subject" field (short description of contents) for emails.',
312
+					'event_espresso'
313
+				),
314
+				'type'       => 'string',
315
+				'required'   => true,
316
+				'validation' => true,
317
+				'css_class'  => 'large-text',
318
+				'format'     => '%s',
319
+			),
320
+			'content' => '',
321
+			//left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
322
+			'extra'   => array(
323
+				'content' => array(
324
+					'main'          => array(
325
+						'input'      => 'wp_editor',
326
+						'label'      => esc_html__('Main Content', 'event_espresso'),
327
+						'type'       => 'string',
328
+						'required'   => true,
329
+						'validation' => true,
330
+						'format'     => '%s',
331
+						'rows'       => '15',
332
+					),
333
+					'event_list'    => array(
334
+						'input'               => 'wp_editor',
335
+						'label'               => '[EVENT_LIST]',
336
+						'type'                => 'string',
337
+						'required'            => true,
338
+						'validation'          => true,
339
+						'format'              => '%s',
340
+						'rows'                => '15',
341
+						'shortcodes_required' => array('[EVENT_LIST]'),
342
+					),
343
+					'attendee_list' => array(
344
+						'input'               => 'textarea',
345
+						'label'               => '[ATTENDEE_LIST]',
346
+						'type'                => 'string',
347
+						'required'            => true,
348
+						'validation'          => true,
349
+						'format'              => '%s',
350
+						'css_class'           => 'large-text',
351
+						'rows'                => '5',
352
+						'shortcodes_required' => array('[ATTENDEE_LIST]'),
353
+					),
354
+					'ticket_list'   => array(
355
+						'input'               => 'textarea',
356
+						'label'               => '[TICKET_LIST]',
357
+						'type'                => 'string',
358
+						'required'            => true,
359
+						'validation'          => true,
360
+						'format'              => '%s',
361
+						'css_class'           => 'large-text',
362
+						'rows'                => '10',
363
+						'shortcodes_required' => array('[TICKET_LIST]'),
364
+					),
365
+					'datetime_list' => array(
366
+						'input'               => 'textarea',
367
+						'label'               => '[DATETIME_LIST]',
368
+						'type'                => 'string',
369
+						'required'            => true,
370
+						'validation'          => true,
371
+						'format'              => '%s',
372
+						'css_class'           => 'large-text',
373
+						'rows'                => '10',
374
+						'shortcodes_required' => array('[DATETIME_LIST]'),
375
+					),
376
+				),
377
+			),
378
+		);
379
+	}
380
+
381
+
382
+	/**
383
+	 * See definition of this class in parent
384
+	 */
385
+	protected function _set_default_message_types()
386
+	{
387
+		$this->_default_message_types = array(
388
+			'payment',
389
+			'payment_refund',
390
+			'registration',
391
+			'not_approved_registration',
392
+			'pending_approval',
393
+		);
394
+	}
395
+
396
+
397
+	/**
398
+	 * @see   definition of this class in parent
399
+	 * @since 4.5.0
400
+	 */
401
+	protected function _set_valid_message_types()
402
+	{
403
+		$this->_valid_message_types = array(
404
+			'payment',
405
+			'registration',
406
+			'not_approved_registration',
407
+			'declined_registration',
408
+			'cancelled_registration',
409
+			'pending_approval',
410
+			'registration_summary',
411
+			'payment_reminder',
412
+			'payment_declined',
413
+			'payment_refund',
414
+		);
415
+	}
416
+
417
+
418
+	/**
419
+	 * setting up admin_settings_fields for messenger.
420
+	 */
421
+	protected function _set_admin_settings_fields()
422
+	{
423
+	}
424
+
425
+	/**
426
+	 * We just deliver the messages don't kill us!!
427
+	 *
428
+	 * @return bool|WP_Error true if message delivered, false if it didn't deliver OR bubble up any error object if
429
+	 *              present.
430
+	 * @throws EE_Error
431
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
432
+	 */
433
+	protected function _send_message()
434
+	{
435
+		$success = wp_mail(
436
+			$this->_to,
437
+			//some old values for subject may be expecting HTML entities to be decoded in the subject
438
+			//and subjects aren't interpreted as HTML, so there should be no HTML in them
439
+			wp_strip_all_tags(wp_specialchars_decode($this->_subject, ENT_QUOTES)),
440
+			$this->_body(),
441
+			$this->_headers()
442
+		);
443
+		if (! $success) {
444
+			EE_Error::add_error(
445
+				sprintf(
446
+					esc_html__(
447
+						'The email did not send successfully.%3$sThe WordPress wp_mail function is used for sending mails but does not give any useful information when an email fails to send.%3$sIt is possible the "to" address (%1$s) or "from" address (%2$s) is invalid.%3$s',
448
+						'event_espresso'
449
+					),
450
+					$this->_to,
451
+					$this->_from,
452
+					'<br />'
453
+				),
454
+				__FILE__,
455
+				__FUNCTION__,
456
+				__LINE__
457
+			);
458
+		}
459
+		return $success;
460
+	}
461
+
462
+
463
+	/**
464
+	 * see parent for definition
465
+	 *
466
+	 * @return string html body of the message content and the related css.
467
+	 * @throws EE_Error
468
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
469
+	 */
470
+	protected function _preview()
471
+	{
472
+		return $this->_body(true);
473
+	}
474
+
475
+
476
+	/**
477
+	 * Setup headers for email
478
+	 *
479
+	 * @access protected
480
+	 * @return string formatted header for email
481
+	 */
482
+	protected function _headers()
483
+	{
484
+		$this->_ensure_has_from_email_address();
485
+		$from    = $this->_from;
486
+		$headers = array(
487
+			'From:' . $from,
488
+			'Reply-To:' . $from,
489
+			'Content-Type:text/html; charset=utf-8',
490
+		);
491
+
492
+		/**
493
+		 * Second condition added as a result of https://events.codebasehq.com/projects/event-espresso/tickets/11416 to
494
+		 * cover back compat where there may be users who have saved cc values in their db for the newsletter message
495
+		 * type which they are no longer able to change.
496
+		 */
497
+		if (! empty($this->_cc) && ! $this->_incoming_message_type instanceof EE_Newsletter_message_type) {
498
+			$headers[] = 'cc: ' . $this->_cc;
499
+		}
500
+
501
+		//but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
502
+		// header.
503
+		add_filter('wp_mail_from', array($this, 'set_from_address'), 100);
504
+		add_filter('wp_mail_from_name', array($this, 'set_from_name'), 100);
505
+		return apply_filters('FHEE__EE_Email_messenger___headers', $headers, $this->_incoming_message_type, $this);
506
+	}
507
+
508
+
509
+	/**
510
+	 * This simply ensures that the from address is not empty.  If it is, then we use whatever is set as the site email
511
+	 * address for the from address to avoid problems with sending emails.
512
+	 */
513
+	protected function _ensure_has_from_email_address()
514
+	{
515
+		if (empty($this->_from)) {
516
+			$this->_from = get_bloginfo('admin_email');
517
+		}
518
+	}
519
+
520
+
521
+	/**
522
+	 * This simply parses whatever is set as the $_from address and determines if it is in the format {name} <{email}>
523
+	 * or just {email} and returns an array with the "from_name" and "from_email" as the values. Note from_name *MAY*
524
+	 * be empty
525
+	 *
526
+	 * @since 4.3.1
527
+	 * @return array
528
+	 */
529
+	private function _parse_from()
530
+	{
531
+		if (strpos($this->_from, '<') !== false) {
532
+			$from_name = substr($this->_from, 0, strpos($this->_from, '<') - 1);
533
+			$from_name = str_replace('"', '', $from_name);
534
+			$from_name = trim($from_name);
535
+
536
+			$from_email = substr($this->_from, strpos($this->_from, '<') + 1);
537
+			$from_email = str_replace('>', '', $from_email);
538
+			$from_email = trim($from_email);
539
+		} elseif (trim($this->_from) !== '') {
540
+			$from_name  = '';
541
+			$from_email = trim($this->_from);
542
+		} else {
543
+			$from_name = $from_email = '';
544
+		}
545
+		return array($from_name, $from_email);
546
+	}
547
+
548
+
549
+	/**
550
+	 * Callback for the wp_mail_from filter.
551
+	 *
552
+	 * @since 4.3.1
553
+	 * @param string $from_email What the original from_email is.
554
+	 * @return string
555
+	 */
556
+	public function set_from_address($from_email)
557
+	{
558
+		$parsed_from = $this->_parse_from();
559
+		//includes fallback if the parsing failed.
560
+		$from_email = is_array($parsed_from) && ! empty($parsed_from[1])
561
+			? $parsed_from[1]
562
+			: get_bloginfo('admin_email');
563
+		return $from_email;
564
+	}
565
+
566
+
567
+	/**
568
+	 * Callback fro the wp_mail_from_name filter.
569
+	 *
570
+	 * @since 4.3.1
571
+	 * @param string $from_name The original from_name.
572
+	 * @return string
573
+	 */
574
+	public function set_from_name($from_name)
575
+	{
576
+		$parsed_from = $this->_parse_from();
577
+		if (is_array($parsed_from) && ! empty($parsed_from[0])) {
578
+			$from_name = $parsed_from[0];
579
+		}
580
+
581
+		//if from name is "WordPress" let's sub in the site name instead (more friendly!)
582
+		//but realize the default name is HTML entity-encoded
583
+		$from_name = $from_name == 'WordPress' ? wp_specialchars_decode(get_bloginfo(), ENT_QUOTES) : $from_name;
584
+
585
+		return $from_name;
586
+	}
587
+
588
+
589
+	/**
590
+	 * setup body for email
591
+	 *
592
+	 * @param bool $preview will determine whether this is preview template or not.
593
+	 * @return string formatted body for email.
594
+	 * @throws EE_Error
595
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
596
+	 */
597
+	protected function _body($preview = false)
598
+	{
599
+		//setup template args!
600
+		$this->_template_args = array(
601
+			'subject'   => $this->_subject,
602
+			'from'      => $this->_from,
603
+			'main_body' => wpautop($this->_content),
604
+		);
605
+		$body                 = $this->_get_main_template($preview);
606
+
607
+		/**
608
+		 * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
609
+		 *
610
+		 * @type    bool $preview Indicates whether a preview is being generated or not.
611
+		 * @return  bool    true  indicates to use the inliner, false bypasses it.
612
+		 */
613
+		if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
614
+			//require CssToInlineStyles library and its dependencies via composer autoloader
615
+			require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
616
+
617
+			//now if this isn't a preview, let's setup the body so it has inline styles
618
+			if (! $preview || ($preview && defined('DOING_AJAX'))) {
619
+				$style = file_get_contents(
620
+					$this->get_variation(
621
+						$this->_tmp_pack,
622
+						$this->_incoming_message_type->name,
623
+						false,
624
+						'main',
625
+						$this->_variation
626
+					),
627
+					true
628
+				);
629
+				$CSS   = new TijsVerkoyen\CssToInlineStyles\CssToInlineStyles($body, $style);
630
+				//for some reason the library has a bracket and new line at the beginning.  This takes care of that.
631
+				$body  = ltrim($CSS->convert(true), ">\n");
632
+				//see https://events.codebasehq.com/projects/event-espresso/tickets/8609
633
+				$body  = ltrim($body, "<?");
634
+			}
635
+
636
+		}
637
+		return $body;
638
+	}
639
+
640
+
641
+	/**
642
+	 * This just returns any existing test settings that might be saved in the database
643
+	 *
644
+	 * @access public
645
+	 * @return array
646
+	 */
647
+	public function get_existing_test_settings()
648
+	{
649
+		$settings = parent::get_existing_test_settings();
650
+		//override subject if present because we always want it to be fresh.
651
+		if (is_array($settings) && ! empty($settings['subject'])) {
652
+			$settings['subject'] = sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name'));
653
+		}
654
+		return $settings;
655
+	}
656 656
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
             ),
59 59
             '<code>wp_mail</code>'
60 60
         );
61
-        $this->label               = array(
61
+        $this->label = array(
62 62
             'singular' => esc_html__('email', 'event_espresso'),
63 63
             'plural'   => esc_html__('emails', 'event_espresso'),
64 64
         );
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
             $this->_body(),
441 441
             $this->_headers()
442 442
         );
443
-        if (! $success) {
443
+        if ( ! $success) {
444 444
             EE_Error::add_error(
445 445
                 sprintf(
446 446
                     esc_html__(
@@ -484,8 +484,8 @@  discard block
 block discarded – undo
484 484
         $this->_ensure_has_from_email_address();
485 485
         $from    = $this->_from;
486 486
         $headers = array(
487
-            'From:' . $from,
488
-            'Reply-To:' . $from,
487
+            'From:'.$from,
488
+            'Reply-To:'.$from,
489 489
             'Content-Type:text/html; charset=utf-8',
490 490
         );
491 491
 
@@ -494,8 +494,8 @@  discard block
 block discarded – undo
494 494
          * cover back compat where there may be users who have saved cc values in their db for the newsletter message
495 495
          * type which they are no longer able to change.
496 496
          */
497
-        if (! empty($this->_cc) && ! $this->_incoming_message_type instanceof EE_Newsletter_message_type) {
498
-            $headers[] = 'cc: ' . $this->_cc;
497
+        if ( ! empty($this->_cc) && ! $this->_incoming_message_type instanceof EE_Newsletter_message_type) {
498
+            $headers[] = 'cc: '.$this->_cc;
499 499
         }
500 500
 
501 501
         //but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
             'from'      => $this->_from,
603 603
             'main_body' => wpautop($this->_content),
604 604
         );
605
-        $body                 = $this->_get_main_template($preview);
605
+        $body = $this->_get_main_template($preview);
606 606
 
607 607
         /**
608 608
          * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
@@ -612,10 +612,10 @@  discard block
 block discarded – undo
612 612
          */
613 613
         if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
614 614
             //require CssToInlineStyles library and its dependencies via composer autoloader
615
-            require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
615
+            require_once EE_THIRD_PARTY.'cssinliner/vendor/autoload.php';
616 616
 
617 617
             //now if this isn't a preview, let's setup the body so it has inline styles
618
-            if (! $preview || ($preview && defined('DOING_AJAX'))) {
618
+            if ( ! $preview || ($preview && defined('DOING_AJAX'))) {
619 619
                 $style = file_get_contents(
620 620
                     $this->get_variation(
621 621
                         $this->_tmp_pack,
Please login to merge, or discard this patch.
core/libraries/messages/EE_Messages_Base.lib.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -300,20 +300,20 @@
 block discarded – undo
300 300
 	}
301 301
 
302 302
 
303
-    /**
304
-     * Allows a message type to specifically exclude template fields for the provided messenger.
305
-     * Filtered so this can be programmatically altered as well.
306
-     * @param string $messenger_name name of messenger
307
-     * @return array
308
-     */
303
+	/**
304
+	 * Allows a message type to specifically exclude template fields for the provided messenger.
305
+	 * Filtered so this can be programmatically altered as well.
306
+	 * @param string $messenger_name name of messenger
307
+	 * @return array
308
+	 */
309 309
 	public function excludedFieldsForMessenger($messenger_name)
310
-    {
311
-        return apply_filters(
312
-            'FHEE__EE_Messages_Base__excludedFieldForMessenger',
313
-            array(),
314
-            $messenger_name,
315
-            $this->name,
316
-            $this
317
-        );
318
-    }
310
+	{
311
+		return apply_filters(
312
+			'FHEE__EE_Messages_Base__excludedFieldForMessenger',
313
+			array(),
314
+			$messenger_name,
315
+			$this->name,
316
+			$this
317
+		);
318
+	}
319 319
 }
Please login to merge, or discard this patch.