Completed
Branch master (11a903)
by
unknown
13:53 queued 12:15
created
modules/messages/EED_Messages.module.php 2 patches
Indentation   +1331 added lines, -1331 removed lines patch added patch discarded remove patch
@@ -16,1344 +16,1344 @@
 block discarded – undo
16 16
 class EED_Messages extends EED_Module
17 17
 {
18 18
 
19
-    /**
20
-     * This holds the EE_messages controller
21
-     *
22
-     * @deprecated 4.9.0
23
-     * @var EE_messages $_EEMSG
24
-     */
25
-    protected static $_EEMSG;
26
-
27
-    /**
28
-     * @type EE_Message_Resource_Manager $_message_resource_manager
29
-     */
30
-    protected static $_message_resource_manager;
31
-
32
-    /**
33
-     * This holds the EE_Messages_Processor business class.
34
-     *
35
-     * @type EE_Messages_Processor
36
-     */
37
-    protected static $_MSG_PROCESSOR;
38
-
39
-    /**
40
-     * holds all the paths for various messages components.
41
-     * Utilized by autoloader registry
42
-     *
43
-     * @var array
44
-     */
45
-    protected static $_MSG_PATHS;
46
-
47
-
48
-    /**
49
-     * This will hold an array of messages template packs that are registered in the messages system.
50
-     * Format is:
51
-     * array(
52
-     *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
53
-     * )
54
-     *
55
-     * @var EE_Messages_Template_Pack[]
56
-     */
57
-    protected static $_TMP_PACKS = array();
58
-
59
-
60
-    /**
61
-     * @return EED_Messages|EED_Module
62
-     * @throws EE_Error
63
-     * @throws ReflectionException
64
-     */
65
-    public static function instance()
66
-    {
67
-        return parent::get_instance(__CLASS__);
68
-    }
69
-
70
-
71
-    /**
72
-     *  set_hooks - for hooking into EE Core, other modules, etc
73
-     *
74
-     * @since 4.5.0
75
-     * @return    void
76
-     */
77
-    public static function set_hooks()
78
-    {
79
-        // actions
80
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
81
-        add_action(
82
-            'AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
83
-            array('EED_Messages', 'maybe_registration'),
84
-            10,
85
-            2
86
-        );
87
-        // filters
88
-        add_filter(
89
-            'FHEE__EE_Registration__receipt_url__receipt_url',
90
-            array('EED_Messages', 'registration_message_trigger_url'),
91
-            10,
92
-            4
93
-        );
94
-        add_filter(
95
-            'FHEE__EE_Registration__invoice_url__invoice_url',
96
-            array('EED_Messages', 'registration_message_trigger_url'),
97
-            10,
98
-            4
99
-        );
100
-        // register routes
101
-        self::_register_routes();
102
-    }
103
-
104
-    /**
105
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
106
-     *
107
-     * @access    public
108
-     * @return    void
109
-     */
110
-    public static function set_hooks_admin()
111
-    {
112
-        // actions
113
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
114
-        add_action(
115
-            'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
116
-            array('EED_Messages', 'payment_reminder'),
117
-            10
118
-        );
119
-        add_action(
120
-            'AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
121
-            array('EED_Messages', 'maybe_registration'),
122
-            10,
123
-            3
124
-        );
125
-        add_action(
126
-            'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
127
-            array('EED_Messages', 'send_newsletter_message'),
128
-            10,
129
-            2
130
-        );
131
-        add_action(
132
-            'AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
133
-            array('EED_Messages', 'cancelled_registration'),
134
-            10
135
-        );
136
-        add_action(
137
-            'AHEE__EE_Admin_Page___process_admin_payment_notification',
138
-            array('EED_Messages', 'process_admin_payment'),
139
-            10,
140
-            1
141
-        );
142
-        // filters
143
-        add_filter(
144
-            'FHEE__EE_Admin_Page___process_resend_registration__success',
145
-            array('EED_Messages', 'process_resend'),
146
-            10,
147
-            2
148
-        );
149
-        add_filter(
150
-            'FHEE__EE_Registration__receipt_url__receipt_url',
151
-            array('EED_Messages', 'registration_message_trigger_url'),
152
-            10,
153
-            4
154
-        );
155
-        add_filter(
156
-            'FHEE__EE_Registration__invoice_url__invoice_url',
157
-            array('EED_Messages', 'registration_message_trigger_url'),
158
-            10,
159
-            4
160
-        );
161
-    }
162
-
163
-
164
-    /**
165
-     * All the message triggers done by route go in here.
166
-     *
167
-     * @since 4.5.0
168
-     * @return void
169
-     */
170
-    protected static function _register_routes()
171
-    {
172
-        EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
173
-        EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
174
-        EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
175
-        EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
176
-        do_action('AHEE__EED_Messages___register_routes');
177
-    }
178
-
179
-
180
-    /**
181
-     * This is called when a browser display trigger is executed.
182
-     * The browser display trigger is typically used when a already generated message is displayed directly in the
183
-     * browser.
184
-     *
185
-     * @since 4.9.0
186
-     * @param WP $WP
187
-     * @throws EE_Error
188
-     * @throws InvalidArgumentException
189
-     * @throws ReflectionException
190
-     * @throws InvalidDataTypeException
191
-     * @throws InvalidInterfaceException
192
-     */
193
-    public function browser_trigger($WP)
194
-    {
195
-        // ensure controller is loaded
196
-        self::_load_controller();
197
-        $token = self::getRequest()->getRequestParam('token');
198
-        try {
199
-            $mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
200
-            self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
201
-        } catch (EE_Error $e) {
202
-            $error_msg = esc_html__(
203
-                'Please note that a system message failed to send due to a technical issue.',
204
-                'event_espresso'
205
-            );
206
-            // add specific message for developers if WP_DEBUG in on
207
-            $error_msg .= '||' . $e->getMessage();
208
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
209
-        }
210
-    }
211
-
212
-
213
-    /**
214
-     * This is called when a browser error trigger is executed.
215
-     * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
216
-     * message and display it.
217
-     *
218
-     * @since 4.9.0
219
-     * @param $WP
220
-     * @throws EE_Error
221
-     * @throws InvalidArgumentException
222
-     * @throws InvalidDataTypeException
223
-     * @throws InvalidInterfaceException
224
-     */
225
-    public function browser_error_trigger($WP)
226
-    {
227
-        $token = self::getRequest()->getRequestParam('token');
228
-        if ($token) {
229
-            $message = EEM_Message::instance()->get_one_by_token($token);
230
-            if ($message instanceof EE_Message) {
231
-                header('HTTP/1.1 200 OK');
232
-                $error_msg = nl2br($message->error_message());
233
-                ?>
19
+	/**
20
+	 * This holds the EE_messages controller
21
+	 *
22
+	 * @deprecated 4.9.0
23
+	 * @var EE_messages $_EEMSG
24
+	 */
25
+	protected static $_EEMSG;
26
+
27
+	/**
28
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
29
+	 */
30
+	protected static $_message_resource_manager;
31
+
32
+	/**
33
+	 * This holds the EE_Messages_Processor business class.
34
+	 *
35
+	 * @type EE_Messages_Processor
36
+	 */
37
+	protected static $_MSG_PROCESSOR;
38
+
39
+	/**
40
+	 * holds all the paths for various messages components.
41
+	 * Utilized by autoloader registry
42
+	 *
43
+	 * @var array
44
+	 */
45
+	protected static $_MSG_PATHS;
46
+
47
+
48
+	/**
49
+	 * This will hold an array of messages template packs that are registered in the messages system.
50
+	 * Format is:
51
+	 * array(
52
+	 *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
53
+	 * )
54
+	 *
55
+	 * @var EE_Messages_Template_Pack[]
56
+	 */
57
+	protected static $_TMP_PACKS = array();
58
+
59
+
60
+	/**
61
+	 * @return EED_Messages|EED_Module
62
+	 * @throws EE_Error
63
+	 * @throws ReflectionException
64
+	 */
65
+	public static function instance()
66
+	{
67
+		return parent::get_instance(__CLASS__);
68
+	}
69
+
70
+
71
+	/**
72
+	 *  set_hooks - for hooking into EE Core, other modules, etc
73
+	 *
74
+	 * @since 4.5.0
75
+	 * @return    void
76
+	 */
77
+	public static function set_hooks()
78
+	{
79
+		// actions
80
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
81
+		add_action(
82
+			'AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
83
+			array('EED_Messages', 'maybe_registration'),
84
+			10,
85
+			2
86
+		);
87
+		// filters
88
+		add_filter(
89
+			'FHEE__EE_Registration__receipt_url__receipt_url',
90
+			array('EED_Messages', 'registration_message_trigger_url'),
91
+			10,
92
+			4
93
+		);
94
+		add_filter(
95
+			'FHEE__EE_Registration__invoice_url__invoice_url',
96
+			array('EED_Messages', 'registration_message_trigger_url'),
97
+			10,
98
+			4
99
+		);
100
+		// register routes
101
+		self::_register_routes();
102
+	}
103
+
104
+	/**
105
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
106
+	 *
107
+	 * @access    public
108
+	 * @return    void
109
+	 */
110
+	public static function set_hooks_admin()
111
+	{
112
+		// actions
113
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
114
+		add_action(
115
+			'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
116
+			array('EED_Messages', 'payment_reminder'),
117
+			10
118
+		);
119
+		add_action(
120
+			'AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
121
+			array('EED_Messages', 'maybe_registration'),
122
+			10,
123
+			3
124
+		);
125
+		add_action(
126
+			'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
127
+			array('EED_Messages', 'send_newsletter_message'),
128
+			10,
129
+			2
130
+		);
131
+		add_action(
132
+			'AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
133
+			array('EED_Messages', 'cancelled_registration'),
134
+			10
135
+		);
136
+		add_action(
137
+			'AHEE__EE_Admin_Page___process_admin_payment_notification',
138
+			array('EED_Messages', 'process_admin_payment'),
139
+			10,
140
+			1
141
+		);
142
+		// filters
143
+		add_filter(
144
+			'FHEE__EE_Admin_Page___process_resend_registration__success',
145
+			array('EED_Messages', 'process_resend'),
146
+			10,
147
+			2
148
+		);
149
+		add_filter(
150
+			'FHEE__EE_Registration__receipt_url__receipt_url',
151
+			array('EED_Messages', 'registration_message_trigger_url'),
152
+			10,
153
+			4
154
+		);
155
+		add_filter(
156
+			'FHEE__EE_Registration__invoice_url__invoice_url',
157
+			array('EED_Messages', 'registration_message_trigger_url'),
158
+			10,
159
+			4
160
+		);
161
+	}
162
+
163
+
164
+	/**
165
+	 * All the message triggers done by route go in here.
166
+	 *
167
+	 * @since 4.5.0
168
+	 * @return void
169
+	 */
170
+	protected static function _register_routes()
171
+	{
172
+		EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
173
+		EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
174
+		EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
175
+		EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
176
+		do_action('AHEE__EED_Messages___register_routes');
177
+	}
178
+
179
+
180
+	/**
181
+	 * This is called when a browser display trigger is executed.
182
+	 * The browser display trigger is typically used when a already generated message is displayed directly in the
183
+	 * browser.
184
+	 *
185
+	 * @since 4.9.0
186
+	 * @param WP $WP
187
+	 * @throws EE_Error
188
+	 * @throws InvalidArgumentException
189
+	 * @throws ReflectionException
190
+	 * @throws InvalidDataTypeException
191
+	 * @throws InvalidInterfaceException
192
+	 */
193
+	public function browser_trigger($WP)
194
+	{
195
+		// ensure controller is loaded
196
+		self::_load_controller();
197
+		$token = self::getRequest()->getRequestParam('token');
198
+		try {
199
+			$mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
200
+			self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
201
+		} catch (EE_Error $e) {
202
+			$error_msg = esc_html__(
203
+				'Please note that a system message failed to send due to a technical issue.',
204
+				'event_espresso'
205
+			);
206
+			// add specific message for developers if WP_DEBUG in on
207
+			$error_msg .= '||' . $e->getMessage();
208
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
209
+		}
210
+	}
211
+
212
+
213
+	/**
214
+	 * This is called when a browser error trigger is executed.
215
+	 * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
216
+	 * message and display it.
217
+	 *
218
+	 * @since 4.9.0
219
+	 * @param $WP
220
+	 * @throws EE_Error
221
+	 * @throws InvalidArgumentException
222
+	 * @throws InvalidDataTypeException
223
+	 * @throws InvalidInterfaceException
224
+	 */
225
+	public function browser_error_trigger($WP)
226
+	{
227
+		$token = self::getRequest()->getRequestParam('token');
228
+		if ($token) {
229
+			$message = EEM_Message::instance()->get_one_by_token($token);
230
+			if ($message instanceof EE_Message) {
231
+				header('HTTP/1.1 200 OK');
232
+				$error_msg = nl2br($message->error_message());
233
+				?>
234 234
                 <!DOCTYPE html>
235 235
                 <html>
236 236
                 <head></head>
237 237
                 <body>
238 238
                 <?php echo empty($error_msg)
239
-                    ? esc_html__(
240
-                        'Unfortunately, we were unable to capture the error message for this message.',
241
-                        'event_espresso'
242
-                    )
243
-                    : wp_kses(
244
-                        $error_msg,
245
-                        array(
246
-                            'a'      => array(
247
-                                'href'  => array(),
248
-                                'title' => array(),
249
-                            ),
250
-                            'span'   => array(),
251
-                            'div'    => array(),
252
-                            'p'      => array(),
253
-                            'strong' => array(),
254
-                            'em'     => array(),
255
-                            'br'     => array(),
256
-                        )
257
-                    ); ?>
239
+					? esc_html__(
240
+						'Unfortunately, we were unable to capture the error message for this message.',
241
+						'event_espresso'
242
+					)
243
+					: wp_kses(
244
+						$error_msg,
245
+						array(
246
+							'a'      => array(
247
+								'href'  => array(),
248
+								'title' => array(),
249
+							),
250
+							'span'   => array(),
251
+							'div'    => array(),
252
+							'p'      => array(),
253
+							'strong' => array(),
254
+							'em'     => array(),
255
+							'br'     => array(),
256
+						)
257
+					); ?>
258 258
                 </body>
259 259
                 </html>
260 260
                 <?php
261
-                exit;
262
-            }
263
-        }
264
-    }
265
-
266
-
267
-    /**
268
-     *  This runs when the msg_url_trigger route has initiated.
269
-     *
270
-     * @since 4.5.0
271
-     * @param WP $WP
272
-     * @throws EE_Error
273
-     * @throws InvalidArgumentException
274
-     * @throws ReflectionException
275
-     * @throws InvalidDataTypeException
276
-     * @throws InvalidInterfaceException
277
-     */
278
-    public function run($WP)
279
-    {
280
-        // ensure controller is loaded
281
-        self::_load_controller();
282
-        // attempt to process message
283
-        try {
284
-            /** @type EE_Message_To_Generate_From_Request $message_to_generate */
285
-            $message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
286
-            self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
287
-        } catch (EE_Error $e) {
288
-            $error_msg = esc_html__(
289
-                'Please note that a system message failed to send due to a technical issue.',
290
-                'event_espresso'
291
-            );
292
-            // add specific message for developers if WP_DEBUG in on
293
-            $error_msg .= '||' . $e->getMessage();
294
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
295
-        }
296
-    }
297
-
298
-
299
-    /**
300
-     * This is triggered by the 'msg_cron_trigger' route.
301
-     *
302
-     * @param WP $WP
303
-     */
304
-    public function execute_batch_request($WP)
305
-    {
306
-        $this->run_cron();
307
-        header('HTTP/1.1 200 OK');
308
-        exit();
309
-    }
310
-
311
-
312
-    /**
313
-     * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
314
-     * request.
315
-     */
316
-    public function run_cron()
317
-    {
318
-        self::_load_controller();
319
-        $request = self::getRequest();
320
-        // get required vars
321
-        $cron_type = $request->getRequestParam('type');
322
-        $transient_key = $request->getRequestParam('key');
323
-
324
-        // now let's verify transient, if not valid exit immediately
325
-        if (! get_transient($transient_key)) {
326
-            /**
327
-             * trigger error so this gets in the error logs.  This is important because it happens on a non-user
328
-             * request.
329
-             */
330
-            trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
331
-        }
332
-
333
-        // if made it here, lets' delete the transient to keep the db clean
334
-        delete_transient($transient_key);
335
-
336
-        if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
337
-            $method = 'batch_' . $cron_type . '_from_queue';
338
-            if (method_exists(self::$_MSG_PROCESSOR, $method)) {
339
-                self::$_MSG_PROCESSOR->$method();
340
-            } else {
341
-                // no matching task
342
-                /**
343
-                 * trigger error so this gets in the error logs.  This is important because it happens on a non user
344
-                 * request.
345
-                 */
346
-                trigger_error(
347
-                    esc_attr(
348
-                        sprintf(
349
-                            esc_html__('There is no task corresponding to this route %s', 'event_espresso'),
350
-                            $cron_type
351
-                        )
352
-                    )
353
-                );
354
-            }
355
-        }
356
-
357
-        do_action('FHEE__EED_Messages__run_cron__end');
358
-    }
359
-
360
-
361
-    /**
362
-     * This is used to retrieve the template pack for the given name.
363
-     * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
364
-     * the default template pack is returned.
365
-     *
366
-     * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
367
-     * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
368
-     *                                   in generating the Pack class name).
369
-     * @return EE_Messages_Template_Pack
370
-     * @throws EE_Error
371
-     * @throws InvalidArgumentException
372
-     * @throws ReflectionException
373
-     * @throws InvalidDataTypeException
374
-     * @throws InvalidInterfaceException
375
-     */
376
-    public static function get_template_pack($template_pack_name)
377
-    {
378
-        EE_Registry::instance()->load_helper('MSG_Template');
379
-        return EEH_MSG_Template::get_template_pack($template_pack_name);
380
-    }
381
-
382
-
383
-    /**
384
-     * Retrieves an array of all template packs.
385
-     * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
386
-     *
387
-     * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
388
-     * @return EE_Messages_Template_Pack[]
389
-     * @throws EE_Error
390
-     * @throws InvalidArgumentException
391
-     * @throws ReflectionException
392
-     * @throws InvalidDataTypeException
393
-     * @throws InvalidInterfaceException
394
-     */
395
-    public static function get_template_packs()
396
-    {
397
-        EE_Registry::instance()->load_helper('MSG_Template');
398
-
399
-        // for backward compat, let's make sure this returns in the same format as originally.
400
-        $template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
401
-        $template_pack_collection->rewind();
402
-        $template_packs = array();
403
-        while ($template_pack_collection->valid()) {
404
-            $template_packs[ $template_pack_collection->current()->dbref ] = $template_pack_collection->current();
405
-            $template_pack_collection->next();
406
-        }
407
-        return $template_packs;
408
-    }
409
-
410
-
411
-    /**
412
-     * This simply makes sure the autoloaders are registered for the EE_messages system.
413
-     *
414
-     * @since 4.5.0
415
-     * @return void
416
-     * @throws EE_Error
417
-     */
418
-    public static function set_autoloaders()
419
-    {
420
-        if (empty(self::$_MSG_PATHS)) {
421
-            self::_set_messages_paths();
422
-            foreach (self::$_MSG_PATHS as $path) {
423
-                EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
424
-            }
425
-            // add aliases
426
-            EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
427
-            EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
428
-        }
429
-    }
430
-
431
-
432
-    /**
433
-     * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
434
-     * for use by the Messages Autoloaders
435
-     *
436
-     * @since 4.5.0
437
-     * @return void.
438
-     */
439
-    protected static function _set_messages_paths()
440
-    {
441
-        $dir_ref = array(
442
-            'messages/message_type',
443
-            'messages/messenger',
444
-            'messages/defaults',
445
-            'messages/defaults/email',
446
-            'messages/data_class',
447
-            'messages/validators',
448
-            'messages/validators/email',
449
-            'messages/validators/html',
450
-            'shortcodes',
451
-        );
452
-        $paths = array();
453
-        foreach ($dir_ref as $index => $dir) {
454
-            $paths[ $index ] = EE_LIBRARIES . $dir;
455
-        }
456
-        self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
457
-    }
458
-
459
-
460
-    /**
461
-     * Takes care of loading dependencies
462
-     *
463
-     * @since 4.5.0
464
-     * @return void
465
-     * @throws EE_Error
466
-     * @throws InvalidArgumentException
467
-     * @throws ReflectionException
468
-     * @throws InvalidDataTypeException
469
-     * @throws InvalidInterfaceException
470
-     */
471
-    protected static function _load_controller()
472
-    {
473
-        if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
474
-            EE_Registry::instance()->load_core('Request_Handler');
475
-            self::set_autoloaders();
476
-            self::$_EEMSG = EE_Registry::instance()->load_lib('messages');
477
-            self::$_MSG_PROCESSOR = EE_Registry::instance()->load_lib('Messages_Processor');
478
-            self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
479
-        }
480
-    }
481
-
482
-
483
-    /**
484
-     * @param EE_Transaction $transaction
485
-     * @throws EE_Error
486
-     * @throws InvalidArgumentException
487
-     * @throws InvalidDataTypeException
488
-     * @throws InvalidInterfaceException
489
-     * @throws ReflectionException
490
-     */
491
-    public static function payment_reminder(EE_Transaction $transaction)
492
-    {
493
-        self::_load_controller();
494
-        $data = array($transaction, null);
495
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
496
-    }
497
-
498
-
499
-    /**
500
-     * Any messages triggers for after successful gateway payments should go in here.
501
-     *
502
-     * @param EE_Transaction  $transaction object
503
-     * @param EE_Payment|null $payment     object
504
-     * @return void
505
-     * @throws EE_Error
506
-     * @throws InvalidArgumentException
507
-     * @throws ReflectionException
508
-     * @throws InvalidDataTypeException
509
-     * @throws InvalidInterfaceException
510
-     */
511
-    public static function payment(EE_Transaction $transaction, EE_Payment $payment = null)
512
-    {
513
-        // if there's no payment object, then we cannot do a payment type message!
514
-        if (! $payment instanceof EE_Payment) {
515
-            return;
516
-        }
517
-        self::_load_controller();
518
-        $data = array($transaction, $payment);
519
-        EE_Registry::instance()->load_helper('MSG_Template');
520
-        $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
521
-        // if payment amount is less than 0 then switch to payment_refund message type.
522
-        $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
523
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
524
-    }
525
-
526
-
527
-    /**
528
-     * @param EE_Transaction $transaction
529
-     * @throws EE_Error
530
-     * @throws InvalidArgumentException
531
-     * @throws InvalidDataTypeException
532
-     * @throws InvalidInterfaceException
533
-     * @throws ReflectionException
534
-     */
535
-    public static function cancelled_registration(EE_Transaction $transaction)
536
-    {
537
-        self::_load_controller();
538
-        $data = array($transaction, null);
539
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
540
-    }
541
-
542
-
543
-    /**
544
-     * Trigger for Registration messages
545
-     * Note that what registration message type is sent depends on what the reg status is for the registrations on the
546
-     * incoming transaction.
547
-     *
548
-     * @param EE_Registration $registration
549
-     * @param array           $extra_details
550
-     * @return void
551
-     * @throws EE_Error
552
-     * @throws InvalidArgumentException
553
-     * @throws InvalidDataTypeException
554
-     * @throws InvalidInterfaceException
555
-     * @throws ReflectionException
556
-     * @throws EntityNotFoundException
557
-     */
558
-    public static function maybe_registration(EE_Registration $registration, $extra_details = array())
559
-    {
560
-
561
-        if (! self::_verify_registration_notification_send($registration, $extra_details)) {
562
-            // no messages please
563
-            return;
564
-        }
565
-
566
-        // get all non-trashed registrations so we make sure we send messages for the right status.
567
-        $all_registrations = $registration->transaction()->registrations(
568
-            array(
569
-                array('REG_deleted' => false),
570
-                'order_by' => array(
571
-                    'Event.EVT_name'     => 'ASC',
572
-                    'Attendee.ATT_lname' => 'ASC',
573
-                    'Attendee.ATT_fname' => 'ASC',
574
-                ),
575
-            )
576
-        );
577
-        // cached array of statuses so we only trigger messages once per status.
578
-        $statuses_sent = array();
579
-        self::_load_controller();
580
-        $mtgs = array();
581
-
582
-        // loop through registrations and trigger messages once per status.
583
-        foreach ($all_registrations as $reg) {
584
-            // already triggered?
585
-            if (in_array($reg->status_ID(), $statuses_sent)) {
586
-                continue;
587
-            }
588
-
589
-            $message_type = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
590
-            $mtgs = array_merge(
591
-                $mtgs,
592
-                self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
593
-                    $message_type,
594
-                    array($registration->transaction(), null, $reg->status_ID())
595
-                )
596
-            );
597
-            $statuses_sent[] = $reg->status_ID();
598
-        }
599
-
600
-        if (count($statuses_sent) > 1) {
601
-            $mtgs = array_merge(
602
-                $mtgs,
603
-                self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
604
-                    'registration_summary',
605
-                    array($registration->transaction(), null)
606
-                )
607
-            );
608
-        }
609
-
610
-        // batch queue and initiate request
611
-        self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
612
-        self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
613
-    }
614
-
615
-
616
-    /**
617
-     * This is a helper method used to very whether a registration notification should be sent or
618
-     * not.  Prevents duplicate notifications going out for registration context notifications.
619
-     *
620
-     * @param EE_Registration $registration  [description]
621
-     * @param array           $extra_details [description]
622
-     * @return bool          true = send away, false = nope halt the presses.
623
-     */
624
-    protected static function _verify_registration_notification_send(
625
-        EE_Registration $registration,
626
-        $extra_details = array()
627
-    ) {
628
-        if (! $registration->is_primary_registrant()) {
629
-            return false;
630
-        }
631
-        $request = self::getRequest();
632
-        // first we check if we're in admin and not doing front ajax
633
-        if ($request->isAdmin() && ! $request->isFrontAjax()) {
634
-            $status_change = $request->getRequestParam('txn_reg_status_change', [], 'int', true);
635
-            // make sure appropriate admin params are set for sending messages
636
-            if (! $status_change['send_notifications']) {
637
-                // no messages sent please.
638
-                return false;
639
-            }
640
-        } else {
641
-            // frontend request (either regular or via AJAX)
642
-            // TXN is NOT finalized ?
643
-            if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
644
-                return false;
645
-            }
646
-            // return visit but nothing changed ???
647
-            if (
648
-                isset($extra_details['revisit'], $extra_details['status_updates']) &&
649
-                $extra_details['revisit'] && ! $extra_details['status_updates']
650
-            ) {
651
-                return false;
652
-            }
653
-            // NOT sending messages && reg status is something other than "Not-Approved"
654
-            if (
655
-                ! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
656
-                $registration->status_ID() !== EEM_Registration::status_id_not_approved
657
-            ) {
658
-                return false;
659
-            }
660
-        }
661
-        // release the kraken
662
-        return true;
663
-    }
664
-
665
-
666
-    /**
667
-     * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
668
-     * status id.
669
-     *
670
-     * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
671
-     *                    or EEH_MSG_Template::convert_reg_status_to_message_type
672
-     * @param string $reg_status
673
-     * @return array
674
-     * @throws EE_Error
675
-     * @throws InvalidArgumentException
676
-     * @throws ReflectionException
677
-     * @throws InvalidDataTypeException
678
-     * @throws InvalidInterfaceException
679
-     */
680
-    protected static function _get_reg_status_array($reg_status = '')
681
-    {
682
-        EE_Registry::instance()->load_helper('MSG_Template');
683
-        return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
684
-            ? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
685
-            : EEH_MSG_Template::reg_status_to_message_type_array();
686
-    }
687
-
688
-
689
-    /**
690
-     * Simply returns the payment message type for the given payment status.
691
-     *
692
-     * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
693
-     *                   or EEH_MSG_Template::convert_payment_status_to_message_type
694
-     * @param string $payment_status The payment status being matched.
695
-     * @return bool|string The payment message type slug matching the status or false if no match.
696
-     * @throws EE_Error
697
-     * @throws InvalidArgumentException
698
-     * @throws ReflectionException
699
-     * @throws InvalidDataTypeException
700
-     * @throws InvalidInterfaceException
701
-     */
702
-    protected static function _get_payment_message_type($payment_status)
703
-    {
704
-        EE_Registry::instance()->load_helper('MSG_Template');
705
-        return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
706
-            ? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
707
-            : false;
708
-    }
709
-
710
-
711
-    /**
712
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
713
-     *
714
-     * @access public
715
-     * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
716
-     * @return bool success/fail
717
-     * @throws EE_Error
718
-     * @throws InvalidArgumentException
719
-     * @throws InvalidDataTypeException
720
-     * @throws InvalidInterfaceException
721
-     * @throws ReflectionException
722
-     */
723
-    public static function process_resend($req_data)
724
-    {
725
-        self::_load_controller();
726
-        $request = self::getRequest();
727
-        // if $msgID in this request then skip to the new resend_message
728
-        if ($request->getRequestParam('MSG_ID')) {
729
-            return self::resend_message();
730
-        }
731
-
732
-        // make sure any incoming request data is set on the request so that it gets picked up later.
733
-        $req_data = (array) $req_data;
734
-        foreach ($req_data as $request_key => $request_value) {
735
-            $request->setRequestParam($request_key, $request_value);
736
-        }
737
-
738
-        if (
739
-            ! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request(
740
-            )
741
-        ) {
742
-            return false;
743
-        }
744
-
745
-        try {
746
-            self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
747
-            self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
748
-        } catch (EE_Error $e) {
749
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
750
-            return false;
751
-        }
752
-        EE_Error::add_success(
753
-            esc_html__('Messages have been successfully queued for generation and sending.', 'event_espresso')
754
-        );
755
-        return true; // everything got queued.
756
-    }
757
-
758
-
759
-    /**
760
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
761
-     *
762
-     * @return bool
763
-     * @throws EE_Error
764
-     * @throws InvalidArgumentException
765
-     * @throws InvalidDataTypeException
766
-     * @throws InvalidInterfaceException
767
-     * @throws ReflectionException
768
-     */
769
-    public static function resend_message()
770
-    {
771
-        self::_load_controller();
772
-
773
-        $msgID = self::getRequest()->getRequestParam('MSG_ID', 0, 'int');
774
-        if (! $msgID) {
775
-            EE_Error::add_error(
776
-                esc_html__(
777
-                    'Something went wrong because there is no "MSG_ID" value in the request',
778
-                    'event_espresso'
779
-                ),
780
-                __FILE__,
781
-                __FUNCTION__,
782
-                __LINE__
783
-            );
784
-            return false;
785
-        }
786
-
787
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array) $msgID);
788
-
789
-        // setup success message.
790
-        $count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
791
-        EE_Error::add_success(
792
-            sprintf(
793
-                _n(
794
-                    'There was %d message queued for resending.',
795
-                    'There were %d messages queued for resending.',
796
-                    $count_ready_for_resend,
797
-                    'event_espresso'
798
-                ),
799
-                $count_ready_for_resend
800
-            )
801
-        );
802
-        return true;
803
-    }
804
-
805
-
806
-    /**
807
-     * Message triggers for manual payment applied by admin
808
-     *
809
-     * @param  EE_Payment $payment EE_payment object
810
-     * @return bool success/fail
811
-     * @throws EE_Error
812
-     * @throws InvalidArgumentException
813
-     * @throws ReflectionException
814
-     * @throws InvalidDataTypeException
815
-     * @throws InvalidInterfaceException
816
-     */
817
-    public static function process_admin_payment(EE_Payment $payment)
818
-    {
819
-        EE_Registry::instance()->load_helper('MSG_Template');
820
-        // we need to get the transaction object
821
-        $transaction = $payment->transaction();
822
-        if ($transaction instanceof EE_Transaction) {
823
-            $data = array($transaction, $payment);
824
-            $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
825
-
826
-            // if payment amount is less than 0 then switch to payment_refund message type.
827
-            $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
828
-
829
-            // if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
830
-            $message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved
831
-                ? false : $message_type;
832
-
833
-            self::_load_controller();
834
-
835
-            self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
836
-
837
-            // get count of queued for generation
838
-            $count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(
839
-                array(
840
-                    EEM_Message::status_incomplete,
841
-                    EEM_Message::status_idle,
842
-                )
843
-            );
844
-
845
-            if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
846
-                add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
847
-                return true;
848
-            } else {
849
-                $count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(
850
-                    EEM_Message::instance()->stati_indicating_failed_sending()
851
-                );
852
-                /**
853
-                 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
854
-                 * IMMEDIATE generation.
855
-                 */
856
-                if ($count_failed > 0) {
857
-                    EE_Error::add_error(
858
-                        sprintf(
859
-                            _n(
860
-                                'The payment notification generation failed.',
861
-                                '%d payment notifications failed being sent.',
862
-                                $count_failed,
863
-                                'event_espresso'
864
-                            ),
865
-                            $count_failed
866
-                        ),
867
-                        __FILE__,
868
-                        __FUNCTION__,
869
-                        __LINE__
870
-                    );
871
-
872
-                    return false;
873
-                } else {
874
-                    add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
875
-                    return true;
876
-                }
877
-            }
878
-        } else {
879
-            EE_Error::add_error(
880
-                'Unable to generate the payment notification because the given value for the transaction is invalid.',
881
-                'event_espresso'
882
-            );
883
-            return false;
884
-        }
885
-    }
886
-
887
-
888
-    /**
889
-     * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
890
-     *
891
-     * @since   4.3.0
892
-     * @param  EE_Registration[] $registrations an array of EE_Registration objects
893
-     * @param  int               $grp_id        a specific message template group id.
894
-     * @return void
895
-     * @throws EE_Error
896
-     * @throws InvalidArgumentException
897
-     * @throws InvalidDataTypeException
898
-     * @throws InvalidInterfaceException
899
-     * @throws ReflectionException
900
-     */
901
-    public static function send_newsletter_message($registrations, $grp_id)
902
-    {
903
-        // make sure mtp is id and set it in the request later messages setup.
904
-        self::getRequest()->setRequestParam('GRP_ID', (int) $grp_id);
905
-        self::_load_controller();
906
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
907
-    }
908
-
909
-
910
-    /**
911
-     * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
912
-     *
913
-     * @since   4.3.0
914
-     * @param    string          $registration_message_trigger_url
915
-     * @param    EE_Registration $registration
916
-     * @param string             $messenger
917
-     * @param string             $message_type
918
-     * @return string
919
-     * @throws EE_Error
920
-     * @throws InvalidArgumentException
921
-     * @throws InvalidDataTypeException
922
-     * @throws InvalidInterfaceException
923
-     */
924
-    public static function registration_message_trigger_url(
925
-        $registration_message_trigger_url,
926
-        EE_Registration $registration,
927
-        $messenger = 'html',
928
-        $message_type = 'invoice'
929
-    ) {
930
-        // whitelist $messenger
931
-        switch ($messenger) {
932
-            case 'pdf':
933
-                $sending_messenger = 'pdf';
934
-                $generating_messenger = 'html';
935
-                break;
936
-            case 'html':
937
-            default:
938
-                $sending_messenger = 'html';
939
-                $generating_messenger = 'html';
940
-                break;
941
-        }
942
-        // whitelist $message_type
943
-        switch ($message_type) {
944
-            case 'receipt':
945
-                $message_type = 'receipt';
946
-                break;
947
-            case 'invoice':
948
-            default:
949
-                $message_type = 'invoice';
950
-                break;
951
-        }
952
-        // verify that both the messenger AND the message type are active
953
-        if (
954
-            EEH_MSG_Template::is_messenger_active($sending_messenger)
955
-            && EEH_MSG_Template::is_mt_active($message_type)
956
-        ) {
957
-            // need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
958
-            $template_query_params = array(
959
-                'MTP_is_active'    => true,
960
-                'MTP_messenger'    => $generating_messenger,
961
-                'MTP_message_type' => $message_type,
962
-                'Event.EVT_ID'     => $registration->event_ID(),
963
-            );
964
-            // get the message template group.
965
-            $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
966
-            // if we don't have an EE_Message_Template_Group then return
967
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
968
-                // remove EVT_ID from query params so that global templates get picked up
969
-                unset($template_query_params['Event.EVT_ID']);
970
-                // get global template as the fallback
971
-                $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
972
-            }
973
-            // if we don't have an EE_Message_Template_Group then return
974
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
975
-                return '';
976
-            }
977
-            // generate the URL
978
-            $registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
979
-                $sending_messenger,
980
-                $generating_messenger,
981
-                'purchaser',
982
-                $message_type,
983
-                $registration,
984
-                $msg_template_group->ID(),
985
-                $registration->transaction_ID()
986
-            );
987
-        }
988
-        return $registration_message_trigger_url;
989
-    }
990
-
991
-
992
-    /**
993
-     * Use to generate and return a message preview!
994
-     *
995
-     * @param  string $type      This should correspond with a valid message type
996
-     * @param  string $context   This should correspond with a valid context for the message type
997
-     * @param  string $messenger This should correspond with a valid messenger.
998
-     * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
999
-     *                           preview
1000
-     * @return bool|string The body of the message or if send is requested, sends.
1001
-     * @throws EE_Error
1002
-     * @throws InvalidArgumentException
1003
-     * @throws InvalidDataTypeException
1004
-     * @throws InvalidInterfaceException
1005
-     * @throws ReflectionException
1006
-     */
1007
-    public static function preview_message($type, $context, $messenger, $send = false)
1008
-    {
1009
-        self::_load_controller();
1010
-        $mtg = new EE_Message_To_Generate(
1011
-            $messenger,
1012
-            $type,
1013
-            array(),
1014
-            $context,
1015
-            true
1016
-        );
1017
-        $generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
1018
-        if ($generated_preview_queue instanceof EE_Messages_Queue) {
1019
-            // loop through all content for the preview and remove any persisted records.
1020
-            $content = '';
1021
-            foreach ($generated_preview_queue->get_message_repository() as $message) {
1022
-                $content = $message->content();
1023
-                if ($message->ID() > 0 && $message->STS_ID() !== EEM_Message::status_failed) {
1024
-                    $message->delete();
1025
-                }
1026
-            }
1027
-            return $content;
1028
-        } else {
1029
-            return $generated_preview_queue;
1030
-        }
1031
-    }
1032
-
1033
-
1034
-    /**
1035
-     * This is a method that allows for sending a message using a messenger matching the string given and the provided
1036
-     * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
1037
-     * content found in the EE_Message objects in the queue.
1038
-     *
1039
-     * @since 4.9.0
1040
-     * @param string            $messenger            a string matching a valid active messenger in the system
1041
-     * @param string            $message_type         Although it seems contrary to the name of the method, a message
1042
-     *                                                type name is still required to send along the message type to the
1043
-     *                                                messenger because this is used for determining what specific
1044
-     *                                                variations might be loaded for the generated message.
1045
-     * @param EE_Messages_Queue $queue
1046
-     * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
1047
-     *                                                aggregate EE_Message object.
1048
-     * @return bool success or fail.
1049
-     * @throws EE_Error
1050
-     * @throws InvalidArgumentException
1051
-     * @throws ReflectionException
1052
-     * @throws InvalidDataTypeException
1053
-     * @throws InvalidInterfaceException
1054
-     */
1055
-    public static function send_message_with_messenger_only(
1056
-        $messenger,
1057
-        $message_type,
1058
-        EE_Messages_Queue $queue,
1059
-        $custom_subject = ''
1060
-    ) {
1061
-        self::_load_controller();
1062
-        /** @type EE_Message_To_Generate_From_Queue $message_to_generate */
1063
-        $message_to_generate = EE_Registry::instance()->load_lib(
1064
-            'Message_To_Generate_From_Queue',
1065
-            array(
1066
-                $messenger,
1067
-                $message_type,
1068
-                $queue,
1069
-                $custom_subject,
1070
-            )
1071
-        );
1072
-        return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
1073
-    }
1074
-
1075
-
1076
-    /**
1077
-     * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
1078
-     *
1079
-     * @since 4.9.0
1080
-     * @param array $message_ids An array of message ids
1081
-     * @return bool|EE_Messages_Queue false if nothing was generated, EE_Messages_Queue containing generated
1082
-     *                           messages.
1083
-     * @throws EE_Error
1084
-     * @throws InvalidArgumentException
1085
-     * @throws InvalidDataTypeException
1086
-     * @throws InvalidInterfaceException
1087
-     * @throws ReflectionException
1088
-     */
1089
-    public static function generate_now($message_ids)
1090
-    {
1091
-        self::_load_controller();
1092
-        $messages = EEM_Message::instance()->get_all(
1093
-            array(
1094
-                0 => array(
1095
-                    'MSG_ID' => array('IN', $message_ids),
1096
-                    'STS_ID' => EEM_Message::status_incomplete,
1097
-                ),
1098
-            )
1099
-        );
1100
-        $generated_queue = false;
1101
-        if ($messages) {
1102
-            $generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
1103
-        }
1104
-
1105
-        if (! $generated_queue instanceof EE_Messages_Queue) {
1106
-            EE_Error::add_error(
1107
-                esc_html__(
1108
-                    'The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
1109
-                    'event_espresso'
1110
-                ),
1111
-                __FILE__,
1112
-                __FUNCTION__,
1113
-                __LINE__
1114
-            );
1115
-        }
1116
-        return $generated_queue;
1117
-    }
1118
-
1119
-
1120
-    /**
1121
-     * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
1122
-     * EEM_Message::status_idle
1123
-     *
1124
-     * @since 4.9.0
1125
-     * @param $message_ids
1126
-     * @return bool|EE_Messages_Queue false if no messages sent.
1127
-     * @throws EE_Error
1128
-     * @throws InvalidArgumentException
1129
-     * @throws InvalidDataTypeException
1130
-     * @throws InvalidInterfaceException
1131
-     * @throws ReflectionException
1132
-     */
1133
-    public static function send_now($message_ids)
1134
-    {
1135
-        self::_load_controller();
1136
-        $messages = EEM_Message::instance()->get_all(
1137
-            array(
1138
-                0 => array(
1139
-                    'MSG_ID' => array('IN', $message_ids),
1140
-                    'STS_ID' => array(
1141
-                        'IN',
1142
-                        array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
1143
-                    ),
1144
-                ),
1145
-            )
1146
-        );
1147
-        $sent_queue = false;
1148
-        if ($messages) {
1149
-            $sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
1150
-        }
1151
-
1152
-        if (! $sent_queue instanceof EE_Messages_Queue) {
1153
-            EE_Error::add_error(
1154
-                esc_html__(
1155
-                    'The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
1156
-                    'event_espresso'
1157
-                ),
1158
-                __FILE__,
1159
-                __FUNCTION__,
1160
-                __LINE__
1161
-            );
1162
-        } else {
1163
-            // can count how many sent by using the messages in the queue
1164
-            $sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
1165
-            if ($sent_count > 0) {
1166
-                EE_Error::add_success(
1167
-                    sprintf(
1168
-                        _n(
1169
-                            'There was %d message successfully sent.',
1170
-                            'There were %d messages successfully sent.',
1171
-                            $sent_count,
1172
-                            'event_espresso'
1173
-                        ),
1174
-                        $sent_count
1175
-                    )
1176
-                );
1177
-            } else {
1178
-                EE_Error::overwrite_errors();
1179
-                EE_Error::add_error(
1180
-                    esc_html__(
1181
-                        'No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
261
+				exit;
262
+			}
263
+		}
264
+	}
265
+
266
+
267
+	/**
268
+	 *  This runs when the msg_url_trigger route has initiated.
269
+	 *
270
+	 * @since 4.5.0
271
+	 * @param WP $WP
272
+	 * @throws EE_Error
273
+	 * @throws InvalidArgumentException
274
+	 * @throws ReflectionException
275
+	 * @throws InvalidDataTypeException
276
+	 * @throws InvalidInterfaceException
277
+	 */
278
+	public function run($WP)
279
+	{
280
+		// ensure controller is loaded
281
+		self::_load_controller();
282
+		// attempt to process message
283
+		try {
284
+			/** @type EE_Message_To_Generate_From_Request $message_to_generate */
285
+			$message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
286
+			self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
287
+		} catch (EE_Error $e) {
288
+			$error_msg = esc_html__(
289
+				'Please note that a system message failed to send due to a technical issue.',
290
+				'event_espresso'
291
+			);
292
+			// add specific message for developers if WP_DEBUG in on
293
+			$error_msg .= '||' . $e->getMessage();
294
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
295
+		}
296
+	}
297
+
298
+
299
+	/**
300
+	 * This is triggered by the 'msg_cron_trigger' route.
301
+	 *
302
+	 * @param WP $WP
303
+	 */
304
+	public function execute_batch_request($WP)
305
+	{
306
+		$this->run_cron();
307
+		header('HTTP/1.1 200 OK');
308
+		exit();
309
+	}
310
+
311
+
312
+	/**
313
+	 * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
314
+	 * request.
315
+	 */
316
+	public function run_cron()
317
+	{
318
+		self::_load_controller();
319
+		$request = self::getRequest();
320
+		// get required vars
321
+		$cron_type = $request->getRequestParam('type');
322
+		$transient_key = $request->getRequestParam('key');
323
+
324
+		// now let's verify transient, if not valid exit immediately
325
+		if (! get_transient($transient_key)) {
326
+			/**
327
+			 * trigger error so this gets in the error logs.  This is important because it happens on a non-user
328
+			 * request.
329
+			 */
330
+			trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
331
+		}
332
+
333
+		// if made it here, lets' delete the transient to keep the db clean
334
+		delete_transient($transient_key);
335
+
336
+		if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
337
+			$method = 'batch_' . $cron_type . '_from_queue';
338
+			if (method_exists(self::$_MSG_PROCESSOR, $method)) {
339
+				self::$_MSG_PROCESSOR->$method();
340
+			} else {
341
+				// no matching task
342
+				/**
343
+				 * trigger error so this gets in the error logs.  This is important because it happens on a non user
344
+				 * request.
345
+				 */
346
+				trigger_error(
347
+					esc_attr(
348
+						sprintf(
349
+							esc_html__('There is no task corresponding to this route %s', 'event_espresso'),
350
+							$cron_type
351
+						)
352
+					)
353
+				);
354
+			}
355
+		}
356
+
357
+		do_action('FHEE__EED_Messages__run_cron__end');
358
+	}
359
+
360
+
361
+	/**
362
+	 * This is used to retrieve the template pack for the given name.
363
+	 * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
364
+	 * the default template pack is returned.
365
+	 *
366
+	 * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
367
+	 * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
368
+	 *                                   in generating the Pack class name).
369
+	 * @return EE_Messages_Template_Pack
370
+	 * @throws EE_Error
371
+	 * @throws InvalidArgumentException
372
+	 * @throws ReflectionException
373
+	 * @throws InvalidDataTypeException
374
+	 * @throws InvalidInterfaceException
375
+	 */
376
+	public static function get_template_pack($template_pack_name)
377
+	{
378
+		EE_Registry::instance()->load_helper('MSG_Template');
379
+		return EEH_MSG_Template::get_template_pack($template_pack_name);
380
+	}
381
+
382
+
383
+	/**
384
+	 * Retrieves an array of all template packs.
385
+	 * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
386
+	 *
387
+	 * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
388
+	 * @return EE_Messages_Template_Pack[]
389
+	 * @throws EE_Error
390
+	 * @throws InvalidArgumentException
391
+	 * @throws ReflectionException
392
+	 * @throws InvalidDataTypeException
393
+	 * @throws InvalidInterfaceException
394
+	 */
395
+	public static function get_template_packs()
396
+	{
397
+		EE_Registry::instance()->load_helper('MSG_Template');
398
+
399
+		// for backward compat, let's make sure this returns in the same format as originally.
400
+		$template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
401
+		$template_pack_collection->rewind();
402
+		$template_packs = array();
403
+		while ($template_pack_collection->valid()) {
404
+			$template_packs[ $template_pack_collection->current()->dbref ] = $template_pack_collection->current();
405
+			$template_pack_collection->next();
406
+		}
407
+		return $template_packs;
408
+	}
409
+
410
+
411
+	/**
412
+	 * This simply makes sure the autoloaders are registered for the EE_messages system.
413
+	 *
414
+	 * @since 4.5.0
415
+	 * @return void
416
+	 * @throws EE_Error
417
+	 */
418
+	public static function set_autoloaders()
419
+	{
420
+		if (empty(self::$_MSG_PATHS)) {
421
+			self::_set_messages_paths();
422
+			foreach (self::$_MSG_PATHS as $path) {
423
+				EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
424
+			}
425
+			// add aliases
426
+			EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
427
+			EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
428
+		}
429
+	}
430
+
431
+
432
+	/**
433
+	 * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
434
+	 * for use by the Messages Autoloaders
435
+	 *
436
+	 * @since 4.5.0
437
+	 * @return void.
438
+	 */
439
+	protected static function _set_messages_paths()
440
+	{
441
+		$dir_ref = array(
442
+			'messages/message_type',
443
+			'messages/messenger',
444
+			'messages/defaults',
445
+			'messages/defaults/email',
446
+			'messages/data_class',
447
+			'messages/validators',
448
+			'messages/validators/email',
449
+			'messages/validators/html',
450
+			'shortcodes',
451
+		);
452
+		$paths = array();
453
+		foreach ($dir_ref as $index => $dir) {
454
+			$paths[ $index ] = EE_LIBRARIES . $dir;
455
+		}
456
+		self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
457
+	}
458
+
459
+
460
+	/**
461
+	 * Takes care of loading dependencies
462
+	 *
463
+	 * @since 4.5.0
464
+	 * @return void
465
+	 * @throws EE_Error
466
+	 * @throws InvalidArgumentException
467
+	 * @throws ReflectionException
468
+	 * @throws InvalidDataTypeException
469
+	 * @throws InvalidInterfaceException
470
+	 */
471
+	protected static function _load_controller()
472
+	{
473
+		if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
474
+			EE_Registry::instance()->load_core('Request_Handler');
475
+			self::set_autoloaders();
476
+			self::$_EEMSG = EE_Registry::instance()->load_lib('messages');
477
+			self::$_MSG_PROCESSOR = EE_Registry::instance()->load_lib('Messages_Processor');
478
+			self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
479
+		}
480
+	}
481
+
482
+
483
+	/**
484
+	 * @param EE_Transaction $transaction
485
+	 * @throws EE_Error
486
+	 * @throws InvalidArgumentException
487
+	 * @throws InvalidDataTypeException
488
+	 * @throws InvalidInterfaceException
489
+	 * @throws ReflectionException
490
+	 */
491
+	public static function payment_reminder(EE_Transaction $transaction)
492
+	{
493
+		self::_load_controller();
494
+		$data = array($transaction, null);
495
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
496
+	}
497
+
498
+
499
+	/**
500
+	 * Any messages triggers for after successful gateway payments should go in here.
501
+	 *
502
+	 * @param EE_Transaction  $transaction object
503
+	 * @param EE_Payment|null $payment     object
504
+	 * @return void
505
+	 * @throws EE_Error
506
+	 * @throws InvalidArgumentException
507
+	 * @throws ReflectionException
508
+	 * @throws InvalidDataTypeException
509
+	 * @throws InvalidInterfaceException
510
+	 */
511
+	public static function payment(EE_Transaction $transaction, EE_Payment $payment = null)
512
+	{
513
+		// if there's no payment object, then we cannot do a payment type message!
514
+		if (! $payment instanceof EE_Payment) {
515
+			return;
516
+		}
517
+		self::_load_controller();
518
+		$data = array($transaction, $payment);
519
+		EE_Registry::instance()->load_helper('MSG_Template');
520
+		$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
521
+		// if payment amount is less than 0 then switch to payment_refund message type.
522
+		$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
523
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
524
+	}
525
+
526
+
527
+	/**
528
+	 * @param EE_Transaction $transaction
529
+	 * @throws EE_Error
530
+	 * @throws InvalidArgumentException
531
+	 * @throws InvalidDataTypeException
532
+	 * @throws InvalidInterfaceException
533
+	 * @throws ReflectionException
534
+	 */
535
+	public static function cancelled_registration(EE_Transaction $transaction)
536
+	{
537
+		self::_load_controller();
538
+		$data = array($transaction, null);
539
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
540
+	}
541
+
542
+
543
+	/**
544
+	 * Trigger for Registration messages
545
+	 * Note that what registration message type is sent depends on what the reg status is for the registrations on the
546
+	 * incoming transaction.
547
+	 *
548
+	 * @param EE_Registration $registration
549
+	 * @param array           $extra_details
550
+	 * @return void
551
+	 * @throws EE_Error
552
+	 * @throws InvalidArgumentException
553
+	 * @throws InvalidDataTypeException
554
+	 * @throws InvalidInterfaceException
555
+	 * @throws ReflectionException
556
+	 * @throws EntityNotFoundException
557
+	 */
558
+	public static function maybe_registration(EE_Registration $registration, $extra_details = array())
559
+	{
560
+
561
+		if (! self::_verify_registration_notification_send($registration, $extra_details)) {
562
+			// no messages please
563
+			return;
564
+		}
565
+
566
+		// get all non-trashed registrations so we make sure we send messages for the right status.
567
+		$all_registrations = $registration->transaction()->registrations(
568
+			array(
569
+				array('REG_deleted' => false),
570
+				'order_by' => array(
571
+					'Event.EVT_name'     => 'ASC',
572
+					'Attendee.ATT_lname' => 'ASC',
573
+					'Attendee.ATT_fname' => 'ASC',
574
+				),
575
+			)
576
+		);
577
+		// cached array of statuses so we only trigger messages once per status.
578
+		$statuses_sent = array();
579
+		self::_load_controller();
580
+		$mtgs = array();
581
+
582
+		// loop through registrations and trigger messages once per status.
583
+		foreach ($all_registrations as $reg) {
584
+			// already triggered?
585
+			if (in_array($reg->status_ID(), $statuses_sent)) {
586
+				continue;
587
+			}
588
+
589
+			$message_type = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
590
+			$mtgs = array_merge(
591
+				$mtgs,
592
+				self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
593
+					$message_type,
594
+					array($registration->transaction(), null, $reg->status_ID())
595
+				)
596
+			);
597
+			$statuses_sent[] = $reg->status_ID();
598
+		}
599
+
600
+		if (count($statuses_sent) > 1) {
601
+			$mtgs = array_merge(
602
+				$mtgs,
603
+				self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
604
+					'registration_summary',
605
+					array($registration->transaction(), null)
606
+				)
607
+			);
608
+		}
609
+
610
+		// batch queue and initiate request
611
+		self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
612
+		self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
613
+	}
614
+
615
+
616
+	/**
617
+	 * This is a helper method used to very whether a registration notification should be sent or
618
+	 * not.  Prevents duplicate notifications going out for registration context notifications.
619
+	 *
620
+	 * @param EE_Registration $registration  [description]
621
+	 * @param array           $extra_details [description]
622
+	 * @return bool          true = send away, false = nope halt the presses.
623
+	 */
624
+	protected static function _verify_registration_notification_send(
625
+		EE_Registration $registration,
626
+		$extra_details = array()
627
+	) {
628
+		if (! $registration->is_primary_registrant()) {
629
+			return false;
630
+		}
631
+		$request = self::getRequest();
632
+		// first we check if we're in admin and not doing front ajax
633
+		if ($request->isAdmin() && ! $request->isFrontAjax()) {
634
+			$status_change = $request->getRequestParam('txn_reg_status_change', [], 'int', true);
635
+			// make sure appropriate admin params are set for sending messages
636
+			if (! $status_change['send_notifications']) {
637
+				// no messages sent please.
638
+				return false;
639
+			}
640
+		} else {
641
+			// frontend request (either regular or via AJAX)
642
+			// TXN is NOT finalized ?
643
+			if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
644
+				return false;
645
+			}
646
+			// return visit but nothing changed ???
647
+			if (
648
+				isset($extra_details['revisit'], $extra_details['status_updates']) &&
649
+				$extra_details['revisit'] && ! $extra_details['status_updates']
650
+			) {
651
+				return false;
652
+			}
653
+			// NOT sending messages && reg status is something other than "Not-Approved"
654
+			if (
655
+				! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
656
+				$registration->status_ID() !== EEM_Registration::status_id_not_approved
657
+			) {
658
+				return false;
659
+			}
660
+		}
661
+		// release the kraken
662
+		return true;
663
+	}
664
+
665
+
666
+	/**
667
+	 * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
668
+	 * status id.
669
+	 *
670
+	 * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
671
+	 *                    or EEH_MSG_Template::convert_reg_status_to_message_type
672
+	 * @param string $reg_status
673
+	 * @return array
674
+	 * @throws EE_Error
675
+	 * @throws InvalidArgumentException
676
+	 * @throws ReflectionException
677
+	 * @throws InvalidDataTypeException
678
+	 * @throws InvalidInterfaceException
679
+	 */
680
+	protected static function _get_reg_status_array($reg_status = '')
681
+	{
682
+		EE_Registry::instance()->load_helper('MSG_Template');
683
+		return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
684
+			? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
685
+			: EEH_MSG_Template::reg_status_to_message_type_array();
686
+	}
687
+
688
+
689
+	/**
690
+	 * Simply returns the payment message type for the given payment status.
691
+	 *
692
+	 * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
693
+	 *                   or EEH_MSG_Template::convert_payment_status_to_message_type
694
+	 * @param string $payment_status The payment status being matched.
695
+	 * @return bool|string The payment message type slug matching the status or false if no match.
696
+	 * @throws EE_Error
697
+	 * @throws InvalidArgumentException
698
+	 * @throws ReflectionException
699
+	 * @throws InvalidDataTypeException
700
+	 * @throws InvalidInterfaceException
701
+	 */
702
+	protected static function _get_payment_message_type($payment_status)
703
+	{
704
+		EE_Registry::instance()->load_helper('MSG_Template');
705
+		return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
706
+			? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
707
+			: false;
708
+	}
709
+
710
+
711
+	/**
712
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
713
+	 *
714
+	 * @access public
715
+	 * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
716
+	 * @return bool success/fail
717
+	 * @throws EE_Error
718
+	 * @throws InvalidArgumentException
719
+	 * @throws InvalidDataTypeException
720
+	 * @throws InvalidInterfaceException
721
+	 * @throws ReflectionException
722
+	 */
723
+	public static function process_resend($req_data)
724
+	{
725
+		self::_load_controller();
726
+		$request = self::getRequest();
727
+		// if $msgID in this request then skip to the new resend_message
728
+		if ($request->getRequestParam('MSG_ID')) {
729
+			return self::resend_message();
730
+		}
731
+
732
+		// make sure any incoming request data is set on the request so that it gets picked up later.
733
+		$req_data = (array) $req_data;
734
+		foreach ($req_data as $request_key => $request_value) {
735
+			$request->setRequestParam($request_key, $request_value);
736
+		}
737
+
738
+		if (
739
+			! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request(
740
+			)
741
+		) {
742
+			return false;
743
+		}
744
+
745
+		try {
746
+			self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
747
+			self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
748
+		} catch (EE_Error $e) {
749
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
750
+			return false;
751
+		}
752
+		EE_Error::add_success(
753
+			esc_html__('Messages have been successfully queued for generation and sending.', 'event_espresso')
754
+		);
755
+		return true; // everything got queued.
756
+	}
757
+
758
+
759
+	/**
760
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
761
+	 *
762
+	 * @return bool
763
+	 * @throws EE_Error
764
+	 * @throws InvalidArgumentException
765
+	 * @throws InvalidDataTypeException
766
+	 * @throws InvalidInterfaceException
767
+	 * @throws ReflectionException
768
+	 */
769
+	public static function resend_message()
770
+	{
771
+		self::_load_controller();
772
+
773
+		$msgID = self::getRequest()->getRequestParam('MSG_ID', 0, 'int');
774
+		if (! $msgID) {
775
+			EE_Error::add_error(
776
+				esc_html__(
777
+					'Something went wrong because there is no "MSG_ID" value in the request',
778
+					'event_espresso'
779
+				),
780
+				__FILE__,
781
+				__FUNCTION__,
782
+				__LINE__
783
+			);
784
+			return false;
785
+		}
786
+
787
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array) $msgID);
788
+
789
+		// setup success message.
790
+		$count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
791
+		EE_Error::add_success(
792
+			sprintf(
793
+				_n(
794
+					'There was %d message queued for resending.',
795
+					'There were %d messages queued for resending.',
796
+					$count_ready_for_resend,
797
+					'event_espresso'
798
+				),
799
+				$count_ready_for_resend
800
+			)
801
+		);
802
+		return true;
803
+	}
804
+
805
+
806
+	/**
807
+	 * Message triggers for manual payment applied by admin
808
+	 *
809
+	 * @param  EE_Payment $payment EE_payment object
810
+	 * @return bool success/fail
811
+	 * @throws EE_Error
812
+	 * @throws InvalidArgumentException
813
+	 * @throws ReflectionException
814
+	 * @throws InvalidDataTypeException
815
+	 * @throws InvalidInterfaceException
816
+	 */
817
+	public static function process_admin_payment(EE_Payment $payment)
818
+	{
819
+		EE_Registry::instance()->load_helper('MSG_Template');
820
+		// we need to get the transaction object
821
+		$transaction = $payment->transaction();
822
+		if ($transaction instanceof EE_Transaction) {
823
+			$data = array($transaction, $payment);
824
+			$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
825
+
826
+			// if payment amount is less than 0 then switch to payment_refund message type.
827
+			$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
828
+
829
+			// if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
830
+			$message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved
831
+				? false : $message_type;
832
+
833
+			self::_load_controller();
834
+
835
+			self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
836
+
837
+			// get count of queued for generation
838
+			$count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(
839
+				array(
840
+					EEM_Message::status_incomplete,
841
+					EEM_Message::status_idle,
842
+				)
843
+			);
844
+
845
+			if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
846
+				add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
847
+				return true;
848
+			} else {
849
+				$count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(
850
+					EEM_Message::instance()->stati_indicating_failed_sending()
851
+				);
852
+				/**
853
+				 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
854
+				 * IMMEDIATE generation.
855
+				 */
856
+				if ($count_failed > 0) {
857
+					EE_Error::add_error(
858
+						sprintf(
859
+							_n(
860
+								'The payment notification generation failed.',
861
+								'%d payment notifications failed being sent.',
862
+								$count_failed,
863
+								'event_espresso'
864
+							),
865
+							$count_failed
866
+						),
867
+						__FILE__,
868
+						__FUNCTION__,
869
+						__LINE__
870
+					);
871
+
872
+					return false;
873
+				} else {
874
+					add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
875
+					return true;
876
+				}
877
+			}
878
+		} else {
879
+			EE_Error::add_error(
880
+				'Unable to generate the payment notification because the given value for the transaction is invalid.',
881
+				'event_espresso'
882
+			);
883
+			return false;
884
+		}
885
+	}
886
+
887
+
888
+	/**
889
+	 * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
890
+	 *
891
+	 * @since   4.3.0
892
+	 * @param  EE_Registration[] $registrations an array of EE_Registration objects
893
+	 * @param  int               $grp_id        a specific message template group id.
894
+	 * @return void
895
+	 * @throws EE_Error
896
+	 * @throws InvalidArgumentException
897
+	 * @throws InvalidDataTypeException
898
+	 * @throws InvalidInterfaceException
899
+	 * @throws ReflectionException
900
+	 */
901
+	public static function send_newsletter_message($registrations, $grp_id)
902
+	{
903
+		// make sure mtp is id and set it in the request later messages setup.
904
+		self::getRequest()->setRequestParam('GRP_ID', (int) $grp_id);
905
+		self::_load_controller();
906
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
907
+	}
908
+
909
+
910
+	/**
911
+	 * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
912
+	 *
913
+	 * @since   4.3.0
914
+	 * @param    string          $registration_message_trigger_url
915
+	 * @param    EE_Registration $registration
916
+	 * @param string             $messenger
917
+	 * @param string             $message_type
918
+	 * @return string
919
+	 * @throws EE_Error
920
+	 * @throws InvalidArgumentException
921
+	 * @throws InvalidDataTypeException
922
+	 * @throws InvalidInterfaceException
923
+	 */
924
+	public static function registration_message_trigger_url(
925
+		$registration_message_trigger_url,
926
+		EE_Registration $registration,
927
+		$messenger = 'html',
928
+		$message_type = 'invoice'
929
+	) {
930
+		// whitelist $messenger
931
+		switch ($messenger) {
932
+			case 'pdf':
933
+				$sending_messenger = 'pdf';
934
+				$generating_messenger = 'html';
935
+				break;
936
+			case 'html':
937
+			default:
938
+				$sending_messenger = 'html';
939
+				$generating_messenger = 'html';
940
+				break;
941
+		}
942
+		// whitelist $message_type
943
+		switch ($message_type) {
944
+			case 'receipt':
945
+				$message_type = 'receipt';
946
+				break;
947
+			case 'invoice':
948
+			default:
949
+				$message_type = 'invoice';
950
+				break;
951
+		}
952
+		// verify that both the messenger AND the message type are active
953
+		if (
954
+			EEH_MSG_Template::is_messenger_active($sending_messenger)
955
+			&& EEH_MSG_Template::is_mt_active($message_type)
956
+		) {
957
+			// need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
958
+			$template_query_params = array(
959
+				'MTP_is_active'    => true,
960
+				'MTP_messenger'    => $generating_messenger,
961
+				'MTP_message_type' => $message_type,
962
+				'Event.EVT_ID'     => $registration->event_ID(),
963
+			);
964
+			// get the message template group.
965
+			$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
966
+			// if we don't have an EE_Message_Template_Group then return
967
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
968
+				// remove EVT_ID from query params so that global templates get picked up
969
+				unset($template_query_params['Event.EVT_ID']);
970
+				// get global template as the fallback
971
+				$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
972
+			}
973
+			// if we don't have an EE_Message_Template_Group then return
974
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
975
+				return '';
976
+			}
977
+			// generate the URL
978
+			$registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
979
+				$sending_messenger,
980
+				$generating_messenger,
981
+				'purchaser',
982
+				$message_type,
983
+				$registration,
984
+				$msg_template_group->ID(),
985
+				$registration->transaction_ID()
986
+			);
987
+		}
988
+		return $registration_message_trigger_url;
989
+	}
990
+
991
+
992
+	/**
993
+	 * Use to generate and return a message preview!
994
+	 *
995
+	 * @param  string $type      This should correspond with a valid message type
996
+	 * @param  string $context   This should correspond with a valid context for the message type
997
+	 * @param  string $messenger This should correspond with a valid messenger.
998
+	 * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
999
+	 *                           preview
1000
+	 * @return bool|string The body of the message or if send is requested, sends.
1001
+	 * @throws EE_Error
1002
+	 * @throws InvalidArgumentException
1003
+	 * @throws InvalidDataTypeException
1004
+	 * @throws InvalidInterfaceException
1005
+	 * @throws ReflectionException
1006
+	 */
1007
+	public static function preview_message($type, $context, $messenger, $send = false)
1008
+	{
1009
+		self::_load_controller();
1010
+		$mtg = new EE_Message_To_Generate(
1011
+			$messenger,
1012
+			$type,
1013
+			array(),
1014
+			$context,
1015
+			true
1016
+		);
1017
+		$generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
1018
+		if ($generated_preview_queue instanceof EE_Messages_Queue) {
1019
+			// loop through all content for the preview and remove any persisted records.
1020
+			$content = '';
1021
+			foreach ($generated_preview_queue->get_message_repository() as $message) {
1022
+				$content = $message->content();
1023
+				if ($message->ID() > 0 && $message->STS_ID() !== EEM_Message::status_failed) {
1024
+					$message->delete();
1025
+				}
1026
+			}
1027
+			return $content;
1028
+		} else {
1029
+			return $generated_preview_queue;
1030
+		}
1031
+	}
1032
+
1033
+
1034
+	/**
1035
+	 * This is a method that allows for sending a message using a messenger matching the string given and the provided
1036
+	 * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
1037
+	 * content found in the EE_Message objects in the queue.
1038
+	 *
1039
+	 * @since 4.9.0
1040
+	 * @param string            $messenger            a string matching a valid active messenger in the system
1041
+	 * @param string            $message_type         Although it seems contrary to the name of the method, a message
1042
+	 *                                                type name is still required to send along the message type to the
1043
+	 *                                                messenger because this is used for determining what specific
1044
+	 *                                                variations might be loaded for the generated message.
1045
+	 * @param EE_Messages_Queue $queue
1046
+	 * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
1047
+	 *                                                aggregate EE_Message object.
1048
+	 * @return bool success or fail.
1049
+	 * @throws EE_Error
1050
+	 * @throws InvalidArgumentException
1051
+	 * @throws ReflectionException
1052
+	 * @throws InvalidDataTypeException
1053
+	 * @throws InvalidInterfaceException
1054
+	 */
1055
+	public static function send_message_with_messenger_only(
1056
+		$messenger,
1057
+		$message_type,
1058
+		EE_Messages_Queue $queue,
1059
+		$custom_subject = ''
1060
+	) {
1061
+		self::_load_controller();
1062
+		/** @type EE_Message_To_Generate_From_Queue $message_to_generate */
1063
+		$message_to_generate = EE_Registry::instance()->load_lib(
1064
+			'Message_To_Generate_From_Queue',
1065
+			array(
1066
+				$messenger,
1067
+				$message_type,
1068
+				$queue,
1069
+				$custom_subject,
1070
+			)
1071
+		);
1072
+		return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
1073
+	}
1074
+
1075
+
1076
+	/**
1077
+	 * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
1078
+	 *
1079
+	 * @since 4.9.0
1080
+	 * @param array $message_ids An array of message ids
1081
+	 * @return bool|EE_Messages_Queue false if nothing was generated, EE_Messages_Queue containing generated
1082
+	 *                           messages.
1083
+	 * @throws EE_Error
1084
+	 * @throws InvalidArgumentException
1085
+	 * @throws InvalidDataTypeException
1086
+	 * @throws InvalidInterfaceException
1087
+	 * @throws ReflectionException
1088
+	 */
1089
+	public static function generate_now($message_ids)
1090
+	{
1091
+		self::_load_controller();
1092
+		$messages = EEM_Message::instance()->get_all(
1093
+			array(
1094
+				0 => array(
1095
+					'MSG_ID' => array('IN', $message_ids),
1096
+					'STS_ID' => EEM_Message::status_incomplete,
1097
+				),
1098
+			)
1099
+		);
1100
+		$generated_queue = false;
1101
+		if ($messages) {
1102
+			$generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
1103
+		}
1104
+
1105
+		if (! $generated_queue instanceof EE_Messages_Queue) {
1106
+			EE_Error::add_error(
1107
+				esc_html__(
1108
+					'The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
1109
+					'event_espresso'
1110
+				),
1111
+				__FILE__,
1112
+				__FUNCTION__,
1113
+				__LINE__
1114
+			);
1115
+		}
1116
+		return $generated_queue;
1117
+	}
1118
+
1119
+
1120
+	/**
1121
+	 * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
1122
+	 * EEM_Message::status_idle
1123
+	 *
1124
+	 * @since 4.9.0
1125
+	 * @param $message_ids
1126
+	 * @return bool|EE_Messages_Queue false if no messages sent.
1127
+	 * @throws EE_Error
1128
+	 * @throws InvalidArgumentException
1129
+	 * @throws InvalidDataTypeException
1130
+	 * @throws InvalidInterfaceException
1131
+	 * @throws ReflectionException
1132
+	 */
1133
+	public static function send_now($message_ids)
1134
+	{
1135
+		self::_load_controller();
1136
+		$messages = EEM_Message::instance()->get_all(
1137
+			array(
1138
+				0 => array(
1139
+					'MSG_ID' => array('IN', $message_ids),
1140
+					'STS_ID' => array(
1141
+						'IN',
1142
+						array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
1143
+					),
1144
+				),
1145
+			)
1146
+		);
1147
+		$sent_queue = false;
1148
+		if ($messages) {
1149
+			$sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
1150
+		}
1151
+
1152
+		if (! $sent_queue instanceof EE_Messages_Queue) {
1153
+			EE_Error::add_error(
1154
+				esc_html__(
1155
+					'The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
1156
+					'event_espresso'
1157
+				),
1158
+				__FILE__,
1159
+				__FUNCTION__,
1160
+				__LINE__
1161
+			);
1162
+		} else {
1163
+			// can count how many sent by using the messages in the queue
1164
+			$sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
1165
+			if ($sent_count > 0) {
1166
+				EE_Error::add_success(
1167
+					sprintf(
1168
+						_n(
1169
+							'There was %d message successfully sent.',
1170
+							'There were %d messages successfully sent.',
1171
+							$sent_count,
1172
+							'event_espresso'
1173
+						),
1174
+						$sent_count
1175
+					)
1176
+				);
1177
+			} else {
1178
+				EE_Error::overwrite_errors();
1179
+				EE_Error::add_error(
1180
+					esc_html__(
1181
+						'No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
1182 1182
 					If there was an error, you can look at the messages in the message activity list table for any error messages.',
1183
-                        'event_espresso'
1184
-                    ),
1185
-                    __FILE__,
1186
-                    __FUNCTION__,
1187
-                    __LINE__
1188
-                );
1189
-            }
1190
-        }
1191
-        return $sent_queue;
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * Generate and send immediately from the given $message_ids
1197
-     *
1198
-     * @param array $message_ids EE_Message entity ids.
1199
-     * @throws EE_Error
1200
-     * @throws InvalidArgumentException
1201
-     * @throws InvalidDataTypeException
1202
-     * @throws InvalidInterfaceException
1203
-     * @throws ReflectionException
1204
-     */
1205
-    public static function generate_and_send_now(array $message_ids)
1206
-    {
1207
-        $generated_queue = self::generate_now($message_ids);
1208
-        // now let's just trigger sending immediately from this queue.
1209
-        $messages_sent = $generated_queue instanceof EE_Messages_Queue
1210
-            ? $generated_queue->execute()
1211
-            : 0;
1212
-        if ($messages_sent) {
1213
-            EE_Error::add_success(
1214
-                esc_html(
1215
-                    sprintf(
1216
-                        _n(
1217
-                            'There was %d message successfully generated and sent.',
1218
-                            'There were %d messages successfully generated and sent.',
1219
-                            $messages_sent,
1220
-                            'event_espresso'
1221
-                        ),
1222
-                        $messages_sent
1223
-                    )
1224
-                )
1225
-            );
1226
-            // errors would be added via the generate_now method.
1227
-        }
1228
-    }
1229
-
1230
-
1231
-    /**
1232
-     * This will queue the incoming message ids for resending.
1233
-     * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
1234
-     *
1235
-     * @since 4.9.0
1236
-     * @param array $message_ids An array of EE_Message IDs
1237
-     * @return bool true means messages were successfully queued for resending, false means none were queued for
1238
-     *                           resending.
1239
-     * @throws EE_Error
1240
-     * @throws InvalidArgumentException
1241
-     * @throws InvalidDataTypeException
1242
-     * @throws InvalidInterfaceException
1243
-     * @throws ReflectionException
1244
-     */
1245
-    public static function queue_for_resending($message_ids)
1246
-    {
1247
-        self::_load_controller();
1248
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1249
-
1250
-        // get queue and count
1251
-        $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1252
-
1253
-        if (
1254
-            $queue_count > 0
1255
-        ) {
1256
-            EE_Error::add_success(
1257
-                sprintf(
1258
-                    _n(
1259
-                        '%d message successfully queued for resending.',
1260
-                        '%d messages successfully queued for resending.',
1261
-                        $queue_count,
1262
-                        'event_espresso'
1263
-                    ),
1264
-                    $queue_count
1265
-                )
1266
-            );
1267
-            /**
1268
-             * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1269
-             */
1270
-        } elseif (
1271
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1272
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1273
-        ) {
1274
-            $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1275
-            if ($queue_count > 0) {
1276
-                EE_Error::add_success(
1277
-                    sprintf(
1278
-                        _n(
1279
-                            '%d message successfully sent.',
1280
-                            '%d messages successfully sent.',
1281
-                            $queue_count,
1282
-                            'event_espresso'
1283
-                        ),
1284
-                        $queue_count
1285
-                    )
1286
-                );
1287
-            } else {
1288
-                EE_Error::add_error(
1289
-                    esc_html__(
1290
-                        'No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1291
-                        'event_espresso'
1292
-                    ),
1293
-                    __FILE__,
1294
-                    __FUNCTION__,
1295
-                    __LINE__
1296
-                );
1297
-            }
1298
-        } else {
1299
-            EE_Error::add_error(
1300
-                esc_html__(
1301
-                    'No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1302
-                    'event_espresso'
1303
-                ),
1304
-                __FILE__,
1305
-                __FUNCTION__,
1306
-                __LINE__
1307
-            );
1308
-        }
1309
-        return (bool) $queue_count;
1310
-    }
1311
-
1312
-
1313
-    /**
1314
-     * debug
1315
-     *
1316
-     * @param string          $class
1317
-     * @param string          $func
1318
-     * @param string          $line
1319
-     * @param \EE_Transaction $transaction
1320
-     * @param array           $info
1321
-     * @param bool            $display_request
1322
-     * @throws EE_Error
1323
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
1324
-     */
1325
-    protected static function log(
1326
-        $class = '',
1327
-        $func = '',
1328
-        $line = '',
1329
-        EE_Transaction $transaction,
1330
-        $info = array(),
1331
-        $display_request = false
1332
-    ) {
1333
-        if (defined('EE_DEBUG') && EE_DEBUG) {
1334
-            if ($transaction instanceof EE_Transaction) {
1335
-                // don't serialize objects
1336
-                $info = EEH_Debug_Tools::strip_objects($info);
1337
-                $info['TXN_status'] = $transaction->status_ID();
1338
-                $info['TXN_reg_steps'] = $transaction->reg_steps();
1339
-                if ($transaction->ID()) {
1340
-                    $index = 'EE_Transaction: ' . $transaction->ID();
1341
-                    EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1342
-                }
1343
-            }
1344
-        }
1345
-    }
1346
-
1347
-
1348
-    /**
1349
-     *  Resets all the static properties in this class when called.
1350
-     */
1351
-    public static function reset()
1352
-    {
1353
-        self::$_EEMSG = null;
1354
-        self::$_message_resource_manager = null;
1355
-        self::$_MSG_PROCESSOR = null;
1356
-        self::$_MSG_PATHS = null;
1357
-        self::$_TMP_PACKS = array();
1358
-    }
1183
+						'event_espresso'
1184
+					),
1185
+					__FILE__,
1186
+					__FUNCTION__,
1187
+					__LINE__
1188
+				);
1189
+			}
1190
+		}
1191
+		return $sent_queue;
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * Generate and send immediately from the given $message_ids
1197
+	 *
1198
+	 * @param array $message_ids EE_Message entity ids.
1199
+	 * @throws EE_Error
1200
+	 * @throws InvalidArgumentException
1201
+	 * @throws InvalidDataTypeException
1202
+	 * @throws InvalidInterfaceException
1203
+	 * @throws ReflectionException
1204
+	 */
1205
+	public static function generate_and_send_now(array $message_ids)
1206
+	{
1207
+		$generated_queue = self::generate_now($message_ids);
1208
+		// now let's just trigger sending immediately from this queue.
1209
+		$messages_sent = $generated_queue instanceof EE_Messages_Queue
1210
+			? $generated_queue->execute()
1211
+			: 0;
1212
+		if ($messages_sent) {
1213
+			EE_Error::add_success(
1214
+				esc_html(
1215
+					sprintf(
1216
+						_n(
1217
+							'There was %d message successfully generated and sent.',
1218
+							'There were %d messages successfully generated and sent.',
1219
+							$messages_sent,
1220
+							'event_espresso'
1221
+						),
1222
+						$messages_sent
1223
+					)
1224
+				)
1225
+			);
1226
+			// errors would be added via the generate_now method.
1227
+		}
1228
+	}
1229
+
1230
+
1231
+	/**
1232
+	 * This will queue the incoming message ids for resending.
1233
+	 * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
1234
+	 *
1235
+	 * @since 4.9.0
1236
+	 * @param array $message_ids An array of EE_Message IDs
1237
+	 * @return bool true means messages were successfully queued for resending, false means none were queued for
1238
+	 *                           resending.
1239
+	 * @throws EE_Error
1240
+	 * @throws InvalidArgumentException
1241
+	 * @throws InvalidDataTypeException
1242
+	 * @throws InvalidInterfaceException
1243
+	 * @throws ReflectionException
1244
+	 */
1245
+	public static function queue_for_resending($message_ids)
1246
+	{
1247
+		self::_load_controller();
1248
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1249
+
1250
+		// get queue and count
1251
+		$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1252
+
1253
+		if (
1254
+			$queue_count > 0
1255
+		) {
1256
+			EE_Error::add_success(
1257
+				sprintf(
1258
+					_n(
1259
+						'%d message successfully queued for resending.',
1260
+						'%d messages successfully queued for resending.',
1261
+						$queue_count,
1262
+						'event_espresso'
1263
+					),
1264
+					$queue_count
1265
+				)
1266
+			);
1267
+			/**
1268
+			 * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1269
+			 */
1270
+		} elseif (
1271
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1272
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1273
+		) {
1274
+			$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1275
+			if ($queue_count > 0) {
1276
+				EE_Error::add_success(
1277
+					sprintf(
1278
+						_n(
1279
+							'%d message successfully sent.',
1280
+							'%d messages successfully sent.',
1281
+							$queue_count,
1282
+							'event_espresso'
1283
+						),
1284
+						$queue_count
1285
+					)
1286
+				);
1287
+			} else {
1288
+				EE_Error::add_error(
1289
+					esc_html__(
1290
+						'No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1291
+						'event_espresso'
1292
+					),
1293
+					__FILE__,
1294
+					__FUNCTION__,
1295
+					__LINE__
1296
+				);
1297
+			}
1298
+		} else {
1299
+			EE_Error::add_error(
1300
+				esc_html__(
1301
+					'No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1302
+					'event_espresso'
1303
+				),
1304
+				__FILE__,
1305
+				__FUNCTION__,
1306
+				__LINE__
1307
+			);
1308
+		}
1309
+		return (bool) $queue_count;
1310
+	}
1311
+
1312
+
1313
+	/**
1314
+	 * debug
1315
+	 *
1316
+	 * @param string          $class
1317
+	 * @param string          $func
1318
+	 * @param string          $line
1319
+	 * @param \EE_Transaction $transaction
1320
+	 * @param array           $info
1321
+	 * @param bool            $display_request
1322
+	 * @throws EE_Error
1323
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
1324
+	 */
1325
+	protected static function log(
1326
+		$class = '',
1327
+		$func = '',
1328
+		$line = '',
1329
+		EE_Transaction $transaction,
1330
+		$info = array(),
1331
+		$display_request = false
1332
+	) {
1333
+		if (defined('EE_DEBUG') && EE_DEBUG) {
1334
+			if ($transaction instanceof EE_Transaction) {
1335
+				// don't serialize objects
1336
+				$info = EEH_Debug_Tools::strip_objects($info);
1337
+				$info['TXN_status'] = $transaction->status_ID();
1338
+				$info['TXN_reg_steps'] = $transaction->reg_steps();
1339
+				if ($transaction->ID()) {
1340
+					$index = 'EE_Transaction: ' . $transaction->ID();
1341
+					EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1342
+				}
1343
+			}
1344
+		}
1345
+	}
1346
+
1347
+
1348
+	/**
1349
+	 *  Resets all the static properties in this class when called.
1350
+	 */
1351
+	public static function reset()
1352
+	{
1353
+		self::$_EEMSG = null;
1354
+		self::$_message_resource_manager = null;
1355
+		self::$_MSG_PROCESSOR = null;
1356
+		self::$_MSG_PATHS = null;
1357
+		self::$_TMP_PACKS = array();
1358
+	}
1359 1359
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
                 'event_espresso'
