Completed
Branch BUG-10489-non-trashed-regs-onl... (b37a8e)
by
unknown
37:13 queued 23:24
created
modules/messages/EED_Messages.module.php 1 patch
Indentation   +1081 added lines, -1081 removed lines patch added patch discarded remove patch
@@ -16,1096 +16,1096 @@
 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
62
-     */
63
-    public static function instance()
64
-    {
65
-        return parent::get_instance(__CLASS__);
66
-    }
67
-
68
-
69
-    /**
70
-     *  set_hooks - for hooking into EE Core, other modules, etc
71
-     *
72
-     * @since 4.5.0
73
-     * @return    void
74
-     */
75
-    public static function set_hooks()
76
-    {
77
-        //actions
78
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
79
-        add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
80
-            array('EED_Messages', 'maybe_registration'), 10, 2);
81
-        //filters
82
-        add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
83
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
84
-        add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
85
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
86
-        //register routes
87
-        self::_register_routes();
88
-    }
89
-
90
-    /**
91
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
92
-     *
93
-     * @access    public
94
-     * @return    void
95
-     */
96
-    public static function set_hooks_admin()
97
-    {
98
-        //actions
99
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
100
-        add_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
101
-            array('EED_Messages', 'payment_reminder'), 10);
102
-        add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
103
-            array('EED_Messages', 'maybe_registration'), 10, 3);
104
-        add_action('AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
105
-            array('EED_Messages', 'send_newsletter_message'), 10, 2);
106
-        add_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
107
-            array('EED_Messages', 'cancelled_registration'), 10);
108
-        add_action('AHEE__EE_Admin_Page___process_admin_payment_notification',
109
-            array('EED_Messages', 'process_admin_payment'), 10, 1);
110
-        //filters
111
-        add_filter('FHEE__EE_Admin_Page___process_resend_registration__success',
112
-            array('EED_Messages', 'process_resend'), 10, 2);
113
-        add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
114
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
115
-        add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
116
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
117
-    }
118
-
119
-
120
-    /**
121
-     * All the message triggers done by route go in here.
122
-     *
123
-     * @since 4.5.0
124
-     * @return void
125
-     */
126
-    protected static function _register_routes()
127
-    {
128
-        EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
129
-        EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
130
-        EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
131
-        EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
132
-        do_action('AHEE__EED_Messages___register_routes');
133
-    }
134
-
135
-
136
-    /**
137
-     * This is called when a browser display trigger is executed.
138
-     * The browser display trigger is typically used when a already generated message is displayed directly in the
139
-     * browser.
140
-     *
141
-     * @since 4.9.0
142
-     * @param WP $WP
143
-     */
144
-    public function browser_trigger($WP)
145
-    {
146
-        //ensure controller is loaded
147
-        self::_load_controller();
148
-        $token = EE_Registry::instance()->REQ->get('token');
149
-        try {
150
-            $mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
151
-            self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
152
-        } catch (EE_Error $e) {
153
-            $error_msg = __('Please note that a system message failed to send due to a technical issue.',
154
-                'event_espresso');
155
-            // add specific message for developers if WP_DEBUG in on
156
-            $error_msg .= '||' . $e->getMessage();
157
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
158
-        }
159
-    }
160
-
161
-
162
-    /**
163
-     * This is called when a browser error trigger is executed.
164
-     * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
165
-     * message and display it.
166
-     *
167
-     * @since 4.9.0
168
-     * @param $WP
169
-     */
170
-    public function browser_error_trigger($WP)
171
-    {
172
-        $token = EE_Registry::instance()->REQ->get('token');
173
-        if ($token) {
174
-            $message = EEM_Message::instance()->get_one_by_token($token);
175
-            if ($message instanceof EE_Message) {
176
-                header('HTTP/1.1 200 OK');
177
-                $error_msg = nl2br($message->error_message());
178
-                ?>
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
62
+	 */
63
+	public static function instance()
64
+	{
65
+		return parent::get_instance(__CLASS__);
66
+	}
67
+
68
+
69
+	/**
70
+	 *  set_hooks - for hooking into EE Core, other modules, etc
71
+	 *
72
+	 * @since 4.5.0
73
+	 * @return    void
74
+	 */
75
+	public static function set_hooks()
76
+	{
77
+		//actions
78
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
79
+		add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
80
+			array('EED_Messages', 'maybe_registration'), 10, 2);
81
+		//filters
82
+		add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
83
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
84
+		add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
85
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
86
+		//register routes
87
+		self::_register_routes();
88
+	}
89
+
90
+	/**
91
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
92
+	 *
93
+	 * @access    public
94
+	 * @return    void
95
+	 */
96
+	public static function set_hooks_admin()
97
+	{
98
+		//actions
99
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
100
+		add_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
101
+			array('EED_Messages', 'payment_reminder'), 10);
102
+		add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
103
+			array('EED_Messages', 'maybe_registration'), 10, 3);
104
+		add_action('AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
105
+			array('EED_Messages', 'send_newsletter_message'), 10, 2);
106
+		add_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
107
+			array('EED_Messages', 'cancelled_registration'), 10);
108
+		add_action('AHEE__EE_Admin_Page___process_admin_payment_notification',
109
+			array('EED_Messages', 'process_admin_payment'), 10, 1);
110
+		//filters
111
+		add_filter('FHEE__EE_Admin_Page___process_resend_registration__success',
112
+			array('EED_Messages', 'process_resend'), 10, 2);
113
+		add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
114
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
115
+		add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
116
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
117
+	}
118
+
119
+
120
+	/**
121
+	 * All the message triggers done by route go in here.
122
+	 *
123
+	 * @since 4.5.0
124
+	 * @return void
125
+	 */
126
+	protected static function _register_routes()
127
+	{
128
+		EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
129
+		EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
130
+		EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
131
+		EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
132
+		do_action('AHEE__EED_Messages___register_routes');
133
+	}
134
+
135
+
136
+	/**
137
+	 * This is called when a browser display trigger is executed.
138
+	 * The browser display trigger is typically used when a already generated message is displayed directly in the
139
+	 * browser.
140
+	 *
141
+	 * @since 4.9.0
142
+	 * @param WP $WP
143
+	 */
144
+	public function browser_trigger($WP)
145
+	{
146
+		//ensure controller is loaded
147
+		self::_load_controller();
148
+		$token = EE_Registry::instance()->REQ->get('token');
149
+		try {
150
+			$mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
151
+			self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
152
+		} catch (EE_Error $e) {
153
+			$error_msg = __('Please note that a system message failed to send due to a technical issue.',
154
+				'event_espresso');
155
+			// add specific message for developers if WP_DEBUG in on
156
+			$error_msg .= '||' . $e->getMessage();
157
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
158
+		}
159
+	}
160
+
161
+
162
+	/**
163
+	 * This is called when a browser error trigger is executed.
164
+	 * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
165
+	 * message and display it.
166
+	 *
167
+	 * @since 4.9.0
168
+	 * @param $WP
169
+	 */
170
+	public function browser_error_trigger($WP)
171
+	{
172
+		$token = EE_Registry::instance()->REQ->get('token');
173
+		if ($token) {
174
+			$message = EEM_Message::instance()->get_one_by_token($token);
175
+			if ($message instanceof EE_Message) {
176
+				header('HTTP/1.1 200 OK');
177
+				$error_msg = nl2br($message->error_message());
178
+				?>
179 179
                 <!DOCTYPE html>
180 180
                 <html>
181 181
                 <head></head>
182 182
                 <body>
183 183
                 <?php echo empty($error_msg)
184
-                    ? esc_html__('Unfortunately, we were unable to capture the error message for this message.',
185
-                        'event_espresso')
186
-                    : wp_kses(
187
-                        $error_msg,
188
-                        array(
189
-                            'a'      => array(
190
-                                'href'  => array(),
191
-                                'title' => array(),
192
-                            ),
193
-                            'span'   => array(),
194
-                            'div'    => array(),
195
-                            'p'      => array(),
196
-                            'strong' => array(),
197
-                            'em'     => array(),
198
-                            'br'     => array(),
199
-                        )
200
-                    ); ?>
184
+					? esc_html__('Unfortunately, we were unable to capture the error message for this message.',
185
+						'event_espresso')
186
+					: wp_kses(
187
+						$error_msg,
188
+						array(
189
+							'a'      => array(
190
+								'href'  => array(),
191
+								'title' => array(),
192
+							),
193
+							'span'   => array(),
194
+							'div'    => array(),
195
+							'p'      => array(),
196
+							'strong' => array(),
197
+							'em'     => array(),
198
+							'br'     => array(),
199
+						)
200
+					); ?>
201 201
                 </body>
202 202
                 </html>
203 203
                 <?php
204
-                exit;
205
-            }
206
-        }
207
-        return;
208
-    }
209
-
210
-
211
-    /**
212
-     *  This runs when the msg_url_trigger route has initiated.
213
-     *
214
-     * @since 4.5.0
215
-     * @param WP $WP
216
-     * @throws EE_Error
217
-     * @return    void
218
-     */
219
-    public function run($WP)
220
-    {
221
-        //ensure controller is loaded
222
-        self::_load_controller();
223
-        // attempt to process message
224
-        try {
225
-            /** @type EE_Message_To_Generate_From_Request $message_to_generate */
226
-            $message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
227
-            self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
228
-        } catch (EE_Error $e) {
229
-            $error_msg = __('Please note that a system message failed to send due to a technical issue.',
230
-                'event_espresso');
231
-            // add specific message for developers if WP_DEBUG in on
232
-            $error_msg .= '||' . $e->getMessage();
233
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
234
-        }
235
-    }
236
-
237
-
238
-    /**
239
-     * This is triggered by the 'msg_cron_trigger' route.
240
-     *
241
-     * @param WP $WP
242
-     */
243
-    public function execute_batch_request($WP)
244
-    {
245
-        $this->run_cron();
246
-        header('HTTP/1.1 200 OK');
247
-        exit();
248
-    }
249
-
250
-
251
-    /**
252
-     * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
253
-     * request.
254
-     */
255
-    public function run_cron()
256
-    {
257
-        self::_load_controller();
258
-        //get required vars
259
-        $cron_type     = EE_Registry::instance()->REQ->get('type');
260
-        $transient_key = EE_Registry::instance()->REQ->get('key');
261
-
262
-        //now let's verify transient, if not valid exit immediately
263
-        if (! get_transient($transient_key)) {
264
-            /**
265
-             * trigger error so this gets in the error logs.  This is important because it happens on a non-user request.
266
-             */
267
-            trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
268
-        }
269
-
270
-        //if made it here, lets' delete the transient to keep the db clean
271
-        delete_transient($transient_key);
272
-
273
-        if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
274
-
275
-            $method = 'batch_' . $cron_type . '_from_queue';
276
-            if (method_exists(self::$_MSG_PROCESSOR, $method)) {
277
-                self::$_MSG_PROCESSOR->$method();
278
-            } else {
279
-                //no matching task
280
-                /**
281
-                 * trigger error so this gets in the error logs.  This is important because it happens on a non user request.
282
-                 */
283
-                trigger_error(esc_attr(sprintf(__('There is no task corresponding to this route %s', 'event_espresso'),
284
-                    $cron_type)));
285
-            }
286
-        }
287
-
288
-        do_action('FHEE__EED_Messages__run_cron__end');
289
-    }
290
-
291
-
292
-    /**
293
-     * This is used to retrieve the template pack for the given name.
294
-     * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
295
-     * the default template pack is returned.
296
-     *
297
-     * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
298
-     * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
299
-     *                                   in generating the Pack class name).
300
-     * @return EE_Messages_Template_Pack
301
-     */
302
-    public static function get_template_pack($template_pack_name)
303
-    {
304
-        EE_Registry::instance()->load_helper('MSG_Template');
305
-        return EEH_MSG_Template::get_template_pack($template_pack_name);
306
-    }
307
-
308
-
309
-    /**
310
-     * Retrieves an array of all template packs.
311
-     * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
312
-     *
313
-     * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
314
-     * @return EE_Messages_Template_Pack[]
315
-     */
316
-    public static function get_template_packs()
317
-    {
318
-        EE_Registry::instance()->load_helper('MSG_Template');
319
-
320
-        //for backward compat, let's make sure this returns in the same format as originally.
321
-        $template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
322
-        $template_pack_collection->rewind();
323
-        $template_packs = array();
324
-        while ($template_pack_collection->valid()) {
325
-            $template_packs[$template_pack_collection->current()->dbref] = $template_pack_collection->current();
326
-            $template_pack_collection->next();
327
-        }
328
-        return $template_packs;
329
-    }
330
-
331
-
332
-    /**
333
-     * This simply makes sure the autoloaders are registered for the EE_messages system.
334
-     *
335
-     * @since 4.5.0
336
-     * @return void
337
-     */
338
-    public static function set_autoloaders()
339
-    {
340
-        if (empty(self::$_MSG_PATHS)) {
341
-            self::_set_messages_paths();
342
-            foreach (self::$_MSG_PATHS as $path) {
343
-                EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
344
-            }
345
-            // add aliases
346
-            EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
347
-            EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
348
-        }
349
-    }
350
-
351
-
352
-    /**
353
-     * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
354
-     * for use by the Messages Autoloaders
355
-     *
356
-     * @since 4.5.0
357
-     * @return void.
358
-     */
359
-    protected static function _set_messages_paths()
360
-    {
361
-        $dir_ref = array(
362
-            'messages/message_type',
363
-            'messages/messenger',
364
-            'messages/defaults',
365
-            'messages/defaults/email',
366
-            'messages/data_class',
367
-            'messages/validators',
368
-            'messages/validators/email',
369
-            'messages/validators/html',
370
-            'shortcodes',
371
-        );
372
-        $paths   = array();
373
-        foreach ($dir_ref as $index => $dir) {
374
-            $paths[$index] = EE_LIBRARIES . $dir;
375
-        }
376
-        self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
377
-    }
378
-
379
-
380
-    /**
381
-     * Takes care of loading dependencies
382
-     *
383
-     * @since 4.5.0
384
-     * @return void
385
-     */
386
-    protected static function _load_controller()
387
-    {
388
-        if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
389
-            EE_Registry::instance()->load_core('Request_Handler');
390
-            self::set_autoloaders();
391
-            self::$_EEMSG                    = EE_Registry::instance()->load_lib('messages');
392
-            self::$_MSG_PROCESSOR            = EE_Registry::instance()->load_lib('Messages_Processor');
393
-            self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
394
-        }
395
-    }
396
-
397
-
398
-    /**
399
-     * @param EE_Transaction $transaction
400
-     */
401
-    public static function payment_reminder(EE_Transaction $transaction)
402
-    {
403
-        self::_load_controller();
404
-        $data = array($transaction, null);
405
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
406
-    }
407
-
408
-
409
-    /**
410
-     * Any messages triggers for after successful gateway payments should go in here.
411
-     *
412
-     * @param  EE_Transaction object
413
-     * @param  EE_Payment     object
414
-     * @return void
415
-     */
416
-    public static function payment(EE_Transaction $transaction, EE_Payment $payment)
417
-    {
418
-        self::_load_controller();
419
-        $data = array($transaction, $payment);
420
-        EE_Registry::instance()->load_helper('MSG_Template');
421
-        $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
422
-        //if payment amount is less than 0 then switch to payment_refund message type.
423
-        $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
424
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
425
-    }
426
-
427
-
428
-    /**
429
-     * @param EE_Transaction $transaction
430
-     */
431
-    public static function cancelled_registration(EE_Transaction $transaction)
432
-    {
433
-        self::_load_controller();
434
-        $data = array($transaction, null);
435
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
436
-    }
437
-
438
-
439
-
440
-    /**
441
-     * Trigger for Registration messages
442
-     * Note that what registration message type is sent depends on what the reg status is for the registrations on the
443
-     * incoming transaction.
444
-     *
445
-     * @param EE_Registration $registration
446
-     * @param array           $extra_details
447
-     * @return void
448
-     * @throws EE_Error
449
-     * @throws EntityNotFoundException
450
-     */
451
-    public static function maybe_registration(EE_Registration $registration, $extra_details = array())
452
-    {
453
-
454
-        if (! self::_verify_registration_notification_send($registration, $extra_details)) {
455
-            //no messages please
456
-            return;
457
-        }
458
-
459
-        // get all non-trashed registrations so we make sure we send messages for the right status.
460
-        $all_registrations = $registration->transaction()->registrations(
461
-            array(
462
-                array('REG_deleted' => false),
463
-                'order_by' => array(
464
-                    'Event.EVT_name'     => 'ASC',
465
-                    'Attendee.ATT_lname' => 'ASC',
466
-                    'Attendee.ATT_fname' => 'ASC'
467
-                )
468
-            )
469
-        );
470
-        //cached array of statuses so we only trigger messages once per status.
471
-        $statuses_sent = array();
472
-        self::_load_controller();
473
-        $mtgs = array();
474
-
475
-        //loop through registrations and trigger messages once per status.
476
-        foreach ($all_registrations as $reg) {
477
-
478
-            //already triggered?
479
-            if (in_array($reg->status_ID(), $statuses_sent)) {
480
-                continue;
481
-            }
482
-
483
-            $message_type    = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
484
-            $mtgs            = array_merge(
485
-                    $mtgs,
486
-                    self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
487
-                            $message_type,
488
-                            array($registration->transaction(), null, $reg->status_ID())
489
-                    )
490
-            );
491
-            $statuses_sent[] = $reg->status_ID();
492
-        }
493
-
494
-        if (count($statuses_sent) > 1) {
495
-            $mtgs = array_merge(
496
-                $mtgs,
497
-                self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
498
-                    'registration_summary',
499
-                    array($registration->transaction(), null)
500
-                )
501
-            );
502
-        }
503
-
504
-        //batch queue and initiate request
505
-        self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
506
-        self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
507
-    }
508
-
509
-
510
-    /**
511
-     * This is a helper method used to very whether a registration notification should be sent or
512
-     * not.  Prevents duplicate notifications going out for registration context notifications.
513
-     *
514
-     * @param EE_Registration $registration  [description]
515
-     * @param array           $extra_details [description]
516
-     * @return bool          true = send away, false = nope halt the presses.
517
-     */
518
-    protected static function _verify_registration_notification_send(
519
-        EE_Registration $registration,
520
-        $extra_details = array()
521
-    ) {
522
-        //self::log(
523
-        //	__CLASS__, __FUNCTION__, __LINE__,
524
-        //	$registration->transaction(),
525
-        //	array( '$extra_details' => $extra_details )
526
-        //);
527
-        // currently only using this to send messages for the primary registrant
528
-        if (! $registration->is_primary_registrant()) {
529
-            return false;
530
-        }
531
-        // first we check if we're in admin and not doing front ajax
532
-        if (is_admin() && ! EE_FRONT_AJAX) {
533
-            //make sure appropriate admin params are set for sending messages
534
-            if (empty($_REQUEST['txn_reg_status_change']['send_notifications']) || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])) {
535
-                //no messages sent please.
536
-                return false;
537
-            }
538
-        } else {
539
-            // frontend request (either regular or via AJAX)
540
-            // TXN is NOT finalized ?
541
-            if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
542
-                return false;
543
-            }
544
-            // return visit but nothing changed ???
545
-            if (
546
-                isset($extra_details['revisit'], $extra_details['status_updates']) &&
547
-                $extra_details['revisit'] && ! $extra_details['status_updates']
548
-            ) {
549
-                return false;
550
-            }
551
-            // NOT sending messages && reg status is something other than "Not-Approved"
552
-            if (
553
-                ! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
554
-                $registration->status_ID() !== EEM_Registration::status_id_not_approved
555
-            ) {
556
-                return false;
557
-            }
558
-        }
559
-        // release the kraken
560
-        return true;
561
-    }
562
-
563
-
564
-    /**
565
-     * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
566
-     * status id.
567
-     *
568
-     * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
569
-     *                    or EEH_MSG_Template::convert_reg_status_to_message_type
570
-     * @param string $reg_status
571
-     * @return array
572
-     */
573
-    protected static function _get_reg_status_array($reg_status = '')
574
-    {
575
-        EE_Registry::instance()->load_helper('MSG_Template');
576
-        return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
577
-            ? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
578
-            : EEH_MSG_Template::reg_status_to_message_type_array();
579
-    }
580
-
581
-
582
-    /**
583
-     * Simply returns the payment message type for the given payment status.
584
-     *
585
-     * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
586
-     *                   or EEH_MSG_Template::convert_payment_status_to_message_type
587
-     * @param string $payment_status The payment status being matched.
588
-     * @return string|bool The payment message type slug matching the status or false if no match.
589
-     */
590
-    protected static function _get_payment_message_type($payment_status)
591
-    {
592
-        EE_Registry::instance()->load_helper('MSG_Template');
593
-        return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
594
-            ? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
595
-            : false;
596
-    }
597
-
598
-
599
-    /**
600
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
601
-     *
602
-     * @access public
603
-     * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
604
-     * @return bool          success/fail
605
-     */
606
-    public static function process_resend($req_data)
607
-    {
608
-        self::_load_controller();
609
-
610
-        //if $msgID in this request then skip to the new resend_message
611
-        if (EE_Registry::instance()->REQ->get('MSG_ID')) {
612
-            return self::resend_message();
613
-        }
614
-
615
-        //make sure any incoming request data is set on the REQ so that it gets picked up later.
616
-        $req_data = (array)$req_data;
617
-        foreach ($req_data as $request_key => $request_value) {
618
-            EE_Registry::instance()->REQ->set($request_key, $request_value);
619
-        }
620
-
621
-        if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
622
-            return false;
623
-        }
624
-
625
-        try {
626
-            self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
627
-            self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
628
-        } catch (EE_Error $e) {
629
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
630
-            return false;
631
-        }
632
-        EE_Error::add_success(
633
-            __('Messages have been successfully queued for generation and sending.', 'event_espresso')
634
-        );
635
-        return true; //everything got queued.
636
-    }
637
-
638
-
639
-    /**
640
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
641
-     *
642
-     * @return bool
643
-     */
644
-    public static function resend_message()
645
-    {
646
-        self::_load_controller();
647
-
648
-        $msgID = EE_Registry::instance()->REQ->get('MSG_ID');
649
-        if (! $msgID) {
650
-            EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
651
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
652
-            return false;
653
-        }
654
-
655
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
656
-
657
-        //setup success message.
658
-        $count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
659
-        EE_Error::add_success(sprintf(
660
-            _n(
661
-                'There was %d message queued for resending.',
662
-                'There were %d messages queued for resending.',
663
-                $count_ready_for_resend,
664
-                'event_espresso'
665
-            ),
666
-            $count_ready_for_resend
667
-        ));
668
-        return true;
669
-    }
670
-
671
-
672
-    /**
673
-     * Message triggers for manual payment applied by admin
674
-     *
675
-     * @param  EE_Payment $payment EE_payment object
676
-     * @return bool              success/fail
677
-     */
678
-    public static function process_admin_payment(EE_Payment $payment)
679
-    {
680
-        EE_Registry::instance()->load_helper('MSG_Template');
681
-        //we need to get the transaction object
682
-        $transaction = $payment->transaction();
683
-        if ($transaction instanceof EE_Transaction) {
684
-            $data         = array($transaction, $payment);
685
-            $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
686
-
687
-            //if payment amount is less than 0 then switch to payment_refund message type.
688
-            $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
689
-
690
-            //if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
691
-            $message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved ? false : $message_type;
692
-
693
-            self::_load_controller();
694
-
695
-            self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
696
-
697
-            //get count of queued for generation
698
-            $count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(array(
699
-                EEM_Message::status_incomplete,
700
-                EEM_Message::status_idle,
701
-            ));
702
-
703
-            if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
704
-                add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
705
-                return true;
706
-            } else {
707
-                $count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending());
708
-                /**
709
-                 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
710
-                 * IMMEDIATE generation.
711
-                 */
712
-                if ($count_failed > 0) {
713
-                    EE_Error::add_error(sprintf(
714
-                        _n(
715
-                            'The payment notification generation failed.',
716
-                            '%d payment notifications failed being sent.',
717
-                            $count_failed,
718
-                            'event_espresso'
719
-                        ),
720
-                        $count_failed
721
-                    ), __FILE__, __FUNCTION__, __LINE__);
722
-
723
-                    return false;
724
-                } else {
725
-                    add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
726
-                    return true;
727
-                }
728
-            }
729
-        } else {
730
-            EE_Error::add_error(
731
-                'Unable to generate the payment notification because the given value for the transaction is invalid.',
732
-                'event_espresso'
733
-            );
734
-            return false;
735
-        }
736
-    }
737
-
738
-
739
-    /**
740
-     * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
741
-     *
742
-     * @since   4.3.0
743
-     * @param  EE_Registration[] $registrations an array of EE_Registration objects
744
-     * @param  int               $grp_id        a specific message template group id.
745
-     * @return void
746
-     */
747
-    public static function send_newsletter_message($registrations, $grp_id)
748
-    {
749
-        //make sure mtp is id and set it in the EE_Request Handler later messages setup.
750
-        EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
751
-        self::_load_controller();
752
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
753
-    }
754
-
755
-
756
-    /**
757
-     * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
758
-     *
759
-     * @since   4.3.0
760
-     * @param    string          $registration_message_trigger_url
761
-     * @param    EE_Registration $registration
762
-     * @param string             $messenger
763
-     * @param string             $message_type
764
-     * @return    string
765
-     */
766
-    public static function registration_message_trigger_url(
767
-        $registration_message_trigger_url,
768
-        EE_Registration $registration,
769
-        $messenger = 'html',
770
-        $message_type = 'invoice'
771
-    ) {
772
-        // whitelist $messenger
773
-        switch ($messenger) {
774
-            case 'pdf' :
775
-                $sending_messenger    = 'pdf';
776
-                $generating_messenger = 'html';
777
-                break;
778
-            case 'html' :
779
-            default :
780
-                $sending_messenger    = 'html';
781
-                $generating_messenger = 'html';
782
-                break;
783
-        }
784
-        // whitelist $message_type
785
-        switch ($message_type) {
786
-            case 'receipt' :
787
-                $message_type = 'receipt';
788
-                break;
789
-            case 'invoice' :
790
-            default :
791
-                $message_type = 'invoice';
792
-                break;
793
-        }
794
-        // verify that both the messenger AND the message type are active
795
-        if (EEH_MSG_Template::is_messenger_active($sending_messenger) && EEH_MSG_Template::is_mt_active($message_type)) {
796
-            //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?)
797
-            $template_query_params = array(
798
-                'MTP_is_active'    => true,
799
-                'MTP_messenger'    => $generating_messenger,
800
-                'MTP_message_type' => $message_type,
801
-                'Event.EVT_ID'     => $registration->event_ID(),
802
-            );
803
-            //get the message template group.
804
-            $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
805
-            //if we don't have an EE_Message_Template_Group then return
806
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
807
-                // remove EVT_ID from query params so that global templates get picked up
808
-                unset($template_query_params['Event.EVT_ID']);
809
-                //get global template as the fallback
810
-                $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
811
-            }
812
-            //if we don't have an EE_Message_Template_Group then return
813
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
814
-                return '';
815
-            }
816
-            // generate the URL
817
-            $registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
818
-                $sending_messenger,
819
-                $generating_messenger,
820
-                'purchaser',
821
-                $message_type,
822
-                $registration,
823
-                $msg_template_group->ID(),
824
-                $registration->transaction_ID()
825
-            );
826
-
827
-        }
828
-        return $registration_message_trigger_url;
829
-    }
830
-
831
-
832
-    /**
833
-     * Use to generate and return a message preview!
834
-     *
835
-     * @param  string $type      This should correspond with a valid message type
836
-     * @param  string $context   This should correspond with a valid context for the message type
837
-     * @param  string $messenger This should correspond with a valid messenger.
838
-     * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
839
-     *                           preview
840
-     * @return string|bool          The body of the message or if send is requested, sends.
841
-     */
842
-    public static function preview_message($type, $context, $messenger, $send = false)
843
-    {
844
-        self::_load_controller();
845
-        $mtg                     = new EE_Message_To_Generate(
846
-            $messenger,
847
-            $type,
848
-            array(),
849
-            $context,
850
-            true
851
-        );
852
-        $generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
853
-        if ($generated_preview_queue instanceof EE_Messages_Queue) {
854
-            return $generated_preview_queue->get_message_repository()->current()->content();
855
-        } else {
856
-            return $generated_preview_queue;
857
-        }
858
-    }
859
-
860
-
861
-    /**
862
-     * This is a method that allows for sending a message using a messenger matching the string given and the provided
863
-     * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
864
-     * content found in the EE_Message objects in the queue.
865
-     *
866
-     * @since 4.9.0
867
-     * @param string            $messenger            a string matching a valid active messenger in the system
868
-     * @param string            $message_type         Although it seems contrary to the name of the method, a message
869
-     *                                                type name is still required to send along the message type to the
870
-     *                                                messenger because this is used for determining what specific
871
-     *                                                variations might be loaded for the generated message.
872
-     * @param EE_Messages_Queue $queue
873
-     * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
874
-     *                                                aggregate EE_Message object.
875
-     * @return bool          success or fail.
876
-     */
877
-    public static function send_message_with_messenger_only(
878
-        $messenger,
879
-        $message_type,
880
-        EE_Messages_Queue $queue,
881
-        $custom_subject = ''
882
-    ) {
883
-        self::_load_controller();
884
-        /** @type EE_Message_To_Generate_From_Queue $message_to_generate */
885
-        $message_to_generate = EE_Registry::instance()->load_lib(
886
-            'Message_To_Generate_From_Queue',
887
-            array(
888
-                $messenger,
889
-                $message_type,
890
-                $queue,
891
-                $custom_subject,
892
-            )
893
-        );
894
-        return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
895
-    }
896
-
897
-
898
-    /**
899
-     * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
900
-     *
901
-     * @since 4.9.0
902
-     * @param array $message_ids An array of message ids
903
-     * @return bool | EE_Messages_Queue     false if nothing was generated, EE_Messages_Queue containing generated
904
-     *              messages.
905
-     */
906
-    public static function generate_now($message_ids)
907
-    {
908
-        self::_load_controller();
909
-        $messages        = EEM_Message::instance()->get_all(
910
-            array(
911
-                0 => array(
912
-                    'MSG_ID' => array('IN', $message_ids),
913
-                    'STS_ID' => EEM_Message::status_incomplete,
914
-                ),
915
-            )
916
-        );
917
-        $generated_queue = false;
918
-        if ($messages) {
919
-            $generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
920
-        }
921
-
922
-        if (! $generated_queue instanceof EE_Messages_Queue) {
923
-            EE_Error::add_error(
924
-                __('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.',
925
-                    'event_espresso'),
926
-                __FILE__, __FUNCTION__, __LINE__
927
-            );
928
-        }
929
-        return $generated_queue;
930
-    }
931
-
932
-
933
-    /**
934
-     * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
935
-     * EEM_Message::status_idle
936
-     *
937
-     * @since 4.9.0
938
-     * @param $message_ids
939
-     * @return bool | EE_Messages_Queue  false if no messages sent.
940
-     */
941
-    public static function send_now($message_ids)
942
-    {
943
-        self::_load_controller();
944
-        $messages   = EEM_Message::instance()->get_all(
945
-            array(
946
-                0 => array(
947
-                    'MSG_ID' => array('IN', $message_ids),
948
-                    'STS_ID' => array(
949
-                        'IN',
950
-                        array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
951
-                    ),
952
-                ),
953
-            )
954
-        );
955
-        $sent_queue = false;
956
-        if ($messages) {
957
-            $sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
958
-        }
959
-
960
-        if (! $sent_queue instanceof EE_Messages_Queue) {
961
-            EE_Error::add_error(
962
-                __('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.',
963
-                    'event_espresso'),
964
-                __FILE__, __FUNCTION__, __LINE__
965
-            );
966
-        } else {
967
-            //can count how many sent by using the messages in the queue
968
-            $sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
969
-            if ($sent_count > 0) {
970
-                EE_Error::add_success(
971
-                    sprintf(
972
-                        _n(
973
-                            'There was %d message successfully sent.',
974
-                            'There were %d messages successfully sent.',
975
-                            $sent_count,
976
-                            'event_espresso'
977
-                        ),
978
-                        $sent_count
979
-                    )
980
-                );
981
-            } else {
982
-                EE_Error::overwrite_errors();
983
-                EE_Error::add_error(
984
-                    __('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.
204
+				exit;
205
+			}
206
+		}
207
+		return;
208
+	}
209
+
210
+
211
+	/**
212
+	 *  This runs when the msg_url_trigger route has initiated.
213
+	 *
214
+	 * @since 4.5.0
215
+	 * @param WP $WP
216
+	 * @throws EE_Error
217
+	 * @return    void
218
+	 */
219
+	public function run($WP)
220
+	{
221
+		//ensure controller is loaded
222
+		self::_load_controller();
223
+		// attempt to process message
224
+		try {
225
+			/** @type EE_Message_To_Generate_From_Request $message_to_generate */
226
+			$message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
227
+			self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
228
+		} catch (EE_Error $e) {
229
+			$error_msg = __('Please note that a system message failed to send due to a technical issue.',
230
+				'event_espresso');
231
+			// add specific message for developers if WP_DEBUG in on
232
+			$error_msg .= '||' . $e->getMessage();
233
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
234
+		}
235
+	}
236
+
237
+
238
+	/**
239
+	 * This is triggered by the 'msg_cron_trigger' route.
240
+	 *
241
+	 * @param WP $WP
242
+	 */
243
+	public function execute_batch_request($WP)
244
+	{
245
+		$this->run_cron();
246
+		header('HTTP/1.1 200 OK');
247
+		exit();
248
+	}
249
+
250
+
251
+	/**
252
+	 * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
253
+	 * request.
254
+	 */
255
+	public function run_cron()
256
+	{
257
+		self::_load_controller();
258
+		//get required vars
259
+		$cron_type     = EE_Registry::instance()->REQ->get('type');
260
+		$transient_key = EE_Registry::instance()->REQ->get('key');
261
+
262
+		//now let's verify transient, if not valid exit immediately
263
+		if (! get_transient($transient_key)) {
264
+			/**
265
+			 * trigger error so this gets in the error logs.  This is important because it happens on a non-user request.
266
+			 */
267
+			trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
268
+		}
269
+
270
+		//if made it here, lets' delete the transient to keep the db clean
271
+		delete_transient($transient_key);
272
+
273
+		if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
274
+
275
+			$method = 'batch_' . $cron_type . '_from_queue';
276
+			if (method_exists(self::$_MSG_PROCESSOR, $method)) {
277
+				self::$_MSG_PROCESSOR->$method();
278
+			} else {
279
+				//no matching task
280
+				/**
281
+				 * trigger error so this gets in the error logs.  This is important because it happens on a non user request.
282
+				 */
283
+				trigger_error(esc_attr(sprintf(__('There is no task corresponding to this route %s', 'event_espresso'),
284
+					$cron_type)));
285
+			}
286
+		}
287
+
288
+		do_action('FHEE__EED_Messages__run_cron__end');
289
+	}
290
+
291
+
292
+	/**
293
+	 * This is used to retrieve the template pack for the given name.
294
+	 * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
295
+	 * the default template pack is returned.
296
+	 *
297
+	 * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
298
+	 * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
299
+	 *                                   in generating the Pack class name).
300
+	 * @return EE_Messages_Template_Pack
301
+	 */
302
+	public static function get_template_pack($template_pack_name)
303
+	{
304
+		EE_Registry::instance()->load_helper('MSG_Template');
305
+		return EEH_MSG_Template::get_template_pack($template_pack_name);
306
+	}
307
+
308
+
309
+	/**
310
+	 * Retrieves an array of all template packs.
311
+	 * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
312
+	 *
313
+	 * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
314
+	 * @return EE_Messages_Template_Pack[]
315
+	 */
316
+	public static function get_template_packs()
317
+	{
318
+		EE_Registry::instance()->load_helper('MSG_Template');
319
+
320
+		//for backward compat, let's make sure this returns in the same format as originally.
321
+		$template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
322
+		$template_pack_collection->rewind();
323
+		$template_packs = array();
324
+		while ($template_pack_collection->valid()) {
325
+			$template_packs[$template_pack_collection->current()->dbref] = $template_pack_collection->current();
326
+			$template_pack_collection->next();
327
+		}
328
+		return $template_packs;
329
+	}
330
+
331
+
332
+	/**
333
+	 * This simply makes sure the autoloaders are registered for the EE_messages system.
334
+	 *
335
+	 * @since 4.5.0
336
+	 * @return void
337
+	 */
338
+	public static function set_autoloaders()
339
+	{
340
+		if (empty(self::$_MSG_PATHS)) {
341
+			self::_set_messages_paths();
342
+			foreach (self::$_MSG_PATHS as $path) {
343
+				EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
344
+			}
345
+			// add aliases
346
+			EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
347
+			EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
348
+		}
349
+	}
350
+
351
+
352
+	/**
353
+	 * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
354
+	 * for use by the Messages Autoloaders
355
+	 *
356
+	 * @since 4.5.0
357
+	 * @return void.
358
+	 */
359
+	protected static function _set_messages_paths()
360
+	{
361
+		$dir_ref = array(
362
+			'messages/message_type',
363
+			'messages/messenger',
364
+			'messages/defaults',
365
+			'messages/defaults/email',
366
+			'messages/data_class',
367
+			'messages/validators',
368
+			'messages/validators/email',
369
+			'messages/validators/html',
370
+			'shortcodes',
371
+		);
372
+		$paths   = array();
373
+		foreach ($dir_ref as $index => $dir) {
374
+			$paths[$index] = EE_LIBRARIES . $dir;
375
+		}
376
+		self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
377
+	}
378
+
379
+
380
+	/**
381
+	 * Takes care of loading dependencies
382
+	 *
383
+	 * @since 4.5.0
384
+	 * @return void
385
+	 */
386
+	protected static function _load_controller()
387
+	{
388
+		if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
389
+			EE_Registry::instance()->load_core('Request_Handler');
390
+			self::set_autoloaders();
391
+			self::$_EEMSG                    = EE_Registry::instance()->load_lib('messages');
392
+			self::$_MSG_PROCESSOR            = EE_Registry::instance()->load_lib('Messages_Processor');
393
+			self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
394
+		}
395
+	}
396
+
397
+
398
+	/**
399
+	 * @param EE_Transaction $transaction
400
+	 */
401
+	public static function payment_reminder(EE_Transaction $transaction)
402
+	{
403
+		self::_load_controller();
404
+		$data = array($transaction, null);
405
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
406
+	}
407
+
408
+
409
+	/**
410
+	 * Any messages triggers for after successful gateway payments should go in here.
411
+	 *
412
+	 * @param  EE_Transaction object
413
+	 * @param  EE_Payment     object
414
+	 * @return void
415
+	 */
416
+	public static function payment(EE_Transaction $transaction, EE_Payment $payment)
417
+	{
418
+		self::_load_controller();
419
+		$data = array($transaction, $payment);
420
+		EE_Registry::instance()->load_helper('MSG_Template');
421
+		$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
422
+		//if payment amount is less than 0 then switch to payment_refund message type.
423
+		$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
424
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
425
+	}
426
+
427
+
428
+	/**
429
+	 * @param EE_Transaction $transaction
430
+	 */
431
+	public static function cancelled_registration(EE_Transaction $transaction)
432
+	{
433
+		self::_load_controller();
434
+		$data = array($transaction, null);
435
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
436
+	}
437
+
438
+
439
+
440
+	/**
441
+	 * Trigger for Registration messages
442
+	 * Note that what registration message type is sent depends on what the reg status is for the registrations on the
443
+	 * incoming transaction.
444
+	 *
445
+	 * @param EE_Registration $registration
446
+	 * @param array           $extra_details
447
+	 * @return void
448
+	 * @throws EE_Error
449
+	 * @throws EntityNotFoundException
450
+	 */
451
+	public static function maybe_registration(EE_Registration $registration, $extra_details = array())
452
+	{
453
+
454
+		if (! self::_verify_registration_notification_send($registration, $extra_details)) {
455
+			//no messages please
456
+			return;
457
+		}
458
+
459
+		// get all non-trashed registrations so we make sure we send messages for the right status.
460
+		$all_registrations = $registration->transaction()->registrations(
461
+			array(
462
+				array('REG_deleted' => false),
463
+				'order_by' => array(
464
+					'Event.EVT_name'     => 'ASC',
465
+					'Attendee.ATT_lname' => 'ASC',
466
+					'Attendee.ATT_fname' => 'ASC'
467
+				)
468
+			)
469
+		);
470
+		//cached array of statuses so we only trigger messages once per status.
471
+		$statuses_sent = array();
472
+		self::_load_controller();
473
+		$mtgs = array();
474
+
475
+		//loop through registrations and trigger messages once per status.
476
+		foreach ($all_registrations as $reg) {
477
+
478
+			//already triggered?
479
+			if (in_array($reg->status_ID(), $statuses_sent)) {
480
+				continue;
481
+			}
482
+
483
+			$message_type    = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
484
+			$mtgs            = array_merge(
485
+					$mtgs,
486
+					self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
487
+							$message_type,
488
+							array($registration->transaction(), null, $reg->status_ID())
489
+					)
490
+			);
491
+			$statuses_sent[] = $reg->status_ID();
492
+		}
493
+
494
+		if (count($statuses_sent) > 1) {
495
+			$mtgs = array_merge(
496
+				$mtgs,
497
+				self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
498
+					'registration_summary',
499
+					array($registration->transaction(), null)
500
+				)
501
+			);
502
+		}
503
+
504
+		//batch queue and initiate request
505
+		self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
506
+		self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
507
+	}
508
+
509
+
510
+	/**
511
+	 * This is a helper method used to very whether a registration notification should be sent or
512
+	 * not.  Prevents duplicate notifications going out for registration context notifications.
513
+	 *
514
+	 * @param EE_Registration $registration  [description]
515
+	 * @param array           $extra_details [description]
516
+	 * @return bool          true = send away, false = nope halt the presses.
517
+	 */
518
+	protected static function _verify_registration_notification_send(
519
+		EE_Registration $registration,
520
+		$extra_details = array()
521
+	) {
522
+		//self::log(
523
+		//	__CLASS__, __FUNCTION__, __LINE__,
524
+		//	$registration->transaction(),
525
+		//	array( '$extra_details' => $extra_details )
526
+		//);
527
+		// currently only using this to send messages for the primary registrant
528
+		if (! $registration->is_primary_registrant()) {
529
+			return false;
530
+		}
531
+		// first we check if we're in admin and not doing front ajax
532
+		if (is_admin() && ! EE_FRONT_AJAX) {
533
+			//make sure appropriate admin params are set for sending messages
534
+			if (empty($_REQUEST['txn_reg_status_change']['send_notifications']) || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])) {
535
+				//no messages sent please.
536
+				return false;
537
+			}
538
+		} else {
539
+			// frontend request (either regular or via AJAX)
540
+			// TXN is NOT finalized ?
541
+			if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
542
+				return false;
543
+			}
544
+			// return visit but nothing changed ???
545
+			if (
546
+				isset($extra_details['revisit'], $extra_details['status_updates']) &&
547
+				$extra_details['revisit'] && ! $extra_details['status_updates']
548
+			) {
549
+				return false;
550
+			}
551
+			// NOT sending messages && reg status is something other than "Not-Approved"
552
+			if (
553
+				! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
554
+				$registration->status_ID() !== EEM_Registration::status_id_not_approved
555
+			) {
556
+				return false;
557
+			}
558
+		}
559
+		// release the kraken
560
+		return true;
561
+	}
562
+
563
+
564
+	/**
565
+	 * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
566
+	 * status id.
567
+	 *
568
+	 * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
569
+	 *                    or EEH_MSG_Template::convert_reg_status_to_message_type
570
+	 * @param string $reg_status
571
+	 * @return array
572
+	 */
573
+	protected static function _get_reg_status_array($reg_status = '')
574
+	{
575
+		EE_Registry::instance()->load_helper('MSG_Template');
576
+		return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
577
+			? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
578
+			: EEH_MSG_Template::reg_status_to_message_type_array();
579
+	}
580
+
581
+
582
+	/**
583
+	 * Simply returns the payment message type for the given payment status.
584
+	 *
585
+	 * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
586
+	 *                   or EEH_MSG_Template::convert_payment_status_to_message_type
587
+	 * @param string $payment_status The payment status being matched.
588
+	 * @return string|bool The payment message type slug matching the status or false if no match.
589
+	 */
590
+	protected static function _get_payment_message_type($payment_status)
591
+	{
592
+		EE_Registry::instance()->load_helper('MSG_Template');
593
+		return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
594
+			? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
595
+			: false;
596
+	}
597
+
598
+
599
+	/**
600
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
601
+	 *
602
+	 * @access public
603
+	 * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
604
+	 * @return bool          success/fail
605
+	 */
606
+	public static function process_resend($req_data)
607
+	{
608
+		self::_load_controller();
609
+
610
+		//if $msgID in this request then skip to the new resend_message
611
+		if (EE_Registry::instance()->REQ->get('MSG_ID')) {
612
+			return self::resend_message();
613
+		}
614
+
615
+		//make sure any incoming request data is set on the REQ so that it gets picked up later.
616
+		$req_data = (array)$req_data;
617
+		foreach ($req_data as $request_key => $request_value) {
618
+			EE_Registry::instance()->REQ->set($request_key, $request_value);
619
+		}
620
+
621
+		if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
622
+			return false;
623
+		}
624
+
625
+		try {
626
+			self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
627
+			self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
628
+		} catch (EE_Error $e) {
629
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
630
+			return false;
631
+		}
632
+		EE_Error::add_success(
633
+			__('Messages have been successfully queued for generation and sending.', 'event_espresso')
634
+		);
635
+		return true; //everything got queued.
636
+	}
637
+
638
+
639
+	/**
640
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
641
+	 *
642
+	 * @return bool
643
+	 */
644
+	public static function resend_message()
645
+	{
646
+		self::_load_controller();
647
+
648
+		$msgID = EE_Registry::instance()->REQ->get('MSG_ID');
649
+		if (! $msgID) {
650
+			EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
651
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
652
+			return false;
653
+		}
654
+
655
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
656
+
657
+		//setup success message.
658
+		$count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
659
+		EE_Error::add_success(sprintf(
660
+			_n(
661
+				'There was %d message queued for resending.',
662
+				'There were %d messages queued for resending.',
663
+				$count_ready_for_resend,
664
+				'event_espresso'
665
+			),
666
+			$count_ready_for_resend
667
+		));
668
+		return true;
669
+	}
670
+
671
+
672
+	/**
673
+	 * Message triggers for manual payment applied by admin
674
+	 *
675
+	 * @param  EE_Payment $payment EE_payment object
676
+	 * @return bool              success/fail
677
+	 */
678
+	public static function process_admin_payment(EE_Payment $payment)
679
+	{
680
+		EE_Registry::instance()->load_helper('MSG_Template');
681
+		//we need to get the transaction object
682
+		$transaction = $payment->transaction();
683
+		if ($transaction instanceof EE_Transaction) {
684
+			$data         = array($transaction, $payment);
685
+			$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
686
+
687
+			//if payment amount is less than 0 then switch to payment_refund message type.
688
+			$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
689
+
690
+			//if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
691
+			$message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved ? false : $message_type;
692
+
693
+			self::_load_controller();
694
+
695
+			self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
696
+
697
+			//get count of queued for generation
698
+			$count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(array(
699
+				EEM_Message::status_incomplete,
700
+				EEM_Message::status_idle,
701
+			));
702
+
703
+			if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
704
+				add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
705
+				return true;
706
+			} else {
707
+				$count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending());
708
+				/**
709
+				 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
710
+				 * IMMEDIATE generation.
711
+				 */
712
+				if ($count_failed > 0) {
713
+					EE_Error::add_error(sprintf(
714
+						_n(
715
+							'The payment notification generation failed.',
716
+							'%d payment notifications failed being sent.',
717
+							$count_failed,
718
+							'event_espresso'
719
+						),
720
+						$count_failed
721
+					), __FILE__, __FUNCTION__, __LINE__);
722
+
723
+					return false;
724
+				} else {
725
+					add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
726
+					return true;
727
+				}
728
+			}
729
+		} else {
730
+			EE_Error::add_error(
731
+				'Unable to generate the payment notification because the given value for the transaction is invalid.',
732
+				'event_espresso'
733
+			);
734
+			return false;
735
+		}
736
+	}
737
+
738
+
739
+	/**
740
+	 * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
741
+	 *
742
+	 * @since   4.3.0
743
+	 * @param  EE_Registration[] $registrations an array of EE_Registration objects
744
+	 * @param  int               $grp_id        a specific message template group id.
745
+	 * @return void
746
+	 */
747
+	public static function send_newsletter_message($registrations, $grp_id)
748
+	{
749
+		//make sure mtp is id and set it in the EE_Request Handler later messages setup.
750
+		EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
751
+		self::_load_controller();
752
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
753
+	}
754
+
755
+
756
+	/**
757
+	 * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
758
+	 *
759
+	 * @since   4.3.0
760
+	 * @param    string          $registration_message_trigger_url
761
+	 * @param    EE_Registration $registration
762
+	 * @param string             $messenger
763
+	 * @param string             $message_type
764
+	 * @return    string
765
+	 */
766
+	public static function registration_message_trigger_url(
767
+		$registration_message_trigger_url,
768
+		EE_Registration $registration,
769
+		$messenger = 'html',
770
+		$message_type = 'invoice'
771
+	) {
772
+		// whitelist $messenger
773
+		switch ($messenger) {
774
+			case 'pdf' :
775
+				$sending_messenger    = 'pdf';
776
+				$generating_messenger = 'html';
777
+				break;
778
+			case 'html' :
779
+			default :
780
+				$sending_messenger    = 'html';
781
+				$generating_messenger = 'html';
782
+				break;
783
+		}
784
+		// whitelist $message_type
785
+		switch ($message_type) {
786
+			case 'receipt' :
787
+				$message_type = 'receipt';
788
+				break;
789
+			case 'invoice' :
790
+			default :
791
+				$message_type = 'invoice';
792
+				break;
793
+		}
794
+		// verify that both the messenger AND the message type are active
795
+		if (EEH_MSG_Template::is_messenger_active($sending_messenger) && EEH_MSG_Template::is_mt_active($message_type)) {
796
+			//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?)
797
+			$template_query_params = array(
798
+				'MTP_is_active'    => true,
799
+				'MTP_messenger'    => $generating_messenger,
800
+				'MTP_message_type' => $message_type,
801
+				'Event.EVT_ID'     => $registration->event_ID(),
802
+			);
803
+			//get the message template group.
804
+			$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
805
+			//if we don't have an EE_Message_Template_Group then return
806
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
807
+				// remove EVT_ID from query params so that global templates get picked up
808
+				unset($template_query_params['Event.EVT_ID']);
809
+				//get global template as the fallback
810
+				$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
811
+			}
812
+			//if we don't have an EE_Message_Template_Group then return
813
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
814
+				return '';
815
+			}
816
+			// generate the URL
817
+			$registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
818
+				$sending_messenger,
819
+				$generating_messenger,
820
+				'purchaser',
821
+				$message_type,
822
+				$registration,
823
+				$msg_template_group->ID(),
824
+				$registration->transaction_ID()
825
+			);
826
+
827
+		}
828
+		return $registration_message_trigger_url;
829
+	}
830
+
831
+
832
+	/**
833
+	 * Use to generate and return a message preview!
834
+	 *
835
+	 * @param  string $type      This should correspond with a valid message type
836
+	 * @param  string $context   This should correspond with a valid context for the message type
837
+	 * @param  string $messenger This should correspond with a valid messenger.
838
+	 * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
839
+	 *                           preview
840
+	 * @return string|bool          The body of the message or if send is requested, sends.
841
+	 */
842
+	public static function preview_message($type, $context, $messenger, $send = false)
843
+	{
844
+		self::_load_controller();
845
+		$mtg                     = new EE_Message_To_Generate(
846
+			$messenger,
847
+			$type,
848
+			array(),
849
+			$context,
850
+			true
851
+		);
852
+		$generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
853
+		if ($generated_preview_queue instanceof EE_Messages_Queue) {
854
+			return $generated_preview_queue->get_message_repository()->current()->content();
855
+		} else {
856
+			return $generated_preview_queue;
857
+		}
858
+	}
859
+
860
+
861
+	/**
862
+	 * This is a method that allows for sending a message using a messenger matching the string given and the provided
863
+	 * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
864
+	 * content found in the EE_Message objects in the queue.
865
+	 *
866
+	 * @since 4.9.0
867
+	 * @param string            $messenger            a string matching a valid active messenger in the system
868
+	 * @param string            $message_type         Although it seems contrary to the name of the method, a message
869
+	 *                                                type name is still required to send along the message type to the
870
+	 *                                                messenger because this is used for determining what specific
871
+	 *                                                variations might be loaded for the generated message.
872
+	 * @param EE_Messages_Queue $queue
873
+	 * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
874
+	 *                                                aggregate EE_Message object.
875
+	 * @return bool          success or fail.
876
+	 */
877
+	public static function send_message_with_messenger_only(
878
+		$messenger,
879
+		$message_type,
880
+		EE_Messages_Queue $queue,
881
+		$custom_subject = ''
882
+	) {
883
+		self::_load_controller();
884
+		/** @type EE_Message_To_Generate_From_Queue $message_to_generate */
885
+		$message_to_generate = EE_Registry::instance()->load_lib(
886
+			'Message_To_Generate_From_Queue',
887
+			array(
888
+				$messenger,
889
+				$message_type,
890
+				$queue,
891
+				$custom_subject,
892
+			)
893
+		);
894
+		return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
895
+	}
896
+
897
+
898
+	/**
899
+	 * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
900
+	 *
901
+	 * @since 4.9.0
902
+	 * @param array $message_ids An array of message ids
903
+	 * @return bool | EE_Messages_Queue     false if nothing was generated, EE_Messages_Queue containing generated
904
+	 *              messages.
905
+	 */
906
+	public static function generate_now($message_ids)
907
+	{
908
+		self::_load_controller();
909
+		$messages        = EEM_Message::instance()->get_all(
910
+			array(
911
+				0 => array(
912
+					'MSG_ID' => array('IN', $message_ids),
913
+					'STS_ID' => EEM_Message::status_incomplete,
914
+				),
915
+			)
916
+		);
917
+		$generated_queue = false;
918
+		if ($messages) {
919
+			$generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
920
+		}
921
+
922
+		if (! $generated_queue instanceof EE_Messages_Queue) {
923
+			EE_Error::add_error(
924
+				__('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.',
925
+					'event_espresso'),
926
+				__FILE__, __FUNCTION__, __LINE__
927
+			);
928
+		}
929
+		return $generated_queue;
930
+	}
931
+
932
+
933
+	/**
934
+	 * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
935
+	 * EEM_Message::status_idle
936
+	 *
937
+	 * @since 4.9.0
938
+	 * @param $message_ids
939
+	 * @return bool | EE_Messages_Queue  false if no messages sent.
940
+	 */
941
+	public static function send_now($message_ids)
942
+	{
943
+		self::_load_controller();
944
+		$messages   = EEM_Message::instance()->get_all(
945
+			array(
946
+				0 => array(
947
+					'MSG_ID' => array('IN', $message_ids),
948
+					'STS_ID' => array(
949
+						'IN',
950
+						array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
951
+					),
952
+				),
953
+			)
954
+		);
955
+		$sent_queue = false;
956
+		if ($messages) {
957
+			$sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
958
+		}
959
+
960
+		if (! $sent_queue instanceof EE_Messages_Queue) {
961
+			EE_Error::add_error(
962
+				__('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.',
963
+					'event_espresso'),
964
+				__FILE__, __FUNCTION__, __LINE__
965
+			);
966
+		} else {
967
+			//can count how many sent by using the messages in the queue
968
+			$sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
969
+			if ($sent_count > 0) {
970
+				EE_Error::add_success(
971
+					sprintf(
972
+						_n(
973
+							'There was %d message successfully sent.',
974
+							'There were %d messages successfully sent.',
975
+							$sent_count,
976
+							'event_espresso'
977
+						),
978
+						$sent_count
979
+					)
980
+				);
981
+			} else {
982
+				EE_Error::overwrite_errors();
983
+				EE_Error::add_error(
984
+					__('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.
985 985
 					If there was an error, you can look at the messages in the message activity list table for any error messages.',
986
-                        'event_espresso'),
987
-                    __FILE__, __FUNCTION__, __LINE__
988
-                );
989
-            }
990
-        }
991
-        return $sent_queue;
992
-    }
993
-
994
-
995
-    /**
996
-     * This will queue the incoming message ids for resending.
997
-     * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
998
-     *
999
-     * @since 4.9.0
1000
-     * @param array $message_ids An array of EE_Message IDs
1001
-     * @return bool  true means messages were successfully queued for resending, false means none were queued for
1002
-     *               resending.
1003
-     */
1004
-    public static function queue_for_resending($message_ids)
1005
-    {
1006
-        self::_load_controller();
1007
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1008
-
1009
-        //get queue and count
1010
-        $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1011
-
1012
-        if (
1013
-            $queue_count > 0
1014
-        ) {
1015
-            EE_Error::add_success(
1016
-                sprintf(
1017
-                    _n(
1018
-                        '%d message successfully queued for resending.',
1019
-                        '%d messages successfully queued for resending.',
1020
-                        $queue_count,
1021
-                        'event_espresso'
1022
-                    ),
1023
-                    $queue_count
1024
-                )
1025
-            );
1026
-            /**
1027
-             * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1028
-             */
1029
-        } elseif (
1030
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1031
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1032
-        ) {
1033
-            $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1034
-            if ($queue_count > 0) {
1035
-                EE_Error::add_success(
1036
-                    sprintf(
1037
-                        _n(
1038
-                            '%d message successfully sent.',
1039
-                            '%d messages successfully sent.',
1040
-                            $queue_count,
1041
-                            'event_espresso'
1042
-                        ),
1043
-                        $queue_count
1044
-                    )
1045
-                );
1046
-            } else {
1047
-                EE_Error::add_error(
1048
-                    __('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.',
1049
-                        'event_espresso'),
1050
-                    __FILE__, __FUNCTION__, __LINE__
1051
-                );
1052
-            }
1053
-        } else {
1054
-            EE_Error::add_error(
1055
-                __('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.',
1056
-                    'event_espresso'),
1057
-                __FILE__, __FUNCTION__, __LINE__
1058
-            );
1059
-        }
1060
-        return (bool)$queue_count;
1061
-    }
1062
-
1063
-
1064
-    /**
1065
-     * debug
1066
-     *
1067
-     * @param string          $class
1068
-     * @param string          $func
1069
-     * @param string          $line
1070
-     * @param \EE_Transaction $transaction
1071
-     * @param array           $info
1072
-     * @param bool            $display_request
1073
-     */
1074
-    protected static function log(
1075
-        $class = '',
1076
-        $func = '',
1077
-        $line = '',
1078
-        EE_Transaction $transaction,
1079
-        $info = array(),
1080
-        $display_request = false
1081
-    ) {
1082
-        if (WP_DEBUG && false) {
1083
-            if ($transaction instanceof EE_Transaction) {
1084
-                // don't serialize objects
1085
-                $info                  = EEH_Debug_Tools::strip_objects($info);
1086
-                $info['TXN_status']    = $transaction->status_ID();
1087
-                $info['TXN_reg_steps'] = $transaction->reg_steps();
1088
-                if ($transaction->ID()) {
1089
-                    $index = 'EE_Transaction: ' . $transaction->ID();
1090
-                    EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1091
-                }
1092
-            }
1093
-        }
1094
-
1095
-    }
1096
-
1097
-
1098
-    /**
1099
-     *  Resets all the static properties in this class when called.
1100
-     */
1101
-    public static function reset()
1102
-    {
1103
-        self::$_EEMSG                    = null;
1104
-        self::$_message_resource_manager = null;
1105
-        self::$_MSG_PROCESSOR            = null;
1106
-        self::$_MSG_PATHS                = null;
1107
-        self::$_TMP_PACKS                = array();
1108
-    }
986
+						'event_espresso'),
987
+					__FILE__, __FUNCTION__, __LINE__
988
+				);
989
+			}
990
+		}
991
+		return $sent_queue;
992
+	}
993
+
994
+
995
+	/**
996
+	 * This will queue the incoming message ids for resending.
997
+	 * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
998
+	 *
999
+	 * @since 4.9.0
1000
+	 * @param array $message_ids An array of EE_Message IDs
1001
+	 * @return bool  true means messages were successfully queued for resending, false means none were queued for
1002
+	 *               resending.
1003
+	 */
1004
+	public static function queue_for_resending($message_ids)
1005
+	{
1006
+		self::_load_controller();
1007
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1008
+
1009
+		//get queue and count
1010
+		$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1011
+
1012
+		if (
1013
+			$queue_count > 0
1014
+		) {
1015
+			EE_Error::add_success(
1016
+				sprintf(
1017
+					_n(
1018
+						'%d message successfully queued for resending.',
1019
+						'%d messages successfully queued for resending.',
1020
+						$queue_count,
1021
+						'event_espresso'
1022
+					),
1023
+					$queue_count
1024
+				)
1025
+			);
1026
+			/**
1027
+			 * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1028
+			 */
1029
+		} elseif (
1030
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1031
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1032
+		) {
1033
+			$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1034
+			if ($queue_count > 0) {
1035
+				EE_Error::add_success(
1036
+					sprintf(
1037
+						_n(
1038
+							'%d message successfully sent.',
1039
+							'%d messages successfully sent.',
1040
+							$queue_count,
1041
+							'event_espresso'
1042
+						),
1043
+						$queue_count
1044
+					)
1045
+				);
1046
+			} else {
1047
+				EE_Error::add_error(
1048
+					__('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.',
1049
+						'event_espresso'),
1050
+					__FILE__, __FUNCTION__, __LINE__
1051
+				);
1052
+			}
1053
+		} else {
1054
+			EE_Error::add_error(
1055
+				__('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.',
1056
+					'event_espresso'),
1057
+				__FILE__, __FUNCTION__, __LINE__
1058
+			);
1059
+		}
1060
+		return (bool)$queue_count;
1061
+	}
1062
+
1063
+
1064
+	/**
1065
+	 * debug
1066
+	 *
1067
+	 * @param string          $class
1068
+	 * @param string          $func
1069
+	 * @param string          $line
1070
+	 * @param \EE_Transaction $transaction
1071
+	 * @param array           $info
1072
+	 * @param bool            $display_request
1073
+	 */
1074
+	protected static function log(
1075
+		$class = '',
1076
+		$func = '',
1077
+		$line = '',
1078
+		EE_Transaction $transaction,
1079
+		$info = array(),
1080
+		$display_request = false
1081
+	) {
1082
+		if (WP_DEBUG && false) {
1083
+			if ($transaction instanceof EE_Transaction) {
1084
+				// don't serialize objects
1085
+				$info                  = EEH_Debug_Tools::strip_objects($info);
1086
+				$info['TXN_status']    = $transaction->status_ID();
1087
+				$info['TXN_reg_steps'] = $transaction->reg_steps();
1088
+				if ($transaction->ID()) {
1089
+					$index = 'EE_Transaction: ' . $transaction->ID();
1090
+					EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1091
+				}
1092
+			}
1093
+		}
1094
+
1095
+	}
1096
+
1097
+
1098
+	/**
1099
+	 *  Resets all the static properties in this class when called.
1100
+	 */
1101
+	public static function reset()
1102
+	{
1103
+		self::$_EEMSG                    = null;
1104
+		self::$_message_resource_manager = null;
1105
+		self::$_MSG_PROCESSOR            = null;
1106
+		self::$_MSG_PATHS                = null;
1107
+		self::$_TMP_PACKS                = array();
1108
+	}
1109 1109
 
