Completed
Branch FET-9046-messages-queue (bdca24)
by
unknown
547:25 queued 529:16
created

EE_Messages::_validate_setup()   B

Complexity

Conditions 8
Paths 32

Size

Total Lines 55
Code Lines 30

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 55
rs 7.4033
cc 8
eloc 30
nc 32
nop 3

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
if (!defined('EVENT_ESPRESSO_VERSION') )
4
	exit('NO direct script access allowed');
5
6
/**
7
 * EE_Messages class
8
 *
9
 * This class is the main controller class for EE_Messages, it delegates messages to the messengers and contains other methods for obtaining various details about the active messengers and message types.
10
 *
11
 * @package		Event Espresso
12
 * @subpackage	includes/core/messages
13
 * @author		Darren Ethier, Brent Christensen
14
 *
15
 * ------------------------------------------------------------------------
16
 */
17
class EE_Messages {
18
19
20
	/**
21
	 * Array of active messengers.
22
	 * Format is this:
23
	 * array(
24
	 *      'messenger_name' => EE_messenger
25
	 * )
26
	 *
27
	 * @type EE_Messenger[]
28
	 */
29
	protected $_active_messengers = array();
30
31
32
33
34
	/**
35
	 * Formatted array of active message types grouped per messenger.
36
	 * Format is this:
37
	 * array(
38
	 *      'messenger_name' => array(
39
	 *          'settings' => array(
40
	 *              '{messenger_name}-message_types' => array(
41
	 *                  'message_type_name' => array() //variable array of settings corresponding to message type.
42
	 *              )
43
	 *          )
44
	 *      )
45
	 * )
46
	 * @type array
47
	 */
48
	protected $_active_message_types = array();
49
50
51
52
53
54
	/**
55
	 * @type EE_message_type[]
56
	 */
57
	protected $_installed_message_types = array();
58
59
60
61
62
63
	/**
64
	 * When setting up values this is a temporary holder of the current EE_messenger object.
65
	 *
66
*@type EE_Messenger
67
	 */
68
	protected $_messenger;
69
70
71
72
73
74
	/**
75
	 * When setting up values this is a temporary holder of the current EE_message_type object.
76
	 * @type EE_message_type
77
	 */
78
	protected $_message_type;
79
80
81
82
83
84
	/**
85
	 * An array of unique message type contexts across all active message types.
86
	 *
87
	 * The array will be indexed by either 'slugs' or 'all'.
88
	 * The slugs index contains an array indexed by unique context slugs with the latest label representation for that slug.
89
	 * array(
90
	 *      'context_slug' => 'localized label for context obtained from latest message type in the loop'.
91
	 * );
92
	 *
93
	 * The all index returns an array in this format:
94
	 * array(
95
	 *      'message_type_name' => array(
96
	 *          'context_slug' => array(
97
	 *              'label' => 'localized label for context',
98
	 *              'description' => 'localized description for context'
99
	 *          )
100
	 *      )
101
	 * );
102
	 * @type array
103
	 */
104
	protected $_contexts = array();
105
106
107
108
109
110
	/**
111
	 * holds the EEM_message_templates model for interacting with the database and retrieving active templates for the messenger
112
	 * @var object
113
	 */
114
	//private $_EEM_data;
115
116
117
118
	/**
119
	 * EE_Messages constructor.
120
	 */
121
	function __construct() {
122
		//load helper
123
		EE_Registry::instance()->load_helper('MSG_Template');
124
		// get list of active messengers and active message types
125
		//$this->_EEM_data = EEM_Message_Template::instance();
126
		$this->_set_active_messengers_and_message_types();
127
128
		//load debug tools
129
		//EE_Registry::instance()->load_helper('Debug_Tools');
130
	}
131
132
133
134
135
136
137
138
	/**
139
	 * get active messengers from db and instantiate them.
140
	 */
141
	private function _set_active_messengers_and_message_types() {
142
		// todo: right now this just gets active global messengers: at some point we'll have to get what the active messengers are for the event.
143
		$_actives = EEH_MSG_Template::get_active_messengers_in_db();
144
		$actives = is_array($_actives) ? array_keys($_actives) : $_actives;
145
		$active_names = $this->_load_files('messenger', $actives);
146
147
		if ( is_array($active_names) ) {
148
			foreach ( $active_names as $name => $class ) {
149
				$active = new $class();
150 View Code Duplication
				if ( ! $active instanceof EE_Messenger ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
151
					//we've got an error so let's bubble up the error_object to be caught by caller.
152
					//todo: would be better to just catch the errors and then return any aggregated errors later.
153
					EE_Error::add_error(
154
						sprintf(
155
							__( 'The "%1$s" messenger is not installed or is invalid', 'event_espresso' ),
156
							$class
157
						),
158
						__FILE__, __FUNCTION__, __LINE__
159
					);
160
				}
161
				$this->_active_messengers[$name] = $active;
162
				$this->_active_message_types[$name] = ! empty( $_actives[$name]['settings'][$name . '-message_types'] )
163
					? $_actives[$name]['settings'][$name . '-message_types']
164
					: array();
165
			}
166
		}
167
	}
168
169
	/**
170
	 * Ensures that the specified messenger is currently active.
171
	 * If not, activates it and its default message types.
172
	 *
173
	 * >>>>>>>>>>>> 1 usage in \EE_Payment_Method_Manager::activate_a_payment_method_of_type()
174
	 * >>>>>>>>>>>> 2 usages in \EE_messages_Test::test_ensure_messenger_is_active()
175
	 *
176
	 * @param string $messenger_name
177
	 * @return boolean TRUE if it was PREVIOUSLY active, and FALSE if it was previously inactive
178
	 */
179
	public function ensure_messenger_is_active( $messenger_name ){
180
		//note: active messengers indexed by their names
181
		$active_messengers = EEH_MSG_Template::get_active_messengers_in_db();
182
		if( ! isset( $active_messengers[ $messenger_name ] ) ) {
183
			$this->activate_messenger( $messenger_name );
184
			return FALSE;
185
		}else{
186
			return TRUE;
187
		}
188
	}
189
190
191
192
	/**
193
	 * Ensures that the specified message type for the given messenger is currently active, if not activates it.
194
	 * This ALSO ensures that the given messenger is active as well!.
195
	 *
196
	 * >>>>>>>>>>>> 1 usage in \EE_Payment_Method_Manager::activate_a_payment_method_of_type()
197
	 * >>>>>>>>>>>> 1 usage in \EE_Register_Message_Type::set_defaults()
198
	 *
199
	 * @param string $message_type message type name
200
	 * @param        $messenger
201
	 * @return bool true if it got activated (or was active) and false if not.
202
	 * @throws \EE_Error
203
	 */
204
	public function ensure_message_type_is_active( $message_type, $messenger ) {
205
		//first validate that the incoming messenger allows this message type to be activated.
206
		$messengers = $this->get_installed_messengers();
207
		if ( ! isset( $messengers[$messenger] ) ) {
208
			throw new EE_Error( sprintf( __('The messenger sent to %s is not installed', 'event_espresso'), __METHOD__ ) );
209
		}
210
211
		$msgr = $messengers[$messenger];
212
		$valid_message_types = $msgr instanceof EE_Messenger ? $msgr->get_valid_message_types() : array();
213
		if ( ! in_array( $message_type, $valid_message_types ) ) {
214
			throw new EE_Error(
215
				sprintf(
216
					__('The message type (%1$s) sent to %2$s is not valid for the %3$s messenger.  Double-check the spelling and verify that message type has been registered as a valid type with the messenger.', 'event_espresso' ),
217
					$message_type,
218
					__METHOD__,
219
					$messenger
220
				)
221
			);
222
		}
223
224
		//all is good so let's just get it active
225
		return $this->activate_messenger( $messenger, array( $message_type ) );
226
	}
227
228
	/**
229
	 * Activates the specified messenger
230
	 *
231
	 * >>>>>>>>>>>> 2 usages found in this file: ensure_message_type_is_active() and ensure_messenger_is_active()
232
	 *
233
	 * @param string $messenger_name
234
	 * @param array $mts_to_activate (optional) An array of message types to activate with this messenger.  If
235
	 *                             				included we do NOT setup the default message types (assuming
236
	 *                             				they are already setup.)
237
	 * @return boolean an array of generated templates or false if nothing generated/activated.
238
	 */
239
	public function activate_messenger( $messenger_name, $mts_to_activate = array() ){
240
		$active_messengers = EEH_MSG_Template::get_active_messengers_in_db();
241
		$message_types = $this->get_installed_message_types();
242
		$installed_messengers = $this->get_installed_messengers();
243
		$templates = false;
244
		$settings = array();
245
		//get has_active so we can be sure its kept up to date.
246
		$has_activated = get_option( 'ee_has_activated_messenger' );
247
248
		//grab the messenger to work with.
249
		$messenger = isset( $installed_messengers[$messenger_name] ) ? $installed_messengers[$messenger_name] : null;
250
251
		//it's inactive. Activate it.
252
253
		if( $messenger instanceof EE_Messenger ) {
254
			$active_messengers[ $messenger->name ][ 'obj' ] = $messenger;
255
256
			/** @var EE_Messenger[] $installed_messengers  */
257
			$mts_to_activate = ! empty( $mts_to_activate ) ? $mts_to_activate :  $messenger->get_default_message_types();
258
			foreach ( $mts_to_activate as $message_type ) {
259
				//we need to setup any initial settings for message types
260
				/** @var EE_message_type[] $installed_mts */
261
				$settings_fields = isset( $message_types[$message_type] ) ? $message_types[ $message_type ]->get_admin_settings_fields() : array();
262
				if ( !empty( $settings_fields ) ) {
263
					foreach ( $settings_fields as $field => $values ) {
264
						$settings[$field] = $values[ 'default' ];
265
					}
266
				} else {
267
					$settings = array();
268
				}
269
270
				$active_messengers[ $messenger->name ][ 'settings' ][ $messenger->name . '-message_types' ][ $message_type ][ 'settings' ] = $settings;
271
272
				if (  ! empty( $has_activated[$messenger->name] ) && ! in_array( $message_type, $has_activated[$messenger->name] ) ) {
273
					$has_activated[$messenger->name][] = $message_type;
274
				}
275
			}
276
277
			//setup any initial settings for the messenger
278
			$msgr_settings = $messenger->get_admin_settings_fields();
279
280 View Code Duplication
			if ( !empty( $msgr_settings ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
281
				foreach ( $msgr_settings as $field => $value ) {
282
					$active_messengers[ $messenger->name ][ 'settings' ][ $field ] = $value;
283
				}
284
			}
285
286
			EEH_MSG_Template::update_active_messengers_in_db( $active_messengers );
287
			update_option( 'ee_has_activated_messenger', $has_activated );
288
289
			//make sure that the cached active_messengers is set on this object
290
			$this->_active_messengers[$messenger->name] = $messenger;
291
			$this->_active_message_types[$messenger->name] = $active_messengers[$messenger->name];
292
293
			//might need to generate new templates
294
			if ( ! empty( $mts_to_activate ) ) {
295
				$templates = EEH_MSG_Template::generate_new_templates( $messenger->name, $mts_to_activate, 0, TRUE );
296
			}
297
		}
298
299
		return $templates;
300
	}
301
302
303
304
	/**
305
	 * load the active files needed (key word... NEEDED)
306
	 *
307
	 * >>>>>>>>> 1 usage in \EE_Messages::_set_active_messengers_and_message_types()
308
	 *
309
	 * @param string $kind    indicates what kind of files we are loading.
310
	 * @param array  $actives indicates what active types of the $kind are actually to be loaded.
311
	 * @return array|void
312
	 */
313
	private function _load_files($kind, $actives) {
314
		$active_names = array();
315
		$base_path = EE_LIBRARIES . 'messages' . DS . $kind . DS;
316
		if ( empty($actives) ) return false;
317
318
		//make sure autoloaders are set (fail-safe)
319
		EED_Messages::set_autoloaders();
320
321
		//make sure $actives is an array
322
		$actives = (array) $actives;
323
324
		EE_Registry::instance()->load_helper( 'File' );
325
		foreach ( $actives as $active ) {
326
			$msg_name = 'EE_' . ucwords( str_replace( ' ', '_', $active) ) . '_' . $kind;
327
			$filename = $msg_name . '.class.php';
328
			$load_file = $base_path . DS . $filename;
329
			if ( is_readable($load_file) ) {
330
				require_once($load_file);
331
				$active_names[$active] = $msg_name;
332
			} else {
333
				$this->_unset_active($active, $kind);
334
				//set WP_Error
335
				EE_Error::add_error(
336
					sprintf(
337
						__('Missing messages system file set as inactive: (%1$s) %2$s has been made inactive.', 'event_espresso'),
338
						$load_file,
339
						$msg_name
340
					),
341
					__FILE__, __FUNCTION__, __LINE__
342
				);
343
				return false;
344
			}
345
		}
346
		return $active_names;
347
	}
348
349
350
351
352
	/**
353
	 * unsets the active if we can't find the file (fail-safe)
354
	 *
355
	 * @access private
356
	 * @param  string $active_name name of messenger or message type
357
	 * @param  string $kind        messenger or message_type?
358
	 * @return void
359
	 */
360
	private function _unset_active( $active_name, $kind ) {
361
		//pluralize
362
		$active_messengers = EEH_MSG_Template::get_active_messengers_in_db();
363
		EE_Registry::instance()->load_helper( 'MSG_Template' );
364
		if ( $kind == 'messenger' ) {
365
			unset( $active_messengers[$active_name] );
366
			EEH_MSG_Template::update_to_inactive( $active_name );
367
			if ( isset( $this->_active_messengers[$active_name] ) ) {
368
				unset( $this->_active_messengers[$active_name] );
369
			}
370
		} else {
371 View Code Duplication
			foreach( $active_messengers as $messenger => $settings ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
372
				if ( ! empty( $settings['settings'][$messenger . '-message_types'][$active_name] ) ) {
373
					unset( $active_messengers[$messenger]['settings'][$messenger . '-message_types'][$active_name] );
374
				}
375
			}
376
			EEH_MSG_Template::update_to_inactive( '', $active_name );
377
			if ( isset( $this->_active_message_types[$active_name] ) ) {
378
				unset( $this->_active_message_types[$active_name] );
379
			}
380
		}
381
382
		EEH_MSG_Template::update_active_messengers_in_db($active_messengers);
383
	}
384
385
386
387
388
	/**
389
	 * Used to verify if a message can be sent for the given messenger and message type and that it is a generating messenger (used for generating message templates).
390
	 *
391
	 * >>>>>>>>>>>> NO usages found
392
	 *
393
	 * @param EE_Messenger    $messenger    messenger used in trigger
394
	 * @param EE_message_type $message_type message type used in trigger
395
	 *
396
	 * @return bool true is a generating messenger and can be sent OR FALSE meaning cannot send.
397
	 */
398
	public function is_generating_messenger_and_active( EE_Messenger $messenger, EE_message_type $message_type ) {
399
		//get the $messengers the message type says it can be used with.
400
		$used_with = $message_type->with_messengers();
401
402
		foreach ( $used_with as $generating_msgr => $secondary_msgrs ) {
403
			if ( $messenger->name == $generating_msgr && isset( $this->_active_message_types[$generating_msgr][$message_type->name] ) ) {
404
				return true;
405
			}
406
		}
407
408
		return false;
409
	}
410
411
412
	/**
413
	 * This returns the corresponding EE_Messenger object for the given string if it is active.
414
	 *
415
	 * >>>>>>>>>>>> 1 usage in \EE_Message_Generated_From_Token::get_EE_Message()
416
	 * >>>>>>>>>>>> 1 usage in \EE_Message_To_Generate_From_Request::__construct()
417
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::validate_for_use()
418
	 * >>>>>>>>>>>> 2 usages in \EE_Messages_Queue::execute()
419
	 *
420
	 * @param string    $messenger
421
	 * @return EE_Messenger | null
422
	 */
423
	public function get_messenger_if_active( $messenger ) {
424
		return ! empty( $this->_active_messengers[$messenger] ) ? $this->_active_messengers[$messenger] : null;
425
	}
426
427
428
	/**
429
	 * This validates whether the given EE_Message object can be used for either sending or generation.
430
	 * This is done by grabbing the messenger and message type on the EE_Message and verifying that both are installed
431
	 * and active.
432
	 *
433
	 * >>>>>>>>>>>> 1 usage in \EE_Message_To_Generate::_set_valid()
434
	 * >>>>>>>>>>>> 1 usage in \EE_Messages_Generator::_validate_messenger_and_message_type()
435
	 *
436
	 * @param EE_Message $message
437
	 *
438
	 * @return array  An array with 'messenger' and 'message_type' as the index and the corresponding valid object if
439
	 *                available.
440
	 *                Eg. Valid Messenger and Message Type:
441
	 *                array(
442
	 *                  'messenger' => new EE_Email_Messenger(),
443
	 *                  'message_type' => new EE_Registration_Approved_message_type()
444
	 *                )
445
	 *                Valid Messenger and Invalid Message Type:
446
	 *                array(
447
	 *                  'messenger' => new EE_Email_Messenger(),
448
	 *                  'message_type' => null
449
	 *                )
450
	 */
451
	public function validate_for_use( EE_Message $message ) {
452
		$validated_for_use['messenger'] = $this->get_messenger_if_active($message->messenger());
0 ignored issues
show
Coding Style Comprehensibility introduced by
$validated_for_use was never initialized. Although not strictly required by PHP, it is generally a good practice to add $validated_for_use = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
Documentation introduced by
$message->messenger() is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
453
		$validated_for_use['message_type'] = $this->get_active_message_type( $message->messenger(), $message->message_type() );
0 ignored issues
show
Documentation introduced by
$message->messenger() is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$message->message_type() is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
454
		return $validated_for_use;
455
	}
456
457
458
459
	/**
460
	 * Delegates message sending to messengers
461
	 *
462
	 * >>>>>>>>>>>> 1 usage in \EED_Ticketing::_generate_tickets()
463
	 * >>>>>>>>>>>> 1 usage in \EED_Ticketing::maybe_ticket_notice()
464
	 * >>>>>>>>>>>> 1 usage in \EED_Ticketing::process_resend_ticket_notice()
465
	 *
466
	 * @deprecated 4.9.0
467
	 * @param  string  $type    What type of message are we sending (corresponds to message types)
468
	 * @param  mixed  $vars    Data being sent for parsing in the message
469
	 * @param  string $sending_messenger if included then we ONLY use the specified messenger for delivery.  Otherwise we cycle through all active messengers.
470
	 * @param string $generating_messenger if included then this messenger is used for generating the message templates (but not for sending).
471
	 * @param string $context If included then only a message type for a specific context will be generated.
472
	 * @param bool  $send 			       Default TRUE.  If false, then this will just return the generated EE_Messages objects which might be used by the trigger to setup a batch message (typically html messenger uses it).
473
	 * @return bool
474
	 */
475
	public function send_message( $type, $vars, $sending_messenger = '', $generating_messenger='', $context='', $send = TRUE ) {
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
476
		$processor = new EE_Messages_Processor( $this );
477
		$error = FALSE;
478
479
		//try to intelligently determine what method we'll call based on the incoming data.
480
		//if generating and sending are different then generate and send immediately.
481
		if ( ! empty( $sending_messenger ) && $sending_messenger != $generating_messenger && $send ) {
482
			//in the legacy system, when generating and sending were different, that means all the
483
			//vars are already in the request object.  So let's just use that.
484
			try {
485
				$mtg = new EE_Message_To_Generate_From_Request( $this, EE_Registry::instance()->REQ );
486
				$processor->generate_and_send_now( $mtg );
487
			} catch ( EE_Error $e ) {
488
				$error_msg = __( 'Please note that a system message failed to send due to a technical issue.', 'event_espresso' );
489
				// add specific message for developers if WP_DEBUG in on
490
				$error_msg .= '||' . $e->getMessage();
491
				EE_Error::add_error( $error_msg, __FILE__, __FUNCTION__, __LINE__ );
492
				$error = true;
493
			}
494
		} else {
495
			$processor->generate_for_all_active_messengers( $type, $vars, $send );
496
			//let's find out if there were any errors and how many successfully were queued.
497
			$count_errors = $processor->get_queue()->count_STS_in_queue( EEM_Message::status_failed );
498
			$count_queued = $processor->get_queue()->count_STS_in_queue( EEM_Message::status_incomplete );
499
			$count_retry = $processor->get_queue()->count_STS_in_queue( EEM_Message::status_retry );
500
			$count_errors = $count_errors + $count_retry;
501
			if ( $count_errors > 0 ) {
502
				$error = true;
503
				if ( $count_errors > 1 && $count_retry > 1 && $count_queued > 1  ) {
504
					$message = sprintf(
505
						__(
506
							'There were %d errors and %d messages successfully queued for generation and sending',
507
							'event_espresso'
508
						),
509
						$count_errors,
510
						$count_queued
511
					);
512
				} elseif ( $count_errors > 1 && $count_queued === 1 ) {
513
					$message = sprintf(
514
						__(
515
							'There were %d errors and %d message successfully queued for generation.',
516
							'event_espresso'
517
						),
518
						$count_errors,
519
						$count_queued
520
					);
521
				} elseif ( $count_errors === 1 && $count_queued > 1 ) {
522
					$message = sprintf(
523
						__(
524
							'There was %d error and %d messages successfully queued for generation.',
525
							'event_espresso'
526
						),
527
						$count_errors,
528
						$count_queued
529
					);
530
				} else {
531
					$message = sprintf(
532
						__(
533
							'There was %d message that failed to be queued for generation.',
534
							'event_espresso'
535
						),
536
						$count_errors
537
					);
538
				}
539
				EE_Error::add_error( $message, __FILE__, __FUNCTION__, __LINE__ );
540
			} else {
541
				if ( $count_queued === 1 ) {
542
					$message = sprintf(
543
						__(
544
							'%d message successfully queued for generation.',
545
							'event_espresso'
546
						),
547
						$count_queued
548
					);
549
				} else {
550
					$message = sprintf(
551
						__(
552
							'%d messages were successfully queued for generation.',
553
							'event_espresso'
554
						),
555
						$count_queued
556
					);
557
				}
558
				EE_Error::add_success( $message );
559
			}
560
		}
561
		//if no error then return the generated message(s).
562
		if ( ! $error && ! $send ) {
563
			$generated_queue = $processor->generate_queue( false );
564
			//get message and return.
565
			$generated_queue->get_queue()->rewind();
566
			$messages = array();
567
			while( $generated_queue->get_queue()->valid() ) {
568
				$message = $generated_queue->get_queue()->current();
569
				if ( $message instanceof EE_Message ) {
570
					//set properties that might be expected by add-ons (backward compat)
571
					$message->content = $message->content();
0 ignored issues
show
Documentation Bug introduced by
The property $content was declared of type string, but $message->content() is of type boolean. Maybe add a type cast?

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

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

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
Deprecated Code introduced by
The property EE_Message::$content has been deprecated with message: 4.9.0 Added for backward compat with add-on's

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
572
					$message->template_pack = $message->get_template_pack();
0 ignored issues
show
Documentation Bug introduced by
It seems like $message->get_template_pack() can also be of type object<EE_Messages_Template_Pack>. However, the property $template_pack is declared as type null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
Deprecated Code introduced by
The property EE_Message::$template_pack has been deprecated with message: 4.9.0 Added for backward compat with add-on's

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
573
					$message->template_variation = $message->get_template_pack_variation();
0 ignored issues
show
Documentation Bug introduced by
It seems like $message->get_template_pack_variation() of type string is incompatible with the declared type null of property $template_variation.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
Deprecated Code introduced by
The property EE_Message::$template_variation has been deprecated with message: 4.9.0 Added for backward compat with add-on's

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
574
					$messages[] = $message;
575
				}
576
				$generated_queue->get_queue()->next();
577
			}
578
579
			return $messages;
580
		}
581
		return $error ? false : true; //yeah backwards eh?  Really what we're returning is if there is a total success for all the messages or not.  We'll modify this once we get message recording in place.
582
	}
583
584
585
586
587
	/**
588
	 * Use to generate and return a message preview!
589
	 *
590
	 * >>>>>>>>>>>> NO usages found
591
	 *
592
	 * @deprecated 4.9.0
593
	 * @param  string $type    This should correspond with a valid message type
594
	 * @param  string $context This should correspond with a valid context for the message type
595
	 * @param  string $messenger This should correspond with a valid messenger.
596
	 * @param bool 	$send true we will do a test send using the messenger delivery, false we just do a regular preview
597
	 * @return string          The body of the message.
598
	 */
599
	public function preview_message( $type, $context, $messenger, $send = FALSE ) {
600
		return EED_Messages::preview_message( $type, $context, $messenger, $send );
601
	}
602
603
604
	/**
605
	 * This is a method that allows for sending a message using a messenger matching the string given and the provided EE_Message stdClass objects.
606
	 *
607
	 * >>>>>>>>>>>> 1 usage in \EED_Ticketing::_generate_tickets()
608
	 *
609
	 * @since 4.5.0
610
	 * @deprecated 4.9.0   Moved to EED_Messages Module
611
	 * @param string       $messenger a string matching a valid active messenger in the system
612
	 * @param string       $message_type   Although it seems contrary to the name of the method, a message type name is still required to send along the message type to the messenger because this is used for determining what specific variations might be loaded for the generated message.
613
	 * @param stdClass $message  a stdClass object in the format expected by the messenger.
614
	 *
615
	 * @return bool          success or fail.
616
	 */
617
	public function send_message_with_messenger_only( $messenger, $message_type, $message ) {
618
		//setup for sending to new method.
619
		$queue = new EE_Messages_Queue( $this );
620
		//make sure we have a proper message object
621
		if ( ! $message instanceof EE_Message && is_object( $message ) && isset( $message->content ) ) {
622
			$msg = EE_Message_Factory::create(
623
				array(
624
					'MSG_messenger' => $messenger,
625
					'MSG_message_type' => $message_type,
626
					'MSG_content' => $message->content,
627
					'MSG_subject' => $message->subject
628
				)
629
			);
630
		} else {
631
			$msg = $message;
632
		}
633
634
		if ( ! $msg instanceof EE_Message ) {
635
			return false;
636
		}
637
		//make sure any content in a content property (if not empty) is set on the MSG_content.
638
		if ( ! empty( $msg->content ) ) {
0 ignored issues
show
Deprecated Code introduced by
The property EE_Message::$content has been deprecated with message: 4.9.0 Added for backward compat with add-on's

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
639
			$msg->set( 'MSG_content', $msg->content );
0 ignored issues
show
Deprecated Code introduced by
The property EE_Message::$content has been deprecated with message: 4.9.0 Added for backward compat with add-on's

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
640
		}
641
		$queue->add( $msg );
642
		return EED_Messages::send_message_with_messenger_only( $messenger, $message_type, $queue );
643
	}
644
645
646
647
648
649
	/**
650
	 * _validate_setup
651
	 *
652
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::create_new_templates()
653
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::get_fields()
654
	 *
655
	 * @param  string $messenger    EE_Messenger
656
	 * @param  string $message_type EE_message_type
657
	 * @param bool $is_global whether this is a global template or not.
658
	 * @throws EE_Error
659
	 * @return bool(true)|WP_Error
0 ignored issues
show
Documentation introduced by
The doc-type bool(true)|WP_Error could not be parsed: Expected "|" or "end of type", but got "(" at position 4. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
660
	 */
661
	private function _validate_setup($messenger, $message_type, $is_global = FALSE) {
662
663
		$message_type = strtolower(str_replace(' ', '_', $message_type) );
664
		$messenger = strtolower(str_replace(' ', '_', $messenger));
665
		$installed_message_types = $this->get_installed_message_types();
666
667
668
		//setup messenger and message_type object
669
		$this->_messenger = isset($this->_active_messengers[$messenger]) ? $this->_active_messengers[$messenger] : null;
670
671
672
		//message type
673
		$mt = isset($installed_message_types[$message_type]) ? $installed_message_types[$message_type] : 'message_type_not_existent';
674
675
		$this->_message_type = is_object($mt) ? $mt : null;
676
677
678
		//do we have the necessary objects loaded?
679
		if ( empty( $this->_messenger ) || empty( $this->_message_type ) ) {
680
			throw new EE_Error(
681
				sprintf(
682
					__(
683
						' The %s messenger or the %s message_type are not active. Are you sure they exist?',
684
						'event_espresso'
685
					),
686
					$messenger,
687
					$message_type
688
				)
689
			);
690
		}
691
		//is given message_type valid for given messenger (if this is not a global save)
692
		if ( !$is_global ) {
693
			$has_active = EEM_Message_Template_Group::instance()->count(
694
				array(
695
					array(
696
						'MTP_is_active' => true, 'MTP_messenger' => $this->_messenger->name,
697
						'MTP_message_type' => $message_type
698
					)
699
				)
700
			);
701
			if ( $has_active == 0 ) {
702
				EE_Error::add_error(
703
					sprintf(
704
						__(' The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.', 'event_espresso'),
705
						$message_type,
706
						$messenger
707
					),
708
					__FILE__, __FUNCTION__, __LINE__
709
				);
710
				return false;
711
			}
712
713
		}
714
		return true;
715
	}
716
717
718
719
	/**
720
	 * This is a wrapper for the protected _create_new_templates function
721
	 *
722
	 * >>>>>>>>>>>> 1 usage in \EEH_MSG_Template::generate_new_templates()
723
	 *
724
	 * @param         $messenger
725
	 * @param  string $message_type message type that the templates are being created for
726
	 * @param int     $GRP_ID
727
	 * @param bool    $is_global
728
	 * @return array|object if creation is successful then we return an array of info, otherwise an error_object is returned.
729
	 * @throws \EE_Error
730
	 */
731
	public function create_new_templates( $messenger, $message_type, $GRP_ID = 0, $is_global = false ) {
732
733
		$valid_mt = $this->_validate_setup($messenger, $message_type, $is_global);
734
735
		if ( is_wp_error($valid_mt) && $is_global ) {
736
			//we're setting up a brand new global templates (with messenger activation) so we're assuming that the message types sent in are valid.
737
			$valid_mt = true;
738
		}
739
740
		if ( is_wp_error($valid_mt) ) {
741
			//if we've still got no valid_mt then bubble up error object
742
			return $valid_mt;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $valid_mt; (boolean) is incompatible with the return type documented by EE_Messages::create_new_templates of type array|object.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
743
		}
744
745
		//whew made it this far!  Okay, let's go ahead and create the templates then
746
		return $this->_create_new_templates($GRP_ID, $is_global);
747
	}
748
749
750
751
	/**
752
	 * @param $GRP_ID
753
	 * @param $is_global
754
	 * @return array|mixed
755
	 */
756
	protected function _create_new_templates( $GRP_ID, $is_global) {
757
758
		//if we're creating a custom template then we don't need to use the defaults class
759
		if ( ! $is_global )
760
			return $this->_create_custom_template_group( $GRP_ID );
761
762
		$DFLT = new EE_Message_Template_Defaults( $this, $this->_messenger->name, $this->_message_type->name, $GRP_ID );
763
764
		//generate templates
765
		$success = $DFLT->create_new_templates();
766
767
		/**
768
		 * $success is in an array in the following format
769
		 * array(
770
		 * 	'GRP_ID' => $new_grp_id,
771
		 * 	'MTP_context' => $first_context_in_new_templates,
772
		 * )
773
		 */
774
		return $success;
775
	}
776
777
778
779
	/**
780
	 * This creates a custom template using the incoming GRP_ID
781
	 *
782
	 * @param  int     $GRP_ID GRP_ID for the template_group being used as the base
783
	 * @return  array $success             This will be an array in the format:
784
	 *                                     			array(
785
	 *                                     				'GRP_ID' => $new_grp_id,
786
	 *                                     				'MTP_context' => $first_context_in_created_template
787
	 *                                     			)
788
	 * @access private
789
	 */
790
	private function _create_custom_template_group( $GRP_ID ) {
791
		//defaults
792
		$success = array( 'GRP_ID' => NULL, 'MTP_context' => '' );
793
794
		//get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
795
		$mtg = empty( $GRP_ID ) ? EEM_Message_Template_Group::instance()->get_one( array( array( 'MTP_messenger' => $this->_messenger->name, 'MTP_message_type' => $this->_message_type->name, 'MTP_is_global' => TRUE ) ) ) : EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
796
797
		//if we don't have a mtg at this point then we need to bail.
798
		if ( ! $mtg instanceof EE_Message_Template_Group ) {
799
			EE_Error::add_error( sprintf( __('Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.', 'event_espresso'), $GRP_ID ), __FILE__, __FUNCTION__, __LINE__ );
800
			return $success;
801
		}
802
803
		//let's get all the related message_template objects for this group.
804
		$mtts = $mtg->message_templates();
805
806
		//now we have what we need to setup the new template
807
		$new_mtg = clone $mtg;
808
		$new_mtg->set('GRP_ID', 0);
809
		$new_mtg->set('MTP_is_global', FALSE);
810
811
		$template_name = defined('DOING_AJAX') && !empty( $_POST['templateName'] ) ? $_POST['templateName'] : __('New Custom Template', 'event_espresso');
812
		$template_description = defined("DOING_AJAX") && !empty( $_POST['templateDescription'] ) ? $_POST['templateDescription'] : sprintf( __('This is a custom template that was created for the %s messenger and %s message type.', 'event_espresso' ), $new_mtg->messenger_obj()->label['singular'], $new_mtg->message_type_obj()->label['singular'] );
813
814
815
		$new_mtg->set('MTP_name', $template_name );
816
		$new_mtg->set('MTP_description', $template_description );
817
		//remove ALL relations on this template group so they don't get saved!
818
		$new_mtg->_remove_relations( 'Message_Template' );
819
		$new_mtg->save();
820
		$success['GRP_ID'] = $new_mtg->ID();
821
		$success['template_name'] = $template_name;
822
823
		//add new message templates and add relation to.
824
		foreach ( $mtts as $mtt ) {
825
			if ( ! $mtt instanceof EE_Message_Template )
826
				continue;
827
			$nmtt = clone $mtt;
828
			$nmtt->set('MTP_ID', 0);
829
			$nmtt->set( 'GRP_ID', $new_mtg->ID() ); //relation
830
			$nmtt->save();
831
			if ( empty( $success['MTP_context'] ) )
832
				$success['MTP_context'] = $nmtt->get('MTP_context');
833
		}
834
835
		return $success;
836
837
	}
838
839
840
841
842
	/**
843
	 * get_fields
844
	 * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
845
	 *
846
	 * >>>>>>>>>>>> 1 usage in \Messages_Admin_Page::_edit_message_template()
847
	 *
848
	 * @param  string $messenger    EE_Messenger
849
	 * @param  string $message_type EE_message_type
850
	 * @return array|WP_Error  template fields indexed by context.
851
	 */
852
	public function get_fields($messenger, $message_type) {
853
		$template_fields = array();
854
855
		$this->_validate_setup($messenger, $message_type);
856
857
858
		//okay now let's assemble an array with the messenger template fields added to the message_type contexts.
859
		foreach ( $this->_message_type->get_contexts() as $context => $details ) {
860
			foreach ( $this->_messenger->get_template_fields() as $field => $value ) {
861
				$template_fields[$context][$field] = $value;
862
			}
863
		}
864
865
		if ( empty($template_fields) ) {
866
			EE_Error::add_error( __('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__ );
867
			return FALSE;
868
		}
869
870
		return $template_fields;
871
	}
872
873
	/**
874
	 * gets an array of installed messengers and message types objects.
875
	 *
876
	 * >>>>>>>>>>>> 1 usage in \EEH_MSG_Template::get_installed_message_objects()
877
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::get_installed_message_types()
878
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::get_installed_messengers()
879
	 *
880
	 * @access public
881
	 * @param string $type 				we can indicate just returning installed message types
882
	 *                     				or messengers (or both) via this parameter.
883
	 * @param bool 		$skip_cache 	if true then we skip the cache and retrieve via files.
884
	 * @return array                    multidimensional array of messenger and message_type objects
885
	 *                                    (messengers index, and message_type index);
886
	 */
887
	public function get_installed( $type = 'all', $skip_cache = false ) {
888
		$installed = array();
889
890
		//first let's account for caching
891
		if ( $skip_cache ) {
892
			$message_base = EE_LIBRARIES . "messages" . DS;
893
894
			$messenger_files = $type == 'all' || $type == 'messengers' ? scandir( $message_base . "messenger", 1) : NULL;
895
			$messagetype_files = $type == 'all' || $type == 'message_types' ? scandir( $message_base . "message_type", 1) : NULL;
896
897
898
			//allow plugins to filter in their messenger/message_type files
899
			$messenger_files = apply_filters('FHEE__EE_messages__get_installed__messenger_files', $messenger_files, $type );
900
			$messagetype_files = apply_filters('FHEE__EE_messages__get_installed__messagetype_files', $messagetype_files, $type );
901
902
			$installed['messengers'] = !empty($messenger_files ) ? $this->_get_installed($messenger_files) : '';
903
			$installed['message_types'] = !empty($messagetype_files) ? $this->_get_installed($messagetype_files) : '';
904
		} else {
905
			$installed['messengers'] = $this->get_installed_messengers();
906
			$installed['message_types'] = $this->get_installed_message_types();
907
		}
908
909
910
		if ( $type != 'all' ) {
911
			$installed = $type == 'messengers' ? $installed['messengers'] : $installed['message_types'];
912
		}
913
914
		return $installed;
915
	}
916
917
918
	/**
919
	 * _get_installed
920
	 * takes an array of filenames and returns an array of objects instantiated from the class name found in the filename.
921
	 * @param  array $filenames and array of filenames
922
	 * @return array       array of objects
923
	 */
924
	private function _get_installed($filenames) {
925
		//make sure incoming filenames are in an array.
926
		$the_goods = array();
927
		$filenames = (array) $filenames;
928
		$replace = ".class.php";
929
		foreach ( $filenames as $filename ) {
930
			$classname = preg_match("/" . $replace . "/", $filename ) ? str_replace($replace, "", $filename) : false;
931
932
			//no classname? no match? move along, nothing to see here. note, the stripos is checking to make sure the filename (classname) begins with EE.
933
			if ( !$classname || 0 !== stripos($classname, 'EE') ) continue;
934
935
			//note: I'm not sure if this will work without including the file.  We do have autoloaders so it "may" work.
936
			$object = new $classname();
937
			$the_goods[ $object->name ] = $object;
938
		}
939
		return $the_goods;
940
	}
941
942
	public function get_active_messengers() {
943
		return $this->_active_messengers;
944
	}
945
946
947
	/**
948
	 * This does NOT return the _active_message_types property but
949
	 * simply returns an array of active message types from that property.
950
	 * (The _active_message_types property is indexed by messenger and active message_types per messenger).
951
	 *
952
	 * >>>>>>>>>>>> 1 usage in \Registrations_Admin_Page::_set_list_table_views_default()
953
	 * >>>>>>>>>>>> 1 usage in \EEH_MSG_Template::is_mt_active()
954
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::get_active_message_type_objects()
955
	 * >>>>>>>>>>>> 1 usage in \EED_Ticketing::process_resend_ticket_notice()
956
	 *
957
	 *
958
	 * @return array array of message_type references (string)
959
	 */
960
	public function get_active_message_types() {
961
		$message_types = array();
962
		foreach ( $this->_active_message_types as $messenger => $mtvalues ) {
963
			foreach ( $mtvalues as $mt => $config ) {
964
				if ( !in_array( $mt, $message_types ) )
965
					$message_types[] = $mt;
966
			}
967
		}
968
969
		return $message_types;
970
	}
971
972
973
	/**
974
	 * Same as get_active_message_types() except this returns actual EE_message_type objects
975
	 *
976
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::get_all_contexts()
977
	 *
978
	 * @since 4.9.0
979
	 * @return EE_message_type[]
980
	 */
981
	public function get_active_message_type_objects() {
982
		$message_types = array();
983
		$message_type_refs = $this->get_active_message_types();
984
		$installed_message_types = $this->get_installed_message_types();
985
		foreach ( $message_type_refs as $ref ) {
986
			if ( isset( $installed_message_types[$ref] ) ) {
987
				$message_types[] = $installed_message_types[$ref];
988
			}
989
		}
990
		return $message_types;
991
	}
992
993
994
995
996
	/**
997
	 * This checks the _active_message_types property for any active message types that are present for the given messenger and returns them.
998
	 *
999
	 * >>>>>>>>>>>> 1 usage in \espresso_events_Messages_Hooks_Extend::messages_metabox()
1000
	 *
1001
	 * @since 4.5.0
1002
	 *
1003
	 * @param string $messenger The messenger being checked
1004
	 *
1005
	 * @return EE_message_type[]    (or empty array if none present)
1006
	 */
1007
	public function get_active_message_types_per_messenger( $messenger ) {
1008
		$messenger = (string) $messenger;
1009
		if ( empty( $this->_active_message_types[$messenger] ) ) {
1010
			return array();
1011
		}
1012
1013
		$mts = array();
1014
		$message_types = $this->_active_message_types[$messenger];
1015
		$installed_message_types = $this->get_installed_message_types();
1016
		foreach ( $message_types as $mt => $settings ) {
1017
			if ( ! empty( $installed_message_types[$mt] ) )  {
1018
				$mts[] = $installed_message_types[$mt];
1019
			}
1020
		}
1021
		return $mts;
1022
	}
1023
1024
1025
	/**
1026
	 * This returns the EE_message_type from the active message types array ( if present );
1027
	 *
1028
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::validate_for_use()
1029
	 * >>>>>>>>>>>> 1 usage in \EE_Messages_Queue::execute()
1030
	 *
1031
	 * @param string $messenger      The string should correspond to the messenger (message types are
1032
	 *                               		    assigned to a messenger in the messages settings)
1033
	 * @param string $message_type The string should correspond to a message type.
1034
	 *
1035
	 * @return EE_Message_Type|null
1036
	 */
1037
	public function get_active_message_type( $messenger, $message_type ) {
1038
		$installed_message_types = $this->get_installed_message_types();
1039
		if ( !empty( $this->_active_message_types[$messenger][$message_type] ) && !empty( $installed_message_types[$message_type] ) )  {
1040
			return $installed_message_types[$message_type];
1041
		}
1042
		return NULL;
1043
	}
1044
1045
1046
1047
	/**
1048
	 *
1049
	 * >>>>>>>>>>>> 1 usage in \Messages_Admin_Page::_get_installed_message_objects()
1050
	 * >>>>>>>>>>>> 1 usage in \EEH_MSG_Template::message_type_obj()
1051
	 * >>>>>>>>>>>> 1 usage in \EE_Message_Template_Defaults::_init()
1052
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::_validate_setup()
1053
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::activate_messenger()
1054
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::get_active_message_type()
1055
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::get_active_message_type_objects()
1056
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::get_active_message_types_per_messenger()
1057
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::get_installed()
1058
	 *
1059
	 * @return array|\EE_message_type[]
1060
	 */
1061
	public function get_installed_message_types() {
1062
		$this->_installed_message_types = empty( $this->_installed_message_types )
1063
			? $this->get_installed( 'message_types', true )
1064
			: $this->_installed_message_types;
1065
		return $this->_installed_message_types;
1066
	}
1067
1068
1069
1070
	/**
1071
	 * >>>>>>>>>>>> 1 usage in \Messages_Admin_Page::_get_installed_message_objects()
1072
	 * >>>>>>>>>>>> 1 usage in \EEH_MSG_Template::messenger_obj()
1073
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::activate_messenger()
1074
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::ensure_message_type_is_active()
1075
	 * >>>>>>>>>>>> 1 usage in \EE_Messages::get_installed()
1076
	 *
1077
	 * @return array
1078
	 */
1079
	public function get_installed_messengers() {
1080
		$this->_installed_messengers = empty( $this->_installed_messengers )
0 ignored issues
show
Bug introduced by
The property _installed_messengers does not seem to exist. Did you mean _messenger?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1081
			? $this->get_installed( 'messengers', true )
1082
			: $this->_installed_messengers;
0 ignored issues
show
Bug introduced by
The property _installed_messengers does not seem to exist. Did you mean _messenger?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1083
		return $this->_installed_messengers;
0 ignored issues
show
Bug introduced by
The property _installed_messengers does not seem to exist. Did you mean _messenger?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1084
	}
1085
1086
1087
1088
	/**
1089
	 * This returns all the contexts that are registered by all message types.
1090
	 *
1091
	 * If $slugs_only is true, then just an array indexed by unique context slugs with the latest label representation for that slug.
1092
	 * array(
1093
	 *      'context_slug' => 'localized label for context obtained from latest message type in the loop'.
1094
	 * );
1095
	 *
1096
	 * If $slugs_only is false, then the format is:
1097
	 * array(
1098
	 *      'message_type_name' => array(
1099
	 *          'context_slug' => array(
1100
	 *              'label' => 'localized label for context',
1101
	 *              'description' => 'localized description for context'
1102
	 *          )
1103
	 *      )
1104
	 * );
1105
	 *
1106
	 * Keep in mind that although different message types may share the same context slugs, it is possible that the context
1107
	 * is described differently by the message type.
1108
	 *
1109
	 * >>>>>>>>>>>> 1 usage in \EE_Message_List_Table::_get_table_filters()
1110
	 * >>>>>>>>>>>> 1 usage in \EE_Message::context_label()
1111
	 * >>>>>>>>>>>> 1 usage in \EE_messages_Test::test_get_all_contexts()
1112
	 *
1113
	 * @since 4.9.0
1114
	 * @param   bool    $slugs_only     Whether to return an array of just slugs and labels (true) or all contexts indexed by message type.
1115
	 * @return array
1116
	 */
1117
	public function get_all_contexts( $slugs_only = true ) {
1118
		$key = $slugs_only ? 'slugs' : 'all';
1119
		if ( ! empty( $this->_contexts[$key] ) ) {
1120
			return $this->_contexts[$key];
1121
		}
1122
1123
		//contexts has not been setup yet.  So let's get all active message type objects and loop through to get all
1124
		//unique contexts
1125
		$contexts = array();
1126
		foreach ( $this->get_active_message_type_objects() as $mt ) {
1127
			if ( $mt instanceof EE_message_type ) {
1128
				$mt_contexts = $mt->get_contexts();
1129
				if ( $slugs_only ) {
1130
					foreach ( $mt_contexts as $context => $context_details ) {
1131
						$contexts[ $context ] = $context_details['label'];
1132
					}
1133
				} else {
1134
					$contexts[$mt->name] = $mt_contexts;
1135
				}
1136
			}
1137
		}
1138
1139
		$this->_contexts[$key] = $contexts;
1140
		return $this->_contexts[$key];
1141
	}
1142
1143
1144
1145
1146
	/**
1147
	 * Validates the given string as a reference for an existing, accessible data handler and returns the class name
1148
	 * For the handler the reference matches.
1149
	 *
1150
	 * >>>>>>>>>>>> No usages found
1151
	 *
1152
	 * @param string $data_handler_reference
1153
	 * @return string
1154
	 */
1155
	public function verify_and_retrieve_class_name_for_data_handler_reference( $data_handler_reference ) {
1156
		return EE_Message_To_Generate::verify_and_retrieve_class_name_for_data_handler_reference(
1157
			$data_handler_reference
1158
		);
1159
	}
1160
1161
1162
1163
}
1164
//end EE_Messages class
1165
// end of file:	includes/core/messages/EE_Messages.core.php
1166