205 205
             );
206 206
             // add specific message for developers if WP_DEBUG in on
207
-            $error_msg .= '||' . $e->getMessage();
207
+            $error_msg .= '||'.$e->getMessage();
208 208
             EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
209 209
         }
210 210
     }
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
                 'event_espresso'
291 291
             );
292 292
             // add specific message for developers if WP_DEBUG in on
293
-            $error_msg .= '||' . $e->getMessage();
293
+            $error_msg .= '||'.$e->getMessage();
294 294
             EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
295 295
         }
296 296
     }
@@ -322,7 +322,7 @@  discard block
 block discarded – undo
322 322
         $transient_key = $request->getRequestParam('key');
323 323
 
324 324
         // now let's verify transient, if not valid exit immediately
325
-        if (! get_transient($transient_key)) {
325
+        if ( ! get_transient($transient_key)) {
326 326
             /**
327 327
              * trigger error so this gets in the error logs.  This is important because it happens on a non-user
328 328
              * request.
@@ -334,7 +334,7 @@  discard block
 block discarded – undo
334 334
         delete_transient($transient_key);
335 335
 
336 336
         if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
337
-            $method = 'batch_' . $cron_type . '_from_queue';
337
+            $method = 'batch_'.$cron_type.'_from_queue';
338 338
             if (method_exists(self::$_MSG_PROCESSOR, $method)) {
339 339
                 self::$_MSG_PROCESSOR->$method();
340 340
             } else {
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
         $template_pack_collection->rewind();
402 402
         $template_packs = array();
403 403
         while ($template_pack_collection->valid()) {
404
-            $template_packs[ $template_pack_collection->current()->dbref ] = $template_pack_collection->current();
404
+            $template_packs[$template_pack_collection->current()->dbref] = $template_pack_collection->current();
405 405
             $template_pack_collection->next();
406 406
         }
407 407
         return $template_packs;
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
         );
452 452
         $paths = array();
453 453
         foreach ($dir_ref as $index => $dir) {
454
-            $paths[ $index ] = EE_LIBRARIES . $dir;
454
+            $paths[$index] = EE_LIBRARIES.$dir;
455 455
         }
456 456
         self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
457 457
     }
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
      */
471 471
     protected static function _load_controller()
472 472
     {
473
-        if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
473
+        if ( ! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
474 474
             EE_Registry::instance()->load_core('Request_Handler');
475 475
             self::set_autoloaders();
476 476
             self::$_EEMSG = EE_Registry::instance()->load_lib('messages');
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
     public static function payment(EE_Transaction $transaction, EE_Payment $payment = null)
512 512
     {
513 513
         // if there's no payment object, then we cannot do a payment type message!
514
-        if (! $payment instanceof EE_Payment) {
514
+        if ( ! $payment instanceof EE_Payment) {
515 515
             return;
516 516
         }
517 517
         self::_load_controller();
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
     public static function maybe_registration(EE_Registration $registration, $extra_details = array())
559 559
     {
560 560
 
561
-        if (! self::_verify_registration_notification_send($registration, $extra_details)) {
561
+        if ( ! self::_verify_registration_notification_send($registration, $extra_details)) {
562 562
             // no messages please
563 563
             return;
564 564
         }
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
         EE_Registration $registration,
626 626
         $extra_details = array()
627 627
     ) {
628
-        if (! $registration->is_primary_registrant()) {
628
+        if ( ! $registration->is_primary_registrant()) {
629 629
             return false;
630 630
         }
631 631
         $request = self::getRequest();
@@ -633,14 +633,14 @@  discard block
 block discarded – undo
633 633
         if ($request->isAdmin() && ! $request->isFrontAjax()) {
634 634
             $status_change = $request->getRequestParam('txn_reg_status_change', [], 'int', true);
635 635
             // make sure appropriate admin params are set for sending messages
636
-            if (! $status_change['send_notifications']) {
636
+            if ( ! $status_change['send_notifications']) {
637 637
                 // no messages sent please.
638 638
                 return false;
639 639
             }
640 640
         } else {
641 641
             // frontend request (either regular or via AJAX)
642 642
             // TXN is NOT finalized ?
643
-            if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
643
+            if ( ! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
644 644
                 return false;
645 645
             }
646 646
             // return visit but nothing changed ???
@@ -771,7 +771,7 @@  discard block
 block discarded – undo
771 771
         self::_load_controller();
772 772
 
773 773
         $msgID = self::getRequest()->getRequestParam('MSG_ID', 0, 'int');
774
-        if (! $msgID) {
774
+        if ( ! $msgID) {
775 775
             EE_Error::add_error(
776 776
                 esc_html__(
777 777
                     'Something went wrong because there is no "MSG_ID" value in the request',
@@ -964,14 +964,14 @@  discard block
 block discarded – undo
964 964
             // get the message template group.
965 965
             $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
966 966
             // if we don't have an EE_Message_Template_Group then return
967
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
967
+            if ( ! $msg_template_group instanceof EE_Message_Template_Group) {
968 968
                 // remove EVT_ID from query params so that global templates get picked up
969 969
                 unset($template_query_params['Event.EVT_ID']);
970 970
                 // get global template as the fallback
971 971
                 $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
972 972
             }
973 973
             // if we don't have an EE_Message_Template_Group then return
974
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
974
+            if ( ! $msg_template_group instanceof EE_Message_Template_Group) {
975 975
                 return '';
976 976
             }
977 977
             // generate the URL
@@ -1102,7 +1102,7 @@  discard block
 block discarded – undo
1102 1102
             $generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
1103 1103
         }
1104 1104
 
1105
-        if (! $generated_queue instanceof EE_Messages_Queue) {
1105
+        if ( ! $generated_queue instanceof EE_Messages_Queue) {
1106 1106
             EE_Error::add_error(
1107 1107
                 esc_html__(
1108 1108
                     'The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
@@ -1149,7 +1149,7 @@  discard block
 block discarded – undo
1149 1149
             $sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
1150 1150
         }
1151 1151
 
1152
-        if (! $sent_queue instanceof EE_Messages_Queue) {
1152
+        if ( ! $sent_queue instanceof EE_Messages_Queue) {
1153 1153
             EE_Error::add_error(
1154 1154
                 esc_html__(
1155 1155
                     'The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
@@ -1337,7 +1337,7 @@  discard block
 block discarded – undo
1337 1337
                 $info['TXN_status'] = $transaction->status_ID();
1338 1338
                 $info['TXN_reg_steps'] = $transaction->reg_steps();
1339 1339
                 if ($transaction->ID()) {
1340
-                    $index = 'EE_Transaction: ' . $transaction->ID();
1340
+                    $index = 'EE_Transaction: '.$transaction->ID();
1341 1341
                     EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1342 1342
                 }
1343 1343
             }
Please login to merge, or discard this patch.
modules/ticket_selector/ProcessTicketSelector.php 2 patches
Indentation   +492 added lines, -492 removed lines patch added patch discarded remove patch
@@ -33,521 +33,521 @@
 block discarded – undo
33 33
 class ProcessTicketSelector
34 34
 {
35 35
 
36
-    /**
37
-     * @var EE_Cart $cart
38
-     */
39
-    private $cart;
36
+	/**
37
+	 * @var EE_Cart $cart
38
+	 */
39
+	private $cart;
40 40
 
41
-    /**
42
-     * @var EE_Core_Config $core_config
43
-     */
44
-    private $core_config;
41
+	/**
42
+	 * @var EE_Core_Config $core_config
43
+	 */
44
+	private $core_config;
45 45
 
46
-    /**
47
-     * @var RequestInterface $request
48
-     */
49
-    private $request;
46
+	/**
47
+	 * @var RequestInterface $request
48
+	 */
49
+	private $request;
50 50
 
51
-    /**
52
-     * @var EE_Session $session
53
-     */
54
-    private $session;
51
+	/**
52
+	 * @var EE_Session $session
53
+	 */
54
+	private $session;
55 55
 
56
-    /**
57
-     * @var EEM_Ticket $ticket_model
58
-     */
59
-    private $ticket_model;
56
+	/**
57
+	 * @var EEM_Ticket $ticket_model
58
+	 */
59
+	private $ticket_model;
60 60
 
61
-    /**
62
-     * @var TicketDatetimeAvailabilityTracker $tracker
63
-     */
64
-    private $tracker;
61
+	/**
62
+	 * @var TicketDatetimeAvailabilityTracker $tracker
63
+	 */
64
+	private $tracker;
65 65
 
66 66
 
67
-    /**
68
-     * ProcessTicketSelector constructor.
69
-     * NOTE: PLZ use the Loader to instantiate this class if need be
70
-     * so that all dependencies get injected correctly (which will happen automatically)
71
-     * Null values for parameters are only for backwards compatibility but will be removed later on.
72
-     *
73
-     * @param EE_Core_Config                    $core_config
74
-     * @param RequestInterface                           $request
75
-     * @param EE_Session                        $session
76
-     * @param EEM_Ticket                        $ticket_model
77
-     * @param TicketDatetimeAvailabilityTracker $tracker
78
-     * @throws InvalidArgumentException
79
-     * @throws InvalidDataTypeException
80
-     * @throws InvalidInterfaceException
81
-     */
82
-    public function __construct(
83
-        EE_Core_Config $core_config = null,
84
-        RequestInterface $request = null,
85
-        EE_Session $session = null,
86
-        EEM_Ticket $ticket_model = null,
87
-        TicketDatetimeAvailabilityTracker $tracker = null
88
-    ) {
89
-        $loader = LoaderFactory::getLoader();
90
-        $this->core_config = $core_config instanceof EE_Core_Config
91
-            ? $core_config
92
-            : $loader->getShared('EE_Core_Config');
93
-        $this->request = $request instanceof RequestInterface
94
-            ? $request
95
-            : $loader->getShared('EventEspresso\core\services\request\Request');
96
-        $this->session = $session instanceof EE_Session
97
-            ? $session
98
-            : $loader->getShared('EE_Session');
99
-        $this->ticket_model = $ticket_model instanceof EEM_Ticket
100
-            ? $ticket_model
101
-            : $loader->getShared('EEM_Ticket');
102
-        $this->tracker = $tracker instanceof TicketDatetimeAvailabilityTracker
103
-            ? $tracker
104
-            : $loader->getShared('EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker');
105
-    }
67
+	/**
68
+	 * ProcessTicketSelector constructor.
69
+	 * NOTE: PLZ use the Loader to instantiate this class if need be
70
+	 * so that all dependencies get injected correctly (which will happen automatically)
71
+	 * Null values for parameters are only for backwards compatibility but will be removed later on.
72
+	 *
73
+	 * @param EE_Core_Config                    $core_config
74
+	 * @param RequestInterface                           $request
75
+	 * @param EE_Session                        $session
76
+	 * @param EEM_Ticket                        $ticket_model
77
+	 * @param TicketDatetimeAvailabilityTracker $tracker
78
+	 * @throws InvalidArgumentException
79
+	 * @throws InvalidDataTypeException
80
+	 * @throws InvalidInterfaceException
81
+	 */
82
+	public function __construct(
83
+		EE_Core_Config $core_config = null,
84
+		RequestInterface $request = null,
85
+		EE_Session $session = null,
86
+		EEM_Ticket $ticket_model = null,
87
+		TicketDatetimeAvailabilityTracker $tracker = null
88
+	) {
89
+		$loader = LoaderFactory::getLoader();
90
+		$this->core_config = $core_config instanceof EE_Core_Config
91
+			? $core_config
92
+			: $loader->getShared('EE_Core_Config');
93
+		$this->request = $request instanceof RequestInterface
94
+			? $request
95
+			: $loader->getShared('EventEspresso\core\services\request\Request');
96
+		$this->session = $session instanceof EE_Session
97
+			? $session
98
+			: $loader->getShared('EE_Session');
99
+		$this->ticket_model = $ticket_model instanceof EEM_Ticket
100
+			? $ticket_model
101
+			: $loader->getShared('EEM_Ticket');
102
+		$this->tracker = $tracker instanceof TicketDatetimeAvailabilityTracker
103
+			? $tracker
104
+			: $loader->getShared('EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker');
105
+	}
106 106
 
107 107
 
108
-    /**
109
-     * cancelTicketSelections
110
-     *
111
-     * @return bool
112
-     * @throws EE_Error
113
-     * @throws InvalidArgumentException
114
-     * @throws InvalidInterfaceException
115
-     * @throws InvalidDataTypeException
116
-     * @throws ReflectionException
117
-     */
118
-    public function cancelTicketSelections()
119
-    {
120
-        // check nonce
121
-        if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
122
-            return false;
123
-        }
124
-        $this->session->clear_session(__CLASS__, __FUNCTION__);
125
-        if ($this->request->requestParamIsSet('event_id')) {
126
-            EEH_URL::safeRedirectAndExit(
127
-                EEH_Event_View::event_link_url(
128
-                    $this->request->getRequestParam('event_id', 0, 'int')
129
-                )
130
-            );
131
-        }
132
-        EEH_URL::safeRedirectAndExit(
133
-            site_url('/' . $this->core_config->event_cpt_slug . '/')
134
-        );
135
-        return true;
136
-    }
108
+	/**
109
+	 * cancelTicketSelections
110
+	 *
111
+	 * @return bool
112
+	 * @throws EE_Error
113
+	 * @throws InvalidArgumentException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws InvalidDataTypeException
116
+	 * @throws ReflectionException
117
+	 */
118
+	public function cancelTicketSelections()
119
+	{
120
+		// check nonce
121
+		if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
122
+			return false;
123
+		}
124
+		$this->session->clear_session(__CLASS__, __FUNCTION__);
125
+		if ($this->request->requestParamIsSet('event_id')) {
126
+			EEH_URL::safeRedirectAndExit(
127
+				EEH_Event_View::event_link_url(
128
+					$this->request->getRequestParam('event_id', 0, 'int')
129
+				)
130
+			);
131
+		}
132
+		EEH_URL::safeRedirectAndExit(
133
+			site_url('/' . $this->core_config->event_cpt_slug . '/')
134
+		);
135
+		return true;
136
+	}
137 137
 
138 138
 
139
-    /**
140
-     * processTicketSelectorNonce
141
-     *
142
-     * @param  string $nonce_name
143
-     * @param string  $id
144
-     * @return bool
145
-     */
146
-    private function processTicketSelectorNonce($nonce_name, $id = '')
147
-    {
148
-        $nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
149
-        if (
150
-            ! $this->request->isAdmin()
151
-            && (
152
-                ! $this->request->requestParamIsSet($nonce_name_with_id)
153
-                || ! wp_verify_nonce(
154
-                    $this->request->getRequestParam($nonce_name_with_id),
155
-                    $nonce_name
156
-                )
157
-            )
158
-        ) {
159
-            EE_Error::add_error(
160
-                sprintf(
161
-                    esc_html__(
162
-                        'We\'re sorry but your request failed to pass a security check.%sPlease click the back button on your browser and try again.',
163
-                        'event_espresso'
164
-                    ),
165
-                    '<br/>'
166
-                ),
167
-                __FILE__,
168
-                __FUNCTION__,
169
-                __LINE__
170
-            );
171
-            return false;
172
-        }
173
-        return true;
174
-    }
139
+	/**
140
+	 * processTicketSelectorNonce
141
+	 *
142
+	 * @param  string $nonce_name
143
+	 * @param string  $id
144
+	 * @return bool
145
+	 */
146
+	private function processTicketSelectorNonce($nonce_name, $id = '')
147
+	{
148
+		$nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
149
+		if (
150
+			! $this->request->isAdmin()
151
+			&& (
152
+				! $this->request->requestParamIsSet($nonce_name_with_id)
153
+				|| ! wp_verify_nonce(
154
+					$this->request->getRequestParam($nonce_name_with_id),
155
+					$nonce_name
156
+				)
157
+			)
158
+		) {
159
+			EE_Error::add_error(
160
+				sprintf(
161
+					esc_html__(
162
+						'We\'re sorry but your request failed to pass a security check.%sPlease click the back button on your browser and try again.',
163
+						'event_espresso'
164
+					),
165
+					'<br/>'
166
+				),
167
+				__FILE__,
168
+				__FUNCTION__,
169
+				__LINE__
170
+			);
171
+			return false;
172
+		}
173
+		return true;
174
+	}
175 175
 
176 176
 
177
-    /**
178
-     * process_ticket_selections
179
-     *
180
-     * @return bool
181
-     * @throws EE_Error
182
-     * @throws InvalidArgumentException
183
-     * @throws InvalidDataTypeException
184
-     * @throws InvalidInterfaceException
185
-     * @throws ReflectionException
186
-     */
187
-    public function processTicketSelections()
188
-    {
189
-        do_action('EED_Ticket_Selector__process_ticket_selections__before');
190
-        if ($this->request->isBot()) {
191
-            EEH_URL::safeRedirectAndExit(
192
-                apply_filters(
193
-                    'FHEE__EE_Ticket_Selector__process_ticket_selections__bot_redirect_url',
194
-                    site_url()
195
-                )
196
-            );
197
-        }
198
-        // do we have an event id?
199
-        $id = $this->getEventId();
200
-        // we should really only have 1 registration in the works now
201
-        // (ie, no MER) so unless otherwise requested, clear the session
202
-        if (apply_filters('FHEE__EE_Ticket_Selector__process_ticket_selections__clear_session', true)) {
203
-            $this->session->clear_session(__CLASS__, __FUNCTION__);
204
-        }
205
-        // validate/sanitize/filter data
206
-        $valid = apply_filters(
207
-            'FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data',
208
-            $this->validatePostData($id)
209
-        );
210
-        // check total tickets ordered vs max number of attendees that can register
211
-        if (! empty($valid) && $valid['total_tickets'] > $valid['max_atndz']) {
212
-            $this->maxAttendeesViolation($valid);
213
-        } else {
214
-            // all data appears to be valid
215
-            if ($this->processSuccessfulCart($this->addTicketsToCart($valid))) {
216
-                return true;
217
-            }
218
-        }
219
-        // die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL BEFORE REDIRECT
220
-        // at this point, just return if registration is being made from admin
221
-        if ($this->request->isAdmin() || $this->request->isFrontAjax()) {
222
-            return false;
223
-        }
224
-        if ($valid['return_url']) {
225
-            EEH_URL::safeRedirectAndExit($valid['return_url']);
226
-        }
227
-        if ($id) {
228
-            EEH_URL::safeRedirectAndExit(get_permalink($id));
229
-        }
230
-        echo EE_Error::get_notices(); // already escaped
231
-        return false;
232
-    }
177
+	/**
178
+	 * process_ticket_selections
179
+	 *
180
+	 * @return bool
181
+	 * @throws EE_Error
182
+	 * @throws InvalidArgumentException
183
+	 * @throws InvalidDataTypeException
184
+	 * @throws InvalidInterfaceException
185
+	 * @throws ReflectionException
186
+	 */
187
+	public function processTicketSelections()
188
+	{
189
+		do_action('EED_Ticket_Selector__process_ticket_selections__before');
190
+		if ($this->request->isBot()) {
191
+			EEH_URL::safeRedirectAndExit(
192
+				apply_filters(
193
+					'FHEE__EE_Ticket_Selector__process_ticket_selections__bot_redirect_url',
194
+					site_url()
195
+				)
196
+			);
197
+		}
198
+		// do we have an event id?
199
+		$id = $this->getEventId();
200
+		// we should really only have 1 registration in the works now
201
+		// (ie, no MER) so unless otherwise requested, clear the session
202
+		if (apply_filters('FHEE__EE_Ticket_Selector__process_ticket_selections__clear_session', true)) {
203
+			$this->session->clear_session(__CLASS__, __FUNCTION__);
204
+		}
205
+		// validate/sanitize/filter data
206
+		$valid = apply_filters(
207
+			'FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data',
208
+			$this->validatePostData($id)
209
+		);
210
+		// check total tickets ordered vs max number of attendees that can register
211
+		if (! empty($valid) && $valid['total_tickets'] > $valid['max_atndz']) {
212
+			$this->maxAttendeesViolation($valid);
213
+		} else {
214
+			// all data appears to be valid
215
+			if ($this->processSuccessfulCart($this->addTicketsToCart($valid))) {
216
+				return true;
217
+			}
218
+		}
219
+		// die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL BEFORE REDIRECT
220
+		// at this point, just return if registration is being made from admin
221
+		if ($this->request->isAdmin() || $this->request->isFrontAjax()) {
222
+			return false;
223
+		}
224
+		if ($valid['return_url']) {
225
+			EEH_URL::safeRedirectAndExit($valid['return_url']);
226
+		}
227
+		if ($id) {
228
+			EEH_URL::safeRedirectAndExit(get_permalink($id));
229
+		}
230
+		echo EE_Error::get_notices(); // already escaped
231
+		return false;
232
+	}
233 233
 
234 234
 
235
-    /**
236
-     * @return int
237
-     */
238
-    private function getEventId()
239
-    {
240
-        // do we have an event id?
241
-        if (! $this->request->requestParamIsSet('tkt-slctr-event-id')) {
242
-            // $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
243
-            EE_Error::add_error(
244
-                sprintf(
245
-                    esc_html__(
246
-                        'An event id was not provided or was not received.%sPlease click the back button on your browser and try again.',
247
-                        'event_espresso'
248
-                    ),
249
-                    '<br/>'
250
-                ),
251
-                __FILE__,
252
-                __FUNCTION__,
253
-                __LINE__
254
-            );
255
-        }
256
-        // if event id is valid
257
-        return $this->request->getRequestParam('tkt-slctr-event-id', 0, 'int');
258
-    }
235
+	/**
236
+	 * @return int
237
+	 */
238
+	private function getEventId()
239
+	{
240
+		// do we have an event id?
241
+		if (! $this->request->requestParamIsSet('tkt-slctr-event-id')) {
242
+			// $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
243
+			EE_Error::add_error(
244
+				sprintf(
245
+					esc_html__(
246
+						'An event id was not provided or was not received.%sPlease click the back button on your browser and try again.',
247
+						'event_espresso'
248
+					),
249
+					'<br/>'
250
+				),
251
+				__FILE__,
252
+				__FUNCTION__,
253
+				__LINE__
254
+			);
255
+		}
256
+		// if event id is valid
257
+		return $this->request->getRequestParam('tkt-slctr-event-id', 0, 'int');
258
+	}
259 259
 
260 260
 
261
-    /**
262
-     * validate_post_data
263
-     *
264
-     * @param int $id
265
-     * @return array
266
-     */
267
-    private function validatePostData($id = 0)
268
-    {
269
-        if (! $id) {
270
-            EE_Error::add_error(
271
-                esc_html__('The event id provided was not valid.', 'event_espresso'),
272
-                __FILE__,
273
-                __FUNCTION__,
274
-                __LINE__
275
-            );
276
-            return array();
277
-        }
278
-        // start with an empty array()
279
-        $valid_data = array();
280
-        // grab valid id
281
-        $valid_data['id'] = $id;
282
-        // array of other form names
283
-        $inputs_to_clean = array(
284
-            'max_atndz'  => 'tkt-slctr-max-atndz-',
285
-            'rows'       => 'tkt-slctr-rows-',
286
-            'qty'        => 'tkt-slctr-qty-',
287
-            'ticket_id'  => 'tkt-slctr-ticket-id-',
288
-            'return_url' => 'tkt-slctr-return-url-',
289
-        );
290
-        // let's track the total number of tickets ordered.'
291
-        $valid_data['total_tickets'] = 0;
292
-        // cycle through $inputs_to_clean array
293
-        foreach ($inputs_to_clean as $what => $input_to_clean) {
294
-            // check for POST data
295
-            if ($this->request->requestParamIsSet($input_to_clean . $id)) {
296
-                switch ($what) {
297
-                    // integers
298
-                    case 'event_id':
299
-                    case 'rows':
300
-                    case 'max_atndz':
301
-                        $valid_data[ $what ] = $this->request->getRequestParam($input_to_clean . $id, 0, 'int');
302
-                        break;
303
-                    // arrays of integers
304
-                    case 'qty':
305
-                        /** @var array $row_qty */
306
-                        $row_qty = $this->request->getRequestParam($input_to_clean . $id, [], 'int', true);
307
-                        // if qty is coming from a radio button input, then we need to assemble an array of rows
308
-                        if (! is_array($row_qty)) {
309
-                            /** @var string $row_qty */
310
-                            // get number of rows
311
-                            $rows = $this->request->getRequestParam('tkt-slctr-rows-' . $id, 1, 'int');
312
-                            // explode integers by the dash
313
-                            $row_qty = explode('-', $row_qty);
314
-                            $row = isset($row_qty[0]) ? absint($row_qty[0]) : 1;
315
-                            $qty = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
316
-                            $row_qty = array($row => $qty);
317
-                            for ($x = 1; $x <= $rows; $x++) {
318
-                                if (! isset($row_qty[ $x ])) {
319
-                                    $row_qty[ $x ] = 0;
320
-                                }
321
-                            }
322
-                        }
323
-                        ksort($row_qty);
324
-                        // cycle thru values
325
-                        foreach ($row_qty as $qty) {
326
-                            $qty = absint($qty);
327
-                            // sanitize as integers
328
-                            $valid_data[ $what ][] = $qty;
329
-                            $valid_data['total_tickets'] += $qty;
330
-                        }
331
-                        break;
332
-                    // array of integers
333
-                    case 'ticket_id':
334
-                        $ticket_ids = (array) $this->request->getRequestParam($input_to_clean . $id, [], 'int', true);
335
-                        // cycle thru values
336
-                        foreach ($ticket_ids as $key => $value) {
337
-                            // allow only integers
338
-                            $valid_data[ $what ][ $key ] = absint($value);
339
-                        }
340
-                        break;
341
-                    case 'return_url':
342
-                        // grab and sanitize return-url
343
-                        $input_value = $this->request->getRequestParam($input_to_clean . $id, '', 'url');
344
-                        // was the request coming from an iframe ? if so, then:
345
-                        if (strpos($input_value, 'event_list=iframe')) {
346
-                            // get anchor fragment
347
-                            $input_value = explode('#', $input_value);
348
-                            $input_value = end($input_value);
349
-                            // use event list url instead, but append anchor
350
-                            $input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
351
-                        }
352
-                        $valid_data[ $what ] = $input_value;
353
-                        break;
354
-                }    // end switch $what
355
-            }
356
-        }    // end foreach $inputs_to_clean
357
-        return $valid_data;
358
-    }
261
+	/**
262
+	 * validate_post_data
263
+	 *
264
+	 * @param int $id
265
+	 * @return array
266
+	 */
267
+	private function validatePostData($id = 0)
268
+	{
269
+		if (! $id) {
270
+			EE_Error::add_error(
271
+				esc_html__('The event id provided was not valid.', 'event_espresso'),
272
+				__FILE__,
273
+				__FUNCTION__,
274
+				__LINE__
275
+			);
276
+			return array();
277
+		}
278
+		// start with an empty array()
279
+		$valid_data = array();
280
+		// grab valid id
281
+		$valid_data['id'] = $id;
282
+		// array of other form names
283
+		$inputs_to_clean = array(
284
+			'max_atndz'  => 'tkt-slctr-max-atndz-',
285
+			'rows'       => 'tkt-slctr-rows-',
286
+			'qty'        => 'tkt-slctr-qty-',
287
+			'ticket_id'  => 'tkt-slctr-ticket-id-',
288
+			'return_url' => 'tkt-slctr-return-url-',
289
+		);
290
+		// let's track the total number of tickets ordered.'
291
+		$valid_data['total_tickets'] = 0;
292
+		// cycle through $inputs_to_clean array
293
+		foreach ($inputs_to_clean as $what => $input_to_clean) {
294
+			// check for POST data
295
+			if ($this->request->requestParamIsSet($input_to_clean . $id)) {
296
+				switch ($what) {
297
+					// integers
298
+					case 'event_id':
299
+					case 'rows':
300
+					case 'max_atndz':
301
+						$valid_data[ $what ] = $this->request->getRequestParam($input_to_clean . $id, 0, 'int');
302
+						break;
303
+					// arrays of integers
304
+					case 'qty':
305
+						/** @var array $row_qty */
306
+						$row_qty = $this->request->getRequestParam($input_to_clean . $id, [], 'int', true);
307
+						// if qty is coming from a radio button input, then we need to assemble an array of rows
308
+						if (! is_array($row_qty)) {
309
+							/** @var string $row_qty */
310
+							// get number of rows
311
+							$rows = $this->request->getRequestParam('tkt-slctr-rows-' . $id, 1, 'int');
312
+							// explode integers by the dash
313
+							$row_qty = explode('-', $row_qty);
314
+							$row = isset($row_qty[0]) ? absint($row_qty[0]) : 1;
315
+							$qty = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
316
+							$row_qty = array($row => $qty);
317
+							for ($x = 1; $x <= $rows; $x++) {
318
+								if (! isset($row_qty[ $x ])) {
319
+									$row_qty[ $x ] = 0;
320
+								}
321
+							}
322
+						}
323
+						ksort($row_qty);
324
+						// cycle thru values
325
+						foreach ($row_qty as $qty) {
326
+							$qty = absint($qty);
327
+							// sanitize as integers
328
+							$valid_data[ $what ][] = $qty;
329
+							$valid_data['total_tickets'] += $qty;
330
+						}
331
+						break;
332
+					// array of integers
333
+					case 'ticket_id':
334
+						$ticket_ids = (array) $this->request->getRequestParam($input_to_clean . $id, [], 'int', true);
335
+						// cycle thru values
336
+						foreach ($ticket_ids as $key => $value) {
337
+							// allow only integers
338
+							$valid_data[ $what ][ $key ] = absint($value);
339
+						}
340
+						break;
341
+					case 'return_url':
342
+						// grab and sanitize return-url
343
+						$input_value = $this->request->getRequestParam($input_to_clean . $id, '', 'url');
344
+						// was the request coming from an iframe ? if so, then:
345
+						if (strpos($input_value, 'event_list=iframe')) {
346
+							// get anchor fragment
347
+							$input_value = explode('#', $input_value);
348
+							$input_value = end($input_value);
349
+							// use event list url instead, but append anchor
350
+							$input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
351
+						}
352
+						$valid_data[ $what ] = $input_value;
353
+						break;
354
+				}    // end switch $what
355
+			}
356
+		}    // end foreach $inputs_to_clean
357
+		return $valid_data;
358
+	}
359 359
 
360 360
 
361
-    /**
362
-     * @param array $valid
363
-     */
364
-    private function maxAttendeesViolation(array $valid)
365
-    {
366
-        // ordering too many tickets !!!
367
-        $total_tickets_string = esc_html(
368
-            _n(
369
-                'You have attempted to purchase %s ticket.',
370
-                'You have attempted to purchase %s tickets.',
371
-                $valid['total_tickets'],
372
-                'event_espresso'
373
-            )
374
-        );
375
-        $limit_error_1 = sprintf($total_tickets_string, $valid['total_tickets']);
376
-        // dev only message
377
-        $max_attendees_string = esc_html(
378
-            _n(
379
-                '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.',
380
-                '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.',
381
-                $valid['max_atndz'],
382
-                'event_espresso'
383
-            )
384
-        );
385
-        $limit_error_2 = sprintf($max_attendees_string, $valid['max_atndz'], $valid['max_atndz']);
386
-        EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
387
-    }
361
+	/**
362
+	 * @param array $valid
363
+	 */
364
+	private function maxAttendeesViolation(array $valid)
365
+	{
366
+		// ordering too many tickets !!!
367
+		$total_tickets_string = esc_html(
368
+			_n(
369
+				'You have attempted to purchase %s ticket.',
370
+				'You have attempted to purchase %s tickets.',
371
+				$valid['total_tickets'],
372
+				'event_espresso'
373
+			)
374
+		);
375
+		$limit_error_1 = sprintf($total_tickets_string, $valid['total_tickets']);
376
+		// dev only message
377
+		$max_attendees_string = esc_html(
378
+			_n(
379
+				'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.',
380
+				'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.',
381
+				$valid['max_atndz'],
382
+				'event_espresso'
383
+			)
384
+		);
385
+		$limit_error_2 = sprintf($max_attendees_string, $valid['max_atndz'], $valid['max_atndz']);
386
+		EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
387
+	}
388 388
 
389 389
 
390
-    /**
391
-     * @param array $valid
392
-     * @return int
393
-     * @throws EE_Error
394
-     * @throws InvalidArgumentException
395
-     * @throws InvalidDataTypeException
396
-     * @throws InvalidInterfaceException
397
-     */
398
-    private function addTicketsToCart(array $valid)
399
-    {
400
-        $tickets_added = 0;
401
-        $tickets_selected = false;
402
-        if (! empty($valid) && $valid['total_tickets'] > 0) {
403
-            // load cart using factory because we don't want to do so until actually needed
404
-            $this->cart = CartFactory::getCart();
405
-            // if the user is an admin that can edit registrations,
406
-            // then we'll also allow them to add any tickets, even if they are expired
407
-            $current_user_is_admin = current_user_can('ee_edit_registrations');
408
-            // cycle thru the number of data rows sent from the event listing
409
-            for ($x = 0; $x < $valid['rows']; $x++) {
410
-                // does this row actually contain a ticket quantity?
411
-                if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
412
-                    // YES we have a ticket quantity
413
-                    $tickets_selected = true;
414
-                    $valid_ticket = false;
415
-                    if (isset($valid['ticket_id'][ $x ])) {
416
-                        // get ticket via the ticket id we put in the form
417
-                        $ticket = $this->ticket_model->get_one_by_ID($valid['ticket_id'][ $x ]);
418
-                        if ($ticket instanceof EE_Ticket && ($ticket->is_on_sale() || $current_user_is_admin)) {
419
-                            $valid_ticket = true;
420
-                            $tickets_added += $this->addTicketToCart(
421
-                                $ticket,
422
-                                $valid['qty'][ $x ]
423
-                            );
424
-                        }
425
-                    }
426
-                    if ($valid_ticket !== true) {
427
-                        // nothing added to cart retrieved
428
-                        EE_Error::add_error(
429
-                            sprintf(
430
-                                esc_html__(
431
-                                    'A valid ticket could not be retrieved for the event.%sPlease click the back button on your browser and try again.',
432
-                                    'event_espresso'
433
-                                ),
434
-                                '<br/>'
435
-                            ),
436
-                            __FILE__,
437
-                            __FUNCTION__,
438
-                            __LINE__
439
-                        );
440
-                    }
441
-                    if (EE_Error::has_error()) {
442
-                        break;
443
-                    }
444
-                }
445
-            }
446
-        }
447
-        do_action(
448
-            'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
449
-            $this->cart,
450
-            $this
451
-        );
452
-        if (! apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tickets_selected)) {
453
-            // no ticket quantities were selected
454
-            EE_Error::add_error(
455
-                esc_html__('You need to select a ticket quantity before you can proceed.', 'event_espresso'),
456
-                __FILE__,
457
-                __FUNCTION__,
458
-                __LINE__
459
-            );
460
-        }
461
-        return $tickets_added;
462
-    }
390
+	/**
391
+	 * @param array $valid
392
+	 * @return int
393
+	 * @throws EE_Error
394
+	 * @throws InvalidArgumentException
395
+	 * @throws InvalidDataTypeException
396
+	 * @throws InvalidInterfaceException
397
+	 */
398
+	private function addTicketsToCart(array $valid)
399
+	{
400
+		$tickets_added = 0;
401
+		$tickets_selected = false;
402
+		if (! empty($valid) && $valid['total_tickets'] > 0) {
403
+			// load cart using factory because we don't want to do so until actually needed
404
+			$this->cart = CartFactory::getCart();
405
+			// if the user is an admin that can edit registrations,
406
+			// then we'll also allow them to add any tickets, even if they are expired
407
+			$current_user_is_admin = current_user_can('ee_edit_registrations');
408
+			// cycle thru the number of data rows sent from the event listing
409
+			for ($x = 0; $x < $valid['rows']; $x++) {
410
+				// does this row actually contain a ticket quantity?
411
+				if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
412
+					// YES we have a ticket quantity
413
+					$tickets_selected = true;
414
+					$valid_ticket = false;
415
+					if (isset($valid['ticket_id'][ $x ])) {
416
+						// get ticket via the ticket id we put in the form
417
+						$ticket = $this->ticket_model->get_one_by_ID($valid['ticket_id'][ $x ]);
418
+						if ($ticket instanceof EE_Ticket && ($ticket->is_on_sale() || $current_user_is_admin)) {
419
+							$valid_ticket = true;
420
+							$tickets_added += $this->addTicketToCart(
421
+								$ticket,
422
+								$valid['qty'][ $x ]
423
+							);
424
+						}
425
+					}
426
+					if ($valid_ticket !== true) {
427
+						// nothing added to cart retrieved
428
+						EE_Error::add_error(
429
+							sprintf(
430
+								esc_html__(
431
+									'A valid ticket could not be retrieved for the event.%sPlease click the back button on your browser and try again.',
432
+									'event_espresso'
433
+								),
434
+								'<br/>'
435
+							),
436
+							__FILE__,
437
+							__FUNCTION__,
438
+							__LINE__
439
+						);
440
+					}
441
+					if (EE_Error::has_error()) {
442
+						break;
443
+					}
444
+				}
445
+			}
446
+		}
447
+		do_action(
448
+			'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
449
+			$this->cart,
450
+			$this
451
+		);
452
+		if (! apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tickets_selected)) {
453
+			// no ticket quantities were selected
454
+			EE_Error::add_error(
455
+				esc_html__('You need to select a ticket quantity before you can proceed.', 'event_espresso'),
456
+				__FILE__,
457
+				__FUNCTION__,
458
+				__LINE__
459
+			);
460
+		}
461
+		return $tickets_added;
462
+	}
463 463
 
464 464
 
465
-    /**
466
-     * adds a ticket to the cart
467
-     *
468
-     * @param EE_Ticket $ticket
469
-     * @param int       $qty
470
-     * @return bool TRUE on success, FALSE on fail
471
-     * @throws InvalidArgumentException
472
-     * @throws InvalidInterfaceException
473
-     * @throws InvalidDataTypeException
474
-     * @throws EE_Error
475
-     */
476
-    private function addTicketToCart(EE_Ticket $ticket, $qty = 1)
477
-    {
478
-        // get the number of spaces left for this datetime ticket
479
-        $available_spaces = $this->tracker->ticketDatetimeAvailability($ticket);
480
-        // compare available spaces against the number of tickets being purchased
481
-        if ($available_spaces >= $qty) {
482
-            // allow addons to prevent a ticket from being added to cart
483
-            if (
484
-                ! apply_filters(
485
-                    'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart',
486
-                    true,
487
-                    $ticket,
488
-                    $qty,
489
-                    $available_spaces
490
-                )
491
-            ) {
492
-                return false;
493
-            }
494
-            $qty = absint(apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty', $qty, $ticket));
495
-            // add event to cart
496
-            if ($this->cart->add_ticket_to_cart($ticket, $qty)) {
497
-                $this->tracker->recalculateTicketDatetimeAvailability($ticket, $qty);
498
-                return true;
499
-            }
500
-            return false;
501
-        }
502
-        $this->tracker->processAvailabilityError($ticket, $qty, $this->cart->all_ticket_quantity_count());
503
-        return false;
504
-    }
465
+	/**
466
+	 * adds a ticket to the cart
467
+	 *
468
+	 * @param EE_Ticket $ticket
469
+	 * @param int       $qty
470
+	 * @return bool TRUE on success, FALSE on fail
471
+	 * @throws InvalidArgumentException
472
+	 * @throws InvalidInterfaceException
473
+	 * @throws InvalidDataTypeException
474
+	 * @throws EE_Error
475
+	 */
476
+	private function addTicketToCart(EE_Ticket $ticket, $qty = 1)
477
+	{
478
+		// get the number of spaces left for this datetime ticket
479
+		$available_spaces = $this->tracker->ticketDatetimeAvailability($ticket);
480
+		// compare available spaces against the number of tickets being purchased
481
+		if ($available_spaces >= $qty) {
482
+			// allow addons to prevent a ticket from being added to cart
483
+			if (
484
+				! apply_filters(
485
+					'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart',
486
+					true,
487
+					$ticket,
488
+					$qty,
489
+					$available_spaces
490
+				)
491
+			) {
492
+				return false;
493
+			}
494
+			$qty = absint(apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty', $qty, $ticket));
495
+			// add event to cart
496
+			if ($this->cart->add_ticket_to_cart($ticket, $qty)) {
497
+				$this->tracker->recalculateTicketDatetimeAvailability($ticket, $qty);
498
+				return true;
499
+			}
500
+			return false;
501
+		}
502
+		$this->tracker->processAvailabilityError($ticket, $qty, $this->cart->all_ticket_quantity_count());
503
+		return false;
504
+	}
505 505
 
506 506
 
507
-    /**
508
-     * @param $tickets_added
509
-     * @return bool
510
-     * @throws InvalidInterfaceException
511
-     * @throws InvalidDataTypeException
512
-     * @throws EE_Error
513
-     * @throws InvalidArgumentException
514
-     */
515
-    private function processSuccessfulCart($tickets_added)
516
-    {
517
-        // exit('KILL REDIRECT BEFORE CART UPDATE'); // <<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
518
-        if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
519
-            // make sure cart is loaded
520
-            if (! $this->cart instanceof EE_Cart) {
521
-                $this->cart = CartFactory::getCart();
522
-            }
523
-            do_action(
524
-                'FHEE__EE_Ticket_Selector__process_ticket_selections__before_redirecting_to_checkout',
525
-                $this->cart,
526
-                $this
527
-            );
528
-            $this->cart->recalculate_all_cart_totals();
529
-            $this->cart->save_cart(false);
530
-            // exit('KILL REDIRECT AFTER CART UPDATE'); // <<<<<<<<  OR HERE TO KILL REDIRECT AFTER CART UPDATE
531
-            // just return TRUE for registrations being made from admin
532
-            if ($this->request->isAdmin() || $this->request->isFrontAjax()) {
533
-                return true;
534
-            }
535
-            EEH_URL::safeRedirectAndExit(
536
-                apply_filters(
537
-                    'FHEE__EE_Ticket_Selector__process_ticket_selections__success_redirect_url',
538
-                    $this->core_config->reg_page_url()
539
-                )
540
-            );
541
-        }
542
-        if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
543
-            // nothing added to cart
544
-            EE_Error::add_attention(
545
-                esc_html__('No tickets were added for the event', 'event_espresso'),
546
-                __FILE__,
547
-                __FUNCTION__,
548
-                __LINE__
549
-            );
550
-        }
551
-        return false;
552
-    }
507
+	/**
508
+	 * @param $tickets_added
509
+	 * @return bool
510
+	 * @throws InvalidInterfaceException
511
+	 * @throws InvalidDataTypeException
512
+	 * @throws EE_Error
513
+	 * @throws InvalidArgumentException
514
+	 */
515
+	private function processSuccessfulCart($tickets_added)
516
+	{
517
+		// exit('KILL REDIRECT BEFORE CART UPDATE'); // <<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
518
+		if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
519
+			// make sure cart is loaded
520
+			if (! $this->cart instanceof EE_Cart) {
521
+				$this->cart = CartFactory::getCart();
522
+			}
523
+			do_action(
524
+				'FHEE__EE_Ticket_Selector__process_ticket_selections__before_redirecting_to_checkout',
525
+				$this->cart,
526
+				$this
527
+			);
528
+			$this->cart->recalculate_all_cart_totals();
529
+			$this->cart->save_cart(false);
530
+			// exit('KILL REDIRECT AFTER CART UPDATE'); // <<<<<<<<  OR HERE TO KILL REDIRECT AFTER CART UPDATE
531
+			// just return TRUE for registrations being made from admin
532
+			if ($this->request->isAdmin() || $this->request->isFrontAjax()) {
533
+				return true;
534
+			}
535
+			EEH_URL::safeRedirectAndExit(
536
+				apply_filters(
537
+					'FHEE__EE_Ticket_Selector__process_ticket_selections__success_redirect_url',
538
+					$this->core_config->reg_page_url()
539
+				)
540
+			);
541
+		}
542
+		if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
543
+			// nothing added to cart
544
+			EE_Error::add_attention(
545
+				esc_html__('No tickets were added for the event', 'event_espresso'),
546
+				__FILE__,
547
+				__FUNCTION__,
548
+				__LINE__
549
+			);
550
+		}
551
+		return false;
552
+	}
553 553
 }
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
     public function cancelTicketSelections()
119 119
     {
120 120
         // check nonce
121
-        if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
121
+        if ( ! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
122 122
             return false;
123 123
         }
124 124
         $this->session->clear_session(__CLASS__, __FUNCTION__);
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
             );
131 131
         }
132 132
         EEH_URL::safeRedirectAndExit(
133
-            site_url('/' . $this->core_config->event_cpt_slug . '/')
133
+            site_url('/'.$this->core_config->event_cpt_slug.'/')
134 134
         );
135 135
         return true;
136 136
     }
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
             $this->validatePostData($id)
209 209
         );
210 210
         // check total tickets ordered vs max number of attendees that can register
211
-        if (! empty($valid) && $valid['total_tickets'] > $valid['max_atndz']) {
211
+        if ( ! empty($valid) && $valid['total_tickets'] > $valid['max_atndz']) {
212 212
             $this->maxAttendeesViolation($valid);
213 213
         } else {
214 214
             // all data appears to be valid
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
     private function getEventId()
239 239
     {
240 240
         // do we have an event id?
241
-        if (! $this->request->requestParamIsSet('tkt-slctr-event-id')) {
241
+        if ( ! $this->request->requestParamIsSet('tkt-slctr-event-id')) {
242 242
             // $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
243 243
             EE_Error::add_error(
244 244
                 sprintf(
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
      */
267 267
     private function validatePostData($id = 0)
268 268
     {
269
-        if (! $id) {
269
+        if ( ! $id) {
270 270
             EE_Error::add_error(
271 271
                 esc_html__('The event id provided was not valid.', 'event_espresso'),
272 272
                 __FILE__,
@@ -292,31 +292,31 @@  discard block
 block discarded – undo
292 292
         // cycle through $inputs_to_clean array
293 293
         foreach ($inputs_to_clean as $what => $input_to_clean) {
294 294
             // check for POST data
295
-            if ($this->request->requestParamIsSet($input_to_clean . $id)) {
295
+            if ($this->request->requestParamIsSet($input_to_clean.$id)) {
296 296
                 switch ($what) {
297 297
                     // integers
298 298
                     case 'event_id':
299 299
                     case 'rows':
300 300
                     case 'max_atndz':
301
-                        $valid_data[ $what ] = $this->request->getRequestParam($input_to_clean . $id, 0, 'int');
301
+                        $valid_data[$what] = $this->request->getRequestParam($input_to_clean.$id, 0, 'int');
302 302
                         break;
303 303
                     // arrays of integers
304 304
                     case 'qty':
305 305
                         /** @var array $row_qty */
306
-                        $row_qty = $this->request->getRequestParam($input_to_clean . $id, [], 'int', true);
306
+                        $row_qty = $this->request->getRequestParam($input_to_clean.$id, [], 'int', true);
307 307
                         // if qty is coming from a radio button input, then we need to assemble an array of rows
308
-                        if (! is_array($row_qty)) {
308
+                        if ( ! is_array($row_qty)) {
309 309
                             /** @var string $row_qty */
310 310
                             // get number of rows
311
-                            $rows = $this->request->getRequestParam('tkt-slctr-rows-' . $id, 1, 'int');
311
+                            $rows = $this->request->getRequestParam('tkt-slctr-rows-'.$id, 1, 'int');
312 312
                             // explode integers by the dash
313 313
                             $row_qty = explode('-', $row_qty);
314 314
                             $row = isset($row_qty[0]) ? absint($row_qty[0]) : 1;
315 315
                             $qty = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
316 316
                             $row_qty = array($row => $qty);
317 317
                             for ($x = 1; $x <= $rows; $x++) {
318
-                                if (! isset($row_qty[ $x ])) {
319
-                                    $row_qty[ $x ] = 0;
318
+                                if ( ! isset($row_qty[$x])) {
319
+                                    $row_qty[$x] = 0;
320 320
                                 }
321 321
                             }
322 322
                         }
@@ -325,31 +325,31 @@  discard block
 block discarded – undo
325 325
                         foreach ($row_qty as $qty) {
326 326
                             $qty = absint($qty);
327 327
                             // sanitize as integers
328
-                            $valid_data[ $what ][] = $qty;
328
+                            $valid_data[$what][] = $qty;
329 329
                             $valid_data['total_tickets'] += $qty;
330 330
                         }
331 331
                         break;
332 332
                     // array of integers
333 333
                     case 'ticket_id':
334
-                        $ticket_ids = (array) $this->request->getRequestParam($input_to_clean . $id, [], 'int', true);
334
+                        $ticket_ids = (array) $this->request->getRequestParam($input_to_clean.$id, [], 'int', true);
335 335
                         // cycle thru values
336 336
                         foreach ($ticket_ids as $key => $value) {
337 337
                             // allow only integers
338
-                            $valid_data[ $what ][ $key ] = absint($value);
338
+                            $valid_data[$what][$key] = absint($value);
339 339
                         }
340 340
                         break;
341 341
                     case 'return_url':
342 342
                         // grab and sanitize return-url
343
-                        $input_value = $this->request->getRequestParam($input_to_clean . $id, '', 'url');
343
+                        $input_value = $this->request->getRequestParam($input_to_clean.$id, '', 'url');
344 344
                         // was the request coming from an iframe ? if so, then:
345 345
                         if (strpos($input_value, 'event_list=iframe')) {
346 346
                             // get anchor fragment
347 347
                             $input_value = explode('#', $input_value);
348 348
                             $input_value = end($input_value);
349 349
                             // use event list url instead, but append anchor
350
-                            $input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
350
+                            $input_value = EEH_Event_View::event_archive_url().'#'.$input_value;
351 351
                         }
352
-                        $valid_data[ $what ] = $input_value;
352
+                        $valid_data[$what] = $input_value;
353 353
                         break;
354 354
                 }    // end switch $what
355 355
             }
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
             )
384 384
         );
385 385
         $limit_error_2 = sprintf($max_attendees_string, $valid['max_atndz'], $valid['max_atndz']);
386
-        EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
386
+        EE_Error::add_error($limit_error_1.'<br/>'.$limit_error_2, __FILE__, __FUNCTION__, __LINE__);
387 387
     }
388 388
 
389 389
 
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
     {
400 400
         $tickets_added = 0;
401 401
         $tickets_selected = false;
402
-        if (! empty($valid) && $valid['total_tickets'] > 0) {
402
+        if ( ! empty($valid) && $valid['total_tickets'] > 0) {
403 403
             // load cart using factory because we don't want to do so until actually needed
404 404
             $this->cart = CartFactory::getCart();
405 405
             // if the user is an admin that can edit registrations,
@@ -408,18 +408,18 @@  discard block
 block discarded – undo
408 408
             // cycle thru the number of data rows sent from the event listing
409 409
             for ($x = 0; $x < $valid['rows']; $x++) {
410 410
                 // does this row actually contain a ticket quantity?
411
-                if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
411
+                if (isset($valid['qty'][$x]) && $valid['qty'][$x] > 0) {
412 412
                     // YES we have a ticket quantity
413 413
                     $tickets_selected = true;
414 414
                     $valid_ticket = false;
415
-                    if (isset($valid['ticket_id'][ $x ])) {
415
+                    if (isset($valid['ticket_id'][$x])) {
416 416
                         // get ticket via the ticket id we put in the form
417
-                        $ticket = $this->ticket_model->get_one_by_ID($valid['ticket_id'][ $x ]);
417
+                        $ticket = $this->ticket_model->get_one_by_ID($valid['ticket_id'][$x]);
418 418
                         if ($ticket instanceof EE_Ticket && ($ticket->is_on_sale() || $current_user_is_admin)) {
419 419
                             $valid_ticket = true;
420 420
                             $tickets_added += $this->addTicketToCart(
421 421
                                 $ticket,
422
-                                $valid['qty'][ $x ]
422
+                                $valid['qty'][$x]
423 423
                             );
424 424
                         }
425 425
                     }
@@ -449,7 +449,7 @@  discard block
 block discarded – undo
449 449
             $this->cart,
450 450
             $this
451 451
         );
452
-        if (! apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tickets_selected)) {
452
+        if ( ! apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tickets_selected)) {
453 453
             // no ticket quantities were selected
454 454
             EE_Error::add_error(
455 455
                 esc_html__('You need to select a ticket quantity before you can proceed.', 'event_espresso'),
@@ -517,7 +517,7 @@  discard block
 block discarded – undo
517 517
         // exit('KILL REDIRECT BEFORE CART UPDATE'); // <<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
518 518
         if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
519 519
             // make sure cart is loaded
520
-            if (! $this->cart instanceof EE_Cart) {
520
+            if ( ! $this->cart instanceof EE_Cart) {
521 521
                 $this->cart = CartFactory::getCart();
522 522
             }
523 523
             do_action(
@@ -539,7 +539,7 @@  discard block
 block discarded – undo
539 539
                 )
540 540
             );
541 541
         }
542
-        if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
542
+        if ( ! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
543 543
             // nothing added to cart
544 544
             EE_Error::add_attention(
545 545
                 esc_html__('No tickets were added for the event', 'event_espresso'),
Please login to merge, or discard this patch.
core/services/request/CurrentPage.php 1 patch
Indentation   +314 added lines, -314 removed lines patch added patch discarded remove patch
@@ -23,318 +23,318 @@
 block discarded – undo
23 23
  */
24 24
 class CurrentPage
25 25
 {
26
-    /**
27
-     * @var EE_CPT_Strategy
28
-     */
29
-    private $cpt_strategy;
30
-
31
-    /**
32
-     * @var bool
33
-     */
34
-    private $initialized;
35
-
36
-    /**
37
-     * @var bool
38
-     */
39
-    private $is_espresso_page = false;
40
-
41
-    /**
42
-     * @var int
43
-     */
44
-    private $post_id = 0;
45
-
46
-    /**
47
-     * @var string
48
-     */
49
-    private $post_name = '';
50
-
51
-    /**
52
-     * @var array
53
-     */
54
-    private $post_type = [];
55
-
56
-    /**
57
-     * @var RequestInterface $request
58
-     */
59
-    private $request;
60
-
61
-
62
-    /**
63
-     * CurrentPage constructor.
64
-     *
65
-     * @param EE_CPT_Strategy  $cpt_strategy
66
-     * @param RequestInterface $request
67
-     */
68
-    public function __construct(EE_CPT_Strategy $cpt_strategy, RequestInterface $request)
69
-    {
70
-        $this->cpt_strategy = $cpt_strategy;
71
-        $this->request      = $request;
72
-        $this->initialized  = is_admin();
73
-        // analyse the incoming WP request
74
-        add_action('parse_request', [$this, 'parseQueryVars'], 2, 1);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param WP $WP
80
-     * @return void
81
-     */
82
-    public function parseQueryVars(WP $WP = null)
83
-    {
84
-        if ($this->initialized) {
85
-            return;
86
-        }
87
-        // if somebody forgot to provide us with WP, that's ok because its global
88
-        if (! $WP instanceof WP) {
89
-            global $WP;
90
-        }
91
-        $this->post_id   = $this->getPostId($WP);
92
-        $this->post_name = $this->getPostName($WP);
93
-        $this->post_type = $this->getPostType($WP);
94
-        // true or false ? is this page being used by EE ?
95
-        $this->setEspressoPage();
96
-        remove_action('parse_request', [$this, 'parseRequest'], 2);
97
-        $this->initialized = true;
98
-    }
99
-
100
-
101
-    /**
102
-     * Just a helper method for getting the url for the displayed page.
103
-     *
104
-     * @param WP|null $WP
105
-     * @return string
106
-     */
107
-    public function getPermalink(WP $WP = null)
108
-    {
109
-        $post_id = $this->post_id ?: $this->getPostId($WP);
110
-        if ($post_id) {
111
-            return get_permalink($post_id);
112
-        }
113
-        if (! $WP instanceof WP) {
114
-            global $WP;
115
-        }
116
-        if ($WP instanceof WP && $WP->request) {
117
-            return site_url($WP->request);
118
-        }
119
-        return esc_url_raw(site_url($_SERVER['REQUEST_URI']));
120
-    }
121
-
122
-
123
-    /**
124
-     * @return array
125
-     */
126
-    public function espressoPostType()
127
-    {
128
-        return array_filter(
129
-            $this->post_type,
130
-            function ($post_type) {
131
-                return strpos($post_type, 'espresso_') === 0;
132
-            }
133
-        );
134
-    }
135
-
136
-
137
-    /**
138
-     * pokes and prods the WP object query_vars in an attempt to shake out a page/post ID
139
-     *
140
-     * @param WP $WP
141
-     * @return int
142
-     */
143
-    private function getPostId(WP $WP = null)
144
-    {
145
-        $post_id = null;
146
-        if ($WP instanceof WP) {
147
-            // look for the post ID in the aptly named 'p' query var
148
-            if (isset($WP->query_vars['p'])) {
149
-                $post_id = $WP->query_vars['p'];
150
-            }
151
-            // not a post? what about a page?
152
-            if (! $post_id && isset($WP->query_vars['page_id'])) {
153
-                $post_id = $WP->query_vars['page_id'];
154
-            }
155
-            // ok... maybe pretty permalinks are off and the ID is set in the raw request...
156
-            // but hasn't been processed yet ie: this method is being called too early :\
157
-            if (! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
158
-                $post_id = basename($WP->request);
159
-            }
160
-        }
161
-        // none of the above? ok what about an explicit "post_id" URL parameter?
162
-        if (! $post_id && $this->request->requestParamIsSet('post_id')) {
163
-            $post_id = $this->request->getRequestParam('post_id');
164
-        }
165
-        return $post_id;
166
-    }
167
-
168
-
169
-    /**
170
-     * similar to getPostId() above but attempts to obtain the "name" for the current page/post
171
-     *
172
-     * @param WP $WP
173
-     * @return string
174
-     */
175
-    private function getPostName(WP $WP = null)
176
-    {
177
-        global $wpdb;
178
-        $post_name = null;
179
-        if ($WP instanceof WP) {
180
-            // if this is a post, then is the post name set?
181
-            if (isset($WP->query_vars['name']) && ! empty($WP->query_vars['name'])) {
182
-                $post_name = $WP->query_vars['name'];
183
-            }
184
-            // what about the page name?
185
-            if (! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
186
-                $post_name = $WP->query_vars['pagename'];
187
-            }
188
-            // this stinks but let's run a query to try and get the post name from the URL
189
-            // (assuming pretty permalinks are on)
190
-            if (! $post_name && $WP->request !== null && ! empty($WP->request)) {
191
-                $possible_post_name = basename($WP->request);
192
-                if (! is_numeric($possible_post_name)) {
193
-                    $SQL                = "SELECT ID from {$wpdb->posts}";
194
-                    $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
195
-                    $SQL                .= ' AND post_name=%s';
196
-                    $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
197
-                    if ($possible_post_name) {
198
-                        $post_name = $possible_post_name;
199
-                    }
200
-                }
201
-            }
202
-        }
203
-        // ug... ok... nothing yet... but do we have a post ID?
204
-        // if so then... sigh... run a query to get the post name :\
205
-        if (! $post_name && $this->post_id) {
206
-            $SQL                = "SELECT post_name from {$wpdb->posts}";
207
-            $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
208
-            $SQL                .= ' AND ID=%d';
209
-            $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->post_id));
210
-            if ($possible_post_name) {
211
-                $post_name = $possible_post_name;
212
-            }
213
-        }
214
-        // still nothing? ok what about an explicit 'post_name' URL parameter?
215
-        if (! $post_name && $this->request->requestParamIsSet('post_name')) {
216
-            $post_name = $this->request->getRequestParam('post_name');
217
-        }
218
-        return $post_name;
219
-    }
220
-
221
-
222
-    /**
223
-     * also similar to getPostId() and getPostName() above but not as insane
224
-     *
225
-     * @param WP $WP
226
-     * @return array
227
-     */
228
-    private function getPostType(WP $WP = null)
229
-    {
230
-        $post_types = [];
231
-        if ($WP instanceof WP) {
232
-            $post_types = isset($WP->query_vars['post_type'])
233
-                ? (array) $WP->query_vars['post_type']
234
-                : [];
235
-        }
236
-        if (empty($post_types) && $this->request->requestParamIsSet('post_type')) {
237
-            $post_types = $this->request->getRequestParam('post_type', [], 'string', true);
238
-        }
239
-        return (array) $post_types;
240
-    }
241
-
242
-
243
-    /**
244
-     * if TRUE, then the current page is somehow utilizing EE logic
245
-     *
246
-     * @return bool
247
-     */
248
-    public function isEspressoPage()
249
-    {
250
-        return $this->is_espresso_page;
251
-    }
252
-
253
-
254
-    /**
255
-     * @return int
256
-     */
257
-    public function postId()
258
-    {
259
-        return $this->post_id;
260
-    }
261
-
262
-
263
-    /**
264
-     * @return string
265
-     */
266
-    public function postName()
267
-    {
268
-        return $this->post_name;
269
-    }
270
-
271
-
272
-    /**
273
-     * @return array
274
-     */
275
-    public function postType()
276
-    {
277
-        return $this->post_type;
278
-    }
279
-
280
-
281
-    /**
282
-     * for manually indicating the current page will utilize EE logic
283
-     *
284
-     * @param null|bool $value
285
-     * @return void
286
-     */
287
-    public function setEspressoPage($value = null)
288
-    {
289
-        $this->is_espresso_page = $value !== null
290
-            ? filter_var($value, FILTER_VALIDATE_BOOLEAN)
291
-            : $this->testForEspressoPage();
292
-    }
293
-
294
-
295
-    /**
296
-     * attempts to determine if the current page/post is an EE related page/post
297
-     * because it utilizes one of our CPT taxonomies, endpoints, or post types
298
-     *
299
-     * @return bool
300
-     */
301
-    private function testForEspressoPage()
302
-    {
303
-        // in case it has already been set
304
-        if ($this->is_espresso_page) {
305
-            return true;
306
-        }
307
-        global $WP;
308
-        $espresso_CPT_taxonomies = $this->cpt_strategy->get_CPT_taxonomies();
309
-        if (is_array($espresso_CPT_taxonomies)) {
310
-            foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
311
-                if (isset($WP->query_vars, $WP->query_vars[ $espresso_CPT_taxonomy ])) {
312
-                    return true;
313
-                }
314
-            }
315
-        }
316
-        // load espresso CPT endpoints
317
-        $espresso_CPT_endpoints  = $this->cpt_strategy->get_CPT_endpoints();
318
-        $post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
319
-        foreach ($this->post_type as $post_type) {
320
-            // was a post name passed ?
321
-            if (isset($post_type_CPT_endpoints[ $post_type ])) {
322
-                // kk we know this is an espresso page, but is it a specific post ?
323
-                if (! $this->post_name) {
324
-                    $espresso_post_type = $this->request->getRequestParam('post_type');
325
-                    // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
326
-                    // this essentially sets the post_name to "events" (or whatever EE CPT)
327
-                    $post_name = isset($post_type_CPT_endpoints[ $espresso_post_type ])
328
-                        ? $post_type_CPT_endpoints[ $espresso_post_type ]
329
-                        : '';
330
-                    // if the post type matches one of ours then set the post name to the endpoint
331
-                    if ($post_name) {
332
-                        $this->post_name = $post_name;
333
-                    }
334
-                }
335
-                return true;
336
-            }
337
-        }
338
-        return false;
339
-    }
26
+	/**
27
+	 * @var EE_CPT_Strategy
28
+	 */
29
+	private $cpt_strategy;
30
+
31
+	/**
32
+	 * @var bool
33
+	 */
34
+	private $initialized;
35
+
36
+	/**
37
+	 * @var bool
38
+	 */
39
+	private $is_espresso_page = false;
40
+
41
+	/**
42
+	 * @var int
43
+	 */
44
+	private $post_id = 0;
45
+
46
+	/**
47
+	 * @var string
48
+	 */
49
+	private $post_name = '';
50
+
51
+	/**
52
+	 * @var array
53
+	 */
54
+	private $post_type = [];
55
+
56
+	/**
57
+	 * @var RequestInterface $request
58
+	 */
59
+	private $request;
60
+
61
+
62
+	/**
63
+	 * CurrentPage constructor.
64
+	 *
65
+	 * @param EE_CPT_Strategy  $cpt_strategy
66
+	 * @param RequestInterface $request
67
+	 */
68
+	public function __construct(EE_CPT_Strategy $cpt_strategy, RequestInterface $request)
69
+	{
70
+		$this->cpt_strategy = $cpt_strategy;
71
+		$this->request      = $request;
72
+		$this->initialized  = is_admin();
73
+		// analyse the incoming WP request
74
+		add_action('parse_request', [$this, 'parseQueryVars'], 2, 1);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param WP $WP
80
+	 * @return void
81
+	 */
82
+	public function parseQueryVars(WP $WP = null)
83
+	{
84
+		if ($this->initialized) {
85
+			return;
86
+		}
87
+		// if somebody forgot to provide us with WP, that's ok because its global
88
+		if (! $WP instanceof WP) {
89
+			global $WP;
90
+		}
91
+		$this->post_id   = $this->getPostId($WP);
92
+		$this->post_name = $this->getPostName($WP);
93
+		$this->post_type = $this->getPostType($WP);
94
+		// true or false ? is this page being used by EE ?
95
+		$this->setEspressoPage();
96
+		remove_action('parse_request', [$this, 'parseRequest'], 2);
97
+		$this->initialized = true;
98
+	}
99
+
100
+
101
+	/**
102
+	 * Just a helper method for getting the url for the displayed page.
103
+	 *
104
+	 * @param WP|null $WP
105
+	 * @return string
106
+	 */
107
+	public function getPermalink(WP $WP = null)
108
+	{
109
+		$post_id = $this->post_id ?: $this->getPostId($WP);
110
+		if ($post_id) {
111
+			return get_permalink($post_id);
112
+		}
113
+		if (! $WP instanceof WP) {
114
+			global $WP;
115
+		}
116
+		if ($WP instanceof WP && $WP->request) {
117
+			return site_url($WP->request);
118
+		}
119
+		return esc_url_raw(site_url($_SERVER['REQUEST_URI']));
120
+	}
121
+
122
+
123
+	/**
124
+	 * @return array
125
+	 */
126
+	public function espressoPostType()
127
+	{
128
+		return array_filter(
129
+			$this->post_type,
130
+			function ($post_type) {
131
+				return strpos($post_type, 'espresso_') === 0;
132
+			}
133
+		);
134
+	}
135
+
136
+
137
+	/**
138
+	 * pokes and prods the WP object query_vars in an attempt to shake out a page/post ID
139
+	 *
140
+	 * @param WP $WP
141
+	 * @return int
142
+	 */
143
+	private function getPostId(WP $WP = null)
144
+	{
145
+		$post_id = null;
146
+		if ($WP instanceof WP) {
147
+			// look for the post ID in the aptly named 'p' query var
148
+			if (isset($WP->query_vars['p'])) {
149
+				$post_id = $WP->query_vars['p'];
150
+			}
151
+			// not a post? what about a page?
152
+			if (! $post_id && isset($WP->query_vars['page_id'])) {
153
+				$post_id = $WP->query_vars['page_id'];
154
+			}
155
+			// ok... maybe pretty permalinks are off and the ID is set in the raw request...
156
+			// but hasn't been processed yet ie: this method is being called too early :\
157
+			if (! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
158
+				$post_id = basename($WP->request);
159
+			}
160
+		}
161
+		// none of the above? ok what about an explicit "post_id" URL parameter?
162
+		if (! $post_id && $this->request->requestParamIsSet('post_id')) {
163
+			$post_id = $this->request->getRequestParam('post_id');
164
+		}
165
+		return $post_id;
166
+	}
167
+
168
+
169
+	/**
170
+	 * similar to getPostId() above but attempts to obtain the "name" for the current page/post
171
+	 *
172
+	 * @param WP $WP
173
+	 * @return string
174
+	 */
175
+	private function getPostName(WP $WP = null)
176
+	{
177
+		global $wpdb;
178
+		$post_name = null;
179
+		if ($WP instanceof WP) {
180
+			// if this is a post, then is the post name set?
181
+			if (isset($WP->query_vars['name']) && ! empty($WP->query_vars['name'])) {
182
+				$post_name = $WP->query_vars['name'];
183
+			}
184
+			// what about the page name?
185
+			if (! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
186
+				$post_name = $WP->query_vars['pagename'];
187
+			}
188
+			// this stinks but let's run a query to try and get the post name from the URL
189
+			// (assuming pretty permalinks are on)
190
+			if (! $post_name && $WP->request !== null && ! empty($WP->request)) {
191
+				$possible_post_name = basename($WP->request);
192
+				if (! is_numeric($possible_post_name)) {
193
+					$SQL                = "SELECT ID from {$wpdb->posts}";
194
+					$SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
195
+					$SQL                .= ' AND post_name=%s';
196
+					$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
197
+					if ($possible_post_name) {
198
+						$post_name = $possible_post_name;
199
+					}
200
+				}
201
+			}
202
+		}
203
+		// ug... ok... nothing yet... but do we have a post ID?
204
+		// if so then... sigh... run a query to get the post name :\
205
+		if (! $post_name && $this->post_id) {
206
+			$SQL                = "SELECT post_name from {$wpdb->posts}";
207
+			$SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
208
+			$SQL                .= ' AND ID=%d';
209
+			$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->post_id));
210
+			if ($possible_post_name) {
211
+				$post_name = $possible_post_name;
212
+			}
213
+		}
214
+		// still nothing? ok what about an explicit 'post_name' URL parameter?
215
+		if (! $post_name && $this->request->requestParamIsSet('post_name')) {
216
+			$post_name = $this->request->getRequestParam('post_name');
217
+		}
218
+		return $post_name;
219
+	}
220
+
221
+
222
+	/**
223
+	 * also similar to getPostId() and getPostName() above but not as insane
224
+	 *
225
+	 * @param WP $WP
226
+	 * @return array
227
+	 */
228
+	private function getPostType(WP $WP = null)
229
+	{
230
+		$post_types = [];
231
+		if ($WP instanceof WP) {
232
+			$post_types = isset($WP->query_vars['post_type'])
233
+				? (array) $WP->query_vars['post_type']
234
+				: [];
235
+		}
236
+		if (empty($post_types) && $this->request->requestParamIsSet('post_type')) {
237
+			$post_types = $this->request->getRequestParam('post_type', [], 'string', true);
238
+		}
239
+		return (array) $post_types;
240
+	}
241
+
242
+
243
+	/**
244
+	 * if TRUE, then the current page is somehow utilizing EE logic
245
+	 *
246
+	 * @return bool
247
+	 */
248
+	public function isEspressoPage()
249
+	{
250
+		return $this->is_espresso_page;
251
+	}
252
+
253
+
254
+	/**
255
+	 * @return int
256
+	 */
257
+	public function postId()
258
+	{
259
+		return $this->post_id;
260
+	}
261
+
262
+
263
+	/**
264
+	 * @return string
265
+	 */
266
+	public function postName()
267
+	{
268
+		return $this->post_name;
269
+	}
270
+
271
+
272
+	/**
273
+	 * @return array
274
+	 */
275
+	public function postType()
276
+	{
277
+		return $this->post_type;
278
+	}
279
+
280
+
281
+	/**
282
+	 * for manually indicating the current page will utilize EE logic
283
+	 *
284
+	 * @param null|bool $value
285
+	 * @return void
286
+	 */
287
+	public function setEspressoPage($value = null)
288
+	{
289
+		$this->is_espresso_page = $value !== null
290
+			? filter_var($value, FILTER_VALIDATE_BOOLEAN)
291
+			: $this->testForEspressoPage();
292
+	}
293
+
294
+
295
+	/**
296
+	 * attempts to determine if the current page/post is an EE related page/post
297
+	 * because it utilizes one of our CPT taxonomies, endpoints, or post types
298
+	 *
299
+	 * @return bool
300
+	 */
301
+	private function testForEspressoPage()
302
+	{
303
+		// in case it has already been set
304
+		if ($this->is_espresso_page) {
305
+			return true;
306
+		}
307
+		global $WP;
308
+		$espresso_CPT_taxonomies = $this->cpt_strategy->get_CPT_taxonomies();
309
+		if (is_array($espresso_CPT_taxonomies)) {
310
+			foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
311
+				if (isset($WP->query_vars, $WP->query_vars[ $espresso_CPT_taxonomy ])) {
312
+					return true;
313
+				}
314
+			}
315
+		}
316
+		// load espresso CPT endpoints
317
+		$espresso_CPT_endpoints  = $this->cpt_strategy->get_CPT_endpoints();
318
+		$post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
319
+		foreach ($this->post_type as $post_type) {
320
+			// was a post name passed ?
321
+			if (isset($post_type_CPT_endpoints[ $post_type ])) {
322
+				// kk we know this is an espresso page, but is it a specific post ?
323
+				if (! $this->post_name) {
324
+					$espresso_post_type = $this->request->getRequestParam('post_type');
325
+					// there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
326
+					// this essentially sets the post_name to "events" (or whatever EE CPT)
327
+					$post_name = isset($post_type_CPT_endpoints[ $espresso_post_type ])
328
+						? $post_type_CPT_endpoints[ $espresso_post_type ]
329
+						: '';
330
+					// if the post type matches one of ours then set the post name to the endpoint
331
+					if ($post_name) {
332
+						$this->post_name = $post_name;
333
+					}
334
+				}
335
+				return true;
336
+			}
337
+		}
338
+		return false;
339
+	}
340 340
 }
Please login to merge, or discard this patch.
core/services/request/RequestParams.php 1 patch
Indentation   +310 added lines, -310 removed lines patch added patch discarded remove patch
@@ -14,314 +14,314 @@
 block discarded – undo
14 14
 class RequestParams
15 15
 {
16 16
 
17
-    /**
18
-     * $_GET parameters
19
-     *
20
-     * @var array
21
-     */
22
-    protected $get;
23
-
24
-    /**
25
-     * $_POST parameters
26
-     *
27
-     * @var array
28
-     */
29
-    protected $post;
30
-
31
-    /**
32
-     * $_REQUEST parameters
33
-     *
34
-     * @var array
35
-     */
36
-    protected $request;
37
-
38
-    /**
39
-     * @var RequestSanitizer
40
-     */
41
-    protected $sanitizer;
42
-
43
-
44
-    /**
45
-     * RequestParams constructor.
46
-     *
47
-     * @param RequestSanitizer $sanitizer
48
-     * @param array            $get
49
-     * @param array            $post
50
-     */
51
-    public function __construct(RequestSanitizer $sanitizer, array $get = [], array $post = [])
52
-    {
53
-        $this->sanitizer = $sanitizer;
54
-        $this->get       = ! empty($get) ? $get : (array) filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
55
-        $this->post      = ! empty($post) ? $post : (array) filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
56
-        $this->request   = array_merge($this->get, $this->post);
57
-    }
58
-
59
-
60
-    /**
61
-     * @return array
62
-     */
63
-    public function getParams()
64
-    {
65
-        return $this->get;
66
-    }
67
-
68
-
69
-    /**
70
-     * @return array
71
-     */
72
-    public function postParams()
73
-    {
74
-        return $this->post;
75
-    }
76
-
77
-
78
-    /**
79
-     * returns contents of $_REQUEST
80
-     *
81
-     * @return array
82
-     */
83
-    public function requestParams()
84
-    {
85
-        return $this->request;
86
-    }
87
-
88
-
89
-    /**
90
-     * @param string     $key
91
-     * @param mixed|null $value
92
-     * @param bool       $override_ee
93
-     * @return    void
94
-     */
95
-    public function setRequestParam($key, $value, $override_ee = false)
96
-    {
97
-        // don't allow "ee" to be overwritten unless explicitly instructed to do so
98
-        if ($override_ee || $key !== 'ee' || empty($this->request['ee'])) {
99
-            $this->request[ $key ] = $value;
100
-        }
101
-    }
102
-
103
-
104
-    /**
105
-     * returns   the value for a request param if the given key exists
106
-     *
107
-     * @param string     $key
108
-     * @param mixed|null $default
109
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
110
-     * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
111
-     * @param string     $delimiter for CSV type strings that should be returned as an array
112
-     * @return array|bool|float|int|string
113
-     */
114
-    public function getRequestParam($key, $default = null, $type = 'string', $is_array = false, $delimiter = '')
115
-    {
116
-        return $this->sanitizer->clean(
117
-            $this->parameterDrillDown($key, $default, 'get'),
118
-            $type,
119
-            $is_array,
120
-            $delimiter
121
-        );
122
-    }
123
-
124
-
125
-    /**
126
-     * check if param exists
127
-     *
128
-     * @param string $key
129
-     * @return bool
130
-     */
131
-    public function requestParamIsSet($key)
132
-    {
133
-        return (bool) $this->parameterDrillDown($key);
134
-    }
135
-
136
-
137
-    /**
138
-     * check if a request parameter exists whose key that matches the supplied wildcard pattern
139
-     * and return the value for the first match found
140
-     * wildcards can be either of the following:
141
-     *      ? to represent a single character of any type
142
-     *      * to represent one or more characters of any type
143
-     *
144
-     * @param string     $pattern
145
-     * @param mixed|null $default
146
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
147
-     * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
148
-     * @param string     $delimiter for CSV type strings that should be returned as an array
149
-     * @return array|bool|float|int|string
150
-     */
151
-    public function getMatch($pattern, $default = null, $type = 'string', $is_array = false, $delimiter = '')
152
-    {
153
-        return $this->sanitizer->clean(
154
-            $this->parameterDrillDown($pattern, $default, 'match'),
155
-            $type,
156
-            $is_array,
157
-            $delimiter
158
-        );
159
-    }
160
-
161
-
162
-    /**
163
-     * check if a request parameter exists whose key matches the supplied wildcard pattern
164
-     * wildcards can be either of the following:
165
-     *      ? to represent a single character of any type
166
-     *      * to represent one or more characters of any type
167
-     * returns true if a match is found or false if not
168
-     *
169
-     * @param string $pattern
170
-     * @return bool
171
-     */
172
-    public function matches($pattern)
173
-    {
174
-        return (bool) $this->parameterDrillDown($pattern, false, 'match', 'bool');
175
-    }
176
-
177
-
178
-    /**
179
-     * @see https://stackoverflow.com/questions/6163055/php-string-matching-with-wildcard
180
-     * @param string $pattern               A string including wildcards to be converted to a regex pattern
181
-     *                                      and used to search through the current request's parameter keys
182
-     * @param array  $request_params        The array of request parameters to search through
183
-     * @param mixed  $default               [optional] The value to be returned if no match is found.
184
-     *                                      Default is null
185
-     * @param string $return                [optional] Controls what kind of value is returned.
186
-     *                                      Options are:
187
-     *                                      'bool' will return true or false if match is found or not
188
-     *                                      'key' will return the first key found that matches the supplied pattern
189
-     *                                      'value' will return the value for the first request parameter
190
-     *                                      whose key matches the supplied pattern
191
-     *                                      Default is 'value'
192
-     * @return boolean|string
193
-     */
194
-    private function match($pattern, array $request_params, $default = null, $return = 'value')
195
-    {
196
-        $return = in_array($return, ['bool', 'key', 'value'], true)
197
-            ? $return
198
-            : 'is_set';
199
-        // replace wildcard chars with regex chars
200
-        $pattern = str_replace(
201
-            ['\*', '\?'],
202
-            ['.*', '.'],
203
-            preg_quote($pattern, '/')
204
-        );
205
-        foreach ($request_params as $key => $request_param) {
206
-            if (preg_match('/^' . $pattern . '$/is', $key)) {
207
-                // return value for request param
208
-                if ($return === 'value') {
209
-                    return $request_param;
210
-                }
211
-                // or actual key or true just to indicate it was found
212
-                return $return === 'key' ? $key : true;
213
-            }
214
-        }
215
-        // match not found so return default value or false
216
-        return $return === 'value' ? $default : false;
217
-    }
218
-
219
-
220
-    /**
221
-     * the supplied key can be a simple string to represent a "top-level" request parameter
222
-     * or represent a key for a request parameter that is nested deeper within the request parameter array,
223
-     * by using square brackets to surround keys for deeper array elements.
224
-     * For example :
225
-     * if the supplied $key was: "first[second][third]"
226
-     * then this will attempt to drill down into the request parameter array to find a value.
227
-     * Given the following request parameters:
228
-     *  array(
229
-     *      'first' => array(
230
-     *          'second' => array(
231
-     *              'third' => 'has a value'
232
-     *          )
233
-     *      )
234
-     *  )
235
-     * would return true if default parameters were set
236
-     *
237
-     * @param string $callback
238
-     * @param        $key
239
-     * @param null   $default
240
-     * @param string $return
241
-     * @param mixed  $request_params
242
-     * @return bool|mixed|null
243
-     */
244
-    private function parameterDrillDown(
245
-        $key,
246
-        $default = null,
247
-        $callback = 'is_set',
248
-        $return = 'value',
249
-        $request_params = []
250
-    ) {
251
-        $callback       = in_array($callback, ['is_set', 'get', 'match'], true)
252
-            ? $callback
253
-            : 'is_set';
254
-        $request_params = ! empty($request_params)
255
-            ? $request_params
256
-            : $this->request;
257
-        // does incoming key represent an array like 'first[second][third]'  ?
258
-        if (strpos($key, '[') !== false) {
259
-            // turn it into an actual array
260
-            $key  = str_replace(']', '', $key);
261
-            $keys = explode('[', $key);
262
-            $key  = array_shift($keys);
263
-            if ($callback === 'match') {
264
-                $real_key = $this->match($key, $request_params, $default, 'key');
265
-                $key      = $real_key ?: $key;
266
-            }
267
-            // check if top level key exists
268
-            if (isset($request_params[ $key ])) {
269
-                // build a new key to pass along like: 'second[third]'
270
-                // or just 'second' depending on depth of keys
271
-                $key_string = array_shift($keys);
272
-                if (! empty($keys)) {
273
-                    $key_string .= '[' . implode('][', $keys) . ']';
274
-                }
275
-                return $this->parameterDrillDown(
276
-                    $key_string,
277
-                    $default,
278
-                    $callback,
279
-                    $return,
280
-                    $request_params[ $key ]
281
-                );
282
-            }
283
-        }
284
-        if ($callback === 'is_set') {
285
-            return isset($request_params[ $key ]);
286
-        }
287
-        if ($callback === 'match') {
288
-            return $this->match($key, $request_params, $default, $return);
289
-        }
290
-        return isset($request_params[ $key ])
291
-            ? $request_params[ $key ]
292
-            : $default;
293
-    }
294
-
295
-
296
-    /**
297
-     * remove param
298
-     *
299
-     * @param      $key
300
-     * @param bool $unset_from_global_too
301
-     */
302
-    public function unSetRequestParam($key, $unset_from_global_too = false)
303
-    {
304
-        // because unset may not actually remove var
305
-        $this->get[ $key ]     = null;
306
-        $this->post[ $key ]    = null;
307
-        $this->request[ $key ] = null;
308
-        unset($this->get[ $key ], $this->post[ $key ], $this->request[ $key ]);
309
-        if ($unset_from_global_too) {
310
-            unset($_GET[ $key ], $_POST[ $key ], $_REQUEST[ $key ]);
311
-        }
312
-    }
313
-
314
-
315
-    /**
316
-     * remove params
317
-     *
318
-     * @param array $keys
319
-     * @param bool  $unset_from_global_too
320
-     */
321
-    public function unSetRequestParams(array $keys, $unset_from_global_too = false)
322
-    {
323
-        foreach ($keys as $key) {
324
-            $this->unSetRequestParam($key, $unset_from_global_too);
325
-        }
326
-    }
17
+	/**
18
+	 * $_GET parameters
19
+	 *
20
+	 * @var array
21
+	 */
22
+	protected $get;
23
+
24
+	/**
25
+	 * $_POST parameters
26
+	 *
27
+	 * @var array
28
+	 */
29
+	protected $post;
30
+
31
+	/**
32
+	 * $_REQUEST parameters
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $request;
37
+
38
+	/**
39
+	 * @var RequestSanitizer
40
+	 */
41
+	protected $sanitizer;
42
+
43
+
44
+	/**
45
+	 * RequestParams constructor.
46
+	 *
47
+	 * @param RequestSanitizer $sanitizer
48
+	 * @param array            $get
49
+	 * @param array            $post
50
+	 */
51
+	public function __construct(RequestSanitizer $sanitizer, array $get = [], array $post = [])
52
+	{
53
+		$this->sanitizer = $sanitizer;
54
+		$this->get       = ! empty($get) ? $get : (array) filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
55
+		$this->post      = ! empty($post) ? $post : (array) filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
56
+		$this->request   = array_merge($this->get, $this->post);
57
+	}
58
+
59
+
60
+	/**
61
+	 * @return array
62
+	 */
63
+	public function getParams()
64
+	{
65
+		return $this->get;
66
+	}
67
+
68
+
69
+	/**
70
+	 * @return array
71
+	 */
72
+	public function postParams()
73
+	{
74
+		return $this->post;
75
+	}
76
+
77
+
78
+	/**
79
+	 * returns contents of $_REQUEST
80
+	 *
81
+	 * @return array
82
+	 */
83
+	public function requestParams()
84
+	{
85
+		return $this->request;
86
+	}
87
+
88
+
89
+	/**
90
+	 * @param string     $key
91
+	 * @param mixed|null $value
92
+	 * @param bool       $override_ee
93
+	 * @return    void
94
+	 */
95
+	public function setRequestParam($key, $value, $override_ee = false)
96
+	{
97
+		// don't allow "ee" to be overwritten unless explicitly instructed to do so
98
+		if ($override_ee || $key !== 'ee' || empty($this->request['ee'])) {
99
+			$this->request[ $key ] = $value;
100
+		}
101
+	}
102
+
103
+
104
+	/**
105
+	 * returns   the value for a request param if the given key exists
106
+	 *
107
+	 * @param string     $key
108
+	 * @param mixed|null $default
109
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
110
+	 * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
111
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
112
+	 * @return array|bool|float|int|string
113
+	 */
114
+	public function getRequestParam($key, $default = null, $type = 'string', $is_array = false, $delimiter = '')
115
+	{
116
+		return $this->sanitizer->clean(
117
+			$this->parameterDrillDown($key, $default, 'get'),
118
+			$type,
119
+			$is_array,
120
+			$delimiter
121
+		);
122
+	}
123
+
124
+
125
+	/**
126
+	 * check if param exists
127
+	 *
128
+	 * @param string $key
129
+	 * @return bool
130
+	 */
131
+	public function requestParamIsSet($key)
132
+	{
133
+		return (bool) $this->parameterDrillDown($key);
134
+	}
135
+
136
+
137
+	/**
138
+	 * check if a request parameter exists whose key that matches the supplied wildcard pattern
139
+	 * and return the value for the first match found
140
+	 * wildcards can be either of the following:
141
+	 *      ? to represent a single character of any type
142
+	 *      * to represent one or more characters of any type
143
+	 *
144
+	 * @param string     $pattern
145
+	 * @param mixed|null $default
146
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
147
+	 * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
148
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
149
+	 * @return array|bool|float|int|string
150
+	 */
151
+	public function getMatch($pattern, $default = null, $type = 'string', $is_array = false, $delimiter = '')
152
+	{
153
+		return $this->sanitizer->clean(
154
+			$this->parameterDrillDown($pattern, $default, 'match'),
155
+			$type,
156
+			$is_array,
157
+			$delimiter
158
+		);
159
+	}
160
+
161
+
162
+	/**
163
+	 * check if a request parameter exists whose key matches the supplied wildcard pattern
164
+	 * wildcards can be either of the following:
165
+	 *      ? to represent a single character of any type
166
+	 *      * to represent one or more characters of any type
167
+	 * returns true if a match is found or false if not
168
+	 *
169
+	 * @param string $pattern
170
+	 * @return bool
171
+	 */
172
+	public function matches($pattern)
173
+	{
174
+		return (bool) $this->parameterDrillDown($pattern, false, 'match', 'bool');
175
+	}
176
+
177
+
178
+	/**
179
+	 * @see https://stackoverflow.com/questions/6163055/php-string-matching-with-wildcard
180
+	 * @param string $pattern               A string including wildcards to be converted to a regex pattern
181
+	 *                                      and used to search through the current request's parameter keys
182
+	 * @param array  $request_params        The array of request parameters to search through
183
+	 * @param mixed  $default               [optional] The value to be returned if no match is found.
184
+	 *                                      Default is null
185
+	 * @param string $return                [optional] Controls what kind of value is returned.
186
+	 *                                      Options are:
187
+	 *                                      'bool' will return true or false if match is found or not
188
+	 *                                      'key' will return the first key found that matches the supplied pattern
189
+	 *                                      'value' will return the value for the first request parameter
190
+	 *                                      whose key matches the supplied pattern
191
+	 *                                      Default is 'value'
192
+	 * @return boolean|string
193
+	 */
194
+	private function match($pattern, array $request_params, $default = null, $return = 'value')
195
+	{
196
+		$return = in_array($return, ['bool', 'key', 'value'], true)
197
+			? $return
198
+			: 'is_set';
199
+		// replace wildcard chars with regex chars
200
+		$pattern = str_replace(
201
+			['\*', '\?'],
202
+			['.*', '.'],
203
+			preg_quote($pattern, '/')
204
+		);
205
+		foreach ($request_params as $key => $request_param) {
206
+			if (preg_match('/^' . $pattern . '$/is', $key)) {
207
+				// return value for request param
208
+				if ($return === 'value') {
209
+					return $request_param;
210
+				}
211
+				// or actual key or true just to indicate it was found
212
+				return $return === 'key' ? $key : true;
213
+			}
214
+		}
215
+		// match not found so return default value or false
216
+		return $return === 'value' ? $default : false;
217
+	}
218
+
219
+
220
+	/**
221
+	 * the supplied key can be a simple string to represent a "top-level" request parameter
222
+	 * or represent a key for a request parameter that is nested deeper within the request parameter array,
223
+	 * by using square brackets to surround keys for deeper array elements.
224
+	 * For example :
225
+	 * if the supplied $key was: "first[second][third]"
226
+	 * then this will attempt to drill down into the request parameter array to find a value.
227
+	 * Given the following request parameters:
228
+	 *  array(
229
+	 *      'first' => array(
230
+	 *          'second' => array(
231
+	 *              'third' => 'has a value'
232
+	 *          )
233
+	 *      )
234
+	 *  )
235
+	 * would return true if default parameters were set
236
+	 *
237
+	 * @param string $callback
238
+	 * @param        $key
239
+	 * @param null   $default
240
+	 * @param string $return
241
+	 * @param mixed  $request_params
242
+	 * @return bool|mixed|null
243
+	 */
244
+	private function parameterDrillDown(
245
+		$key,
246
+		$default = null,
247
+		$callback = 'is_set',
248
+		$return = 'value',
249
+		$request_params = []
250
+	) {
251
+		$callback       = in_array($callback, ['is_set', 'get', 'match'], true)
252
+			? $callback
253
+			: 'is_set';
254
+		$request_params = ! empty($request_params)
255
+			? $request_params
256
+			: $this->request;
257
+		// does incoming key represent an array like 'first[second][third]'  ?
258
+		if (strpos($key, '[') !== false) {
259
+			// turn it into an actual array
260
+			$key  = str_replace(']', '', $key);
261
+			$keys = explode('[', $key);
262
+			$key  = array_shift($keys);
263
+			if ($callback === 'match') {
264
+				$real_key = $this->match($key, $request_params, $default, 'key');
265
+				$key      = $real_key ?: $key;
266
+			}
267
+			// check if top level key exists
268
+			if (isset($request_params[ $key ])) {
269
+				// build a new key to pass along like: 'second[third]'
270
+				// or just 'second' depending on depth of keys
271
+				$key_string = array_shift($keys);
272
+				if (! empty($keys)) {
273
+					$key_string .= '[' . implode('][', $keys) . ']';
274
+				}
275
+				return $this->parameterDrillDown(
276
+					$key_string,
277
+					$default,
278
+					$callback,
279
+					$return,
280
+					$request_params[ $key ]
281
+				);
282
+			}
283
+		}
284
+		if ($callback === 'is_set') {
285
+			return isset($request_params[ $key ]);
286
+		}
287
+		if ($callback === 'match') {
288
+			return $this->match($key, $request_params, $default, $return);
289
+		}
290
+		return isset($request_params[ $key ])
291
+			? $request_params[ $key ]
292
+			: $default;
293
+	}
294
+
295
+
296
+	/**
297
+	 * remove param
298
+	 *
299
+	 * @param      $key
300
+	 * @param bool $unset_from_global_too
301
+	 */
302
+	public function unSetRequestParam($key, $unset_from_global_too = false)
303
+	{
304
+		// because unset may not actually remove var
305
+		$this->get[ $key ]     = null;
306
+		$this->post[ $key ]    = null;
307
+		$this->request[ $key ] = null;
308
+		unset($this->get[ $key ], $this->post[ $key ], $this->request[ $key ]);
309
+		if ($unset_from_global_too) {
310
+			unset($_GET[ $key ], $_POST[ $key ], $_REQUEST[ $key ]);
311
+		}
312
+	}
313
+
314
+
315
+	/**
316
+	 * remove params
317
+	 *
318
+	 * @param array $keys
319
+	 * @param bool  $unset_from_global_too
320
+	 */
321
+	public function unSetRequestParams(array $keys, $unset_from_global_too = false)
322
+	{
323
+		foreach ($keys as $key) {
324
+			$this->unSetRequestParam($key, $unset_from_global_too);
325
+		}
326
+	}
327 327
 }
Please login to merge, or discard this patch.
core/services/request/Request.php 1 patch
Indentation   +478 added lines, -478 removed lines patch added patch discarded remove patch
@@ -17,482 +17,482 @@
 block discarded – undo
17 17
 class Request implements InterminableInterface, RequestInterface, ReservedInstanceInterface
18 18
 {
19 19
 
20
-    /**
21
-     * $_COOKIE parameters
22
-     *
23
-     * @var array
24
-     */
25
-    protected $cookies;
26
-
27
-    /**
28
-     * $_FILES parameters
29
-     *
30
-     * @var array
31
-     */
32
-    protected $files;
33
-
34
-    /**
35
-     * true if current user appears to be some kind of bot
36
-     *
37
-     * @var bool
38
-     */
39
-    protected $is_bot;
40
-
41
-    /**
42
-     * @var RequestParams
43
-     */
44
-    protected $request_params;
45
-
46
-    /**
47
-     * @var RequestTypeContextCheckerInterface
48
-     */
49
-    protected $request_type;
50
-
51
-    /**
52
-     * @var ServerParams
53
-     */
54
-    protected $server_params;
55
-
56
-
57
-    public function __construct(
58
-        RequestParams $request_params,
59
-        ServerParams $server_params,
60
-        array $cookies = [],
61
-        array $files = []
62
-    ) {
63
-        $this->cookies = ! empty($cookies)
64
-            ? $cookies
65
-            : filter_input_array(INPUT_COOKIE, FILTER_SANITIZE_STRING);
66
-        $this->files          = ! empty($files) ? $files : $_FILES;
67
-        $this->request_params = $request_params;
68
-        $this->server_params  = $server_params;
69
-    }
70
-
71
-
72
-    /**
73
-     * @param RequestTypeContextCheckerInterface $type
74
-     */
75
-    public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type)
76
-    {
77
-        $this->request_type = $type;
78
-    }
79
-
80
-
81
-    /**
82
-     * @return array
83
-     */
84
-    public function getParams()
85
-    {
86
-        return $this->request_params->getParams();
87
-    }
88
-
89
-
90
-    /**
91
-     * @return array
92
-     */
93
-    public function postParams()
94
-    {
95
-        return $this->request_params->postParams();
96
-    }
97
-
98
-
99
-    /**
100
-     * @return array
101
-     */
102
-    public function cookieParams()
103
-    {
104
-        return $this->cookies;
105
-    }
106
-
107
-
108
-    /**
109
-     * @return array
110
-     */
111
-    public function serverParams()
112
-    {
113
-        return $this->server_params->getAllServerParams();
114
-    }
115
-
116
-
117
-    /**
118
-     * @param string $key
119
-     * @param mixed|null $default
120
-     * @return array|int|float|string
121
-     */
122
-    public function getServerParam($key, $default = null)
123
-    {
124
-        return $this->server_params->getServerParam($key, $default);
125
-    }
126
-
127
-
128
-    /**
129
-     * @param string                 $key
130
-     * @param array|int|float|string $value
131
-     * @return void
132
-     */
133
-    public function setServerParam($key, $value)
134
-    {
135
-        $this->server_params->setServerParam($key, $value);
136
-    }
137
-
138
-
139
-    /**
140
-     * @param string $key
141
-     * @return bool
142
-     */
143
-    public function serverParamIsSet($key)
144
-    {
145
-        return $this->server_params->serverParamIsSet($key);
146
-    }
147
-
148
-
149
-    /**
150
-     * @return array
151
-     */
152
-    public function filesParams()
153
-    {
154
-        return $this->files;
155
-    }
156
-
157
-
158
-    /**
159
-     * returns sanitized contents of $_REQUEST
160
-     *
161
-     * @return array
162
-     */
163
-    public function requestParams()
164
-    {
165
-        return $this->request_params->requestParams();
166
-    }
167
-
168
-
169
-    /**
170
-     * @param string     $key
171
-     * @param mixed|null $value
172
-     * @param bool       $override_ee
173
-     * @return void
174
-     */
175
-    public function setRequestParam($key, $value, $override_ee = false)
176
-    {
177
-        $this->request_params->setRequestParam($key, $value, $override_ee);
178
-    }
179
-
180
-
181
-    /**
182
-     * returns sanitized value for a request param if the given key exists
183
-     *
184
-     * @param string     $key
185
-     * @param mixed|null $default
186
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
187
-     * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
188
-     * @param string     $delimiter for CSV type strings that should be returned as an array
189
-     * @return array|bool|float|int|string
190
-     */
191
-    public function getRequestParam($key, $default = null, $type = 'string', $is_array = false, $delimiter = '')
192
-    {
193
-        return $this->request_params->getRequestParam($key, $default, $type, $is_array, $delimiter);
194
-    }
195
-
196
-
197
-    /**
198
-     * check if param exists
199
-     *
200
-     * @param string $key
201
-     * @return bool
202
-     */
203
-    public function requestParamIsSet($key)
204
-    {
205
-        return $this->request_params->requestParamIsSet($key);
206
-    }
207
-
208
-
209
-    /**
210
-     * check if a request parameter exists whose key that matches the supplied wildcard pattern
211
-     * and return the sanitized 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 mixed|null $default
218
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
219
-     * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
220
-     * @param string     $delimiter for CSV type strings that should be returned as an array
221
-     * @return array|bool|float|int|string
222
-     */
223
-    public function getMatch($pattern, $default = null, $type = 'string', $is_array = false, $delimiter = '')
224
-    {
225
-        return $this->request_params->getMatch($pattern, $default, $type, $is_array, $delimiter);
226
-    }
227
-
228
-
229
-    /**
230
-     * check if a request parameter exists whose key matches the supplied wildcard pattern
231
-     * wildcards can be either of the following:
232
-     *      ? to represent a single character of any type
233
-     *      * to represent one or more characters of any type
234
-     * returns true if a match is found or false if not
235
-     *
236
-     * @param string $pattern
237
-     * @return bool
238
-     */
239
-    public function matches($pattern)
240
-    {
241
-        return $this->request_params->matches($pattern);
242
-    }
243
-
244
-
245
-    /**
246
-     * remove param
247
-     *
248
-     * @param      $key
249
-     * @param bool $unset_from_global_too
250
-     */
251
-    public function unSetRequestParam($key, $unset_from_global_too = false)
252
-    {
253
-        $this->request_params->unSetRequestParam($key, $unset_from_global_too);
254
-    }
255
-
256
-
257
-    /**
258
-     * remove params
259
-     *
260
-     * @param array $keys
261
-     * @param bool  $unset_from_global_too
262
-     */
263
-    public function unSetRequestParams(array $keys, $unset_from_global_too = false)
264
-    {
265
-        $this->request_params->unSetRequestParams($keys, $unset_from_global_too);
266
-    }
267
-
268
-
269
-    /**
270
-     * @return string
271
-     */
272
-    public function ipAddress()
273
-    {
274
-        return $this->server_params->ipAddress();
275
-    }
276
-
277
-
278
-    /**
279
-     * Gets the request's literal URI. Related to `requestUriAfterSiteHomeUri`, see its description for a comparison.
280
-     *
281
-     * @param boolean $relativeToWpRoot If home_url() is "http://mysite.com/wp/", and a request comes to
282
-     *                                  "http://mysite.com/wp/wp-json", setting $relativeToWpRoot=true will return
283
-     *                                  "/wp-json", whereas $relativeToWpRoot=false will return "/wp/wp-json/".
284
-     * @return string
285
-     */
286
-    public function requestUri($relativeToWpRoot = false)
287
-    {
288
-        return $this->server_params->requestUri();
289
-    }
290
-
291
-
292
-    /**
293
-     * @return string
294
-     */
295
-    public function userAgent()
296
-    {
297
-        return $this->server_params->userAgent();
298
-    }
299
-
300
-
301
-    /**
302
-     * @param string $user_agent
303
-     */
304
-    public function setUserAgent($user_agent = '')
305
-    {
306
-        $this->server_params->setUserAgent($user_agent);
307
-    }
308
-
309
-
310
-    /**
311
-     * @return bool
312
-     */
313
-    public function isBot()
314
-    {
315
-        return $this->is_bot;
316
-    }
317
-
318
-
319
-    /**
320
-     * @param bool $is_bot
321
-     */
322
-    public function setIsBot($is_bot)
323
-    {
324
-        $this->is_bot = filter_var($is_bot, FILTER_VALIDATE_BOOLEAN);
325
-    }
326
-
327
-
328
-    /**
329
-     * @return bool
330
-     */
331
-    public function isActivation()
332
-    {
333
-        return $this->request_type->isActivation();
334
-    }
335
-
336
-
337
-    /**
338
-     * @param $is_activation
339
-     * @return bool
340
-     */
341
-    public function setIsActivation($is_activation)
342
-    {
343
-        return $this->request_type->setIsActivation($is_activation);
344
-    }
345
-
346
-
347
-    /**
348
-     * @return bool
349
-     */
350
-    public function isAdmin()
351
-    {
352
-        return $this->request_type->isAdmin();
353
-    }
354
-
355
-
356
-    /**
357
-     * @return bool
358
-     */
359
-    public function isAdminAjax()
360
-    {
361
-        return $this->request_type->isAdminAjax();
362
-    }
363
-
364
-
365
-    /**
366
-     * @return bool
367
-     */
368
-    public function isAjax()
369
-    {
370
-        return $this->request_type->isAjax();
371
-    }
372
-
373
-
374
-    /**
375
-     * @return bool
376
-     */
377
-    public function isEeAjax()
378
-    {
379
-        return $this->request_type->isEeAjax();
380
-    }
381
-
382
-
383
-    /**
384
-     * @return bool
385
-     */
386
-    public function isOtherAjax()
387
-    {
388
-        return $this->request_type->isOtherAjax();
389
-    }
390
-
391
-
392
-    /**
393
-     * @return bool
394
-     */
395
-    public function isApi()
396
-    {
397
-        return $this->request_type->isApi();
398
-    }
399
-
400
-
401
-    /**
402
-     * @return bool
403
-     */
404
-    public function isCli()
405
-    {
406
-        return $this->request_type->isCli();
407
-    }
408
-
409
-
410
-    /**
411
-     * @return bool
412
-     */
413
-    public function isCron()
414
-    {
415
-        return $this->request_type->isCron();
416
-    }
417
-
418
-
419
-    /**
420
-     * @return bool
421
-     */
422
-    public function isFeed()
423
-    {
424
-        return $this->request_type->isFeed();
425
-    }
426
-
427
-
428
-    /**
429
-     * @return bool
430
-     */
431
-    public function isFrontend()
432
-    {
433
-        return $this->request_type->isFrontend();
434
-    }
435
-
436
-
437
-    /**
438
-     * @return bool
439
-     */
440
-    public function isFrontAjax()
441
-    {
442
-        return $this->request_type->isFrontAjax();
443
-    }
444
-
445
-
446
-    /**
447
-     * @return bool
448
-     */
449
-    public function isIframe()
450
-    {
451
-        return $this->request_type->isIframe();
452
-    }
453
-
454
-
455
-    /**
456
-     * @return bool
457
-     */
458
-    public function isWordPressApi()
459
-    {
460
-        return $this->request_type->isWordPressApi();
461
-    }
462
-
463
-
464
-    /**
465
-     * @return bool
466
-     */
467
-    public function isWordPressHeartbeat()
468
-    {
469
-        return $this->request_type->isWordPressHeartbeat();
470
-    }
471
-
472
-
473
-    /**
474
-     * @return bool
475
-     */
476
-    public function isWordPressScrape()
477
-    {
478
-        return $this->request_type->isWordPressScrape();
479
-    }
480
-
481
-
482
-    /**
483
-     * @return string
484
-     */
485
-    public function slug()
486
-    {
487
-        return $this->request_type->slug();
488
-    }
489
-
490
-
491
-    /**
492
-     * @return RequestTypeContextCheckerInterface
493
-     */
494
-    public function getRequestType()
495
-    {
496
-        return $this->request_type;
497
-    }
20
+	/**
21
+	 * $_COOKIE parameters
22
+	 *
23
+	 * @var array
24
+	 */
25
+	protected $cookies;
26
+
27
+	/**
28
+	 * $_FILES parameters
29
+	 *
30
+	 * @var array
31
+	 */
32
+	protected $files;
33
+
34
+	/**
35
+	 * true if current user appears to be some kind of bot
36
+	 *
37
+	 * @var bool
38
+	 */
39
+	protected $is_bot;
40
+
41
+	/**
42
+	 * @var RequestParams
43
+	 */
44
+	protected $request_params;
45
+
46
+	/**
47
+	 * @var RequestTypeContextCheckerInterface
48
+	 */
49
+	protected $request_type;
50
+
51
+	/**
52
+	 * @var ServerParams
53
+	 */
54
+	protected $server_params;
55
+
56
+
57
+	public function __construct(
58
+		RequestParams $request_params,
59
+		ServerParams $server_params,
60
+		array $cookies = [],
61
+		array $files = []
62
+	) {
63
+		$this->cookies = ! empty($cookies)
64
+			? $cookies
65
+			: filter_input_array(INPUT_COOKIE, FILTER_SANITIZE_STRING);
66
+		$this->files          = ! empty($files) ? $files : $_FILES;
67
+		$this->request_params = $request_params;
68
+		$this->server_params  = $server_params;
69
+	}
70
+
71
+
72
+	/**
73
+	 * @param RequestTypeContextCheckerInterface $type
74
+	 */
75
+	public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type)
76
+	{
77
+		$this->request_type = $type;
78
+	}
79
+
80
+
81
+	/**
82
+	 * @return array
83
+	 */
84
+	public function getParams()
85
+	{
86
+		return $this->request_params->getParams();
87
+	}
88
+
89
+
90
+	/**
91
+	 * @return array
92
+	 */
93
+	public function postParams()
94
+	{
95
+		return $this->request_params->postParams();
96
+	}
97
+
98
+
99
+	/**
100
+	 * @return array
101
+	 */
102
+	public function cookieParams()
103
+	{
104
+		return $this->cookies;
105
+	}
106
+
107
+
108
+	/**
109
+	 * @return array
110
+	 */
111
+	public function serverParams()
112
+	{
113
+		return $this->server_params->getAllServerParams();
114
+	}
115
+
116
+
117
+	/**
118
+	 * @param string $key
119
+	 * @param mixed|null $default
120
+	 * @return array|int|float|string
121
+	 */
122
+	public function getServerParam($key, $default = null)
123
+	{
124
+		return $this->server_params->getServerParam($key, $default);
125
+	}
126
+
127
+
128
+	/**
129
+	 * @param string                 $key
130
+	 * @param array|int|float|string $value
131
+	 * @return void
132
+	 */
133
+	public function setServerParam($key, $value)
134
+	{
135
+		$this->server_params->setServerParam($key, $value);
136
+	}
137
+
138
+
139
+	/**
140
+	 * @param string $key
141
+	 * @return bool
142
+	 */
143
+	public function serverParamIsSet($key)
144
+	{
145
+		return $this->server_params->serverParamIsSet($key);
146
+	}
147
+
148
+
149
+	/**
150
+	 * @return array
151
+	 */
152
+	public function filesParams()
153
+	{
154
+		return $this->files;
155
+	}
156
+
157
+
158
+	/**
159
+	 * returns sanitized contents of $_REQUEST
160
+	 *
161
+	 * @return array
162
+	 */
163
+	public function requestParams()
164
+	{
165
+		return $this->request_params->requestParams();
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param string     $key
171
+	 * @param mixed|null $value
172
+	 * @param bool       $override_ee
173
+	 * @return void
174
+	 */
175
+	public function setRequestParam($key, $value, $override_ee = false)
176
+	{
177
+		$this->request_params->setRequestParam($key, $value, $override_ee);
178
+	}
179
+
180
+
181
+	/**
182
+	 * returns sanitized value for a request param if the given key exists
183
+	 *
184
+	 * @param string     $key
185
+	 * @param mixed|null $default
186
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
187
+	 * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
188
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
189
+	 * @return array|bool|float|int|string
190
+	 */
191
+	public function getRequestParam($key, $default = null, $type = 'string', $is_array = false, $delimiter = '')
192
+	{
193
+		return $this->request_params->getRequestParam($key, $default, $type, $is_array, $delimiter);
194
+	}
195
+
196
+
197
+	/**
198
+	 * check if param exists
199
+	 *
200
+	 * @param string $key
201
+	 * @return bool
202
+	 */
203
+	public function requestParamIsSet($key)
204
+	{
205
+		return $this->request_params->requestParamIsSet($key);
206
+	}
207
+
208
+
209
+	/**
210
+	 * check if a request parameter exists whose key that matches the supplied wildcard pattern
211
+	 * and return the sanitized 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 mixed|null $default
218
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
219
+	 * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
220
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
221
+	 * @return array|bool|float|int|string
222
+	 */
223
+	public function getMatch($pattern, $default = null, $type = 'string', $is_array = false, $delimiter = '')
224
+	{
225
+		return $this->request_params->getMatch($pattern, $default, $type, $is_array, $delimiter);
226
+	}
227
+
228
+
229
+	/**
230
+	 * check if a request parameter exists whose key matches the supplied wildcard pattern
231
+	 * wildcards can be either of the following:
232
+	 *      ? to represent a single character of any type
233
+	 *      * to represent one or more characters of any type
234
+	 * returns true if a match is found or false if not
235
+	 *
236
+	 * @param string $pattern
237
+	 * @return bool
238
+	 */
239
+	public function matches($pattern)
240
+	{
241
+		return $this->request_params->matches($pattern);
242
+	}
243
+
244
+
245
+	/**
246
+	 * remove param
247
+	 *
248
+	 * @param      $key
249
+	 * @param bool $unset_from_global_too
250
+	 */
251
+	public function unSetRequestParam($key, $unset_from_global_too = false)
252
+	{
253
+		$this->request_params->unSetRequestParam($key, $unset_from_global_too);
254
+	}
255
+
256
+
257
+	/**
258
+	 * remove params
259
+	 *
260
+	 * @param array $keys
261
+	 * @param bool  $unset_from_global_too
262
+	 */
263
+	public function unSetRequestParams(array $keys, $unset_from_global_too = false)
264
+	{
265
+		$this->request_params->unSetRequestParams($keys, $unset_from_global_too);
266
+	}
267
+
268
+
269
+	/**
270
+	 * @return string
271
+	 */
272
+	public function ipAddress()
273
+	{
274
+		return $this->server_params->ipAddress();
275
+	}
276
+
277
+
278
+	/**
279
+	 * Gets the request's literal URI. Related to `requestUriAfterSiteHomeUri`, see its description for a comparison.
280
+	 *
281
+	 * @param boolean $relativeToWpRoot If home_url() is "http://mysite.com/wp/", and a request comes to
282
+	 *                                  "http://mysite.com/wp/wp-json", setting $relativeToWpRoot=true will return
283
+	 *                                  "/wp-json", whereas $relativeToWpRoot=false will return "/wp/wp-json/".
284
+	 * @return string
285
+	 */
286
+	public function requestUri($relativeToWpRoot = false)
287
+	{
288
+		return $this->server_params->requestUri();
289
+	}
290
+
291
+
292
+	/**
293
+	 * @return string
294
+	 */
295
+	public function userAgent()
296
+	{
297
+		return $this->server_params->userAgent();
298
+	}
299
+
300
+
301
+	/**
302
+	 * @param string $user_agent
303
+	 */
304
+	public function setUserAgent($user_agent = '')
305
+	{
306
+		$this->server_params->setUserAgent($user_agent);
307
+	}
308
+
309
+
310
+	/**
311
+	 * @return bool
312
+	 */
313
+	public function isBot()
314
+	{
315
+		return $this->is_bot;
316
+	}
317
+
318
+
319
+	/**
320
+	 * @param bool $is_bot
321
+	 */
322
+	public function setIsBot($is_bot)
323
+	{
324
+		$this->is_bot = filter_var($is_bot, FILTER_VALIDATE_BOOLEAN);
325
+	}
326
+
327
+
328
+	/**
329
+	 * @return bool
330
+	 */
331
+	public function isActivation()
332
+	{
333
+		return $this->request_type->isActivation();
334
+	}
335
+
336
+
337
+	/**
338
+	 * @param $is_activation
339
+	 * @return bool
340
+	 */
341
+	public function setIsActivation($is_activation)
342
+	{
343
+		return $this->request_type->setIsActivation($is_activation);
344
+	}
345
+
346
+
347
+	/**
348
+	 * @return bool
349
+	 */
350
+	public function isAdmin()
351
+	{
352
+		return $this->request_type->isAdmin();
353
+	}
354
+
355
+
356
+	/**
357
+	 * @return bool
358
+	 */
359
+	public function isAdminAjax()
360
+	{
361
+		return $this->request_type->isAdminAjax();
362
+	}
363
+
364
+
365
+	/**
366
+	 * @return bool
367
+	 */
368
+	public function isAjax()
369
+	{
370
+		return $this->request_type->isAjax();
371
+	}
372
+
373
+
374
+	/**
375
+	 * @return bool
376
+	 */
377
+	public function isEeAjax()
378
+	{
379
+		return $this->request_type->isEeAjax();
380
+	}
381
+
382
+
383
+	/**
384
+	 * @return bool
385
+	 */
386
+	public function isOtherAjax()
387
+	{
388
+		return $this->request_type->isOtherAjax();
389
+	}
390
+
391
+
392
+	/**
393
+	 * @return bool
394
+	 */
395
+	public function isApi()
396
+	{
397
+		return $this->request_type->isApi();
398
+	}
399
+
400
+
401
+	/**
402
+	 * @return bool
403
+	 */
404
+	public function isCli()
405
+	{
406
+		return $this->request_type->isCli();
407
+	}
408
+
409
+
410
+	/**
411
+	 * @return bool
412
+	 */
413
+	public function isCron()
414
+	{
415
+		return $this->request_type->isCron();
416
+	}
417
+
418
+
419
+	/**
420
+	 * @return bool
421
+	 */
422
+	public function isFeed()
423
+	{
424
+		return $this->request_type->isFeed();
425
+	}
426
+
427
+
428
+	/**
429
+	 * @return bool
430
+	 */
431
+	public function isFrontend()
432
+	{
433
+		return $this->request_type->isFrontend();
434
+	}
435
+
436
+
437
+	/**
438
+	 * @return bool
439
+	 */
440
+	public function isFrontAjax()
441
+	{
442
+		return $this->request_type->isFrontAjax();
443
+	}
444
+
445
+
446
+	/**
447
+	 * @return bool
448
+	 */
449
+	public function isIframe()
450
+	{
451
+		return $this->request_type->isIframe();
452
+	}
453
+
454
+
455
+	/**
456
+	 * @return bool
457
+	 */
458
+	public function isWordPressApi()
459
+	{
460
+		return $this->request_type->isWordPressApi();
461
+	}
462
+
463
+
464
+	/**
465
+	 * @return bool
466
+	 */
467
+	public function isWordPressHeartbeat()
468
+	{
469
+		return $this->request_type->isWordPressHeartbeat();
470
+	}
471
+
472
+
473
+	/**
474
+	 * @return bool
475
+	 */
476
+	public function isWordPressScrape()
477
+	{
478
+		return $this->request_type->isWordPressScrape();
479
+	}
480
+
481
+
482
+	/**
483
+	 * @return string
484
+	 */
485
+	public function slug()
486
+	{
487
+		return $this->request_type->slug();
488
+	}
489
+
490
+
491
+	/**
492
+	 * @return RequestTypeContextCheckerInterface
493
+	 */
494
+	public function getRequestType()
495
+	{
496
+		return $this->request_type;
497
+	}
498 498
 }
Please login to merge, or discard this patch.
core/services/request/RequestInterface.php 1 patch
Indentation   +179 added lines, -179 removed lines patch added patch discarded remove patch
@@ -16,185 +16,185 @@
 block discarded – undo
16 16
 interface RequestInterface extends RequestTypeContextCheckerInterface
17 17
 {
18 18
 
19
-    /**
20
-     * @param RequestTypeContextCheckerInterface $type
21
-     */
22
-    public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type);
19
+	/**
20
+	 * @param RequestTypeContextCheckerInterface $type
21
+	 */
22
+	public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type);
23 23
 
24 24
 
25
-    /**
26
-     * @return array
27
-     */
28
-    public function getParams();
29
-
30
-
31
-    /**
32
-     * @return array
33
-     */
34
-    public function postParams();
35
-
36
-
37
-    /**
38
-     * @return array
39
-     */
40
-    public function cookieParams();
41
-
42
-
43
-    /**
44
-     * @return array
45
-     */
46
-    public function serverParams();
47
-
48
-
49
-    /**
50
-     * @param string $key
51
-     * @param mixed|null $default
52
-     * @return array|int|float|string
53
-     */
54
-    public function getServerParam($key, $default = null);
55
-
56
-
57
-    /**
58
-     * @param string                 $key
59
-     * @param array|int|float|string $value
60
-     * @return void
61
-     */
62
-    public function setServerParam($key, $value);
63
-
64
-
65
-    /**
66
-     * @param string $key
67
-     * @return bool
68
-     */
69
-    public function serverParamIsSet($key);
70
-
71
-
72
-    /**
73
-     * @return array
74
-     */
75
-    public function filesParams();
76
-
77
-
78
-    /**
79
-     * returns sanitized contents of $_REQUEST
80
-     *
81
-     * @return array
82
-     */
83
-    public function requestParams();
84
-
85
-
86
-    /**
87
-     * @param string $key
88
-     * @param string $value
89
-     * @param bool   $override_ee
90
-     * @return void
91
-     */
92
-    public function setRequestParam($key, $value, $override_ee = false);
93
-
94
-
95
-    /**
96
-     * returns   the value for a request param if the given key exists
97
-     *
98
-     * @param string     $key
99
-     * @param mixed|null $default
100
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
101
-     * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
102
-     * @param string     $delimiter for CSV type strings that should be returned as an array
103
-     * @return array|bool|float|int|string
104
-     */
105
-    public function getRequestParam($key, $default = null, $type = 'string', $is_array = false, $delimiter = '');
106
-
107
-
108
-    /**
109
-     * check if param exists
110
-     *
111
-     * @param string $key
112
-     * @return bool
113
-     */
114
-    public function requestParamIsSet($key);
115
-
116
-
117
-    /**
118
-     * check if a request parameter exists whose key that matches the supplied wildcard pattern
119
-     * and return the value for the first match found
120
-     * wildcards can be either of the following:
121
-     *      ? to represent a single character of any type
122
-     *      * to represent one or more characters of any type
123
-     *
124
-     * @param string     $pattern
125
-     * @param mixed|null $default
126
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
127
-     * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
128
-     * @param string     $delimiter for CSV type strings that should be returned as an array
129
-     * @return array|bool|float|int|string
130
-     */
131
-    public function getMatch($pattern, $default = null, $type = 'string', $is_array = false, $delimiter = '');
132
-
133
-
134
-    /**
135
-     * check if a request parameter exists whose key matches the supplied wildcard pattern
136
-     * wildcards can be either of the following:
137
-     *      ? to represent a single character of any type
138
-     *      * to represent one or more characters of any type
139
-     * returns true if a match is found or false if not
140
-     *
141
-     * @param string $pattern
142
-     * @return false|int
143
-     */
144
-    public function matches($pattern);
145
-
146
-
147
-    /**
148
-     * remove param
149
-     *
150
-     * @param string $key
151
-     * @param bool   $unset_from_global_too
152
-     */
153
-    public function unSetRequestParam($key, $unset_from_global_too = false);
154
-
155
-
156
-    /**
157
-     * remove params
158
-     *
159
-     * @param array $keys
160
-     * @param bool  $unset_from_global_too
161
-     */
162
-    public function unSetRequestParams(array $keys, $unset_from_global_too = false);
163
-
164
-
165
-    /**
166
-     * @return string
167
-     */
168
-    public function ipAddress();
169
-
170
-
171
-    /**
172
-     * @param boolean $relativeToWpRoot whether to return the uri relative to WordPress' home URL, or not.
173
-     * @return string
174
-     */
175
-    public function requestUri($relativeToWpRoot = false);
176
-
177
-
178
-    /**
179
-     * @return string
180
-     */
181
-    public function userAgent();
182
-
183
-
184
-    /**
185
-     * @param string $user_agent
186
-     */
187
-    public function setUserAgent($user_agent = '');
188
-
189
-
190
-    /**
191
-     * @return bool
192
-     */
193
-    public function isBot();
194
-
195
-
196
-    /**
197
-     * @param bool $is_bot
198
-     */
199
-    public function setIsBot($is_bot);
25
+	/**
26
+	 * @return array
27
+	 */
28
+	public function getParams();
29
+
30
+
31
+	/**
32
+	 * @return array
33
+	 */
34
+	public function postParams();
35
+
36
+
37
+	/**
38
+	 * @return array
39
+	 */
40
+	public function cookieParams();
41
+
42
+
43
+	/**
44
+	 * @return array
45
+	 */
46
+	public function serverParams();
47
+
48
+
49
+	/**
50
+	 * @param string $key
51
+	 * @param mixed|null $default
52
+	 * @return array|int|float|string
53
+	 */
54
+	public function getServerParam($key, $default = null);
55
+
56
+
57
+	/**
58
+	 * @param string                 $key
59
+	 * @param array|int|float|string $value
60
+	 * @return void
61
+	 */
62
+	public function setServerParam($key, $value);
63
+
64
+
65
+	/**
66
+	 * @param string $key
67
+	 * @return bool
68
+	 */
69
+	public function serverParamIsSet($key);
70
+
71
+
72
+	/**
73
+	 * @return array
74
+	 */
75
+	public function filesParams();
76
+
77
+
78
+	/**
79
+	 * returns sanitized contents of $_REQUEST
80
+	 *
81
+	 * @return array
82
+	 */
83
+	public function requestParams();
84
+
85
+
86
+	/**
87
+	 * @param string $key
88
+	 * @param string $value
89
+	 * @param bool   $override_ee
90
+	 * @return void
91
+	 */
92
+	public function setRequestParam($key, $value, $override_ee = false);
93
+
94
+
95
+	/**
96
+	 * returns   the value for a request param if the given key exists
97
+	 *
98
+	 * @param string     $key
99
+	 * @param mixed|null $default
100
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
101
+	 * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
102
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
103
+	 * @return array|bool|float|int|string
104
+	 */
105
+	public function getRequestParam($key, $default = null, $type = 'string', $is_array = false, $delimiter = '');
106
+
107
+
108
+	/**
109
+	 * check if param exists
110
+	 *
111
+	 * @param string $key
112
+	 * @return bool
113
+	 */
114
+	public function requestParamIsSet($key);
115
+
116
+
117
+	/**
118
+	 * check if a request parameter exists whose key that matches the supplied wildcard pattern
119
+	 * and return the value for the first match found
120
+	 * wildcards can be either of the following:
121
+	 *      ? to represent a single character of any type
122
+	 *      * to represent one or more characters of any type
123
+	 *
124
+	 * @param string     $pattern
125
+	 * @param mixed|null $default
126
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
127
+	 * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
128
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
129
+	 * @return array|bool|float|int|string
130
+	 */
131
+	public function getMatch($pattern, $default = null, $type = 'string', $is_array = false, $delimiter = '');
132
+
133
+
134
+	/**
135
+	 * check if a request parameter exists whose key matches the supplied wildcard pattern
136
+	 * wildcards can be either of the following:
137
+	 *      ? to represent a single character of any type
138
+	 *      * to represent one or more characters of any type
139
+	 * returns true if a match is found or false if not
140
+	 *
141
+	 * @param string $pattern
142
+	 * @return false|int
143
+	 */
144
+	public function matches($pattern);
145
+
146
+
147
+	/**
148
+	 * remove param
149
+	 *
150
+	 * @param string $key
151
+	 * @param bool   $unset_from_global_too
152
+	 */
153
+	public function unSetRequestParam($key, $unset_from_global_too = false);
154
+
155
+
156
+	/**
157
+	 * remove params
158
+	 *
159
+	 * @param array $keys
160
+	 * @param bool  $unset_from_global_too
161
+	 */
162
+	public function unSetRequestParams(array $keys, $unset_from_global_too = false);
163
+
164
+
165
+	/**
166
+	 * @return string
167
+	 */
168
+	public function ipAddress();
169
+
170
+
171
+	/**
172
+	 * @param boolean $relativeToWpRoot whether to return the uri relative to WordPress' home URL, or not.
173
+	 * @return string
174
+	 */
175
+	public function requestUri($relativeToWpRoot = false);
176
+
177
+
178
+	/**
179
+	 * @return string
180
+	 */
181
+	public function userAgent();
182
+
183
+
184
+	/**
185
+	 * @param string $user_agent
186
+	 */
187
+	public function setUserAgent($user_agent = '');
188
+
189
+
190
+	/**
191
+	 * @return bool
192
+	 */
193
+	public function isBot();
194
+
195
+
196
+	/**
197
+	 * @param bool $is_bot
198
+	 */
199
+	public function setIsBot($is_bot);
200 200
 }
Please login to merge, or discard this patch.
libraries/messages/data_class/EE_Messages_Preview_incoming_data.class.php 1 patch
Indentation   +599 added lines, -599 removed lines patch added patch discarded remove patch
@@ -21,603 +21,603 @@
 block discarded – undo
21 21
 class EE_Messages_Preview_incoming_data extends EE_Messages_incoming_data
22 22
 {
23 23
 
24
-    // some specific properties we need for this class
25
-    private $_events        = [];
26
-
27
-    private $_attendees     = [];
28
-
29
-    private $_registrations = [];
30
-
31
-
32
-    /**
33
-     * For the constructor of this special preview class.  We're either looking for an event id or empty data.  If we
34
-     * have an event id (or ids) then we'll use that as the source for the "dummy" data.  If the data is empty then
35
-     * we'll get the first three published events from the users database and use that as a source.
36
-     *
37
-     * @param array $data
38
-     * @throws EE_Error
39
-     * @throws EE_Error
40
-     * @throws ReflectionException
41
-     */
42
-    public function __construct($data = [])
43
-    {
44
-        $this->_data = isset($data['event_ids']) ? $data['event_ids'] : [];
45
-        $this->_setup_attendees_events();
46
-        parent::__construct($data);
47
-    }
48
-
49
-
50
-    /**
51
-     * Returns database safe representation of the data later used to when instantiating this object.
52
-     *
53
-     * @param array $data The incoming data to be prepped.
54
-     *
55
-     * @return array   The prepped data for db
56
-     */
57
-    public static function convert_data_for_persistent_storage($data)
58
-    {
59
-        return $data;
60
-    }
61
-
62
-
63
-    /**
64
-     * Data that has been stored in persistent storage that was prepped by _convert_data_for_persistent_storage
65
-     * can be sent into this method and converted back into the format used for instantiating with this data handler.
66
-     *
67
-     * @param array $data
68
-     *
69
-     * @return array
70
-     */
71
-    public static function convert_data_from_persistent_storage($data)
72
-    {
73
-        return $data;
74
-    }
75
-
76
-
77
-    /**
78
-     * This will just setup the _events property in the expected format.
79
-     *
80
-     * @throws EE_Error
81
-     * @throws ReflectionException
82
-     */
83
-    private function _setup_attendees_events()
84
-    {
85
-
86
-        // setup some attendee objects
87
-        $attendees = $this->_get_some_attendees();
88
-
89
-        // if empty $data we'll do a query to get some events from the server.
90
-        // otherwise we'll retrieve the event data for the given ids.
91
-        $events = $this->_get_some_events($this->_data);
92
-
93
-        $answers_n_questions = $this->_get_some_q_and_as();
94
-
95
-        if (count($events) < 1) {
96
-            throw new EE_Error(
97
-                esc_html__(
98
-                    'We can\'t generate a preview for you because there are no active events in your database',
99
-                    'event_espresso'
100
-                )
101
-            );
102
-        }
103
-
104
-
105
-        // now let's loop and set up the _events property.  At the same time we'll set up attendee properties.
106
-        // we'll actually use the generated line_item identifiers for our loop
107
-        $dtts = $tkts = [];
108
-        foreach ($events as $id => $event) {
109
-            if (! $event instanceof EE_Event) {
110
-                continue;
111
-            }
112
-            $this->_events[ $id ]['ID']       = $id;
113
-            $this->_events[ $id ]['name']     = $event->get('EVT_name');
114
-            $datetime                         = $event->get_first_related('Datetime');
115
-            $tickets                          = $datetime instanceof EE_Datetime ? $datetime->get_many_related(
116
-                'Ticket',
117
-                ['default_where_conditions' => 'none']
118
-            ) : [];
119
-            $this->_events[ $id ]['event']    = $event;
120
-            $this->_events[ $id ]['reg_objs'] = [];
121
-            $this->_events[ $id ]['tkt_objs'] = $tickets;
122
-            $this->_events[ $id ]['dtt_objs'] = [];
123
-
124
-            $dttcache = [];
125
-            $tkts     = [];
126
-            foreach ($tickets as $ticket) {
127
-                if (! $ticket instanceof EE_Ticket) {
128
-                    continue;
129
-                }
130
-                $reldatetime                       = $ticket->datetimes();
131
-                $tkts[ $ticket->ID() ]             = [];
132
-                $tkts[ $ticket->ID() ]['ticket']   = $ticket;
133
-                $tkts[ $ticket->ID() ]['dtt_objs'] = $reldatetime;
134
-                $tkts[ $ticket->ID() ]['att_objs'] = $attendees;
135
-                $tkts[ $ticket->ID() ]['count']    = count($attendees);
136
-                $tkts[ $ticket->ID() ]['EE_Event'] = $event;
137
-                foreach ($reldatetime as $datetime) {
138
-                    if ($datetime instanceof EE_Datetime && ! isset($dtts[ $datetime->ID() ])) {
139
-                        $this->_events[ $id ]['dtt_objs'][ $datetime->ID() ] = $datetime;
140
-                        $dtts[ $datetime->ID() ]['datetime']                 = $datetime;
141
-                        $dtts[ $datetime->ID() ]['tkt_objs'][]               = $ticket;
142
-                        $dtts[ $datetime->ID() ]['evt_objs'][]               = $event;
143
-                        $dttcache[ $datetime->ID() ]                         = $datetime;
144
-                    }
145
-                }
146
-            }
147
-
148
-            $this->_events[ $id ]['total_attendees'] = count($attendees);
149
-            $this->_events[ $id ]['att_objs']        = $attendees;
150
-
151
-            // let's also setup the dummy attendees property!
152
-            foreach ($attendees as $att_key => $attendee) {
153
-                if (! $attendee instanceof EE_Attendee) {
154
-                    continue;
155
-                }
156
-                $this->_attendees[ $att_key ]['line_ref'][] =
157
-                    $id;  // so later it can be determined what events this attendee registered for!
158
-                $this->_attendees[ $att_key ]['evt_objs'][] = $event;
159
-                $this->_attendees[ $att_key ]['att_obj']    = $attendee;
160
-                // $this->_attendees[$att_key]['registration_id'] = 0;
161
-                $this->_attendees[ $att_key ]['attendee_email'] = $attendee->email();
162
-                $this->_attendees[ $att_key ]['tkt_objs']       = $tickets;
163
-                if ($att_key == 999999991) {
164
-                    $this->_attendees[ $att_key ]['ans_objs'][999]  = $answers_n_questions['answers'][999];
165
-                    $this->_attendees[ $att_key ]['ans_objs'][1002] = $answers_n_questions['answers'][1002];
166
-                    $this->_attendees[ $att_key ]['ans_objs'][1005] = $answers_n_questions['answers'][1005];
167
-                } elseif ($att_key == 999999992) {
168
-                    $this->_attendees[ $att_key ]['ans_objs'][1000] = $answers_n_questions['answers'][1000];
169
-                    $this->_attendees[ $att_key ]['ans_objs'][1003] = $answers_n_questions['answers'][1003];
170
-                    $this->_attendees[ $att_key ]['ans_objs'][1006] = $answers_n_questions['answers'][1006];
171
-                } elseif ($att_key == 999999993) {
172
-                    $this->_attendees[ $att_key ]['ans_objs'][1001] = $answers_n_questions['answers'][1001];
173
-                    $this->_attendees[ $att_key ]['ans_objs'][1004] = $answers_n_questions['answers'][1004];
174
-                    $this->_attendees[ $att_key ]['ans_objs'][1007] = $answers_n_questions['answers'][1007];
175
-                }
176
-            }
177
-        }
178
-
179
-        $this->tickets            = $tkts;
180
-        $this->datetimes          = $dtts;
181
-        $this->answers            = $answers_n_questions['answers'];
182
-        $this->questions          = $answers_n_questions['questions'];
183
-        $this->total_ticket_count = count($tkts) * count($this->_attendees);
184
-    }
185
-
186
-
187
-    /**
188
-     * This just returns an array of dummy attendee objects that we'll use to attach to events for our preview data
189
-     *
190
-     * @access private
191
-     * @return array an array of attendee objects
192
-     * @throws EE_Error
193
-     * @throws EE_Error
194
-     */
195
-    private function _get_some_attendees()
196
-    {
197
-        // let's just setup a dummy array of various attendee details
198
-        $dummy_attendees = [
199
-            0 => [
200
-                'Luke',
201
-                'Skywalker',
202
-                '[email protected]',
203
-                '804 Bantha Dr.',
204
-                'Complex 8',
205
-                'Mos Eisley',
206
-                32,
207
-                'US',
208
-                'f0r3e',
209
-                '222-333-4763',
210
-                false,
211
-                '999999991',
212
-            ],
213
-            1 => [
214
-                'Princess',
215
-                'Leia',
216
-                '[email protected]',
217
-                '1456 Valley Way Boulevard',
218
-                'Suite 9',
219
-                'Alderaan',
220
-                15,
221
-                'US',
222
-                'c1h2c',
223
-                '78-123-111-1111',
224
-                false,
225
-                '999999992',
226
-            ],
227
-            2 => [
228
-                'Yoda',
229
-                'I Am',
230
-                '[email protected]',
231
-                '4th Tree',
232
-                '5th Knot',
233
-                'Marsh',
234
-                22,
235
-                'US',
236
-                'l18n',
237
-                '999-999-9999',
238
-                false,
239
-                '999999993',
240
-            ],
241
-        ];
242
-
243
-        // let's generate the attendee objects
244
-        $attendees = [];
245
-        $var_array = [
246
-            'fname',
247
-            'lname',
248
-            'email',
249
-            'address',
250
-            'address2',
251
-            'city',
252
-            'staid',
253
-            'cntry',
254
-            'zip',
255
-            'phone',
256
-            'deleted',
257
-            'attid',
258
-        ];
259
-
260
-        // EE_Registry::instance()->load_class( 'Attendee', array(), FALSE, false, TRUE );
261
-        foreach ($dummy_attendees as $dummy) {
262
-            $att = array_combine($var_array, $dummy);
263
-            extract($att);
264
-            /** @var $fname string */
265
-            /** @var $lname string */
266
-            /** @var $address string */
267
-            /** @var $address2 string */
268
-            /** @var $city string */
269
-            /** @var $staid string */
270
-            /** @var $cntry string */
271
-            /** @var $zip string */
272
-            /** @var $email string */
273
-            /** @var $phone string */
274
-            /** @var $attid string */
275
-            $attendees[ $attid ] = EE_Attendee::new_instance(
276
-                [
277
-                    'ATT_fname'    => $fname,
278
-                    'ATT_lname'    => $lname,
279
-                    'ATT_address'  => $address,
280
-                    'ATT_address2' => $address2,
281
-                    'ATT_city'     => $city,
282
-                    'STA_ID'       => $staid,
283
-                    'CNT_ISO'      => $cntry,
284
-                    'ATT_zip'      => $zip,
285
-                    'ATT_email'    => $email,
286
-                    'ATT_phone'    => $phone,
287
-                    'ATT_ID'       => $attid,
288
-                ]
289
-            );
290
-        }
291
-
292
-        return $attendees;
293
-    }
294
-
295
-
296
-    /**
297
-     * Return an array of dummy question objects indexed by answer id and dummy answer objects indexed by answer id.
298
-     * This will be used in our dummy data setup
299
-     *
300
-     * @return array
301
-     * @throws EE_Error
302
-     * @throws ReflectionException
303
-     */
304
-    private function _get_some_q_and_as()
305
-    {
306
-        $quests_array = [
307
-            0 => [
308
-                555,
309
-                esc_html__('What is your favorite planet?', 'event_espresso'),
310
-                0,
311
-            ],
312
-            1 => [
313
-                556,
314
-                esc_html__('What is your favorite food?', 'event_espresso'),
315
-                0,
316
-            ],
317
-            2 => [
318
-                557,
319
-                esc_html__('How many lightyears have you travelled', 'event_espresso'),
320
-                0,
321
-            ],
322
-        ];
323
-
324
-        $ans_array = [
325
-            0 => [
326
-                999,
327
-                555,
328
-                'Tattoine',
329
-            ],
330
-            1 => [
331
-                1000,
332
-                555,
333
-                'Alderaan',
334
-            ],
335
-            2 => [
336
-                1001,
337
-                555,
338
-                'Dantooine',
339
-            ],
340
-            3 => [
341
-                1002,
342
-                556,
343
-                'Fish Fingers',
344
-            ],
345
-            4 => [
346
-                1003,
347
-                556,
348
-                'Sushi',
349
-            ],
350
-            5 => [
351
-                1004,
352
-                556,
353
-                'Water',
354
-            ],
355
-            6 => [
356
-                1005,
357
-                557,
358
-                'A lot',
359
-            ],
360
-            7 => [
361
-                1006,
362
-                557,
363
-                "That's none of your business.",
364
-            ],
365
-            8 => [
366
-                1007,
367
-                557,
368
-                "People less travel me then.",
369
-            ],
370
-        ];
371
-
372
-        $qst_columns = ['QST_ID', 'QST_display_text', 'QST_system'];
373
-        $ans_columns = ['ANS_ID', 'QST_ID', 'ANS_value'];
374
-
375
-        // EE_Registry::instance()->load_class( 'Question', array(), FALSE, TRUE, TRUE );
376
-        // EE_Registry::instance()->load_class( 'Answer', array(), FALSE, TRUE, TRUE );
377
-
378
-        $qsts = [];
379
-        // first the questions
380
-        foreach ($quests_array as $qst) {
381
-            $qstobj                    = array_combine($qst_columns, $qst);
382
-            $qsts[ $qstobj['QST_ID'] ] = EE_Question::new_instance($qstobj);
383
-        }
384
-
385
-        // now the answers (and we'll setup our arrays)
386
-        $q_n_as = [];
387
-        foreach ($ans_array as $ans) {
388
-            $ansobj                               = array_combine($ans_columns, $ans);
389
-            $ansobj                               = EE_Answer::new_instance($ansobj);
390
-            $q_n_as['answers'][ $ansobj->ID() ]   = $ansobj;
391
-            $q_n_as['questions'][ $ansobj->ID() ] = $qsts[ $ansobj->get('QST_ID') ];
392
-        }
393
-
394
-        return $q_n_as;
395
-    }
396
-
397
-
398
-    /**
399
-     * Return an array of event objects from the database
400
-     *
401
-     * If event ids are not included then we'll just retrieve the first published event from the database.
402
-     *
403
-     * @param array $event_ids if set, this will be an array of event ids to obtain events for.
404
-     *
405
-     * @return array    An array of event objects from the db.
406
-     * @throws EE_Error
407
-     */
408
-    private function _get_some_events(array $event_ids = [])
409
-    {
410
-        /** @var RequestInterface $request */
411
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
412
-        // if we have an evt_id then we want to make sure we use that for the preview
413
-        // (because a specific event template is being viewed);
414
-        $event_ids = $request->getRequestParam('evt_id', $event_ids, 'int', true);
415
-        $limit     = ! empty($event_ids)
416
-            ? null
417
-            : apply_filters('FHEE__EE_Messages_Preview_incoming_data___get_some_events__limit', '0,1');
418
-
419
-        $where = ! empty($event_ids)
420
-            ? [
421
-                'EVT_ID'                 => ['IN', $event_ids],
422
-                'Datetime.Ticket.TKT_ID' => ['>', 1],
423
-            ]
424
-            : ['Datetime.Ticket.TKT_ID' => ['>', 1]];
425
-
426
-        return EEM_Event::instance()->get_all([$where, 'limit' => $limit]);
427
-    }
428
-
429
-
430
-    /**
431
-     * @throws EE_Error
432
-     * @throws ReflectionException
433
-     */
434
-    protected function _setup_data()
435
-    {
436
-        // need to figure out the running total for test purposes so... we're going to create a temp cart and add the tickets to it!
437
-        if (EE_Registry::instance()->SSN instanceof EE_Session) {
438
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
439
-            $session = EE_Registry::instance()->SSN;
440
-        } else {
441
-            $session = EE_Registry::instance()->load_core('Session');
442
-        }
443
-        $cart = EE_Cart::instance(null, $session);
444
-
445
-        // add tickets to cart
446
-        foreach ($this->tickets as $ticket) {
447
-            $cart->add_ticket_to_cart($ticket['ticket']);
448
-        }
449
-
450
-        // setup txn property
451
-        $this->txn = EE_Transaction::new_instance(
452
-            [
453
-                'TXN_timestamp'    => time(), // unix timestamp
454
-                'TXN_total'        => 0, // txn_total
455
-                'TXN_paid'         => 0, // txn_paid
456
-                'STS_ID'           => EEM_Transaction::incomplete_status_code, // sts_id
457
-                'TXN_session_data' => null, // dump of txn session object (we're just going to leave blank here)
458
-                'TXN_hash_salt'    => null, // hash salt blank as well
459
-                'TXN_ID'           => 999999,
460
-            ]
461
-        );
462
-
463
-
464
-        // setup reg_objects
465
-        // note we're setting up a reg object for each attendee in each event but ALSO adding to the reg_object array.
466
-        $this->reg_objs = [];
467
-        $regid          = 9999990;
468
-        foreach ($this->_attendees as $key => $attendee) {
469
-            // note we need to setup reg_objects for each event this attendee belongs to
470
-            $regatt = $attendee['att_obj'] instanceof EE_Attendee ? $attendee['att_obj']->ID() : null;
471
-            $regtxn = $this->txn->ID();
472
-            $regcnt = 1;
473
-            foreach ($attendee['line_ref'] as $evtid) {
474
-                foreach ($this->_events[ $evtid ]['tkt_objs'] as $ticket) {
475
-                    if (! $ticket instanceof EE_Ticket) {
476
-                        continue;
477
-                    }
478
-                    $reg_array                                            = [
479
-                        'EVT_ID'           => $evtid,
480
-                        'ATT_ID'           => $regatt,
481
-                        'TXN_ID'           => $regtxn,
482
-                        'TKT_ID'           => $ticket->ID(),
483
-                        'STS_ID'           => EEM_Registration::status_id_pending_payment,
484
-                        'REG_date'         => time(),
485
-                        'REG_final_price'  => $ticket->get('TKT_price'),
486
-                        'REG_session'      => 'dummy_session_id',
487
-                        'REG_code'         => $regid . '-dummy-generated-code',
488
-                        'REG_url_link'     => $regcnt . '-daafpapasdlfakasdfpqasdfasdf',
489
-                        'REG_count'        => $regcnt,
490
-                        'REG_group_size'   => $this->_events[ $evtid ]['total_attendees'],
491
-                        'REG_att_is_going' => true,
492
-                        'REG_ID'           => $regid,
493
-                    ];
494
-                    $REG_OBJ                                              = EE_Registration::new_instance($reg_array);
495
-                    $this->_attendees[ $key ]['reg_objs'][ $regid ]       = $REG_OBJ;
496
-                    $this->_events[ $evtid ]['reg_objs'][]                = $REG_OBJ;
497
-                    $this->reg_objs[]                                     = $REG_OBJ;
498
-                    $this->tickets[ $ticket->ID() ]['reg_objs'][ $regid ] = $REG_OBJ;
499
-
500
-                    $regcnt++;
501
-                    $regid++;
502
-                }
503
-            }
504
-        }
505
-
506
-
507
-        // setup line items!
508
-        $line_item_total = EEH_Line_Item::create_total_line_item($this->txn);
509
-
510
-        // add tickets
511
-        foreach ($this->tickets as $item) {
512
-            $qty    = $item['count'];
513
-            $ticket = $item['ticket'];
514
-            EEH_Line_Item::add_ticket_purchase($line_item_total, $ticket, $qty);
515
-        }
516
-
517
-        $shipping_line_item = EE_Line_Item::new_instance(
518
-            [
519
-                'LIN_name'       => esc_html__(
520
-                    'Shipping Surcharge',
521
-                    'event_espresso'
522
-                ),
523
-                'LIN_desc'       => esc_html__(
524
-                    'Sent via Millenium Falcon',
525
-                    'event_espresso'
526
-                ),
527
-                'LIN_unit_price' => 20,
528
-                'LIN_quantity'   => 1,
529
-                'LIN_is_taxable' => true,
530
-                'LIN_total'      => 20,
531
-                'LIN_type'       => EEM_Line_Item::type_line_item,
532
-            ]
533
-        );
534
-        EEH_Line_Item::add_item($line_item_total, $shipping_line_item);
535
-        $this->additional_line_items = [$shipping_line_item];
536
-
537
-        // now let's add taxes
538
-        EEH_Line_Item::apply_taxes($line_item_total);
539
-
540
-        // now we should be able to get the items we need from this object
541
-        $event_line_items = EEH_Line_Item::get_pre_tax_subtotal($line_item_total)->children();
542
-        $line_items       = [];
543
-        foreach ($event_line_items as $line_item) {
544
-            if (! $line_item instanceof EE_Line_Item || $line_item->OBJ_type() !== 'Event') {
545
-                continue;
546
-            }
547
-            $ticket_line_items = EEH_Line_Item::get_ticket_line_items($line_item);
548
-            foreach ($ticket_line_items as $ticket_line_item) {
549
-                if (! $ticket_line_item instanceof EE_Line_Item) {
550
-                    continue;
551
-                }
552
-                $this->tickets[ $ticket_line_item->OBJ_ID() ]['line_item']      = $ticket_line_item;
553
-                $this->tickets[ $ticket_line_item->OBJ_ID() ]['sub_line_items'] = $ticket_line_item->children();
554
-                $line_items[ $ticket_line_item->ID() ]['children']              = $ticket_line_item->children();
555
-                $line_items[ $ticket_line_item->ID() ]['EE_Ticket']             =
556
-                    $this->tickets[ $ticket_line_item->OBJ_ID() ]['ticket'];
557
-            }
558
-        }
559
-
560
-        $this->line_items_with_children = $line_items;
561
-        $this->tax_line_items           = $line_item_total->tax_descendants();
562
-
563
-        // add proper total to transaction object.
564
-        $grand_total                 = $line_item_total->recalculate_total_including_taxes();
565
-        $this->grand_total_line_item = $line_item_total;
566
-        $this->txn->set_total($grand_total);
567
-
568
-
569
-        // add additional details for each registration
570
-        foreach ($this->reg_objs as $reg) {
571
-            if (! $reg instanceof EE_Registration) {
572
-                continue;
573
-            }
574
-            $this->_registrations[ $reg->ID() ]['tkt_obj']  = $this->tickets[ $reg->get('TKT_ID') ]['ticket'];
575
-            $this->_registrations[ $reg->ID() ]['evt_obj']  = $this->_events[ $reg->get('EVT_ID') ]['event'];
576
-            $this->_registrations[ $reg->ID() ]['reg_obj']  = $reg;
577
-            $this->_registrations[ $reg->ID() ]['ans_objs'] = $this->_attendees[ $reg->get('ATT_ID') ]['ans_objs'];
578
-            $this->_registrations[ $reg->ID() ]['att_obj']  = $this->_attendees[ $reg->get('ATT_ID') ]['att_obj'];
579
-            $this->_registrations[ $reg->ID() ]['dtt_objs'] = $this->tickets[ $reg->get('TKT_ID') ]['dtt_objs'];
580
-        }
581
-
582
-
583
-        // events and attendees
584
-        $this->events        = $this->_events;
585
-        $this->attendees     = $this->_attendees;
586
-        $this->registrations = $this->_registrations;
587
-
588
-        $attendees_to_shift = $this->_attendees;
589
-
590
-        // setup primary attendee property
591
-        $this->primary_attendee_data = [
592
-            'fname' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
593
-                ? $this->_attendees[999999991]['att_obj']->fname()
594
-                : '',
595
-
596
-            'lname' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
597
-                ? $this->_attendees[999999991]['att_obj']->lname()
598
-                : '',
599
-
600
-            'email' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
601
-                ? $this->_attendees[999999991]['att_obj']->email()
602
-                : '',
603
-
604
-            'att_obj' => $this->_attendees[999999991]['att_obj'],
605
-
606
-            'reg_obj' => array_shift($attendees_to_shift[999999991]['reg_objs']),
607
-        ];
608
-
609
-        // reg_info property
610
-        // note this isn't referenced by any shortcode parsers so we'll ignore for now.
611
-        $this->reg_info = [];
612
-
613
-        // let's set a reg_obj for messengers expecting one.
614
-        $this->reg_obj = array_shift($this->_attendees[999999991]['reg_objs']);
615
-
616
-        // the below are just dummy items.
617
-        $this->user_id     = 1;
618
-        $this->ip_address  = '192.0.2.1';
619
-        $this->user_agent  = '';
620
-        $this->init_access = time();
621
-        $this->last_access = time();
622
-    }
24
+	// some specific properties we need for this class
25
+	private $_events        = [];
26
+
27
+	private $_attendees     = [];
28
+
29
+	private $_registrations = [];
30
+
31
+
32
+	/**
33
+	 * For the constructor of this special preview class.  We're either looking for an event id or empty data.  If we
34
+	 * have an event id (or ids) then we'll use that as the source for the "dummy" data.  If the data is empty then
35
+	 * we'll get the first three published events from the users database and use that as a source.
36
+	 *
37
+	 * @param array $data
38
+	 * @throws EE_Error
39
+	 * @throws EE_Error
40
+	 * @throws ReflectionException
41
+	 */
42
+	public function __construct($data = [])
43
+	{
44
+		$this->_data = isset($data['event_ids']) ? $data['event_ids'] : [];
45
+		$this->_setup_attendees_events();
46
+		parent::__construct($data);
47
+	}
48
+
49
+
50
+	/**
51
+	 * Returns database safe representation of the data later used to when instantiating this object.
52
+	 *
53
+	 * @param array $data The incoming data to be prepped.
54
+	 *
55
+	 * @return array   The prepped data for db
56
+	 */
57
+	public static function convert_data_for_persistent_storage($data)
58
+	{
59
+		return $data;
60
+	}
61
+
62
+
63
+	/**
64
+	 * Data that has been stored in persistent storage that was prepped by _convert_data_for_persistent_storage
65
+	 * can be sent into this method and converted back into the format used for instantiating with this data handler.
66
+	 *
67
+	 * @param array $data
68
+	 *
69
+	 * @return array
70
+	 */
71
+	public static function convert_data_from_persistent_storage($data)
72
+	{
73
+		return $data;
74
+	}
75
+
76
+
77
+	/**
78
+	 * This will just setup the _events property in the expected format.
79
+	 *
80
+	 * @throws EE_Error
81
+	 * @throws ReflectionException
82
+	 */
83
+	private function _setup_attendees_events()
84
+	{
85
+
86
+		// setup some attendee objects
87
+		$attendees = $this->_get_some_attendees();
88
+
89
+		// if empty $data we'll do a query to get some events from the server.
90
+		// otherwise we'll retrieve the event data for the given ids.
91
+		$events = $this->_get_some_events($this->_data);
92
+
93
+		$answers_n_questions = $this->_get_some_q_and_as();
94
+
95
+		if (count($events) < 1) {
96
+			throw new EE_Error(
97
+				esc_html__(
98
+					'We can\'t generate a preview for you because there are no active events in your database',
99
+					'event_espresso'
100
+				)
101
+			);
102
+		}
103
+
104
+
105
+		// now let's loop and set up the _events property.  At the same time we'll set up attendee properties.
106
+		// we'll actually use the generated line_item identifiers for our loop
107
+		$dtts = $tkts = [];
108
+		foreach ($events as $id => $event) {
109
+			if (! $event instanceof EE_Event) {
110
+				continue;
111
+			}
112
+			$this->_events[ $id ]['ID']       = $id;
113
+			$this->_events[ $id ]['name']     = $event->get('EVT_name');
114
+			$datetime                         = $event->get_first_related('Datetime');
115
+			$tickets                          = $datetime instanceof EE_Datetime ? $datetime->get_many_related(
116
+				'Ticket',
117
+				['default_where_conditions' => 'none']
118
+			) : [];
119
+			$this->_events[ $id ]['event']    = $event;
120
+			$this->_events[ $id ]['reg_objs'] = [];
121
+			$this->_events[ $id ]['tkt_objs'] = $tickets;
122
+			$this->_events[ $id ]['dtt_objs'] = [];
123
+
124
+			$dttcache = [];
125
+			$tkts     = [];
126
+			foreach ($tickets as $ticket) {
127
+				if (! $ticket instanceof EE_Ticket) {
128
+					continue;
129
+				}
130
+				$reldatetime                       = $ticket->datetimes();
131
+				$tkts[ $ticket->ID() ]             = [];
132
+				$tkts[ $ticket->ID() ]['ticket']   = $ticket;
133
+				$tkts[ $ticket->ID() ]['dtt_objs'] = $reldatetime;
134
+				$tkts[ $ticket->ID() ]['att_objs'] = $attendees;
135
+				$tkts[ $ticket->ID() ]['count']    = count($attendees);
136
+				$tkts[ $ticket->ID() ]['EE_Event'] = $event;
137
+				foreach ($reldatetime as $datetime) {
138
+					if ($datetime instanceof EE_Datetime && ! isset($dtts[ $datetime->ID() ])) {
139
+						$this->_events[ $id ]['dtt_objs'][ $datetime->ID() ] = $datetime;
140
+						$dtts[ $datetime->ID() ]['datetime']                 = $datetime;
141
+						$dtts[ $datetime->ID() ]['tkt_objs'][]               = $ticket;
142
+						$dtts[ $datetime->ID() ]['evt_objs'][]               = $event;
143
+						$dttcache[ $datetime->ID() ]                         = $datetime;
144
+					}
145
+				}
146
+			}
147
+
148
+			$this->_events[ $id ]['total_attendees'] = count($attendees);
149
+			$this->_events[ $id ]['att_objs']        = $attendees;
150
+
151
+			// let's also setup the dummy attendees property!
152
+			foreach ($attendees as $att_key => $attendee) {
153
+				if (! $attendee instanceof EE_Attendee) {
154
+					continue;
155
+				}
156
+				$this->_attendees[ $att_key ]['line_ref'][] =
157
+					$id;  // so later it can be determined what events this attendee registered for!
158
+				$this->_attendees[ $att_key ]['evt_objs'][] = $event;
159
+				$this->_attendees[ $att_key ]['att_obj']    = $attendee;
160
+				// $this->_attendees[$att_key]['registration_id'] = 0;
161
+				$this->_attendees[ $att_key ]['attendee_email'] = $attendee->email();
162
+				$this->_attendees[ $att_key ]['tkt_objs']       = $tickets;
163
+				if ($att_key == 999999991) {
164
+					$this->_attendees[ $att_key ]['ans_objs'][999]  = $answers_n_questions['answers'][999];
165
+					$this->_attendees[ $att_key ]['ans_objs'][1002] = $answers_n_questions['answers'][1002];
166
+					$this->_attendees[ $att_key ]['ans_objs'][1005] = $answers_n_questions['answers'][1005];
167
+				} elseif ($att_key == 999999992) {
168
+					$this->_attendees[ $att_key ]['ans_objs'][1000] = $answers_n_questions['answers'][1000];
169
+					$this->_attendees[ $att_key ]['ans_objs'][1003] = $answers_n_questions['answers'][1003];
170
+					$this->_attendees[ $att_key ]['ans_objs'][1006] = $answers_n_questions['answers'][1006];
171
+				} elseif ($att_key == 999999993) {
172
+					$this->_attendees[ $att_key ]['ans_objs'][1001] = $answers_n_questions['answers'][1001];
173
+					$this->_attendees[ $att_key ]['ans_objs'][1004] = $answers_n_questions['answers'][1004];
174
+					$this->_attendees[ $att_key ]['ans_objs'][1007] = $answers_n_questions['answers'][1007];
175
+				}
176
+			}
177
+		}
178
+
179
+		$this->tickets            = $tkts;
180
+		$this->datetimes          = $dtts;
181
+		$this->answers            = $answers_n_questions['answers'];
182
+		$this->questions          = $answers_n_questions['questions'];
183
+		$this->total_ticket_count = count($tkts) * count($this->_attendees);
184
+	}
185
+
186
+
187
+	/**
188
+	 * This just returns an array of dummy attendee objects that we'll use to attach to events for our preview data
189
+	 *
190
+	 * @access private
191
+	 * @return array an array of attendee objects
192
+	 * @throws EE_Error
193
+	 * @throws EE_Error
194
+	 */
195
+	private function _get_some_attendees()
196
+	{
197
+		// let's just setup a dummy array of various attendee details
198
+		$dummy_attendees = [
199
+			0 => [
200
+				'Luke',
201
+				'Skywalker',
202
+				'[email protected]',
203
+				'804 Bantha Dr.',
204
+				'Complex 8',
205
+				'Mos Eisley',
206
+				32,
207
+				'US',
208
+				'f0r3e',
209
+				'222-333-4763',
210
+				false,
211
+				'999999991',
212
+			],
213
+			1 => [
214
+				'Princess',
215
+				'Leia',
216
+				'[email protected]',
217
+				'1456 Valley Way Boulevard',
218
+				'Suite 9',
219
+				'Alderaan',
220
+				15,
221
+				'US',
222
+				'c1h2c',
223
+				'78-123-111-1111',
224
+				false,
225
+				'999999992',
226
+			],
227
+			2 => [
228
+				'Yoda',
229
+				'I Am',
230
+				'[email protected]',
231
+				'4th Tree',
232
+				'5th Knot',
233
+				'Marsh',
234
+				22,
235
+				'US',
236
+				'l18n',
237
+				'999-999-9999',
238
+				false,
239
+				'999999993',
240
+			],
241
+		];
242
+
243
+		// let's generate the attendee objects
244
+		$attendees = [];
245
+		$var_array = [
246
+			'fname',
247
+			'lname',
248
+			'email',
249
+			'address',
250
+			'address2',
251
+			'city',
252
+			'staid',
253
+			'cntry',
254
+			'zip',
255
+			'phone',
256
+			'deleted',
257
+			'attid',
258
+		];
259
+
260
+		// EE_Registry::instance()->load_class( 'Attendee', array(), FALSE, false, TRUE );
261
+		foreach ($dummy_attendees as $dummy) {
262
+			$att = array_combine($var_array, $dummy);
263
+			extract($att);
264
+			/** @var $fname string */
265
+			/** @var $lname string */
266
+			/** @var $address string */
267
+			/** @var $address2 string */
268
+			/** @var $city string */
269
+			/** @var $staid string */
270
+			/** @var $cntry string */
271
+			/** @var $zip string */
272
+			/** @var $email string */
273
+			/** @var $phone string */
274
+			/** @var $attid string */
275
+			$attendees[ $attid ] = EE_Attendee::new_instance(
276
+				[
277
+					'ATT_fname'    => $fname,
278
+					'ATT_lname'    => $lname,
279
+					'ATT_address'  => $address,
280
+					'ATT_address2' => $address2,
281
+					'ATT_city'     => $city,
282
+					'STA_ID'       => $staid,
283
+					'CNT_ISO'      => $cntry,
284
+					'ATT_zip'      => $zip,
285
+					'ATT_email'    => $email,
286
+					'ATT_phone'    => $phone,
287
+					'ATT_ID'       => $attid,
288
+				]
289
+			);
290
+		}
291
+
292
+		return $attendees;
293
+	}
294
+
295
+
296
+	/**
297
+	 * Return an array of dummy question objects indexed by answer id and dummy answer objects indexed by answer id.
298
+	 * This will be used in our dummy data setup
299
+	 *
300
+	 * @return array
301
+	 * @throws EE_Error
302
+	 * @throws ReflectionException
303
+	 */
304
+	private function _get_some_q_and_as()
305
+	{
306
+		$quests_array = [
307
+			0 => [
308
+				555,
309
+				esc_html__('What is your favorite planet?', 'event_espresso'),
310
+				0,
311
+			],
312
+			1 => [
313
+				556,
314
+				esc_html__('What is your favorite food?', 'event_espresso'),
315
+				0,
316
+			],
317
+			2 => [
318
+				557,
319
+				esc_html__('How many lightyears have you travelled', 'event_espresso'),
320
+				0,
321
+			],
322
+		];
323
+
324
+		$ans_array = [
325
+			0 => [
326
+				999,
327
+				555,
328
+				'Tattoine',
329
+			],
330
+			1 => [
331
+				1000,
332
+				555,
333
+				'Alderaan',
334
+			],
335
+			2 => [
336
+				1001,
337
+				555,
338
+				'Dantooine',
339
+			],
340
+			3 => [
341
+				1002,
342
+				556,
343
+				'Fish Fingers',
344
+			],
345
+			4 => [
346
+				1003,
347
+				556,
348
+				'Sushi',
349
+			],
350
+			5 => [
351
+				1004,
352
+				556,
353
+				'Water',
354
+			],
355
+			6 => [
356
+				1005,
357
+				557,
358
+				'A lot',
359
+			],
360
+			7 => [
361
+				1006,
362
+				557,
363
+				"That's none of your business.",
364
+			],
365
+			8 => [
366
+				1007,
367
+				557,
368
+				"People less travel me then.",
369
+			],
370
+		];
371
+
372
+		$qst_columns = ['QST_ID', 'QST_display_text', 'QST_system'];
373
+		$ans_columns = ['ANS_ID', 'QST_ID', 'ANS_value'];
374
+
375
+		// EE_Registry::instance()->load_class( 'Question', array(), FALSE, TRUE, TRUE );
376
+		// EE_Registry::instance()->load_class( 'Answer', array(), FALSE, TRUE, TRUE );
377
+
378
+		$qsts = [];
379
+		// first the questions
380
+		foreach ($quests_array as $qst) {
381
+			$qstobj                    = array_combine($qst_columns, $qst);
382
+			$qsts[ $qstobj['QST_ID'] ] = EE_Question::new_instance($qstobj);
383
+		}
384
+
385
+		// now the answers (and we'll setup our arrays)
386
+		$q_n_as = [];
387
+		foreach ($ans_array as $ans) {
388
+			$ansobj                               = array_combine($ans_columns, $ans);
389
+			$ansobj                               = EE_Answer::new_instance($ansobj);
390
+			$q_n_as['answers'][ $ansobj->ID() ]   = $ansobj;
391
+			$q_n_as['questions'][ $ansobj->ID() ] = $qsts[ $ansobj->get('QST_ID') ];
392
+		}
393
+
394
+		return $q_n_as;
395
+	}
396
+
397
+
398
+	/**
399
+	 * Return an array of event objects from the database
400
+	 *
401
+	 * If event ids are not included then we'll just retrieve the first published event from the database.
402
+	 *
403
+	 * @param array $event_ids if set, this will be an array of event ids to obtain events for.
404
+	 *
405
+	 * @return array    An array of event objects from the db.
406
+	 * @throws EE_Error
407
+	 */
408
+	private function _get_some_events(array $event_ids = [])
409
+	{
410
+		/** @var RequestInterface $request */
411
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
412
+		// if we have an evt_id then we want to make sure we use that for the preview
413
+		// (because a specific event template is being viewed);
414
+		$event_ids = $request->getRequestParam('evt_id', $event_ids, 'int', true);
415
+		$limit     = ! empty($event_ids)
416
+			? null
417
+			: apply_filters('FHEE__EE_Messages_Preview_incoming_data___get_some_events__limit', '0,1');
418
+
419
+		$where = ! empty($event_ids)
420
+			? [
421
+				'EVT_ID'                 => ['IN', $event_ids],
422
+				'Datetime.Ticket.TKT_ID' => ['>', 1],
423
+			]
424
+			: ['Datetime.Ticket.TKT_ID' => ['>', 1]];
425
+
426
+		return EEM_Event::instance()->get_all([$where, 'limit' => $limit]);
427
+	}
428
+
429
+
430
+	/**
431
+	 * @throws EE_Error
432
+	 * @throws ReflectionException
433
+	 */
434
+	protected function _setup_data()
435
+	{
436
+		// need to figure out the running total for test purposes so... we're going to create a temp cart and add the tickets to it!
437
+		if (EE_Registry::instance()->SSN instanceof EE_Session) {
438
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
439
+			$session = EE_Registry::instance()->SSN;
440
+		} else {
441
+			$session = EE_Registry::instance()->load_core('Session');
442
+		}
443
+		$cart = EE_Cart::instance(null, $session);
444
+
445
+		// add tickets to cart
446
+		foreach ($this->tickets as $ticket) {
447
+			$cart->add_ticket_to_cart($ticket['ticket']);
448
+		}
449
+
450
+		// setup txn property
451
+		$this->txn = EE_Transaction::new_instance(
452
+			[
453
+				'TXN_timestamp'    => time(), // unix timestamp
454
+				'TXN_total'        => 0, // txn_total
455
+				'TXN_paid'         => 0, // txn_paid
456
+				'STS_ID'           => EEM_Transaction::incomplete_status_code, // sts_id
457
+				'TXN_session_data' => null, // dump of txn session object (we're just going to leave blank here)
458
+				'TXN_hash_salt'    => null, // hash salt blank as well
459
+				'TXN_ID'           => 999999,
460
+			]
461
+		);
462
+
463
+
464
+		// setup reg_objects
465
+		// note we're setting up a reg object for each attendee in each event but ALSO adding to the reg_object array.
466
+		$this->reg_objs = [];
467
+		$regid          = 9999990;
468
+		foreach ($this->_attendees as $key => $attendee) {
469
+			// note we need to setup reg_objects for each event this attendee belongs to
470
+			$regatt = $attendee['att_obj'] instanceof EE_Attendee ? $attendee['att_obj']->ID() : null;
471
+			$regtxn = $this->txn->ID();
472
+			$regcnt = 1;
473
+			foreach ($attendee['line_ref'] as $evtid) {
474
+				foreach ($this->_events[ $evtid ]['tkt_objs'] as $ticket) {
475
+					if (! $ticket instanceof EE_Ticket) {
476
+						continue;
477
+					}
478
+					$reg_array                                            = [
479
+						'EVT_ID'           => $evtid,
480
+						'ATT_ID'           => $regatt,
481
+						'TXN_ID'           => $regtxn,
482
+						'TKT_ID'           => $ticket->ID(),
483
+						'STS_ID'           => EEM_Registration::status_id_pending_payment,
484
+						'REG_date'         => time(),
485
+						'REG_final_price'  => $ticket->get('TKT_price'),
486
+						'REG_session'      => 'dummy_session_id',
487
+						'REG_code'         => $regid . '-dummy-generated-code',
488
+						'REG_url_link'     => $regcnt . '-daafpapasdlfakasdfpqasdfasdf',
489
+						'REG_count'        => $regcnt,
490
+						'REG_group_size'   => $this->_events[ $evtid ]['total_attendees'],
491
+						'REG_att_is_going' => true,
492
+						'REG_ID'           => $regid,
493
+					];
494
+					$REG_OBJ                                              = EE_Registration::new_instance($reg_array);
495
+					$this->_attendees[ $key ]['reg_objs'][ $regid ]       = $REG_OBJ;
496
+					$this->_events[ $evtid ]['reg_objs'][]                = $REG_OBJ;
497
+					$this->reg_objs[]                                     = $REG_OBJ;
498
+					$this->tickets[ $ticket->ID() ]['reg_objs'][ $regid ] = $REG_OBJ;
499
+
500
+					$regcnt++;
501
+					$regid++;
502
+				}
503
+			}
504
+		}
505
+
506
+
507
+		// setup line items!
508
+		$line_item_total = EEH_Line_Item::create_total_line_item($this->txn);
509
+
510
+		// add tickets
511
+		foreach ($this->tickets as $item) {
512
+			$qty    = $item['count'];
513
+			$ticket = $item['ticket'];
514
+			EEH_Line_Item::add_ticket_purchase($line_item_total, $ticket, $qty);
515
+		}
516
+
517
+		$shipping_line_item = EE_Line_Item::new_instance(
518
+			[
519
+				'LIN_name'       => esc_html__(
520
+					'Shipping Surcharge',
521
+					'event_espresso'
522
+				),
523
+				'LIN_desc'       => esc_html__(
524
+					'Sent via Millenium Falcon',
525
+					'event_espresso'
526
+				),
527
+				'LIN_unit_price' => 20,
528
+				'LIN_quantity'   => 1,
529
+				'LIN_is_taxable' => true,
530
+				'LIN_total'      => 20,
531
+				'LIN_type'       => EEM_Line_Item::type_line_item,
532
+			]
533
+		);
534
+		EEH_Line_Item::add_item($line_item_total, $shipping_line_item);
535
+		$this->additional_line_items = [$shipping_line_item];
536
+
537
+		// now let's add taxes
538
+		EEH_Line_Item::apply_taxes($line_item_total);
539
+
540
+		// now we should be able to get the items we need from this object
541
+		$event_line_items = EEH_Line_Item::get_pre_tax_subtotal($line_item_total)->children();
542
+		$line_items       = [];
543
+		foreach ($event_line_items as $line_item) {
544
+			if (! $line_item instanceof EE_Line_Item || $line_item->OBJ_type() !== 'Event') {
545
+				continue;
546
+			}
547
+			$ticket_line_items = EEH_Line_Item::get_ticket_line_items($line_item);
548
+			foreach ($ticket_line_items as $ticket_line_item) {
549
+				if (! $ticket_line_item instanceof EE_Line_Item) {
550
+					continue;
551
+				}
552
+				$this->tickets[ $ticket_line_item->OBJ_ID() ]['line_item']      = $ticket_line_item;
553
+				$this->tickets[ $ticket_line_item->OBJ_ID() ]['sub_line_items'] = $ticket_line_item->children();
554
+				$line_items[ $ticket_line_item->ID() ]['children']              = $ticket_line_item->children();
555
+				$line_items[ $ticket_line_item->ID() ]['EE_Ticket']             =
556
+					$this->tickets[ $ticket_line_item->OBJ_ID() ]['ticket'];
557
+			}
558
+		}
559
+
560
+		$this->line_items_with_children = $line_items;
561
+		$this->tax_line_items           = $line_item_total->tax_descendants();
562
+
563
+		// add proper total to transaction object.
564
+		$grand_total                 = $line_item_total->recalculate_total_including_taxes();
565
+		$this->grand_total_line_item = $line_item_total;
566
+		$this->txn->set_total($grand_total);
567
+
568
+
569
+		// add additional details for each registration
570
+		foreach ($this->reg_objs as $reg) {
571
+			if (! $reg instanceof EE_Registration) {
572
+				continue;
573
+			}
574
+			$this->_registrations[ $reg->ID() ]['tkt_obj']  = $this->tickets[ $reg->get('TKT_ID') ]['ticket'];
575
+			$this->_registrations[ $reg->ID() ]['evt_obj']  = $this->_events[ $reg->get('EVT_ID') ]['event'];
576
+			$this->_registrations[ $reg->ID() ]['reg_obj']  = $reg;
577
+			$this->_registrations[ $reg->ID() ]['ans_objs'] = $this->_attendees[ $reg->get('ATT_ID') ]['ans_objs'];
578
+			$this->_registrations[ $reg->ID() ]['att_obj']  = $this->_attendees[ $reg->get('ATT_ID') ]['att_obj'];
579
+			$this->_registrations[ $reg->ID() ]['dtt_objs'] = $this->tickets[ $reg->get('TKT_ID') ]['dtt_objs'];
580
+		}
581
+
582
+
583
+		// events and attendees
584
+		$this->events        = $this->_events;
585
+		$this->attendees     = $this->_attendees;
586
+		$this->registrations = $this->_registrations;
587
+
588
+		$attendees_to_shift = $this->_attendees;
589
+
590
+		// setup primary attendee property
591
+		$this->primary_attendee_data = [
592
+			'fname' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
593
+				? $this->_attendees[999999991]['att_obj']->fname()
594
+				: '',
595
+
596
+			'lname' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
597
+				? $this->_attendees[999999991]['att_obj']->lname()
598
+				: '',
599
+
600
+			'email' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
601
+				? $this->_attendees[999999991]['att_obj']->email()
602
+				: '',
603
+
604
+			'att_obj' => $this->_attendees[999999991]['att_obj'],
605
+
606
+			'reg_obj' => array_shift($attendees_to_shift[999999991]['reg_objs']),
607
+		];
608
+
609
+		// reg_info property
610
+		// note this isn't referenced by any shortcode parsers so we'll ignore for now.
611
+		$this->reg_info = [];
612
+
613
+		// let's set a reg_obj for messengers expecting one.
614
+		$this->reg_obj = array_shift($this->_attendees[999999991]['reg_objs']);
615
+
616
+		// the below are just dummy items.
617
+		$this->user_id     = 1;
618
+		$this->ip_address  = '192.0.2.1';
619
+		$this->user_agent  = '';
620
+		$this->init_access = time();
621
+		$this->last_access = time();
622
+	}
623 623
 }
Please login to merge, or discard this patch.
core/libraries/messages/EE_Messages_Processor.lib.php 1 patch
Indentation   +587 added lines, -587 removed lines patch added patch discarded remove patch
@@ -16,595 +16,595 @@
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * @type EE_Message_Resource_Manager $_message_resource_manager
21
-     */
22
-    protected $_message_resource_manager;
23
-
24
-    /**
25
-     * @type EE_Messages_Queue
26
-     */
27
-    protected $_queue;
28
-
29
-    /**
30
-     * @type  EE_Messages_Generator
31
-     */
32
-    protected $_generator;
33
-
34
-
35
-
36
-
37
-    /**
38
-     * constructor
39
-     *
40
-     * @param EE_Message_Resource_Manager $message_resource_manager
41
-     */
42
-    public function __construct(EE_Message_Resource_Manager $message_resource_manager)
43
-    {
44
-        $this->_message_resource_manager = $message_resource_manager;
45
-        $this->_init_queue_and_generator();
46
-    }
47
-
48
-
49
-
50
-
51
-    /**
52
-     * This method sets (or resets) the various properties for use.
53
-     *
54
-     * - $_queue = holds the messages queue
55
-     * - $_generator = holds the messages generator
56
-     */
57
-    protected function _init_queue_and_generator()
58
-    {
59
-        $this->_generator = EE_Registry::factory('EE_Messages_Generator');
60
-        $this->_queue = $this->_generator->generation_queue();
61
-    }
62
-
63
-
64
-
65
-
66
-    /**
67
-     * This returns the current set queue.
68
-     * @return EE_Messages_Queue
69
-     */
70
-    public function get_queue()
71
-    {
72
-        return $this->_queue;
73
-    }
74
-
75
-
76
-    /**
77
-     * This method can be utilized to process messages from a queue and they will be processed immediately on the same
78
-     * request. Please note that this method alone does not bypass the usual "locks" for generation/sending (it assumes
79
-     * client code has already filtered those if necessary).
80
-     *
81
-     * @param EE_Messages_Queue $queue_to_process
82
-     * @return bool  true for success false for error.
83
-     * @throws EE_Error
84
-     * @throws EE_Error
85
-     */
86
-    public function process_immediately_from_queue(EE_Messages_Queue $queue_to_process)
87
-    {
88
-        $success = false;
89
-        $messages_to_send = array();
90
-        $messages_to_generate = array();
91
-        // loop through and setup the various messages from the queue so we know what is being processed
92
-        $queue_to_process->get_message_repository()->rewind();
93
-        foreach ($queue_to_process->get_message_repository() as $message) {
94
-            if ($message->STS_ID() === EEM_Message::status_incomplete) {
95
-                $messages_to_generate[] = $message;
96
-                continue;
97
-            }
98
-
99
-            if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
100
-                $messages_to_send[] = $message;
101
-                continue;
102
-            }
103
-        }
104
-
105
-        // do generation/sends
106
-        if ($messages_to_generate) {
107
-            $success = $this->batch_generate_from_queue($messages_to_generate, true);
108
-        }
109
-
110
-        if ($messages_to_send) {
111
-            $sent = $this->batch_send_from_queue($messages_to_send, true);
112
-            // if there was messages to generate and it failed, then we override any success value for the sending process
113
-            // otherwise we just use the return from batch send.  The intent is that there is a simple response for success/fail.
114
-            // Either everything was successful or we consider it a fail.  To be clear, this is a limitation of doing
115
-            // all messages processing on the same request.
116
-            $success = $messages_to_generate && ! $success ? false : $sent;
117
-        }
118
-        return $success;
119
-    }
120
-
121
-
122
-    /**
123
-     * Calls the EE_Messages_Queue::get_batch_to_generate() method and sends to EE_Messages_Generator.
124
-     *
125
-     * @param  EE_Message[] $messages    Array of EE_Message objects (optional) to build the queue with.
126
-     * @param  bool         $clear_queue Whether to ensure a fresh queue or not.
127
-     *
128
-     * @return bool|EE_Messages_Queue return false if nothing generated.  This returns a new EE_Message_Queue with
129
-     *                                   generated messages.
130
-     */
131
-    public function batch_generate_from_queue($messages = array(), $clear_queue = false)
132
-    {
133
-        if ($this->_build_queue_for_generation($messages, $clear_queue)) {
134
-            $new_queue = $this->_generator->generate();
135
-            if ($new_queue instanceof EE_Messages_Queue) {
136
-                // unlock queue
137
-                $this->_queue->unlock_queue();
138
-                $new_queue->initiate_request_by_priority('send');
139
-                return $new_queue;
140
-            }
141
-        }
142
-        $this->_queue->unlock_queue();
143
-        return false;
144
-    }
145
-
146
-
147
-
148
-    /**
149
-     * This method preps a queue for generation.
150
-     *
151
-     * @since    4.9.0
152
-     *
153
-     * @param EE_Message[] $messages    Array of EE_Message objects to build the queue with
154
-     *
155
-     * @param   bool       $clear_queue This indicates whether the existing queue should be dumped or not.
156
-     *
157
-     * @return bool true means queue prepped, false means there was a lock so no generation please.
158
-     */
159
-    protected function _build_queue_for_generation($messages = array(), $clear_queue = false)
160
-    {
161
-
162
-        if ($clear_queue) {
163
-            $this->_init_queue_and_generator();
164
-        }
165
-
166
-        if ($messages) {
167
-            // if generation is locked then get out now because that means processing is already happening.
168
-            if ($this->_queue->is_locked()) {
169
-                return false;
170
-            }
171
-
172
-            $this->_queue->lock_queue();
173
-            $messages = is_array($messages) ? $messages : array( $messages );
174
-            foreach ($messages as $message) {
175
-                if ($message instanceof EE_Message) {
176
-                    $data = $message->all_extra_meta_array();
177
-                    $this->_queue->add($message, $data);
178
-                }
179
-            }
180
-            return true;
181
-        } else {
182
-            return $this->_queue->get_batch_to_generate();
183
-        }
184
-    }
185
-
186
-
187
-    /**
188
-     * This method preps a queue for sending.
189
-     *
190
-     * @param EE_Message[] $messages
191
-     * @param bool  $clear_queue Used to indicate whether to start with a fresh queue or not.
192
-     *
193
-     * @return bool true means queue prepped, false means there was a lock so no queue prepped.
194
-     */
195
-    protected function _build_queue_for_sending($messages, $clear_queue = false)
196
-    {
197
-        // if sending is locked then get out now because that means processing is already happening.
198
-        if ($this->_queue->is_locked(EE_Messages_Queue::action_sending)) {
199
-            return false;
200
-        }
201
-
202
-        $this->_queue->lock_queue(EE_Messages_Queue::action_sending);
203
-
204
-        if ($clear_queue) {
205
-            $this->_init_queue_and_generator();
206
-        }
207
-
208
-        $messages = is_array($messages) ? $messages : array( $messages );
209
-
210
-        foreach ($messages as $message) {
211
-            $this->_queue->add($message);
212
-        }
213
-        return true;
214
-    }
215
-
216
-
217
-    /**
218
-     * Calls the EE_Message_Queue::get_to_send_batch_and_send() method and then immediately just calls EE_Message_Queue::execute()
219
-     * to iterate and send unsent messages.
220
-     *
221
-     * @param EE_Message[] $messages    If an array of messages is sent in then use it.
222
-     *
223
-     * @param bool         $clear_queue Whether to initialize a new queue or keep the existing one.
224
-     *
225
-     * @return EE_Messages_Queue
226
-     */
227
-    public function batch_send_from_queue($messages = array(), $clear_queue = false)
228
-    {
229
-
230
-        if ($messages && $this->_build_queue_for_sending($messages, $clear_queue)) {
231
-            $this->_queue->execute();
232
-            $this->_queue->unlock_queue(EE_Messages_Queue::action_sending);
233
-        } else {
234
-            // get messages to send and execute.
235
-            $this->_queue->get_to_send_batch_and_send();
236
-        }
237
-        // note: callers can use the EE_Messages_Queue::count_STS_in_queue() method to find out if there were any failed
238
-        // messages in the queue and decide how to handle at that point.
239
-        return $this->_queue;
240
-    }
241
-
242
-
243
-
244
-
245
-
246
-
247
-    /**
248
-     * This immediately generates messages using the given array of EE_Message_To_Generate objects and returns the
249
-     * EE_Message_Queue with the generated messages for the caller to work with.  Note, this does NOT save the generated
250
-     * messages in the queue, leaving it up to the caller to do so.
251
-     *
252
-     * @param EE_Message_To_Generate[] $messages_to_generate
253
-     * @return EE_Messages_Queue
254
-     */
255
-    public function generate_and_return($messages_to_generate)
256
-    {
257
-        $this->_init_queue_and_generator();
258
-        $this->_queue_for_generation_loop($messages_to_generate);
259
-        return $this->_generator->generate(false);
260
-    }
261
-
262
-
263
-
264
-
265
-    /**
266
-     * Executes the generator generate method on the current internal queue, and returns the generated queue.
267
-     * @param  bool     $persist    Indicate whether to instruct the generator to persist the generated queue (true) or not (false).
268
-     * @return EE_Messages_Queue
269
-     */
270
-    public function generate_queue($persist = true)
271
-    {
272
-        return $this->_generator->generate($persist);
273
-    }
19
+	/**
20
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
21
+	 */
22
+	protected $_message_resource_manager;
23
+
24
+	/**
25
+	 * @type EE_Messages_Queue
26
+	 */
27
+	protected $_queue;
28
+
29
+	/**
30
+	 * @type  EE_Messages_Generator
31
+	 */
32
+	protected $_generator;
33
+
34
+
35
+
36
+
37
+	/**
38
+	 * constructor
39
+	 *
40
+	 * @param EE_Message_Resource_Manager $message_resource_manager
41
+	 */
42
+	public function __construct(EE_Message_Resource_Manager $message_resource_manager)
43
+	{
44
+		$this->_message_resource_manager = $message_resource_manager;
45
+		$this->_init_queue_and_generator();
46
+	}
47
+
48
+
49
+
50
+
51
+	/**
52
+	 * This method sets (or resets) the various properties for use.
53
+	 *
54
+	 * - $_queue = holds the messages queue
55
+	 * - $_generator = holds the messages generator
56
+	 */
57
+	protected function _init_queue_and_generator()
58
+	{
59
+		$this->_generator = EE_Registry::factory('EE_Messages_Generator');
60
+		$this->_queue = $this->_generator->generation_queue();
61
+	}
62
+
63
+
64
+
65
+
66
+	/**
67
+	 * This returns the current set queue.
68
+	 * @return EE_Messages_Queue
69
+	 */
70
+	public function get_queue()
71
+	{
72
+		return $this->_queue;
73
+	}
74
+
75
+
76
+	/**
77
+	 * This method can be utilized to process messages from a queue and they will be processed immediately on the same
78
+	 * request. Please note that this method alone does not bypass the usual "locks" for generation/sending (it assumes
79
+	 * client code has already filtered those if necessary).
80
+	 *
81
+	 * @param EE_Messages_Queue $queue_to_process
82
+	 * @return bool  true for success false for error.
83
+	 * @throws EE_Error
84
+	 * @throws EE_Error
85
+	 */
86
+	public function process_immediately_from_queue(EE_Messages_Queue $queue_to_process)
87
+	{
88
+		$success = false;
89
+		$messages_to_send = array();
90
+		$messages_to_generate = array();
91
+		// loop through and setup the various messages from the queue so we know what is being processed
92
+		$queue_to_process->get_message_repository()->rewind();
93
+		foreach ($queue_to_process->get_message_repository() as $message) {
94
+			if ($message->STS_ID() === EEM_Message::status_incomplete) {
95
+				$messages_to_generate[] = $message;
96
+				continue;
97
+			}
98
+
99
+			if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
100
+				$messages_to_send[] = $message;
101
+				continue;
102
+			}
103
+		}
104
+
105
+		// do generation/sends
106
+		if ($messages_to_generate) {
107
+			$success = $this->batch_generate_from_queue($messages_to_generate, true);
108
+		}
109
+
110
+		if ($messages_to_send) {
111
+			$sent = $this->batch_send_from_queue($messages_to_send, true);
112
+			// if there was messages to generate and it failed, then we override any success value for the sending process
113
+			// otherwise we just use the return from batch send.  The intent is that there is a simple response for success/fail.
114
+			// Either everything was successful or we consider it a fail.  To be clear, this is a limitation of doing
115
+			// all messages processing on the same request.
116
+			$success = $messages_to_generate && ! $success ? false : $sent;
117
+		}
118
+		return $success;
119
+	}
120
+
121
+
122
+	/**
123
+	 * Calls the EE_Messages_Queue::get_batch_to_generate() method and sends to EE_Messages_Generator.
124
+	 *
125
+	 * @param  EE_Message[] $messages    Array of EE_Message objects (optional) to build the queue with.
126
+	 * @param  bool         $clear_queue Whether to ensure a fresh queue or not.
127
+	 *
128
+	 * @return bool|EE_Messages_Queue return false if nothing generated.  This returns a new EE_Message_Queue with
129
+	 *                                   generated messages.
130
+	 */
131
+	public function batch_generate_from_queue($messages = array(), $clear_queue = false)
132
+	{
133
+		if ($this->_build_queue_for_generation($messages, $clear_queue)) {
134
+			$new_queue = $this->_generator->generate();
135
+			if ($new_queue instanceof EE_Messages_Queue) {
136
+				// unlock queue
137
+				$this->_queue->unlock_queue();
138
+				$new_queue->initiate_request_by_priority('send');
139
+				return $new_queue;
140
+			}
141
+		}
142
+		$this->_queue->unlock_queue();
143
+		return false;
144
+	}
145
+
146
+
147
+
148
+	/**
149
+	 * This method preps a queue for generation.
150
+	 *
151
+	 * @since    4.9.0
152
+	 *
153
+	 * @param EE_Message[] $messages    Array of EE_Message objects to build the queue with
154
+	 *
155
+	 * @param   bool       $clear_queue This indicates whether the existing queue should be dumped or not.
156
+	 *
157
+	 * @return bool true means queue prepped, false means there was a lock so no generation please.
158
+	 */
159
+	protected function _build_queue_for_generation($messages = array(), $clear_queue = false)
160
+	{
161
+
162
+		if ($clear_queue) {
163
+			$this->_init_queue_and_generator();
164
+		}
165
+
166
+		if ($messages) {
167
+			// if generation is locked then get out now because that means processing is already happening.
168
+			if ($this->_queue->is_locked()) {
169
+				return false;
170
+			}
171
+
172
+			$this->_queue->lock_queue();
173
+			$messages = is_array($messages) ? $messages : array( $messages );
174
+			foreach ($messages as $message) {
175
+				if ($message instanceof EE_Message) {
176
+					$data = $message->all_extra_meta_array();
177
+					$this->_queue->add($message, $data);
178
+				}
179
+			}
180
+			return true;
181
+		} else {
182
+			return $this->_queue->get_batch_to_generate();
183
+		}
184
+	}
185
+
186
+
187
+	/**
188
+	 * This method preps a queue for sending.
189
+	 *
190
+	 * @param EE_Message[] $messages
191
+	 * @param bool  $clear_queue Used to indicate whether to start with a fresh queue or not.
192
+	 *
193
+	 * @return bool true means queue prepped, false means there was a lock so no queue prepped.
194
+	 */
195
+	protected function _build_queue_for_sending($messages, $clear_queue = false)
196
+	{
197
+		// if sending is locked then get out now because that means processing is already happening.
198
+		if ($this->_queue->is_locked(EE_Messages_Queue::action_sending)) {
199
+			return false;
200
+		}
201
+
202
+		$this->_queue->lock_queue(EE_Messages_Queue::action_sending);
203
+
204
+		if ($clear_queue) {
205
+			$this->_init_queue_and_generator();
206
+		}
207
+
208
+		$messages = is_array($messages) ? $messages : array( $messages );
209
+
210
+		foreach ($messages as $message) {
211
+			$this->_queue->add($message);
212
+		}
213
+		return true;
214
+	}
215
+
216
+
217
+	/**
218
+	 * Calls the EE_Message_Queue::get_to_send_batch_and_send() method and then immediately just calls EE_Message_Queue::execute()
219
+	 * to iterate and send unsent messages.
220
+	 *
221
+	 * @param EE_Message[] $messages    If an array of messages is sent in then use it.
222
+	 *
223
+	 * @param bool         $clear_queue Whether to initialize a new queue or keep the existing one.
224
+	 *
225
+	 * @return EE_Messages_Queue
226
+	 */
227
+	public function batch_send_from_queue($messages = array(), $clear_queue = false)
228
+	{
229
+
230
+		if ($messages && $this->_build_queue_for_sending($messages, $clear_queue)) {
231
+			$this->_queue->execute();
232
+			$this->_queue->unlock_queue(EE_Messages_Queue::action_sending);
233
+		} else {
234
+			// get messages to send and execute.
235
+			$this->_queue->get_to_send_batch_and_send();
236
+		}
237
+		// note: callers can use the EE_Messages_Queue::count_STS_in_queue() method to find out if there were any failed
238
+		// messages in the queue and decide how to handle at that point.
239
+		return $this->_queue;
240
+	}
241
+
242
+
243
+
244
+
245
+
246
+
247
+	/**
248
+	 * This immediately generates messages using the given array of EE_Message_To_Generate objects and returns the
249
+	 * EE_Message_Queue with the generated messages for the caller to work with.  Note, this does NOT save the generated
250
+	 * messages in the queue, leaving it up to the caller to do so.
251
+	 *
252
+	 * @param EE_Message_To_Generate[] $messages_to_generate
253
+	 * @return EE_Messages_Queue
254
+	 */
255
+	public function generate_and_return($messages_to_generate)
256
+	{
257
+		$this->_init_queue_and_generator();
258
+		$this->_queue_for_generation_loop($messages_to_generate);
259
+		return $this->_generator->generate(false);
260
+	}
261
+
262
+
263
+
264
+
265
+	/**
266
+	 * Executes the generator generate method on the current internal queue, and returns the generated queue.
267
+	 * @param  bool     $persist    Indicate whether to instruct the generator to persist the generated queue (true) or not (false).
268
+	 * @return EE_Messages_Queue
269
+	 */
270
+	public function generate_queue($persist = true)
271
+	{
272
+		return $this->_generator->generate($persist);
273
+	}
274 274
 
275 275
 
276 276
 
277 277
 
278
-    /**
279
-     * Queue for generation.  Note this does NOT persist to the db.  Client code should call get_message_repository()->save() if desire
280
-     * to persist.  This method is provided to client code to decide what it wants to do with queued messages for generation.
281
-     * @param EE_Message_To_Generate $message_to_generate
282
-     * @param bool                   $test_send             Whether this item is for a test send or not.
283
-     * @return  EE_Messages_Queue
284
-     */
285
-    public function queue_for_generation(EE_Message_To_Generate $message_to_generate, $test_send = false)
286
-    {
287
-        if ($message_to_generate->valid()) {
288
-            $this->_generator->create_and_add_message_to_queue($message_to_generate, $test_send);
289
-        }
290
-    }
291
-
292
-
293
-
294
-
295
-
296
-
297
-
298
-    /**
299
-     * This receives an array of EE_Message_To_Generate objects, converts them to EE_Message adds them to the generation queue
300
-     * and then persists to storage.
301
-     *
302
-     * @param EE_Message_To_Generate[] $messages_to_generate
303
-     */
304
-    public function batch_queue_for_generation_and_persist($messages_to_generate)
305
-    {
306
-        $this->_init_queue_and_generator();
307
-        $this->_queue_for_generation_loop($messages_to_generate);
308
-        $this->_queue->save();
309
-    }
310
-
311
-
312
-
313
-
314
-
315
-
316
-    /**
317
-     * This receives an array of EE_Message_To_Generate objects, converts them to EE_Message and adds them to the generation
318
-     * queue.  Does NOT persist to storage (unless there is an error.
319
-     * Client code can retrieve the generated queue by calling EEM_Messages_Processor::get_queue()
320
-     *
321
-     * @param EE_Message_To_Generate[]  $messages_to_generate
322
-     */
323
-    public function batch_queue_for_generation_no_persist($messages_to_generate)
324
-    {
325
-        $this->_init_queue_and_generator();
326
-        $this->_queue_for_generation_loop($messages_to_generate);
327
-    }
328
-
329
-
330
-
331
-
332
-    /**
333
-     * Simply loops through the given array of EE_Message_To_Generate objects and adds them to the _queue as EE_Message
334
-     * objects.
335
-     *
336
-     * @param EE_Message_To_Generate[] $messages_to_generate
337
-     */
338
-    protected function _queue_for_generation_loop($messages_to_generate)
339
-    {
340
-        // make sure is in an array.
341
-        if (! is_array($messages_to_generate)) {
342
-            $messages_to_generate = array( $messages_to_generate );
343
-        }
344
-
345
-        foreach ($messages_to_generate as $message_to_generate) {
346
-            if ($message_to_generate instanceof EE_Message_To_Generate && $message_to_generate->valid()) {
347
-                $this->queue_for_generation($message_to_generate);
348
-            }
349
-        }
350
-    }
351
-
352
-
353
-
354
-
355
-
356
-    /**
357
-     * Receives an array of EE_Message_To_Generate objects and generates the EE_Message objects, then persists (so its
358
-     * queued for sending).
359
-     * @param  EE_Message_To_Generate[]
360
-     * @return EE_Messages_Queue
361
-     */
362
-    public function generate_and_queue_for_sending($messages_to_generate)
363
-    {
364
-        $this->_init_queue_and_generator();
365
-        $this->_queue_for_generation_loop($messages_to_generate);
366
-        return $this->_generator->generate(true);
367
-    }
368
-
369
-
370
-
371
-
372
-
373
-    /**
374
-     * Generate for preview and execute right away.
375
-     *
376
-     * @param   EE_Message_To_Generate $message_to_generate
377
-     * @param   bool                   $test_send                Whether this is a test send or not.
378
-     * @return  EE_Messages_Queue | bool   false if unable to generate otherwise the generated queue.
379
-     */
380
-    public function generate_for_preview(EE_Message_To_Generate $message_to_generate, $test_send = false)
381
-    {
382
-        if (! $message_to_generate->valid()) {
383
-            EE_Error::add_error(
384
-                esc_html__('Unable to generate preview because of invalid data', 'event_espresso'),
385
-                __FILE__,
386
-                __FUNCTION__,
387
-                __LINE__
388
-            );
389
-            return false;
390
-        }
391
-        // just make sure preview is set on the $message_to_generate (in case client forgot)
392
-        $message_to_generate->set_preview(true);
393
-        $this->_init_queue_and_generator();
394
-        $this->queue_for_generation($message_to_generate, $test_send);
395
-        $generated_queue = $this->_generator->generate(false);
396
-        if ($generated_queue->execute(false)) {
397
-            // the first queue item should be the preview
398
-            $generated_queue->get_message_repository()->rewind();
399
-            if (! $generated_queue->get_message_repository()->valid()) {
400
-                return $generated_queue;
401
-            }
402
-            return $generated_queue;
403
-        } else {
404
-            return false;
405
-        }
406
-    }
407
-
408
-
409
-    /**
410
-     * This queues for sending.
411
-     * The messenger send now method is also verified to see if sending immediately is requested.
412
-     * otherwise its just saved to the queue.
413
-     *
414
-     * @param EE_Message_To_Generate $message_to_generate
415
-     * @return bool true or false for success.
416
-     * @throws EE_Error
417
-     * @throws EE_Error
418
-     */
419
-    public function queue_for_sending(EE_Message_To_Generate $message_to_generate)
420
-    {
421
-        if (! $message_to_generate->valid()) {
422
-            return false;
423
-        }
424
-        $this->_init_queue_and_generator();
425
-        $message = $message_to_generate->get_EE_Message();
426
-        $this->_queue->add($message);
427
-        if ($message->send_now()) {
428
-            $this->_queue->execute(false);
429
-        } else {
430
-            $this->_queue->save();
431
-        }
432
-        return true;
433
-    }
434
-
435
-
436
-    /**
437
-     * This generates and sends from the given EE_Message_To_Generate class immediately.
438
-     * @param EE_Message_To_Generate $message_to_generate
439
-     * @return EE_Messages_Queue | null
440
-     */
441
-    public function generate_and_send_now(EE_Message_To_Generate $message_to_generate)
442
-    {
443
-        if (! $message_to_generate->valid()) {
444
-            return null;
445
-        }
446
-        // is there supposed to be a sending messenger for this message?
447
-        if ($message_to_generate instanceof EEI_Has_Sending_Messenger) {
448
-            // make sure it's valid, but if it's not,
449
-            // then set the value of $sending_messenger to an EE_Error object
450
-            // so that downstream code can easily see that things went wrong.
451
-            $sending_messenger = $message_to_generate->sending_messenger() instanceof EE_messenger
452
-                ? $message_to_generate->sending_messenger()
453
-                : new EE_Error(
454
-                    esc_html__(
455
-                        'There was a specific sending messenger requested for the send action, but it was either invalid or not active at time of sending.',
456
-                        'event_espresso'
457
-                    )
458
-                );
459
-        } else {
460
-            $sending_messenger = null;
461
-        }
462
-
463
-        if ($message_to_generate->get_EE_Message()->STS_ID() === EEM_Message::status_idle) {
464
-            $this->_init_queue_and_generator();
465
-            $this->_queue->add($message_to_generate->get_EE_Message());
466
-            $this->_queue->execute(false, $sending_messenger);
467
-            return $this->_queue;
468
-        } elseif ($message_to_generate->get_EE_Message()->STS_ID() === EEM_Message::status_incomplete) {
469
-            $generated_queue = $this->generate_and_return(array( $message_to_generate ));
470
-            $generated_queue->execute(false, $sending_messenger);
471
-            return $generated_queue;
472
-        }
473
-        return null;
474
-    }
475
-
476
-
477
-
478
-
479
-    /**
480
-     * Creates mtg objects for all active messengers and queues for generation.
481
-     * This method also calls the execute by priority method on the queue which will optionally kick off a new non-blocking
482
-     * request to complete the action if the priority for the message requires immediate action.
483
-     * @param string $message_type
484
-     * @param mixed  $data   The data being used for generation.
485
-     * @param bool   $persist   Whether to persist the queued messages to the db or not.
486
-     */
487
-    public function generate_for_all_active_messengers($message_type, $data, $persist = true)
488
-    {
489
-        $messages_to_generate = $this->setup_mtgs_for_all_active_messengers($message_type, $data);
490
-        if ($persist) {
491
-            $this->batch_queue_for_generation_and_persist($messages_to_generate);
492
-            $this->_queue->initiate_request_by_priority();
493
-        } else {
494
-            $this->batch_queue_for_generation_no_persist($messages_to_generate);
495
-        }
496
-    }
497
-
498
-
499
-
500
-
501
-    /**
502
-     * This simply loops through all active messengers and takes care of setting up the
503
-     * EE_Message_To_Generate objects.
504
-     * @param $message_type
505
-     * @param $data
506
-     *
507
-     * @return EE_Message_To_Generate[]
508
-     */
509
-    public function setup_mtgs_for_all_active_messengers($message_type, $data)
510
-    {
511
-        $messages_to_generate = array();
512
-        foreach ($this->_message_resource_manager->active_messengers() as $messenger_slug => $messenger_object) {
513
-            $message_to_generate = new EE_Message_To_Generate($messenger_slug, $message_type, $data);
514
-            if ($message_to_generate->valid()) {
515
-                $messages_to_generate[] = $message_to_generate;
516
-            }
517
-        }
518
-        return $messages_to_generate;
519
-    }
520
-
521
-
522
-    /**
523
-     * This accepts an array of EE_Message::MSG_ID values and will use that to retrieve the objects from the database
524
-     * and send.
525
-     *
526
-     * @param array $message_ids
527
-     * @throws EE_Error
528
-     * @throws EE_Error
529
-     */
530
-    public function setup_messages_from_ids_and_send($message_ids)
531
-    {
532
-        $this->_init_queue_and_generator();
533
-        $messages = EEM_Message::instance()->get_all(array(
534
-            array(
535
-                'MSG_ID' => array( 'IN', $message_ids ),
536
-                'STS_ID' => array(
537
-                    'IN',
538
-                    array_merge(
539
-                        EEM_Message::instance()->stati_indicating_sent(),
540
-                        array( EEM_Message::status_retry )
541
-                    ),
542
-                ),
543
-            ),
544
-        ));
545
-        // set the Messages to resend.
546
-        foreach ($messages as $message) {
547
-            if ($message instanceof EE_Message) {
548
-                $message->set_STS_ID(EEM_Message::status_resend);
549
-                $this->_queue->add($message);
550
-            }
551
-        }
552
-
553
-        $this->_queue->initiate_request_by_priority('send');
554
-    }
555
-
556
-
557
-    /**
558
-     * This method checks for registration IDs in the request via the given key and creates the messages to generate
559
-     * objects from them, then returns the array of messages to generate objects.
560
-     * Note, this sets up registrations for the registration family of message types.
561
-     *
562
-     * @param string $registration_ids_key This is used to indicate what represents the registration ids in the request.
563
-     *
564
-     * @return EE_Message_To_Generate[]|bool
565
-     * @throws EE_Error
566
-     */
567
-    public function setup_messages_to_generate_from_registration_ids_in_request($registration_ids_key = '_REG_ID')
568
-    {
569
-        /** @var RequestInterface $request */
570
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
571
-        $regs_to_send = array();
572
-        $regIDs = $request->getRequestParam($registration_ids_key, [], 'int', true);
573
-        if (empty($regIDs)) {
574
-            EE_Error::add_error(esc_html__('Something went wrong because we\'re missing the registration ID', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
575
-            return false;
576
-        }
577
-
578
-        // make sure is an array
579
-        $regIDs = is_array($regIDs) ? $regIDs : array( $regIDs );
580
-
581
-        foreach ($regIDs as $regID) {
582
-            $reg = EEM_Registration::instance()->get_one_by_ID($regID);
583
-            if (! $reg instanceof EE_Registration) {
584
-                EE_Error::add_error(sprintf(esc_html__('Unable to retrieve a registration object for the given reg id (%s)', 'event_espresso'), $regID));
585
-                return false;
586
-            }
587
-            $regs_to_send[ $reg->transaction_ID() ][ $reg->status_ID() ][] = $reg;
588
-        }
589
-
590
-        $messages_to_generate = array();
591
-
592
-        foreach ($regs_to_send as $status_group) {
593
-            foreach ($status_group as $status_id => $registrations) {
594
-                $message_type = EEH_MSG_Template::convert_reg_status_to_message_type($status_id);
595
-                if (! $message_type) {
596
-                    continue;
597
-                }
598
-                $messages_to_generate = array_merge(
599
-                    $messages_to_generate,
600
-                    $this->setup_mtgs_for_all_active_messengers(
601
-                        $message_type,
602
-                        array( $registrations, $status_id )
603
-                    )
604
-                );
605
-            }
606
-        }
607
-
608
-        return $messages_to_generate;
609
-    }
278
+	/**
279
+	 * Queue for generation.  Note this does NOT persist to the db.  Client code should call get_message_repository()->save() if desire
280
+	 * to persist.  This method is provided to client code to decide what it wants to do with queued messages for generation.
281
+	 * @param EE_Message_To_Generate $message_to_generate
282
+	 * @param bool                   $test_send             Whether this item is for a test send or not.
283
+	 * @return  EE_Messages_Queue
284
+	 */
285
+	public function queue_for_generation(EE_Message_To_Generate $message_to_generate, $test_send = false)
286
+	{
287
+		if ($message_to_generate->valid()) {
288
+			$this->_generator->create_and_add_message_to_queue($message_to_generate, $test_send);
289
+		}
290
+	}
291
+
292
+
293
+
294
+
295
+
296
+
297
+
298
+	/**
299
+	 * This receives an array of EE_Message_To_Generate objects, converts them to EE_Message adds them to the generation queue
300
+	 * and then persists to storage.
301
+	 *
302
+	 * @param EE_Message_To_Generate[] $messages_to_generate
303
+	 */
304
+	public function batch_queue_for_generation_and_persist($messages_to_generate)
305
+	{
306
+		$this->_init_queue_and_generator();
307
+		$this->_queue_for_generation_loop($messages_to_generate);
308
+		$this->_queue->save();
309
+	}
310
+
311
+
312
+
313
+
314
+
315
+
316
+	/**
317
+	 * This receives an array of EE_Message_To_Generate objects, converts them to EE_Message and adds them to the generation
318
+	 * queue.  Does NOT persist to storage (unless there is an error.
319
+	 * Client code can retrieve the generated queue by calling EEM_Messages_Processor::get_queue()
320
+	 *
321
+	 * @param EE_Message_To_Generate[]  $messages_to_generate
322
+	 */
323
+	public function batch_queue_for_generation_no_persist($messages_to_generate)
324
+	{
325
+		$this->_init_queue_and_generator();
326
+		$this->_queue_for_generation_loop($messages_to_generate);
327
+	}
328
+
329
+
330
+
331
+
332
+	/**
333
+	 * Simply loops through the given array of EE_Message_To_Generate objects and adds them to the _queue as EE_Message
334
+	 * objects.
335
+	 *
336
+	 * @param EE_Message_To_Generate[] $messages_to_generate
337
+	 */
338
+	protected function _queue_for_generation_loop($messages_to_generate)
339
+	{
340
+		// make sure is in an array.
341
+		if (! is_array($messages_to_generate)) {
342
+			$messages_to_generate = array( $messages_to_generate );
343
+		}
344
+
345
+		foreach ($messages_to_generate as $message_to_generate) {
346
+			if ($message_to_generate instanceof EE_Message_To_Generate && $message_to_generate->valid()) {
347
+				$this->queue_for_generation($message_to_generate);
348
+			}
349
+		}
350
+	}
351
+
352
+
353
+
354
+
355
+
356
+	/**
357
+	 * Receives an array of EE_Message_To_Generate objects and generates the EE_Message objects, then persists (so its
358
+	 * queued for sending).
359
+	 * @param  EE_Message_To_Generate[]
360
+	 * @return EE_Messages_Queue
361
+	 */
362
+	public function generate_and_queue_for_sending($messages_to_generate)
363
+	{
364
+		$this->_init_queue_and_generator();
365
+		$this->_queue_for_generation_loop($messages_to_generate);
366
+		return $this->_generator->generate(true);
367
+	}
368
+
369
+
370
+
371
+
372
+
373
+	/**
374
+	 * Generate for preview and execute right away.
375
+	 *
376
+	 * @param   EE_Message_To_Generate $message_to_generate
377
+	 * @param   bool                   $test_send                Whether this is a test send or not.
378
+	 * @return  EE_Messages_Queue | bool   false if unable to generate otherwise the generated queue.
379
+	 */
380
+	public function generate_for_preview(EE_Message_To_Generate $message_to_generate, $test_send = false)
381
+	{
382
+		if (! $message_to_generate->valid()) {
383
+			EE_Error::add_error(
384
+				esc_html__('Unable to generate preview because of invalid data', 'event_espresso'),
385
+				__FILE__,
386
+				__FUNCTION__,
387
+				__LINE__
388
+			);
389
+			return false;
390
+		}
391
+		// just make sure preview is set on the $message_to_generate (in case client forgot)
392
+		$message_to_generate->set_preview(true);
393
+		$this->_init_queue_and_generator();
394
+		$this->queue_for_generation($message_to_generate, $test_send);
395
+		$generated_queue = $this->_generator->generate(false);
396
+		if ($generated_queue->execute(false)) {
397
+			// the first queue item should be the preview
398
+			$generated_queue->get_message_repository()->rewind();
399
+			if (! $generated_queue->get_message_repository()->valid()) {
400
+				return $generated_queue;
401
+			}
402
+			return $generated_queue;
403
+		} else {
404
+			return false;
405
+		}
406
+	}
407
+
408
+
409
+	/**
410
+	 * This queues for sending.
411
+	 * The messenger send now method is also verified to see if sending immediately is requested.
412
+	 * otherwise its just saved to the queue.
413
+	 *
414
+	 * @param EE_Message_To_Generate $message_to_generate
415
+	 * @return bool true or false for success.
416
+	 * @throws EE_Error
417
+	 * @throws EE_Error
418
+	 */
419
+	public function queue_for_sending(EE_Message_To_Generate $message_to_generate)
420
+	{
421
+		if (! $message_to_generate->valid()) {
422
+			return false;
423
+		}
424
+		$this->_init_queue_and_generator();
425
+		$message = $message_to_generate->get_EE_Message();
426
+		$this->_queue->add($message);
427
+		if ($message->send_now()) {
428
+			$this->_queue->execute(false);
429
+		} else {
430
+			$this->_queue->save();
431
+		}
432
+		return true;
433
+	}
434
+
435
+
436
+	/**
437
+	 * This generates and sends from the given EE_Message_To_Generate class immediately.
438
+	 * @param EE_Message_To_Generate $message_to_generate
439
+	 * @return EE_Messages_Queue | null
440
+	 */
441
+	public function generate_and_send_now(EE_Message_To_Generate $message_to_generate)
442
+	{
443
+		if (! $message_to_generate->valid()) {
444
+			return null;
445
+		}
446
+		// is there supposed to be a sending messenger for this message?
447
+		if ($message_to_generate instanceof EEI_Has_Sending_Messenger) {
448
+			// make sure it's valid, but if it's not,
449
+			// then set the value of $sending_messenger to an EE_Error object
450
+			// so that downstream code can easily see that things went wrong.
451
+			$sending_messenger = $message_to_generate->sending_messenger() instanceof EE_messenger
452
+				? $message_to_generate->sending_messenger()
453
+				: new EE_Error(
454
+					esc_html__(
455
+						'There was a specific sending messenger requested for the send action, but it was either invalid or not active at time of sending.',
456
+						'event_espresso'
457
+					)
458
+				);
459
+		} else {
460
+			$sending_messenger = null;
461
+		}
462
+
463
+		if ($message_to_generate->get_EE_Message()->STS_ID() === EEM_Message::status_idle) {
464
+			$this->_init_queue_and_generator();
465
+			$this->_queue->add($message_to_generate->get_EE_Message());
466
+			$this->_queue->execute(false, $sending_messenger);
467
+			return $this->_queue;
468
+		} elseif ($message_to_generate->get_EE_Message()->STS_ID() === EEM_Message::status_incomplete) {
469
+			$generated_queue = $this->generate_and_return(array( $message_to_generate ));
470
+			$generated_queue->execute(false, $sending_messenger);
471
+			return $generated_queue;
472
+		}
473
+		return null;
474
+	}
475
+
476
+
477
+
478
+
479
+	/**
480
+	 * Creates mtg objects for all active messengers and queues for generation.
481
+	 * This method also calls the execute by priority method on the queue which will optionally kick off a new non-blocking
482
+	 * request to complete the action if the priority for the message requires immediate action.
483
+	 * @param string $message_type
484
+	 * @param mixed  $data   The data being used for generation.
485
+	 * @param bool   $persist   Whether to persist the queued messages to the db or not.
486
+	 */
487
+	public function generate_for_all_active_messengers($message_type, $data, $persist = true)
488
+	{
489
+		$messages_to_generate = $this->setup_mtgs_for_all_active_messengers($message_type, $data);
490
+		if ($persist) {
491
+			$this->batch_queue_for_generation_and_persist($messages_to_generate);
492
+			$this->_queue->initiate_request_by_priority();
493
+		} else {
494
+			$this->batch_queue_for_generation_no_persist($messages_to_generate);
495
+		}
496
+	}
497
+
498
+
499
+
500
+
501
+	/**
502
+	 * This simply loops through all active messengers and takes care of setting up the
503
+	 * EE_Message_To_Generate objects.
504
+	 * @param $message_type
505
+	 * @param $data
506
+	 *
507
+	 * @return EE_Message_To_Generate[]
508
+	 */
509
+	public function setup_mtgs_for_all_active_messengers($message_type, $data)
510
+	{
511
+		$messages_to_generate = array();
512
+		foreach ($this->_message_resource_manager->active_messengers() as $messenger_slug => $messenger_object) {
513
+			$message_to_generate = new EE_Message_To_Generate($messenger_slug, $message_type, $data);
514
+			if ($message_to_generate->valid()) {
515
+				$messages_to_generate[] = $message_to_generate;
516
+			}
517
+		}
518
+		return $messages_to_generate;
519
+	}
520
+
521
+
522
+	/**
523
+	 * This accepts an array of EE_Message::MSG_ID values and will use that to retrieve the objects from the database
524
+	 * and send.
525
+	 *
526
+	 * @param array $message_ids
527
+	 * @throws EE_Error
528
+	 * @throws EE_Error
529
+	 */
530
+	public function setup_messages_from_ids_and_send($message_ids)
531
+	{
532
+		$this->_init_queue_and_generator();
533
+		$messages = EEM_Message::instance()->get_all(array(
534
+			array(
535
+				'MSG_ID' => array( 'IN', $message_ids ),
536
+				'STS_ID' => array(
537
+					'IN',
538
+					array_merge(
539
+						EEM_Message::instance()->stati_indicating_sent(),
540
+						array( EEM_Message::status_retry )
541
+					),
542
+				),
543
+			),
544
+		));
545
+		// set the Messages to resend.
546
+		foreach ($messages as $message) {
547
+			if ($message instanceof EE_Message) {
548
+				$message->set_STS_ID(EEM_Message::status_resend);
549
+				$this->_queue->add($message);
550
+			}
551
+		}
552
+
553
+		$this->_queue->initiate_request_by_priority('send');
554
+	}
555
+
556
+
557
+	/**
558
+	 * This method checks for registration IDs in the request via the given key and creates the messages to generate
559
+	 * objects from them, then returns the array of messages to generate objects.
560
+	 * Note, this sets up registrations for the registration family of message types.
561
+	 *
562
+	 * @param string $registration_ids_key This is used to indicate what represents the registration ids in the request.
563
+	 *
564
+	 * @return EE_Message_To_Generate[]|bool
565
+	 * @throws EE_Error
566
+	 */
567
+	public function setup_messages_to_generate_from_registration_ids_in_request($registration_ids_key = '_REG_ID')
568
+	{
569
+		/** @var RequestInterface $request */
570
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
571
+		$regs_to_send = array();
572
+		$regIDs = $request->getRequestParam($registration_ids_key, [], 'int', true);
573
+		if (empty($regIDs)) {
574
+			EE_Error::add_error(esc_html__('Something went wrong because we\'re missing the registration ID', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
575
+			return false;
576
+		}
577
+
578
+		// make sure is an array
579
+		$regIDs = is_array($regIDs) ? $regIDs : array( $regIDs );
580
+
581
+		foreach ($regIDs as $regID) {
582
+			$reg = EEM_Registration::instance()->get_one_by_ID($regID);
583
+			if (! $reg instanceof EE_Registration) {
584
+				EE_Error::add_error(sprintf(esc_html__('Unable to retrieve a registration object for the given reg id (%s)', 'event_espresso'), $regID));
585
+				return false;
586
+			}
587
+			$regs_to_send[ $reg->transaction_ID() ][ $reg->status_ID() ][] = $reg;
588
+		}
589
+
590
+		$messages_to_generate = array();
591
+
592
+		foreach ($regs_to_send as $status_group) {
593
+			foreach ($status_group as $status_id => $registrations) {
594
+				$message_type = EEH_MSG_Template::convert_reg_status_to_message_type($status_id);
595
+				if (! $message_type) {
596
+					continue;
597
+				}
598
+				$messages_to_generate = array_merge(
599
+					$messages_to_generate,
600
+					$this->setup_mtgs_for_all_active_messengers(
601
+						$message_type,
602
+						array( $registrations, $status_id )
603
+					)
604
+				);
605
+			}
606
+		}
607
+
608
+		return $messages_to_generate;
609
+	}
610 610
 }
Please login to merge, or discard this patch.
core/domain/services/admin/ajax/WordpressHeartbeat.php 1 patch
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -17,52 +17,52 @@
 block discarded – undo
17 17
 class WordpressHeartbeat
18 18
 {
19 19
 
20
-    const RESPONSE_KEY_THANK_YOU_PAGE = 'espresso_thank_you_page';
20
+	const RESPONSE_KEY_THANK_YOU_PAGE = 'espresso_thank_you_page';
21 21
 
22
-    /**
23
-     * @var LoaderInterface $loader
24
-     */
25
-    protected $loader;
22
+	/**
23
+	 * @var LoaderInterface $loader
24
+	 */
25
+	protected $loader;
26 26
 
27
-    /**
28
-     * @var RequestInterface $request
29
-     */
30
-    protected $request;
27
+	/**
28
+	 * @var RequestInterface $request
29
+	 */
30
+	protected $request;
31 31
 
32 32
 
33
-    /**
34
-     * WordpressHeartbeat constructor.
35
-     *
36
-     * @param LoaderInterface  $loader
37
-     * @param RequestInterface $request
38
-     */
39
-    public function __construct(
40
-        LoaderInterface $loader,
41
-        RequestInterface $request
42
-    ) {
43
-        $this->loader = $loader;
44
-        $this->request = $request;
45
-        do_action('AHEE__EventEspresso_core_domain_services_admin_ajax_WordpressHeartbeat__constructor', $this);
46
-        add_action('AHEE__EE_System__core_loaded_and_ready', array($this, 'resolveRoutes'));
47
-    }
33
+	/**
34
+	 * WordpressHeartbeat constructor.
35
+	 *
36
+	 * @param LoaderInterface  $loader
37
+	 * @param RequestInterface $request
38
+	 */
39
+	public function __construct(
40
+		LoaderInterface $loader,
41
+		RequestInterface $request
42
+	) {
43
+		$this->loader = $loader;
44
+		$this->request = $request;
45
+		do_action('AHEE__EventEspresso_core_domain_services_admin_ajax_WordpressHeartbeat__constructor', $this);
46
+		add_action('AHEE__EE_System__core_loaded_and_ready', array($this, 'resolveRoutes'));
47
+	}
48 48
 
49 49
 
50
-    /**
51
-     * @since 4.9.76.p
52
-     * @throws InvalidClassException
53
-     */
54
-    public function resolveRoutes()
55
-    {
56
-        $screenID = $this->request->getRequestParam('screen_id');
57
-        $heartbeat_data = $this->request->getRequestParam('data', [], 'string', true);
58
-        if ($screenID === 'espresso_events') {
59
-            $this->loader->getShared(
60
-                'EventEspresso\core\domain\services\admin\ajax\EventEditorHeartbeat'
61
-            );
62
-        } elseif ($screenID === 'front' && ! empty($heartbeat_data[ self::RESPONSE_KEY_THANK_YOU_PAGE ])) {
63
-            $this->loader->getShared(
64
-                'EventEspresso\core\domain\services\admin\ajax\ThankYouPageIpnMonitor'
65
-            );
66
-        }
67
-    }
50
+	/**
51
+	 * @since 4.9.76.p
52
+	 * @throws InvalidClassException
53
+	 */
54
+	public function resolveRoutes()
55
+	{
56
+		$screenID = $this->request->getRequestParam('screen_id');
57
+		$heartbeat_data = $this->request->getRequestParam('data', [], 'string', true);
58
+		if ($screenID === 'espresso_events') {
59
+			$this->loader->getShared(
60
+				'EventEspresso\core\domain\services\admin\ajax\EventEditorHeartbeat'
61
+			);
62
+		} elseif ($screenID === 'front' && ! empty($heartbeat_data[ self::RESPONSE_KEY_THANK_YOU_PAGE ])) {
63
+			$this->loader->getShared(
64
+				'EventEspresso\core\domain\services\admin\ajax\ThankYouPageIpnMonitor'
65
+			);
66
+		}
67
+	}
68 68
 }
Please login to merge, or discard this patch.