1110 1110
 }
1111 1111
 // End of file EED_Messages.module.php
Please login to merge, or discard this patch.
libraries/messages/data_class/EE_Messages_Gateways_incoming_data.class.php 2 patches
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -135,11 +135,11 @@  discard block
 block discarded – undo
135 135
 
136 136
 
137 137
 
138
-    /**
139
-     * _setup_data
140
-     *
141
-     * @throws EE_Error
142
-     */
138
+	/**
139
+	 * _setup_data
140
+	 *
141
+	 * @throws EE_Error
142
+	 */
143 143
 	protected function _setup_data() {
144 144
 
145 145
 		$this->reg_info = array();
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 		$this->ip_address = isset( $session_data['ip_address'] ) ? $session_data['ip_address'] : '';
158 158
 		$this->user_agent = isset( $session_data['user_agent'] ) ? $session_data['user_agent'] : '';
159 159
 		$this->init_access = $this->last_access = '';
160
-        //get all non-trashed registrations
160
+		//get all non-trashed registrations
161 161
 		$this->reg_objs = $this->txn->registrations(array(array('REG_deleted' => false)));
162 162
 		$this->_assemble_data();
163 163
 
Please login to merge, or discard this patch.
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-if (!defined('EVENT_ESPRESSO_VERSION') )
3
+if ( ! defined('EVENT_ESPRESSO_VERSION'))
4 4
 	exit('NO direct script access allowed');
5 5
 
6 6
 /**
@@ -44,25 +44,25 @@  discard block
 block discarded – undo
44 44
 	 * @param array $data
45 45
 	 * @throws EE_Error
46 46
 	 */
47
-	public function __construct( $data ) {
47
+	public function __construct($data) {
48 48
 
49 49
 		//test for valid params
50
-		if ( ! ( $data[0] instanceof EE_Transaction ))
51
-			throw new EE_Error( __('Incoming data for the Gateways data handler must have an EE_Transaction object as the value for the first array index.', 'event_espresso') );
50
+		if ( ! ($data[0] instanceof EE_Transaction))
51
+			throw new EE_Error(__('Incoming data for the Gateways data handler must have an EE_Transaction object as the value for the first array index.', 'event_espresso'));
52 52
 
53
-		if ( empty( $data[1] ) || ! $data[1] instanceof  EE_Payment  )
54
-			$pmt_obj = $this->_get_empty_payment_obj( $data[0] );
53
+		if (empty($data[1]) || ! $data[1] instanceof  EE_Payment)
54
+			$pmt_obj = $this->_get_empty_payment_obj($data[0]);
55 55
 
56
-		if ( ! empty( $data[2] ) ) {
56
+		if ( ! empty($data[2])) {
57 57
 			$filtered_reg_status = $data[2];
58 58
 		}
59 59
 
60 60
 		$data = array(
61 61
 			'txn_obj' => $data[0],
62 62
 			'pmt_obj' => isset($pmt_obj) ? $pmt_obj : $data[1],
63
-			'filtered_reg_status' => isset( $filtered_reg_status ) ? $filtered_reg_status : null
63
+			'filtered_reg_status' => isset($filtered_reg_status) ? $filtered_reg_status : null
64 64
 			);
65
-		parent::__construct( $data );
65
+		parent::__construct($data);
66 66
 	}
67 67
 
68 68
 
@@ -76,18 +76,18 @@  discard block
 block discarded – undo
76 76
 	 *
77 77
 	 * @return array   The prepped data for db
78 78
 	 */
79
-	static public function convert_data_for_persistent_storage( $data ) {
79
+	static public function convert_data_for_persistent_storage($data) {
80 80
 		$prepped_data = array();
81 81
 
82
-		if ( $data[0] instanceof EE_Transaction ) {
82
+		if ($data[0] instanceof EE_Transaction) {
83 83
 			$prepped_data['Transaction'] = $data[0]->ID();
84 84
 		}
85 85
 
86
-		if ( isset( $data[1] ) && $data[1] instanceof EE_Payment ) {
86
+		if (isset($data[1]) && $data[1] instanceof EE_Payment) {
87 87
 			$prepped_data['Payment'] = $data[1]->ID();
88 88
 		}
89 89
 
90
-		if ( ! empty( $data[2] ) ) {
90
+		if ( ! empty($data[2])) {
91 91
 			$prepped_data['filter'] = $data[2];
92 92
 		}
93 93
 
@@ -107,11 +107,11 @@  discard block
 block discarded – undo
107 107
 	 *
108 108
 	 * @return array
109 109
 	 */
110
-	static public function convert_data_from_persistent_storage( $data ) {
110
+	static public function convert_data_from_persistent_storage($data) {
111 111
 		$prepped_data = array(
112
-			0 => isset( $data['Transaction'] ) ? EEM_Transaction::instance()->get_one_by_ID( $data['Transaction'] ) : null,
113
-			1 => isset( $data['Payment'] ) ? EEM_Payment::instance()->get_one_by_ID( $data['Payment'] ) : null,
114
-			2 => isset( $data['filter'] ) ? $data['filter'] : null
112
+			0 => isset($data['Transaction']) ? EEM_Transaction::instance()->get_one_by_ID($data['Transaction']) : null,
113
+			1 => isset($data['Payment']) ? EEM_Payment::instance()->get_one_by_ID($data['Payment']) : null,
114
+			2 => isset($data['filter']) ? $data['filter'] : null
115 115
 		);
116 116
 		return $prepped_data;
117 117
 	}
@@ -122,8 +122,8 @@  discard block
 block discarded – undo
122 122
 	 * @param \EE_Transaction $txn
123 123
 	 * @return \EE_Payment
124 124
 	 */
125
-	private function _get_empty_payment_obj( EE_Transaction $txn ) {
126
-		$PMT = EE_Payment::new_instance( array(
125
+	private function _get_empty_payment_obj(EE_Transaction $txn) {
126
+		$PMT = EE_Payment::new_instance(array(
127 127
 			'STS_ID' => EEM_Payment::status_id_pending,
128 128
 			'PAY_timestamp' => time(),
129 129
 			'PMD_ID' => $txn->payment_method_ID(),
@@ -153,9 +153,9 @@  discard block
 block discarded – undo
153 153
 
154 154
 
155 155
 		//other data from the session (if possible)
156
-		$this->user_id = isset( $session_data['user_id'] ) ? $session_data['user_id'] : '';
157
-		$this->ip_address = isset( $session_data['ip_address'] ) ? $session_data['ip_address'] : '';
158
-		$this->user_agent = isset( $session_data['user_agent'] ) ? $session_data['user_agent'] : '';
156
+		$this->user_id = isset($session_data['user_id']) ? $session_data['user_id'] : '';
157
+		$this->ip_address = isset($session_data['ip_address']) ? $session_data['ip_address'] : '';
158
+		$this->user_agent = isset($session_data['user_agent']) ? $session_data['user_agent'] : '';
159 159
 		$this->init_access = $this->last_access = '';
160 160
         //get all non-trashed registrations
161 161
 		$this->reg_objs = $this->txn->registrations(array(array('REG_deleted' => false)));
Please login to merge, or discard this patch.
core/services/Benchmark.php 2 patches
Indentation   +226 added lines, -226 removed lines patch added patch discarded remove patch
@@ -17,232 +17,232 @@
 block discarded – undo
17 17
 class Benchmark
18 18
 {
19 19
 
20
-    /**
21
-     * array containing the start time for the timers
22
-     */
23
-    private static $start_times;
24
-
25
-    /**
26
-     * array containing all the timer'd times, which can be outputted via show_times()
27
-     */
28
-    private static $times = array();
29
-
30
-    /**
31
-     * @var array
32
-     */
33
-    protected static $memory_usage = array();
34
-
35
-
36
-
37
-    /**
38
-     * whether to benchmark code or not
39
-     */
40
-    public static function doNotRun()
41
-    {
42
-        return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
43
-    }
44
-
45
-
46
-
47
-    /**
48
-     * resetTimes
49
-     */
50
-    public static function resetTimes()
51
-    {
52
-        Benchmark::$times = array();
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * Add Benchmark::startTimer() before a block of code you want to measure the performance of
59
-     *
60
-     * @param null $timer_name
61
-     */
62
-    public static function startTimer($timer_name = null)
63
-    {
64
-        if (Benchmark::doNotRun()) {
65
-            return;
66
-        }
67
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
68
-        Benchmark::$start_times[$timer_name] = microtime(true);
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
75
-     *
76
-     * @param string $timer_name
77
-     */
78
-    public static function stopTimer($timer_name = '')
79
-    {
80
-        if (Benchmark::doNotRun()) {
81
-            return;
82
-        }
83
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
84
-        if (isset(Benchmark::$start_times[$timer_name])) {
85
-            $start_time = Benchmark::$start_times[$timer_name];
86
-            unset(Benchmark::$start_times[$timer_name]);
87
-        } else {
88
-            $start_time = array_pop(Benchmark::$start_times);
89
-        }
90
-        Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     * Measure the memory usage by PHP so far.
97
-     *
98
-     * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
99
-     * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
100
-     * @return void
101
-     */
102
-    public static function measureMemory($label, $output_now = false)
103
-    {
104
-        if (Benchmark::doNotRun()) {
105
-            return;
106
-        }
107
-        $memory_used = Benchmark::convert(memory_get_peak_usage(true));
108
-        Benchmark::$memory_usage[$label] = $memory_used;
109
-        if ($output_now) {
110
-            echo "\r\n<br>$label : $memory_used";
111
-        }
112
-    }
113
-
114
-
115
-
116
-    /**
117
-     * will display the benchmarking results at shutdown
118
-     *
119
-     * @return void
120
-     */
121
-    public static function displayResultsAtShutdown()
122
-    {
123
-        add_action(
124
-            'shutdown',
125
-            function () {
126
-                Benchmark::displayResults();
127
-            }
128
-        );
129
-    }
130
-
131
-
132
-
133
-    /**
134
-     * displayResults
135
-     *
136
-     * @param bool $echo
137
-     * @return string
138
-     */
139
-    public static function displayResults($echo = true)
140
-    {
141
-        if (Benchmark::doNotRun()) {
142
-            return '';
143
-        }
144
-        $output = '';
145
-        if (! empty(Benchmark::$times)) {
146
-            $total = 0;
147
-            $output .= '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />';
148
-            foreach (Benchmark::$times as $timer_name => $total_time) {
149
-                $output .= Benchmark::formatTime($timer_name, $total_time) . '<br />';
150
-                $total += $total_time;
151
-            }
152
-            $output .= '<br />';
153
-            $output .= '<h4>TOTAL TIME</h4>';
154
-            $output .= Benchmark::formatTime('', $total);
155
-            $output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
156
-            $output .= '<br />';
157
-            $output .= '<h5>Performance scale (from best to worse)</h5>';
158
-            $output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
159
-            $output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
160
-            $output .= '<span style="color:limegreen">Like...groovy!</span><br />';
161
-            $output .= '<span style="color:gold">Ruh Oh</span><br />';
162
-            $output .= '<span style="color:darkorange">Zoinks!</span><br />';
163
-            $output .= '<span style="color:red">Like...HEEELLLP</span><br />';
164
-        }
165
-        if (! empty(Benchmark::$memory_usage)) {
166
-            $output .= '<h5>Memory</h5>';
167
-            foreach (Benchmark::$memory_usage as $label => $memory_usage) {
168
-                $output .= "<br /> {$memory_usage} : {$label}";
169
-            }
170
-        }
171
-        if (empty($output)) {
172
-            return '';
173
-        }
174
-        $output = '<div style="border:1px solid #dddddd; background-color:#ffffff;'
175
-                  . (is_admin() ? ' margin:2em 2em 2em 180px;' : ' margin:2em;')
176
-                  . ' padding:2em;">'
177
-                  . '<h4>BENCHMARKING</h4>'
178
-                  . $output
179
-                  . '</div>';
180
-        if ($echo) {
181
-            echo $output;
182
-            return '';
183
-        }
184
-        return $output;
185
-    }
186
-
187
-
188
-
189
-    /**
190
-     * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
191
-     *
192
-     * @param int $size
193
-     * @return string
194
-     */
195
-    public static function convert($size)
196
-    {
197
-        $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
198
-        return round($size / pow(1024, $i = floor(log($size, 1024))), 2) . ' ' . $unit[absint($i)];
199
-    }
200
-
201
-
202
-
203
-    /**
204
-     * @param string $timer_name
205
-     * @param float  $total_time
206
-     * @return string
207
-     */
208
-    public static function formatTime($timer_name, $total_time)
209
-    {
210
-        $total_time *= 1000;
211
-        switch ($total_time) {
212
-            case $total_time > 12500 :
213
-                $color = 'red';
214
-                $bold = 'bold';
215
-                break;
216
-            case $total_time > 2500 :
217
-                $color = 'darkorange';
218
-                $bold = 'bold';
219
-                break;
220
-            case $total_time > 500 :
221
-                $color = 'gold';
222
-                $bold = 'bold';
223
-                break;
224
-            case $total_time > 100 :
225
-                $color = 'limegreen';
226
-                $bold = 'normal';
227
-                break;
228
-            case $total_time > 20 :
229
-                $color = 'deepskyblue';
230
-                $bold = 'normal';
231
-                break;
232
-            default :
233
-                $color = 'mediumpurple';
234
-                $bold = 'normal';
235
-                break;
236
-        }
237
-        return '<span style="min-width: 10px; margin:0 1em; color:'
238
-               . $color
239
-               . '; font-weight:'
240
-               . $bold
241
-               . '; font-size:1.2em;">'
242
-               . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
243
-               . '</span> '
244
-               . $timer_name;
245
-    }
20
+	/**
21
+	 * array containing the start time for the timers
22
+	 */
23
+	private static $start_times;
24
+
25
+	/**
26
+	 * array containing all the timer'd times, which can be outputted via show_times()
27
+	 */
28
+	private static $times = array();
29
+
30
+	/**
31
+	 * @var array
32
+	 */
33
+	protected static $memory_usage = array();
34
+
35
+
36
+
37
+	/**
38
+	 * whether to benchmark code or not
39
+	 */
40
+	public static function doNotRun()
41
+	{
42
+		return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
43
+	}
44
+
45
+
46
+
47
+	/**
48
+	 * resetTimes
49
+	 */
50
+	public static function resetTimes()
51
+	{
52
+		Benchmark::$times = array();
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * Add Benchmark::startTimer() before a block of code you want to measure the performance of
59
+	 *
60
+	 * @param null $timer_name
61
+	 */
62
+	public static function startTimer($timer_name = null)
63
+	{
64
+		if (Benchmark::doNotRun()) {
65
+			return;
66
+		}
67
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
68
+		Benchmark::$start_times[$timer_name] = microtime(true);
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
75
+	 *
76
+	 * @param string $timer_name
77
+	 */
78
+	public static function stopTimer($timer_name = '')
79
+	{
80
+		if (Benchmark::doNotRun()) {
81
+			return;
82
+		}
83
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
84
+		if (isset(Benchmark::$start_times[$timer_name])) {
85
+			$start_time = Benchmark::$start_times[$timer_name];
86
+			unset(Benchmark::$start_times[$timer_name]);
87
+		} else {
88
+			$start_time = array_pop(Benchmark::$start_times);
89
+		}
90
+		Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 * Measure the memory usage by PHP so far.
97
+	 *
98
+	 * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
99
+	 * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
100
+	 * @return void
101
+	 */
102
+	public static function measureMemory($label, $output_now = false)
103
+	{
104
+		if (Benchmark::doNotRun()) {
105
+			return;
106
+		}
107
+		$memory_used = Benchmark::convert(memory_get_peak_usage(true));
108
+		Benchmark::$memory_usage[$label] = $memory_used;
109
+		if ($output_now) {
110
+			echo "\r\n<br>$label : $memory_used";
111
+		}
112
+	}
113
+
114
+
115
+
116
+	/**
117
+	 * will display the benchmarking results at shutdown
118
+	 *
119
+	 * @return void
120
+	 */
121
+	public static function displayResultsAtShutdown()
122
+	{
123
+		add_action(
124
+			'shutdown',
125
+			function () {
126
+				Benchmark::displayResults();
127
+			}
128
+		);
129
+	}
130
+
131
+
132
+
133
+	/**
134
+	 * displayResults
135
+	 *
136
+	 * @param bool $echo
137
+	 * @return string
138
+	 */
139
+	public static function displayResults($echo = true)
140
+	{
141
+		if (Benchmark::doNotRun()) {
142
+			return '';
143
+		}
144
+		$output = '';
145
+		if (! empty(Benchmark::$times)) {
146
+			$total = 0;
147
+			$output .= '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />';
148
+			foreach (Benchmark::$times as $timer_name => $total_time) {
149
+				$output .= Benchmark::formatTime($timer_name, $total_time) . '<br />';
150
+				$total += $total_time;
151
+			}
152
+			$output .= '<br />';
153
+			$output .= '<h4>TOTAL TIME</h4>';
154
+			$output .= Benchmark::formatTime('', $total);
155
+			$output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
156
+			$output .= '<br />';
157
+			$output .= '<h5>Performance scale (from best to worse)</h5>';
158
+			$output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
159
+			$output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
160
+			$output .= '<span style="color:limegreen">Like...groovy!</span><br />';
161
+			$output .= '<span style="color:gold">Ruh Oh</span><br />';
162
+			$output .= '<span style="color:darkorange">Zoinks!</span><br />';
163
+			$output .= '<span style="color:red">Like...HEEELLLP</span><br />';
164
+		}
165
+		if (! empty(Benchmark::$memory_usage)) {
166
+			$output .= '<h5>Memory</h5>';
167
+			foreach (Benchmark::$memory_usage as $label => $memory_usage) {
168
+				$output .= "<br /> {$memory_usage} : {$label}";
169
+			}
170
+		}
171
+		if (empty($output)) {
172
+			return '';
173
+		}
174
+		$output = '<div style="border:1px solid #dddddd; background-color:#ffffff;'
175
+				  . (is_admin() ? ' margin:2em 2em 2em 180px;' : ' margin:2em;')
176
+				  . ' padding:2em;">'
177
+				  . '<h4>BENCHMARKING</h4>'
178
+				  . $output
179
+				  . '</div>';
180
+		if ($echo) {
181
+			echo $output;
182
+			return '';
183
+		}
184
+		return $output;
185
+	}
186
+
187
+
188
+
189
+	/**
190
+	 * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
191
+	 *
192
+	 * @param int $size
193
+	 * @return string
194
+	 */
195
+	public static function convert($size)
196
+	{
197
+		$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
198
+		return round($size / pow(1024, $i = floor(log($size, 1024))), 2) . ' ' . $unit[absint($i)];
199
+	}
200
+
201
+
202
+
203
+	/**
204
+	 * @param string $timer_name
205
+	 * @param float  $total_time
206
+	 * @return string
207
+	 */
208
+	public static function formatTime($timer_name, $total_time)
209
+	{
210
+		$total_time *= 1000;
211
+		switch ($total_time) {
212
+			case $total_time > 12500 :
213
+				$color = 'red';
214
+				$bold = 'bold';
215
+				break;
216
+			case $total_time > 2500 :
217
+				$color = 'darkorange';
218
+				$bold = 'bold';
219
+				break;
220
+			case $total_time > 500 :
221
+				$color = 'gold';
222
+				$bold = 'bold';
223
+				break;
224
+			case $total_time > 100 :
225
+				$color = 'limegreen';
226
+				$bold = 'normal';
227
+				break;
228
+			case $total_time > 20 :
229
+				$color = 'deepskyblue';
230
+				$bold = 'normal';
231
+				break;
232
+			default :
233
+				$color = 'mediumpurple';
234
+				$bold = 'normal';
235
+				break;
236
+		}
237
+		return '<span style="min-width: 10px; margin:0 1em; color:'
238
+			   . $color
239
+			   . '; font-weight:'
240
+			   . $bold
241
+			   . '; font-size:1.2em;">'
242
+			   . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
243
+			   . '</span> '
244
+			   . $timer_name;
245
+	}
246 246
 
247 247
 
248 248
 
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
     {
123 123
         add_action(
124 124
             'shutdown',
125
-            function () {
125
+            function() {
126 126
                 Benchmark::displayResults();
127 127
             }
128 128
         );
@@ -142,11 +142,11 @@  discard block
 block discarded – undo
142 142
             return '';
143 143
         }
144 144
         $output = '';
145
-        if (! empty(Benchmark::$times)) {
145
+        if ( ! empty(Benchmark::$times)) {
146 146
             $total = 0;
147 147
             $output .= '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />';
148 148
             foreach (Benchmark::$times as $timer_name => $total_time) {
149
-                $output .= Benchmark::formatTime($timer_name, $total_time) . '<br />';
149
+                $output .= Benchmark::formatTime($timer_name, $total_time).'<br />';
150 150
                 $total += $total_time;
151 151
             }
152 152
             $output .= '<br />';
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
             $output .= '<span style="color:darkorange">Zoinks!</span><br />';
163 163
             $output .= '<span style="color:red">Like...HEEELLLP</span><br />';
164 164
         }
165
-        if (! empty(Benchmark::$memory_usage)) {
165
+        if ( ! empty(Benchmark::$memory_usage)) {
166 166
             $output .= '<h5>Memory</h5>';
167 167
             foreach (Benchmark::$memory_usage as $label => $memory_usage) {
168 168
                 $output .= "<br /> {$memory_usage} : {$label}";
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
     public static function convert($size)
196 196
     {
197 197
         $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
198
-        return round($size / pow(1024, $i = floor(log($size, 1024))), 2) . ' ' . $unit[absint($i)];
198
+        return round($size / pow(1024, $i = floor(log($size, 1024))), 2).' '.$unit[absint($i)];
199 199
     }
200 200
 
201 201
 
Please login to merge, or discard this patch.