Completed
Branch FET-9586-add-search-input (524ff8)
by
unknown
436:51 queued 422:19
created

Messages_Admin_Page   F

Complexity

Total Complexity 411

Size/Duplication

Total Lines 3463
Duplicated Lines 3.35 %

Coupling/Cohesion

Components 4
Dependencies 21

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 411
c 2
b 0
f 1
lcom 4
cbo 21
dl 116
loc 3463
rs 0.6314

91 Methods

Rating   Name   Duplication   Size   Complexity  
A get_messengers_for_list_table() 14 14 3
A get_message_types_for_list_table() 13 13 3
B get_contexts_for_message_types_for_list_table() 0 16 5
A __construct() 0 5 1
A _init_page_props() 0 11 3
A _load_message_resource_manager() 0 3 1
A _ajax_hooks() 0 7 1
A _define_page_props() 0 11 1
C _set_page_routes() 0 136 7
B _set_page_config() 0 143 1
A _add_screen_options() 0 3 1
A _add_screen_options_global_mtps() 6 10 1
A _add_screen_options_default() 0 4 1
A _add_feature_pointers() 0 1 1
A admin_init() 0 2 1
A admin_notices() 0 1 1
A admin_footer_scripts() 0 1 1
A messages_help_tab() 0 3 1
A messengers_help_tab() 0 3 1
A message_types_help_tab() 0 3 1
A messages_overview_help_tab() 0 3 1
A message_templates_help_tab() 0 3 1
A edit_message_template_help_tab() 0 8 1
A message_template_shortcodes_help_tab() 0 5 1
A preview_message_help_tab() 0 3 1
A settings_help_tab() 0 7 1
A load_scripts_styles() 7 7 1
A load_scripts_styles_default() 0 3 1
A wp_editor_css() 0 12 3
A load_scripts_styles_edit_message_template() 0 19 1
A load_scripts_styles_display_preview_message() 0 13 3
A load_scripts_styles_settings() 0 7 1
A _set_list_table_views_global_mtps() 12 12 1
C _set_list_table_views_default() 0 64 15
A _ee_default_messages_overview_list_table() 0 4 1
A _message_queue_list_table() 0 7 1
B _message_legend_items() 0 50 5
A _custom_mtps_preview() 6 6 1
F get_message_templates() 0 30 10
A get_installed_message_types() 0 10 2
F _add_message_template() 0 27 13
A add_message_template() 0 3 1
F _edit_message_template() 0 480 47
A filter_tinymce_init() 0 3 1
A add_context_switcher() 0 3 1
A _add_form_element_before() 0 3 1
A _add_form_element_after() 0 3 1
B switch_template_pack() 0 51 6
A _display_preview_message() 0 3 1
A _register_edit_meta_boxes() 0 5 1
B template_pack_meta_box() 0 69 6
C extra_actions_meta_box() 0 61 14
A _get_shortcode_selector() 0 8 1
A shortcode_meta_box() 0 16 2
A _set_shortcodes() 0 7 2
B _get_shortcodes() 0 9 5
B _set_message_template_group() 0 20 6
C _set_context_switcher() 0 39 8
B _set_message_template_column_values() 0 32 5
B _do_test_send() 0 24 5
A _generate_new_templates() 0 9 2
D _trash_or_restore_message_template() 0 47 16
B _delete_message_template() 0 21 5
A _delete_mtp_permanently() 0 18 4
A _learn_more_about_message_templates_link() 0 3 1
A _settings() 0 15 2
C _set_m_mt_settings() 0 57 10
B _message_type_settings_content() 0 56 9
D _messages_settings_metaboxes() 10 91 16
A _get_mt_tabs() 0 11 2
D _get_messenger_box_content() 0 84 12
C activate_messenger_toggle() 4 64 8
C activate_mt_toggle() 4 61 9
B _activate_messenger() 8 26 6
A _deactivate_messenger() 0 6 1
A _activate_message_type_for_messenger() 6 18 3
A _deactivate_message_type_for_messenger() 0 8 1
A _prep_default_response_for_messenger_or_message_type_toggle() 0 4 1
C _setup_response_message_for_activating_messenger_with_message_types() 0 80 8
C _setup_response_message_for_deactivating_messenger_with_message_types() 0 49 7
A update_mt_form() 0 16 3
A _generate_now() 0 5 1
A _generate_and_send_now() 0 5 1
A _queue_for_resending() 0 5 1
A _send_now() 0 5 1
A _get_msg_ids_from_request() 0 6 3
F _reset_to_default_template() 0 76 14
B _preview_message() 0 51 4
F _insert_or_update_message_template() 0 189 30
C save_settings() 26 62 11
B _delete_ee_messages() 0 22 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Messages_Admin_Page often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Messages_Admin_Page, and based on these observations, apply Extract Interface, too.

1
<?php if (!defined('EVENT_ESPRESSO_VERSION') )
2
	{exit('NO direct script access allowed');}
3
4
/**
5
 *
6
 * EE_Message_Admin_Page class
7
 *
8
 * for Admin setup of the message pages
9
 *
10
 * @package		Event Espresso
11
 * @subpackage	includes/core/message/EE_Message_Admin_Page.core.php
12
 * @author		Darren Ethier
13
 *
14
 * ------------------------------------------------------------------------
15
 */
16
class Messages_Admin_Page extends EE_Admin_Page {
17
18
	/**
19
	 * @type EE_Message_Resource_Manager $_message_resource_manager
20
	 */
21
	 protected $_message_resource_manager;
22
23
	/**
24
	 * @type string $_active_message_type_name
25
	 */
26
	protected  $_active_message_type_name = '';
27
28
	/**
29
	 * @type EE_messenger $_active_messenger
30
	 */
31
	protected  $_active_messenger;
32
	protected  $_activate_state;
33
	protected  $_activate_meta_box_type;
34
	protected  $_current_message_meta_box;
35
	protected  $_current_message_meta_box_object;
36
	protected  $_context_switcher;
37
	protected  $_shortcodes = array();
38
39
	/**
40
	 * @type EE_Message_Template_Group $_message_template_group
41
	 */
42
	protected  $_message_template_group;
43
	protected  $_m_mt_settings = array();
44
45
46
	/**
47
	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
48
	 * IF there is no group then it gets automatically set to the Default template pack.
49
	 *
50
	 * @since 4.5.0
51
	 *
52
	 * @var EE_Messages_Template_Pack
53
	 */
54
	protected $_template_pack;
55
56
57
58
59
	/**
60
	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
61
	 * group is.  If there is no group then it automatically gets set to default.
62
	 *
63
	 * @since 4.5.0
64
	 *
65
	 * @var string
66
	 */
67
	protected $_variation;
68
69
70
71
72
	/**
73
	 * @param bool $routing
74
	 */
75
	public function __construct( $routing = true ) {
76
		//make sure messages autoloader is running
77
		EED_Messages::set_autoloaders();
78
		parent::__construct( $routing );
79
	}
80
81
82
83
84
	protected function _init_page_props() {
85
		$this->page_slug = EE_MSG_PG_SLUG;
86
		$this->page_label = __('Messages Settings', 'event_espresso');
87
		$this->_admin_base_url = EE_MSG_ADMIN_URL;
88
		$this->_admin_base_path = EE_MSG_ADMIN;
89
90
		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state'] : array();
91
92
		$this->_active_messenger = isset( $this->_req_data['messenger'] ) ? $this->_req_data['messenger'] : null;
0 ignored issues
show
Documentation Bug introduced by
It seems like isset($this->_req_data['...ata['messenger'] : null can also be of type string. However, the property $_active_messenger is declared as type object<EE_messenger>. 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...
93
		$this->_load_message_resource_manager();
94
	}
95
96
97
98
99
	/**
100
	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
101
	 *
102
	 *
103
	 * @throws EE_Error
104
	*/
105
	protected function _load_message_resource_manager() {
106
		$this->_message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
0 ignored issues
show
Documentation Bug introduced by
It seems like \EE_Registry::instance()...sage_Resource_Manager') can also be of type boolean. However, the property $_message_resource_manager is declared as type object<EE_Message_Resource_Manager>. 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...
107
	}
108
109
110
111
	/**
112
	 * get_messengers_for_list_table
113
	 *
114
	 * @return array
115
	 * @throws \EE_Error
116
	 */
117 View Code Duplication
	public function get_messengers_for_list_table() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
118
		$m_values = array();
119
		$active_messengers = EEM_Message::instance()->get_all( array( 'group_by' => 'MSG_messenger' ) );
120
		//setup messengers for selects
121
		$i = 1;
122
		foreach ( $active_messengers as $active_messenger ) {
123
			if ( $active_messenger instanceof EE_Message ) {
124
				$m_values[ $i ]['id'] = $active_messenger->messenger();
125
				$m_values[ $i ]['text'] = ucwords( $active_messenger->messenger_label() );
126
				$i++;
127
			}
128
		}
129
		return $m_values;
130
	}
131
132
133
134
	/**
135
	 * get_message_types_for_list_table
136
	 *
137
	 * @return array
138
	 * @throws \EE_Error
139
	 */
140 View Code Duplication
	public function get_message_types_for_list_table() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
141
		$mt_values = array();
142
		$active_messages = EEM_Message::instance()->get_all( array( 'group_by' => 'MSG_message_type' ) );
143
		$i = 1;
144
		foreach ( $active_messages as $active_message ) {
145
			if ( $active_message instanceof EE_Message ) {
146
				$mt_values[ $i ]['id'] = $active_message->message_type();
147
				$mt_values[ $i ]['text'] = ucwords( $active_message->message_type_label() );
148
				$i++;
149
			}
150
		}
151
		return $mt_values;
152
	}
153
154
155
156
	/**
157
	 * get_contexts_for_message_types_for_list_table
158
	 *
159
	 * @return array
160
	 * @throws \EE_Error
161
	 */
162
	public function get_contexts_for_message_types_for_list_table() {
163
		$contexts = array();
164
		$active_message_contexts = EEM_Message::instance()->get_all( array( 'group_by' => 'MSG_context' ) );
165
		foreach ( $active_message_contexts as $active_message ) {
166
			if ( $active_message instanceof EE_Message ) {
167
				$message_type = $active_message->message_type_object();
168
				if ( $message_type instanceof EE_message_type ) {
169
					$message_type_contexts = $message_type->get_contexts();
170
					foreach ( $message_type_contexts as $context => $context_details ) {
171
						$contexts[ $context ] = $context_details['label'];
172
					}
173
				}
174
			}
175
		}
176
		return $contexts;
177
	}
178
179
180
181
	protected function _ajax_hooks() {
182
		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle' ) );
183
		add_action('wp_ajax_activate_mt', array( $this, 'activate_mt_toggle') );
184
		add_action('wp_ajax_ee_msgs_save_settings', array( $this, 'save_settings') );
185
		add_action('wp_ajax_ee_msgs_update_mt_form', array( $this, 'update_mt_form' ) );
186
		add_action('wp_ajax_switch_template_pack', array( $this, 'switch_template_pack' ) );
187
	}
188
189
190
191
192
193
194
	protected function _define_page_props() {
195
		$this->_admin_page_title = $this->page_label;
196
		$this->_labels = array(
197
			'buttons' => array(
198
				'add' => __('Add New Message Template', 'event_espresso'),
199
				'edit' => __('Edit Message Template', 'event_espresso'),
200
				'delete' => __('Delete Message Template', 'event_espresso')
201
			),
202
			'publishbox' => __('Update Actions', 'event_espresso')
203
		);
204
	}
205
206
207
208
209
210
211
212
	/**
213
	 * 		an array for storing key => value pairs of request actions and their corresponding methods
214
	*		@access protected
215
	*		@return void
216
	*/
217
	protected function _set_page_routes() {
218
		$grp_id = ! empty( $this->_req_data['GRP_ID'] ) && ! is_array( $this->_req_data['GRP_ID'] )
219
			? $this->_req_data['GRP_ID']
220
			: 0;
221
		$grp_id = empty( $grp_id ) && !empty( $this->_req_data['id'] )
222
			? $this->_req_data['id']
223
			: $grp_id;
224
		$msg_id = ! empty( $this->_req_data['MSG_ID'] ) && ! is_array( $this->_req_data['MSG_ID'] )
225
			? $this->_req_data['MSG_ID']
226
			: 0;
227
228
		$this->_page_routes = array(
229
			'default' => array(
230
				'func' => '_message_queue_list_table',
231
				'capability' => 'ee_read_messages'
232
			),
233
			'global_mtps'=> array(
234
				'func' => '_ee_default_messages_overview_list_table',
235
				'capability' => 'ee_read_global_messages'
236
			),
237
			'custom_mtps' => array(
238
				'func' => '_custom_mtps_preview',
239
				'capability' => 'ee_read_messages'
240
			),
241
			'add_new_message_template'	=>array(
242
				 'func' => '_add_message_template',
243
				 'capability' => 'ee_edit_messages',
244
				 'noheader' => true
245
			),
246
			'edit_message_template' => array(
247
				'func' => '_edit_message_template',
248
				'capability' => 'ee_edit_message',
249
				'obj_id' => $grp_id
250
			),
251
			'preview_message' => array(
252
				'func' => '_preview_message',
253
				'capability' => 'ee_read_message',
254
				'obj_id' => $grp_id,
255
				'noheader' => true,
256
				'headers_sent_route' => 'display_preview_message'
257
			),
258
			'display_preview_message' => array(
259
				'func' => '_display_preview_message',
260
				'capability' => 'ee_read_message',
261
				'obj_id' => $grp_id
262
			),
263
			'insert_message_template' => array(
264
				'func' => '_insert_or_update_message_template',
265
				'capability' => 'ee_edit_messages',
266
				'args' => array( 'new_template' => true ),
267
				'noheader' => true
268
			 ),
269
			'update_message_template' => array(
270
				'func' => '_insert_or_update_message_template',
271
				'capability' => 'ee_edit_message',
272
				'obj_id' => $grp_id,
273
				'args' => array( 'new_template' => false ),
274
				'noheader' => true
275
			),
276
			'trash_message_template' => array(
277
				'func' => '_trash_or_restore_message_template',
278
				'capability' => 'ee_delete_message',
279
				'obj_id' => $grp_id,
280
				'args' => array( 'trash' => true, 'all' => true ),
281
				'noheader' => true
282
			),
283
			'trash_message_template_context' => array(
284
				'func' => '_trash_or_restore_message_template',
285
				'capability' => 'ee_delete_message',
286
				'obj_id' => $grp_id,
287
				'args' => array( 'trash' => true ),
288
				'noheader' => true
289
			),
290
			'restore_message_template' => array(
291
				'func' => '_trash_or_restore_message_template',
292
				'capability' => 'ee_delete_message',
293
				'obj_id' => $grp_id,
294
				'args' => array( 'trash' => false, 'all' => true ),
295
				'noheader' => true
296
			),
297
			'restore_message_template_context' => array(
298
				'func' => '_trash_or_restore_message_template',
299
				'capability' => 'ee_delete_message',
300
				'obj_id' => $grp_id,
301
				'args' => array('trash' => false),
302
				'noheader' => true
303
			),
304
			'delete_message_template' => array(
305
				'func' => '_delete_message_template',
306
				'capability' => 'ee_delete_message',
307
				'obj_id' => $grp_id,
308
				'noheader' => true
309
			),
310
			'reset_to_default' => array(
311
				'func' => '_reset_to_default_template',
312
				'capability' => 'ee_edit_message',
313
				'obj_id' => $grp_id,
314
				'noheader' => true
315
			),
316
			'settings' => array(
317
				'func' => '_settings',
318
				'capability' => 'manage_options'
319
			),
320
			'generate_now' => array(
321
				'func' => '_generate_now',
322
				'capability' => 'ee_send_message',
323
				'noheader' => true
324
			),
325
			'generate_and_send_now' => array(
326
				'func' => '_generate_and_send_now',
327
				'capability' => 'ee_send_message',
328
				'noheader' => true
329
			),
330
			'queue_for_resending' => array(
331
				'func' => '_queue_for_resending',
332
				'capability' => 'ee_send_message',
333
				'noheader' => true
334
			),
335
			'send_now' => array(
336
				'func' => '_send_now',
337
				'capability' => 'ee_send_message',
338
				'noheader' => true
339
			),
340
			'delete_ee_message' => array(
341
				'func' => '_delete_ee_messages',
342
				'capability' => 'ee_delete_message',
343
				'noheader' => true
344
			),
345
			'delete_ee_messages' => array(
346
				'func' => '_delete_ee_messages',
347
				'capability' => 'ee_delete_messages',
348
				'noheader' => true,
349
				'obj_id' => $msg_id
350
			)
351
		);
352
	}
353
354
355
356
357
358
359
360
361
	protected function _set_page_config() {
362
		$this->_page_config = array(
363
			'default' => array(
364
				'nav' => array(
365
					'label' => __('Message Activity', 'event_espresso'),
366
					'order' => 10
367
				),
368
				'list_table' => 'EE_Message_List_Table',
369
				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
370
				'require_nonce' => false
371
			),
372
			'global_mtps' => array(
373
				'nav' => array(
374
					'label' => __('Default Message Templates', 'event_espresso'),
375
					'order' => 20
376
				),
377
				'list_table' => 'Messages_Template_List_Table',
378
				'help_tabs' => array(
379
					'messages_overview_help_tab' => array(
380
						'title' => __('Messages Overview', 'event_espresso'),
381
						'filename' => 'messages_overview'
382
					),
383
					'messages_overview_messages_table_column_headings_help_tab' => array(
384
						'title' => __('Messages Table Column Headings', 'event_espresso'),
385
						'filename' => 'messages_overview_table_column_headings'
386
					),
387
					'messages_overview_messages_filters_help_tab' => array(
388
						'title' => __('Message Filters', 'event_espresso'),
389
						'filename' => 'messages_overview_filters'
390
					),
391
					'messages_overview_messages_views_help_tab' => array(
392
						'title' => __('Message Views', 'event_espresso'),
393
						'filename' => 'messages_overview_views'
394
					),
395
					'message_overview_message_types_help_tab' => array(
396
						'title' => __('Message Types', 'event_espresso'),
397
						'filename' => 'messages_overview_types'
398
					),
399
					'messages_overview_messengers_help_tab' => array(
400
						'title' => __('Messengers', 'event_espresso'),
401
						'filename' => 'messages_overview_messengers',
402
					),
403
					'messages_overview_other_help_tab' => array(
404
						'title' => __('Messages Other', 'event_espresso'),
405
						'filename' => 'messages_overview_other',
406
					),
407
				),
408
				'help_tour' => array( 'Messages_Overview_Help_Tour' ),
409
				'require_nonce' => false
410
			),
411
			'custom_mtps' => array(
412
				'nav' => array(
413
					'label' => __('Custom Message Templates', 'event_espresso'),
414
					'order' => 30
415
				),
416
				'help_tabs' => array(),
417
				'help_tour' => array(),
418
				'require_nonce' => false
419
			),
420
			'add_new_message_template' => array(
421
				'nav' => array(
422
					'label' => __('Add New Message Templates', 'event_espresso'),
423
					'order' => 5,
424
					'persistent' => false
425
				),
426
				'require_nonce' => false
427
			),
428
			'edit_message_template' => array(
429
				'labels' => array(
430
					'buttons' => array(
431
						'reset' => __('Reset Templates'),
432
					),
433
					'publishbox' => __('Update Actions', 'event_espresso')
434
				),
435
				'nav' => array(
436
					'label' => __('Edit Message Templates', 'event_espresso'),
437
					'order' => 5,
438
					'persistent' => false,
439
					'url' => ''
440
				),
441
				'metaboxes' => array('_publish_post_box', '_register_edit_meta_boxes'),
442
				'has_metaboxes' => true,
443
				'help_tour' => array( 'Message_Templates_Edit_Help_Tour' ),
444
				'help_tabs' => array(
445
					'edit_message_template' => array(
446
						'title' => __('Message Template Editor', 'event_espresso'),
447
						'callback' => 'edit_message_template_help_tab'
448
					),
449
					'message_templates_help_tab' => array(
450
						'title' => __('Message Templates', 'event_espresso'),
451
						'filename' => 'messages_templates'
452
					),
453
					'message_template_shortcodes' => array(
454
						'title' => __('Message Shortcodes', 'event_espresso'),
455
						'callback' => 'message_template_shortcodes_help_tab'
456
					),
457
					'message_preview_help_tab' => array(
458
						'title' => __('Message Preview', 'event_espresso'),
459
						'filename' => 'messages_preview'
460
					),
461
				),
462
				'require_nonce' => false
463
			),
464
			'display_preview_message' => array(
465
				'nav' => array(
466
					'label' => __('Message Preview', 'event_espresso'),
467
					'order' => 5,
468
					'url' => '',
469
					'persistent' => false
470
				),
471
				'help_tabs' => array(
472
					'preview_message' => array(
473
						'title' => __('About Previews', 'event_espresso'),
474
						'callback' => 'preview_message_help_tab'
475
					)
476
				),
477
				'require_nonce' => false
478
			),
479
			'settings' => array(
480
				'nav' => array(
481
					'label' => __('Settings', 'event_espresso'),
482
					'order' => 40
483
				),
484
				'metaboxes' => array('_messages_settings_metaboxes'),
485
				'help_tabs' => array(
486
					'messages_settings_help_tab' => array(
487
						'title' => __('Messages Settings', 'event_espresso'),
488
						'filename' => 'messages_settings'
489
					),
490
					'messages_settings_message_types_help_tab' => array(
491
						'title' => __('Activating / Deactivating Message Types', 'event_espresso'),
492
						'filename' => 'messages_settings_message_types'
493
					),
494
					'messages_settings_messengers_help_tab' => array(
495
						'title' => __('Activating / Deactivating Messengers', 'event_espresso'),
496
						'filename' => 'messages_settings_messengers'
497
					),
498
				),
499
				'help_tour' => array( 'Messages_Settings_Help_Tour' ),
500
				'require_nonce' => false
501
			)
502
		);
503
	}
504
505
506
507
508
509
	protected function _add_screen_options() {
510
		//todo
511
	}
512
513
514
515
516
517 View Code Duplication
	protected function _add_screen_options_global_mtps() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
518
		/**
519
		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
520
         * uses the $_admin_page_title property and we want different outputs in the different spots.
521
         */
522
		$page_title = $this->_admin_page_title;
523
		$this->_admin_page_title = __('Global Message Templates', 'event_espresso');
524
		$this->_per_page_screen_option();
525
		$this->_admin_page_title = $page_title;
526
	}
527
528
529
530
531
	protected function _add_screen_options_default() {
532
		$this->_admin_page_title = __( 'Message Activity', 'event_espresso' );
533
		$this->_per_page_screen_option();
534
	}
535
536
537
538
539
540
541
	//none of the below group are currently used for Messages
542
	protected function _add_feature_pointers() {}
543
	public function admin_init() {
544
	}
545
	public function admin_notices() {}
546
	public function admin_footer_scripts() {}
547
548
549
550
551
552
553
	public function messages_help_tab() {
554
		EEH_Template::display_template( EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php' );
555
	}
556
557
558
	public function messengers_help_tab() {
559
		EEH_Template::display_template( EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php' );
560
	}
561
562
563
	public function message_types_help_tab() {
564
		EEH_Template::display_template( EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php' );
565
	}
566
567
568
	public function messages_overview_help_tab() {
569
		EEH_Template::display_template( EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php' );
570
	}
571
572
573
	public function message_templates_help_tab() {
574
		EEH_Template::display_template( EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php' );
575
	}
576
577
578
	public function edit_message_template_help_tab() {
579
		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title', 'event_espresso') . '" />';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$args was never initialized. Although not strictly required by PHP, it is generally a good practice to add $args = 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...
580
		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview', 'event_espresso') . '" />';
581
		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields', 'event_espresso') . '" />';
582
		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox', 'event_espresso') . '" />';
583
		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox', 'event_espresso') . '" />';
584
		EEH_Template::display_template( EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php', $args);
585
	}
586
587
588
589
	public function message_template_shortcodes_help_tab() {
590
		$this->_set_shortcodes();
591
		$args['shortcodes'] = $this->_shortcodes;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$args was never initialized. Although not strictly required by PHP, it is generally a good practice to add $args = 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...
592
		EEH_Template::display_template( EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php', $args );
593
	}
594
595
596
597
	public function preview_message_help_tab() {
598
		EEH_Template::display_template( EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php' );
599
	}
600
601
602
	public function settings_help_tab() {
603
		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$args was never initialized. Although not strictly required by PHP, it is generally a good practice to add $args = 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...
604
		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
605
		$args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
606
		$args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
607
		EEH_Template::display_template( EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
608
	}
609
610
611
612
613
614 View Code Duplication
	public function load_scripts_styles() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
615
		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION );
616
		wp_enqueue_style('espresso_ee_msg');
617
618
		wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js', array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true );
619
		wp_register_script( 'ee-msg-list-table-js', EE_MSG_ASSETS_URL. 'ee_message_admin_list_table.js', array( 'ee-dialog' ), EVENT_ESPRESSO_VERSION );
620
	}
621
622
623
624
	public function load_scripts_styles_default() {
625
		wp_enqueue_script( 'ee-msg-list-table-js' );
626
	}
627
628
629
630
631
632
	public function wp_editor_css( $mce_css ) {
633
		//if we're on the edit_message_template route
634
		if ( $this->_req_action == 'edit_message_template' && $this->_active_messenger instanceof EE_messenger  ) {
635
			$message_type_name = $this->_active_message_type_name;
636
637
			//we're going to REPLACE the existing mce css
638
			//we need to get the css file location from the active messenger
639
			$mce_css = $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true, 'wpeditor', $this->_variation );
640
		}
641
642
		return $mce_css;
643
	}
644
645
646
647
648
	public function load_scripts_styles_edit_message_template() {
649
650
		$this->_set_shortcodes();
651
652
		EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
653
			__('Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.', 'event_espresso'),
654
			$this->_message_template_group->messenger_obj()->label['singular'],
655
			$this->_message_template_group->message_type_obj()->label['singular']
656
		);
657
		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?', 'event_espresso' );
658
659
		wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'), EVENT_ESPRESSO_VERSION );
660
661
		wp_enqueue_script('ee_admin_js');
662
		wp_enqueue_script('ee_msgs_edit_js');
663
664
		//add in special css for tiny_mce
665
		add_filter( 'mce_css', array( $this, 'wp_editor_css' ) );
666
	}
667
668
669
670
	public function load_scripts_styles_display_preview_message() {
671
672
		$this->_set_message_template_group();
673
674
		if ( isset( $this->_req_data['messenger'] ) ) {
675
			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger( $this->_req_data['messenger'] );
676
		}
677
678
		$message_type_name = isset( $this->_req_data['message_type'] ) ? $this->_req_data['message_type'] : '';
679
680
681
		wp_enqueue_style('espresso_preview_css', $this->_active_messenger->get_variation( $this->_template_pack, $message_type_name, true, 'preview', $this->_variation ) );
682
	}
683
684
685
686
	public function load_scripts_styles_settings() {
687
		wp_register_style( 'ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(), EVENT_ESPRESSO_VERSION );
688
		wp_enqueue_style( 'ee-text-links' );
689
		wp_enqueue_style( 'ee-message-settings' );
690
691
		wp_enqueue_script('ee-messages-settings');
692
	}
693
694
695
696
	/**
697
	 * set views array for List Table
698
	 */
699 View Code Duplication
	public function _set_list_table_views_global_mtps() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
700
		$this->_views = array(
701
			'in_use' => array(
702
				'slug' => 'in_use',
703
				'label' => __('In Use', 'event_espresso'),
704
				'count' => 0,
705
				'bulk_action' => array(
706
					'trash_message_template' => __('Move to Trash', 'event_espresso')
707
				)
708
			)
709
		);
710
	}
711
712
713
714
715
	/**
716
	 * set views array for message queue list table
717
	 */
718
	public function _set_list_table_views_default() {
719
		EE_Registry::instance()->load_helper( 'Template' );
720
721
		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can( 'ee_send_message', 'message_list_table_bulk_actions' )
722
			? array(
723
				'generate_now' => __( 'Generate Now', 'event_espresso' ),
724
		        'generate_and_send_now' => __( 'Generate and Send Now', 'event_espresso' ),
725
		        'queue_for_resending' => __( 'Queue for Resending', 'event_espresso' ),
726
		        'send_now' => __( 'Send Now', 'event_espresso' )
727
				)
728
			: array();
729
730
		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can( 'ee_delete_messages', 'message_list_table_bulk_actions' )
731
			? array( 'delete_ee_messages' => __( 'Delete Messages', 'event_espresso' ) )
732
			: array();
733
734
735
		$this->_views = array(
736
			 'all' => array(
737
			    'slug' => 'all',
738
			    'label' => __( 'All', 'event_espresso' ),
739
			    'count' => 0,
740
			    'bulk_action' => array_merge( $common_bulk_actions, $delete_bulk_action )
741
			 )
742
		);
743
744
745
		foreach ( EEM_Message::instance()->all_statuses() as $status ) {
746
			if ( $status === EEM_Message::status_debug_only && ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) ) {
747
				continue;
748
			}
749
			$status_bulk_actions = $common_bulk_actions;
750
			//unset bulk actions not applying to status
751
			if ( ! empty( $status_bulk_actions ) ) {
752
				switch ( $status ) {
753
					case EEM_Message::status_idle :
754
					case EEM_Message::status_resend :
755
						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
756
						break;
757
758
					case EEM_Message::status_failed :
759
					case EEM_Message::status_debug_only :
760
						$status_bulk_actions = array();
761
						break;
762
763
					case EEM_Message::status_incomplete :
764
						unset( $status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now'] );
765
						break;
766
767
					case EEM_Message::status_retry :
768
					case EEM_Message::status_sent :
769
						unset( $status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now'] );
770
						break;
771
				}
772
			}
773
774
			$this->_views[ strtolower( $status ) ] = array(
775
				'slug' => strtolower( $status ),
776
				'label' => EEH_Template::pretty_status( $status, false, 'sentence' ),
777
				'count' => 0,
778
				'bulk_action' => array_merge( $status_bulk_actions, $delete_bulk_action )
779
			);
780
		}
781
	}
782
783
784
785
	protected function _ee_default_messages_overview_list_table() {
786
		$this->_admin_page_title = __('Default Message Templates', 'event_espresso');
787
		$this->display_admin_list_table_page_with_no_sidebar();
788
	}
789
790
791
792
793
794
	protected function _message_queue_list_table() {
795
		$this->_search_btn_label = __('Message Activity', 'event_espresso');
796
		$this->_template_args['per_column'] = 6;
797
		$this->_template_args['after_list_table'] = $this->_display_legend( $this->_message_legend_items() );
798
		$this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
799
		$this->display_admin_list_table_page_with_no_sidebar();
800
	}
801
802
803
804
805
806
	protected function _message_legend_items() {
807
808
		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
809
		$action_items = array();
810
811
		foreach( $action_css_classes as $action_item => $action_details ) {
812
			if ( $action_item === 'see_notifications_for' ) {
813
				continue;
814
			}
815
			$action_items[$action_item] = array(
816
				'class' => $action_details['css_class'],
817
				'desc' => $action_details['label']
818
			);
819
		}
820
821
		/** @type array $status_items status legend setup*/
822
		$status_items = array(
823
			'sent_status' => array(
824
				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
825
				'desc' => EEH_Template::pretty_status( EEM_Message::status_sent, false, 'sentence' )
826
				),
827
			'idle_status' => array(
828
				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
829
				'desc' => EEH_Template::pretty_status( EEM_Message::status_idle, false, 'sentence' )
830
				),
831
			'failed_status' => array(
832
				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
833
				'desc' => EEH_Template::pretty_status( EEM_Message::status_failed, false, 'sentence' )
834
			),
835
			'resend_status' => array(
836
				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
837
				'desc' => EEH_Template::pretty_status( EEM_Message::status_resend, false, 'sentence' )
838
				),
839
			'incomplete_status' => array(
840
				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
841
				'desc' => EEH_Template::pretty_status( EEM_Message::status_incomplete, false, 'sentence' )
842
				),
843
			'retry_status' => array(
844
				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
845
				'desc' => EEH_Template::pretty_status( EEM_Message::status_retry, false, 'sentence' )
846
				)
847
		);
848
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
849
			$status_items['debug_only_status'] = array(
850
				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
851
				'desc' => EEH_Template::pretty_status( EEM_Message::status_debug_only, false, 'sentence' )
852
			);
853
		}
854
		return array_merge( $action_items, $status_items );
855
	}
856
857
858
859
860
861
862 View Code Duplication
	protected function _custom_mtps_preview() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
863
		$this->_admin_page_title = __('Custom Message Templates (Preview)', 'event_espresso');
864
		$this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot', 'event_espresso' ) . '" />';
865
		$this->_template_args['preview_text'] = '<strong>'.__('Custom Message Templates is a feature that is only available in the caffeinated version of Event Espresso.  With the Custom Message Templates feature, you are able to create custom templates and set them per event.', 'event_espresso').'</strong>';
866
		$this->display_admin_caf_preview_page( 'custom_message_types', false );
867
	}
868
869
870
871
872
873
874
875
876
	/**
877
	 * get_message_templates
878
	 * This gets all the message templates for listing on the overview list.
879
	 *
880
	 * @access public
881
	 *
882
	 * @param int $perpage the amount of templates groups to show per page
883
	 * @param string $type the current _view we're getting templates for
884
	 * @param bool $count return count?
885
	 * @param bool $all disregard any paging info (get all data);
886
	 * @param bool $global whether to return just global (true) or custom templates (false)
887
	 *
888
	 * @return array
889
	 */
890
	public function get_message_templates( $perpage = 10, $type = 'in_use', $count = false, $all = false, $global = true ) {
891
892
		$MTP = EEM_Message_Template_Group::instance();
893
894
		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
895
		$orderby = $this->_req_data['orderby'];
896
897
		$order = ( isset( $this->_req_data['order'] ) && ! empty( $this->_req_data['order'] ) ) ? $this->_req_data['order'] : 'ASC';
898
899
		$current_page = isset( $this->_req_data['paged'] ) && !empty( $this->_req_data['paged'] ) ? $this->_req_data['paged'] : 1;
900
		$per_page = isset( $this->_req_data['perpage'] ) && !empty( $this->_req_data['perpage'] ) ? $this->_req_data['perpage'] : $perpage;
901
902
		$offset = ($current_page-1)*$per_page;
903
		$limit = $all ? null : array( $offset, $per_page );
904
905
906
		//options will match what is in the _views array property
907
		switch( $type ) {
908
909
			case 'in_use':
910
				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true );
911
				break;
912
913
			default:
914
				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global );
915
916
		}
917
918
		return $templates;
919
	}
920
921
922
923
924
925
	/**
926
	 * filters etc might need a list of installed message_types
927
	 * @return array an array of message type objects
928
	 */
929
	public function get_installed_message_types() {
930
		$installed_message_types = $this->_message_resource_manager->installed_message_types();
931
		$installed = array();
932
933
		foreach ( $installed_message_types as $message_type ) {
934
			$installed[ $message_type->name ] = $message_type;
935
		}
936
937
		return $installed;
938
	}
939
940
941
942
	/**
943
	 * _add_message_template
944
	 *
945
	 * This is used when creating a custom template. All Custom Templates start based off another template.
946
	 *
947
	 * @param string $message_type
948
	 * @param string $messenger
949
	 * @param string $GRP_ID
950
	 *
951
	 * @throws EE_error
952
	 */
953
	protected function _add_message_template(  $message_type = '', $messenger='', $GRP_ID = '' ) {
954
		//set values override any request data
955
		$message_type = !empty( $message_type ) ? $message_type : '';
956
		$message_type = empty( $message_type ) && !empty( $this->_req_data['message_type'] ) ? $this->_req_data['message_type'] : $message_type;
957
958
		$messenger = !empty( $messenger ) ? $messenger : '';
959
		$messenger = empty( $messenger ) && !empty( $this->_req_data['messenger'] ) ? $this->_req_data['messenger'] : $messenger;
960
961
		$GRP_ID = !empty( $GRP_ID ) ? $GRP_ID : '';
962
		$GRP_ID = empty( $GRP_ID ) && !empty( $this->_req_data['GRP_ID'] ) ? $this->_req_data['GRP_ID'] : $GRP_ID;
963
964
		//we need messenger and message type.  They should be coming from the event editor. If not here then return error
965
		if ( empty( $message_type ) || empty( $messenger )  )
966
			{throw new EE_error(__('Sorry, but we can\'t create new templates because we\'re missing the messenger or message type', 'event_espresso'));}
967
968
		//we need the GRP_ID for the template being used as the base for the new template
969
		if ( empty( $GRP_ID ) )
970
			{throw new EE_Error( __('In order to create a custom message template the GRP_ID of the template being used as a base is needed', 'event_espresso' ) );}
971
972
		//let's just make sure the template gets generated!
973
974
		//we need to reassign some variables for what the insert is expecting
975
		$this->_req_data['MTP_messenger'] = $messenger;
976
		$this->_req_data['MTP_message_type'] = $message_type;
977
		$this->_req_data['GRP_ID'] = $GRP_ID;
978
		$this->_insert_or_update_message_template(true);
979
	}
980
981
982
983
	/**
984
	 * public wrapper for the _add_message_template method
985
	 *
986
	 * @param string $message_type message type slug
987
	 * @param string $messenger    messenger slug
988
	 * @param int      $GRP_ID         GRP_ID for the related message template group this new template will be based
989
	 *                                 off of.
990
	 */
991
	public function add_message_template( $message_type, $messenger, $GRP_ID ) {
992
		$this->_add_message_template( $message_type, $messenger, $GRP_ID );
993
	}
994
995
996
	/**
997
	 * _edit_message_template
998
	 *
999
	 * @access protected
1000
	 * @return void
1001
	 */
1002
	protected function _edit_message_template() {
1003
		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '');
1004
		$template_fields = '';
1005
		$sidebar_fields = '';
1006
		//we filter the tinyMCE settings to remove the validation since message templates by their nature will not have valid html in the templates.
1007
		add_filter( 'tiny_mce_before_init', array( $this, 'filter_tinymce_init'), 10, 2 );
1008
1009
		$GRP_ID = isset( $this->_req_data['id'] ) && !empty( $this->_req_data['id'] )
1010
			? absint( $this->_req_data['id'] )
1011
			: false;
1012
1013
		$this->_set_shortcodes(); //this also sets the _message_template property.
1014
		$message_template_group = $this->_message_template_group;
1015
		$c_label = $message_template_group->context_label();
1016
		$c_config = $message_template_group->contexts_config();
1017
1018
		reset( $c_config );
1019
		$context = isset( $this->_req_data['context']) && !empty($this->_req_data['context'] )
1020
			? strtolower($this->_req_data['context'])
1021
			: key($c_config);
1022
1023
1024
		if ( empty($GRP_ID) ) {
1025
			$action = 'insert_message_template';
1026
			//$button_both = false;
1027
			//$button_text = array( __( 'Save','event_espresso') );
1028
			//$button_actions = array('something_different');
1029
			//$referrer = false;
1030
			$edit_message_template_form_url = add_query_arg(
1031
				array( 'action' => $action, 'noheader' => true ),
1032
				EE_MSG_ADMIN_URL
1033
			);
1034
		} else {
1035
			$action = 'update_message_template';
1036
			//$button_both = true;
1037
			//$button_text = array();
1038
			//$button_actions = array();
1039
			//$referrer = $this->_admin_base_url;
1040
			$edit_message_template_form_url = add_query_arg(
1041
				array( 'action' => $action, 'noheader' => true ),
1042
				EE_MSG_ADMIN_URL
1043
			);
1044
		}
1045
1046
		//set active messenger for this view
1047
		$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1048
			$message_template_group->messenger()
1049
		);
1050
		$this->_active_message_type_name = $message_template_group->message_type();
1051
1052
1053
		//Do we have any validation errors?
1054
		$validators = $this->_get_transient();
1055
		$v_fields = !empty($validators) ? array_keys($validators) : array();
1056
1057
1058
		//we need to assemble the title from Various details
1059
		$context_label = sprintf(
1060
			__('(%s %s)', 'event_espresso'),
1061
			$c_config[$context]['label'],
1062
			ucwords($c_label['label'] )
1063
		);
1064
1065
		$title = sprintf(
1066
			__(' %s %s Template %s', 'event_espresso'),
1067
			ucwords($message_template_group->messenger_obj()->label['singular']),
1068
			ucwords($message_template_group->message_type_obj()->label['singular']),
1069
			$context_label
1070
		);
1071
1072
		$this->_template_args['GRP_ID'] = $GRP_ID;
1073
		$this->_template_args['message_template'] = $message_template_group;
1074
		$this->_template_args['is_extra_fields'] = false;
1075
1076
1077
		//let's get EEH_MSG_Template so we can get template form fields
1078
		$template_field_structure = EEH_MSG_Template::get_fields(
1079
			$message_template_group->messenger(),
1080
			$message_template_group->message_type()
1081
		);
1082
1083
		if ( !$template_field_structure ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $template_field_structure of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1084
			$template_field_structure = false;
1085
			$template_fields = __('There was an error in assembling the fields for this display (you should see an error message)', 'event_espresso');
1086
		}
1087
1088
1089
		$message_templates = $message_template_group->context_templates();
1090
1091
1092
		//if we have the extra key.. then we need to remove the content index from the template_field_structure as it will get handled in the "extra" array.
1093
		if ( is_array($template_field_structure[$context]) && isset( $template_field_structure[$context]['extra']) ) {
1094
			foreach ( $template_field_structure[$context]['extra'] as $reference_field => $new_fields ) {
1095
				unset( $template_field_structure[$context][$reference_field] );
1096
			}
1097
		}
1098
1099
		//let's loop through the template_field_structure and actually assemble the input fields!
1100
		if ( !empty($template_field_structure) ) {
1101
			foreach ( $template_field_structure[$context] as $template_field => $field_setup_array ) {
1102
				//if this is an 'extra' template field then we need to remove any existing fields that are keyed up in the extra array and reset them.
1103
				if ( $template_field == 'extra' ) {
1104
					$this->_template_args['is_extra_fields'] = true;
1105
					foreach ( $field_setup_array as $reference_field => $new_fields_array ) {
1106
						$message_template = $message_templates[ $context ][ $reference_field ];
1107
						$content = $message_template instanceof EE_Message_Template
1108
							? $message_template->get( 'MTP_content' )
1109
							: '';
1110
						foreach ( $new_fields_array as $extra_field =>  $extra_array ) {
1111
							//let's verify if we need this extra field via the shortcodes parameter.
1112
							$continue = false;
1113
							if ( isset( $extra_array['shortcodes_required'] ) ) {
1114
								foreach ( (array) $extra_array['shortcodes_required'] as $shortcode ) {
1115
									if ( !array_key_exists( $shortcode, $this->_shortcodes ) )
1116
										{$continue = true;}
1117
								}
1118
								if ( $continue ) {continue;}
1119
							}
1120
1121
							$field_id = $reference_field . '-' . $extra_field . '-content';
1122
							$template_form_fields[$field_id] = $extra_array;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$template_form_fields was never initialized. Although not strictly required by PHP, it is generally a good practice to add $template_form_fields = 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...
1123
							$template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
0 ignored issues
show
Bug introduced by
The variable $template_form_fields does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1124
							$css_class = isset( $extra_array['css_class'] ) ? $extra_array['css_class'] : '';
1125
1126
							$template_form_fields[$field_id]['css_class'] = ! empty( $v_fields )
1127
																			&& in_array($extra_field, $v_fields)
1128
																			&&
1129
																			(
1130
								                                                is_array($validators[$extra_field] )
1131
																				&& isset( $validators[$extra_field]['msg'] )
1132
							                                                )
1133
								? 'validate-error ' . $css_class
1134
								: $css_class;
1135
1136
							$template_form_fields[$field_id]['value'] = !empty($message_templates) && isset($content[$extra_field])
1137
								? stripslashes( html_entity_decode( $content[$extra_field], ENT_QUOTES, "UTF-8") )
1138
								: '';
1139
1140
							//do we have a validation error?  if we do then let's use that value instead
1141
							$template_form_fields[$field_id]['value'] = isset($validators[$extra_field]) ? $validators[$extra_field]['value'] : $template_form_fields[$field_id]['value'];
1142
1143
1144
							$template_form_fields[$field_id]['db-col'] = 'MTP_content';
1145
1146
							//shortcode selector
1147
							$field_name_to_use = $extra_field == 'main' ? 'content' : $extra_field;
1148
							$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1149
								$field_name_to_use,
1150
								$field_id
1151
							);
1152
1153
							if ( isset( $extra_array['input'] ) && $extra_array['input'] == 'wp_editor' ) {
1154
								//we want to decode the entities
1155
								$template_form_fields[$field_id]['value'] = stripslashes(
1156
									html_entity_decode( $template_form_fields[$field_id]['value'], ENT_QUOTES, "UTF-8")
1157
								);
1158
1159
							}/**/
1160
						}
1161
						$templatefield_MTP_id = $reference_field . '-MTP_ID';
1162
						$templatefield_templatename_id = $reference_field . '-name';
1163
1164
						$template_form_fields[$templatefield_MTP_id] = array(
1165
							'name' => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1166
							'label' => null,
1167
							'input' => 'hidden',
1168
							'type' => 'int',
1169
							'required' => false,
1170
							'validation' => false,
1171
							'value' => !empty($message_templates) ? $message_template->ID() : '',
1172
							'css_class' => '',
1173
							'format' => '%d',
1174
							'db-col' => 'MTP_ID'
1175
						);
1176
1177
						$template_form_fields[$templatefield_templatename_id] = array(
1178
							'name' => 'MTP_template_fields[' . $reference_field . '][name]',
1179
							'label' => null,
1180
							'input' => 'hidden',
1181
							'type' => 'string',
1182
							'required' => false,
1183
							'validation' => true,
1184
							'value' => $reference_field,
1185
							'css_class' => '',
1186
							'format' => '%s',
1187
							'db-col' => 'MTP_template_field'
1188
						);
1189
					}
1190
					continue; //skip the next stuff, we got the necessary fields here for this dataset.
1191
				} else {
1192
					$field_id = $template_field . '-content';
1193
					$template_form_fields[$field_id] = $field_setup_array;
1194
					$template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1195
					$message_template = isset( $message_templates[ $context ][ $template_field ] )
1196
						? $message_templates[ $context ][ $template_field ]
1197
						: null;
1198
					$template_form_fields[$field_id]['value'] = ! empty( $message_templates )
1199
																&& is_array( $message_templates[$context] )
1200
																&& $message_template instanceof EE_Message_Template
1201
						? $message_template->get('MTP_content')
1202
						: '';
1203
1204
					//do we have a validator error for this field?  if we do then we'll use that value instead
1205
					$template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1206
						? $validators[$template_field]['value']
1207
						: $template_form_fields[$field_id]['value'];
1208
1209
1210
					$template_form_fields[$field_id]['db-col'] = 'MTP_content';
1211
					$css_class = isset($field_setup_array['css_class']) ? $field_setup_array['css_class'] : '';
1212
					$template_form_fields[$field_id]['css_class'] =  ! empty( $v_fields )
1213
																	 && in_array( $template_field, $v_fields )
1214
																	 && isset( $validators[$template_field]['msg'] )
1215
						? 'validate-error ' . $css_class
1216
						: $css_class;
1217
1218
					//shortcode selector
1219
					$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1220
						$template_field, $field_id
1221
					);
1222
				}
1223
1224
				//k took care of content field(s) now let's take care of others.
1225
1226
				$templatefield_MTP_id = $template_field . '-MTP_ID';
1227
				$templatefield_field_templatename_id = $template_field . '-name';
1228
1229
				//foreach template field there are actually two form fields created
1230
				$template_form_fields[$templatefield_MTP_id] = array(
1231
					'name' => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1232
					'label' => null,
1233
					'input' => 'hidden',
1234
					'type' => 'int',
1235
					'required' => false,
1236
					'validation' => true,
1237
					'value' => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1238
					'css_class' => '',
1239
					'format' => '%d',
1240
					'db-col' => 'MTP_ID'
1241
				);
1242
1243
				$template_form_fields[$templatefield_field_templatename_id] = array(
1244
					'name' => 'MTP_template_fields[' . $template_field . '][name]',
1245
					'label' => null,
1246
					'input' => 'hidden',
1247
					'type' => 'string',
1248
					'required' => false,
1249
					'validation' => true,
1250
					'value' => $template_field,
1251
					'css_class' => '',
1252
					'format' => '%s',
1253
					'db-col' => 'MTP_template_field'
1254
				);
1255
1256
			}
1257
1258
			//add other fields
1259
			$template_form_fields['ee-msg-current-context'] = array(
1260
					'name' => 'MTP_context',
1261
					'label' => null,
1262
					'input' => 'hidden',
1263
					'type' => 'string',
1264
					'required' => false,
1265
					'validation' => true,
1266
					'value' => $context,
1267
					'css_class' => '',
1268
					'format' => '%s',
1269
					'db-col' => 'MTP_context'
1270
				);
1271
1272
			$template_form_fields['ee-msg-grp-id'] = array(
1273
					'name' => 'GRP_ID',
1274
					'label' => null,
1275
					'input' => 'hidden',
1276
					'type' => 'int',
1277
					'required' => false,
1278
					'validation' => true,
1279
					'value' => $GRP_ID,
1280
					'css_class' => '',
1281
					'format' => '%d',
1282
					'db-col' => 'GRP_ID'
1283
				);
1284
1285
			$template_form_fields['ee-msg-messenger'] = array(
1286
					'name' => 'MTP_messenger',
1287
					'label' => null,
1288
					'input' => 'hidden',
1289
					'type' => 'string',
1290
					'required' => false,
1291
					'validation' => true,
1292
					'value' => $message_template_group->messenger(),
1293
					'css_class' => '',
1294
					'format' => '%s',
1295
					'db-col' => 'MTP_messenger'
1296
				);
1297
1298
			$template_form_fields['ee-msg-message-type'] = array(
1299
					'name' => 'MTP_message_type',
1300
					'label' => null,
1301
					'input' => 'hidden',
1302
					'type' => 'string',
1303
					'required' => false,
1304
					'validation' => true,
1305
					'value' => $message_template_group->message_type(),
1306
					'css_class' => '',
1307
					'format' => '%s',
1308
					'db-col' => 'MTP_message_type'
1309
				);
1310
1311
			$sidebar_form_fields['ee-msg-is-global'] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$sidebar_form_fields was never initialized. Although not strictly required by PHP, it is generally a good practice to add $sidebar_form_fields = 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...
1312
					'name' => 'MTP_is_global',
1313
					'label' => __('Global Template', 'event_espresso'),
1314
					'input' => 'hidden',
1315
					'type' => 'int',
1316
					'required' => false,
1317
					'validation' => true,
1318
					'value' => $message_template_group->get('MTP_is_global'),
1319
					'css_class' => '',
1320
					'format' => '%d',
1321
					'db-col' => 'MTP_is_global'
1322
				);
1323
1324
			$sidebar_form_fields['ee-msg-is-override'] = array(
1325
					'name' => 'MTP_is_override',
1326
					'label' => __('Override all custom', 'event_espresso'),
1327
					'input' => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1328
					'type' => 'int',
1329
					'required' => false,
1330
					'validation' => true,
1331
					'value' => $message_template_group->get('MTP_is_override'),
1332
					'css_class' => '',
1333
					'format' => '%d',
1334
					'db-col' => 'MTP_is_override'
1335
				);
1336
1337
			$sidebar_form_fields['ee-msg-is-active'] = array(
1338
					'name' => 'MTP_is_active',
1339
					'label' => __('Active Template', 'event_espresso'),
1340
					'input' => 'hidden',
1341
					'type' => 'int',
1342
					'required' => false,
1343
					'validation' => true,
1344
					'value' => $message_template_group->is_active(),
1345
					'css_class' => '',
1346
					'format' => '%d',
1347
					'db-col' => 'MTP_is_active'
1348
				);
1349
1350
			$sidebar_form_fields['ee-msg-deleted'] = array(
1351
					'name' => 'MTP_deleted',
1352
					'label' => null,
1353
					'input' => 'hidden',
1354
					'type' => 'int',
1355
					'required' => false,
1356
					'validation' => true,
1357
					'value' => $message_template_group->get('MTP_deleted'),
1358
					'css_class' => '',
1359
					'format' => '%d',
1360
					'db-col' => 'MTP_deleted'
1361
				);
1362
			$sidebar_form_fields['ee-msg-author'] = array(
1363
				'name' => 'MTP_user_id',
1364
				'label' => __('Author', 'event_espresso'),
1365
				'input' => 'hidden',
1366
				'type'=> 'int',
1367
				'required' => false,
1368
				'validation' => false,
1369
				'value' => $message_template_group->user(),
1370
				'format' => '%d',
1371
				'db-col' => 'MTP_user_id'
1372
			);
1373
1374
			$sidebar_form_fields['ee-msg-route'] = array(
1375
				'name' => 'action',
1376
				'input' => 'hidden',
1377
				'type' => 'string',
1378
				'value' => $action
1379
				);
1380
1381
			$sidebar_form_fields['ee-msg-id'] = array(
1382
				'name' => 'id',
1383
				'input' => 'hidden',
1384
				'type' => 'int',
1385
				'value' => $GRP_ID
1386
				);
1387
			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1388
				'name' => $action . '_nonce',
1389
				'input' => 'hidden',
1390
				'type' => 'string',
1391
				'value' => wp_create_nonce( $action . '_nonce')
1392
				);
1393
1394
			if ( isset($this->_req_data['template_switch']) && $this->_req_data['template_switch'] ) {
1395
				$sidebar_form_fields['ee-msg-template-switch'] = array(
1396
					'name' => 'template_switch',
1397
					'input' => 'hidden',
1398
					'type' => 'int',
1399
					'value' => 1
1400
					);
1401
			}
1402
1403
1404
			$template_fields = $this->_generate_admin_form_fields( $template_form_fields );
1405
			$sidebar_fields = $this->_generate_admin_form_fields( $sidebar_form_fields );
1406
1407
1408
		} //end if ( !empty($template_field_structure) )
1409
1410
		//set extra content for publish box
1411
		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1412
		$this->_set_publish_post_box_vars(
1413
			'id',
1414
			 $GRP_ID,
1415
			 false,
1416
			 add_query_arg(
1417
			    array( 'action' => 'global_mtps' ),
1418
			    $this->_admin_base_url
1419
			 )
1420
		);
1421
1422
		//add preview button
1423
		$preview_url = parent::add_query_args_and_nonce(
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (add_query_args_and_nonce() instead of _edit_message_template()). Are you sure this is correct? If so, you might want to change this to $this->add_query_args_and_nonce().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
1424
			array(
1425
				'message_type' => $message_template_group->message_type(),
1426
				'messenger'    => $message_template_group->messenger(),
1427
				'context'      => $context,
1428
				'GRP_ID'       => $GRP_ID,
1429
				'action'       => 'preview_message'
1430
			),
1431
			$this->_admin_base_url
1432
		);
1433
		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview', 'event_espresso') . '</a>';
1434
1435
1436
		//setup context switcher
1437
		$context_switcher_args = array(
1438
			'page'    => 'espresso_messages',
1439
			'action'  => 'edit_message_template',
1440
			'id'      => $GRP_ID,
1441
			'context' => $context,
1442
			'extra'   => $preview_button
1443
		);
1444
		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1445
1446
1447
		//main box
1448
		$this->_template_args['template_fields'] = $template_fields;
1449
		$this->_template_args['sidebar_box_id'] = 'details';
1450
		$this->_template_args['action'] = $action;
1451
		$this->_template_args['context'] = $context;
1452
		$this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1453
		$this->_template_args['learn_more_about_message_templates_link'] = $this->_learn_more_about_message_templates_link();
1454
1455
1456
		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1457
		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1458
		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1459
1460
		$this->_template_path = $this->_template_args['GRP_ID']
1461
			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1462
			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1463
1464
		//send along EE_Message_Template_Group object for further template use.
1465
		$this->_template_args['MTP'] = $message_template_group;
1466
1467
		$this->_template_args['admin_page_content'] = EEH_Template::display_template( $this->_template_path, $this->_template_args, true );
1468
1469
1470
		//finally, let's set the admin_page title
1471
		$this->_admin_page_title = sprintf( __('Editing %s', 'event_espresso'), $title );
1472
1473
1474
		//we need to take care of setting the shortcodes property for use elsewhere.
1475
		$this->_set_shortcodes();
1476
1477
1478
1479
		//final template wrapper
1480
		$this->display_admin_page_with_sidebar();
1481
	}
1482
1483
1484
	public function filter_tinymce_init( $mceInit, $editor_id ) {
0 ignored issues
show
Unused Code introduced by
The parameter $editor_id 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...
1485
		return $mceInit;
1486
	}
1487
1488
1489
1490
	public function add_context_switcher() {
1491
		return $this->_context_switcher;
1492
	}
1493
1494
	public function _add_form_element_before() {
1495
		return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1496
	}
1497
1498
	public function _add_form_element_after() {
1499
		return '</form>';
1500
	}
1501
1502
1503
1504
1505
	/**
1506
	 * This executes switching the template pack for a message template.
1507
	 *
1508
	 * @since 4.5.0
1509
	 *
1510
	 */
1511
	public function switch_template_pack() {
1512
		$GRP_ID = ! empty( $this->_req_data['GRP_ID'] ) ? $this->_req_data['GRP_ID'] : 0;
1513
		$template_pack = ! empty( $this->_req_data['template_pack'] ) ? $this->_req_data['template_pack'] : '';
1514
1515
		//verify we have needed values.
1516
		if ( empty( $GRP_ID ) || empty( $template_pack ) ) {
1517
			$this->_template_args['error'] = true;
1518
			EE_Error::add_error( __('The required date for switching templates is not available.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__  );
1519
		} else {
1520
			//get template, set the new template_pack and then reset to default
1521
			/** @type EE_Message_Template_Group $message_template_group */
1522
			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
1523
1524
			$message_template_group->set_template_pack_name( $template_pack );
1525
			$this->_req_data['msgr'] = $message_template_group->messenger();
1526
			$this->_req_data['mt'] = $message_template_group->message_type();
1527
1528
			$query_args = $this->_reset_to_default_template();
1529
1530
			if ( empty( $query_args['id'] ) ) {
1531
				EE_Error::add_error(
1532
					__(
1533
						'Something went wrong with switching the template pack. Please try again or contact EE support',
1534
						'event_espresso'
1535
					),
1536
					__FILE__, __FUNCTION__, __LINE__
1537
				);
1538
				$this->_template_args['error'] = true;
1539
			} else {
1540
				$template_label =$message_template_group->get_template_pack()->label;
1541
				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1542
				EE_Error::add_success(
1543
					sprintf(
1544
						__(
1545
							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1546
							'event_espresso'
1547
						),
1548
						$template_label,
1549
						$template_pack_labels->template_pack
1550
					)
1551
				);
1552
				//generate the redirect url for js.
1553
				$url = self::add_query_args_and_nonce( $query_args, $this->_admin_base_url );
1554
				$this->_template_args['data']['redirect_url'] = $url;
1555
				$this->_template_args['success'] = true;
1556
			}
1557
1558
			$this->_return_json();
1559
1560
		}
1561
	}
1562
1563
1564
1565
	/**
1566
	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
1567
	 * they want.
1568
	 *
1569
	 * @access protected
1570
	 * @return array|null
1571
	 */
1572
	protected function _reset_to_default_template() {
1573
1574
		$templates = array();
1575
		$GRP_ID = !empty( $this->_req_data['GRP_ID'] ) ? $this->_req_data['GRP_ID'] : 0;
1576
		//we need to make sure we've got the info we need.
1577
		if ( ! isset( $this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'] ) ) {
1578
			EE_Error::add_error(
1579
				__(
1580
					'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
1581
					'event_espresso'
1582
				),
1583
				__FILE__, __FUNCTION__, __LINE__
1584
			);
1585
		}
1586
1587
		// all templates will be reset to whatever the defaults are
1588
		// for the global template matching the messenger and message type.
1589
		$success = !empty( $GRP_ID ) ? true : false;
1590
1591
		if ( $success ) {
1592
1593
			//let's first determine if the incoming template is a global template,
1594
			// if it isn't then we need to get the global template matching messenger and message type.
1595
			//$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
1596
1597
1598
			//note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
1599
			$success = $this->_delete_mtp_permanently( $GRP_ID, false );
1600
1601
			if ( $success ) {
1602
				// if successfully deleted, lets generate the new ones.
1603
				// Note. We set GLOBAL to true, because resets on ANY template
1604
				// will use the related global template defaults for regeneration.
1605
				// This means that if a custom template is reset it resets to whatever the related global template is.
1606
				// HOWEVER, we DO keep the template pack and template variation set
1607
				// for the current custom template when resetting.
1608
				$templates = $this->_generate_new_templates(
1609
					$this->_req_data['msgr'],
1610
					$this->_req_data['mt'],
1611
					$GRP_ID,
1612
					true
1613
				);
1614
			}
1615
1616
		}
1617
1618
		//any error messages?
1619
		if ( !$success ) {
1620
			EE_Error::add_error(
1621
				__( 'Something went wrong with deleting existing templates. Unable to reset to default', 'event_espresso' ),
1622
				__FILE__, __FUNCTION__, __LINE__
1623
			);
1624
		}
1625
1626
		//all good, let's add a success message!
1627
		if ( $success && ! empty( $templates ) ) {
1628
			$templates = $templates[0]; //the info for the template we generated is the first element in the returned array.
1629
			EE_Error::overwrite_success();
1630
			EE_Error::add_success( __('Templates have been reset to defaults.', 'event_espresso') );
1631
		}
1632
1633
1634
		$query_args = array(
1635
			'id' => isset( $templates['GRP_ID'] ) ? $templates['GRP_ID'] : null,
1636
			'context' => isset( $templates['MTP_context'] ) ? $templates['MTP_context'] : null,
1637
			'action' => isset( $templates['GRP_ID'] ) ? 'edit_message_template' : 'global_mtps'
1638
			);
1639
1640
		//if called via ajax then we return query args otherwise redirect
1641
		if ( defined('DOING_AJAX') && DOING_AJAX ) {
1642
			return $query_args;
1643
		} else {
1644
			$this->_redirect_after_action( false, '', '', $query_args, true );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

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...
1645
			return null;
1646
		}
1647
	}
1648
1649
1650
1651
	/**
1652
	 * Retrieve and set the message preview for display.
1653
	 *
1654
	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
1655
	 * @return string
1656
	 */
1657
	public function _preview_message( $send = false ) {
1658
		//first make sure we've got the necessary parameters
1659
		if (
1660
			! isset(
1661
				$this->_req_data['message_type'],
1662
				$this->_req_data['messenger'],
1663
				$this->_req_data['messenger'],
1664
				$this->_req_data['GRP_ID']
1665
			)
1666
		) {
1667
			EE_Error::add_error(
1668
				__('Missing necessary parameters for displaying preview', 'event_espresso'),
1669
				__FILE__, __FUNCTION__, __LINE__
1670
			);
1671
		}
1672
1673
		EE_Registry::instance()->REQ->set( 'GRP_ID', $this->_req_data['GRP_ID'] );
1674
1675
1676
		//get the preview!
1677
		$preview = EED_Messages::preview_message( $this->_req_data['message_type'], $this->_req_data['context'], $this->_req_data['messenger'], $send );
1678
1679
		if ( $send ) {
1680
			return $preview;
1681
		}
1682
1683
		//let's add a button to go back to the edit view
1684
		$query_args = array(
1685
			'id' => $this->_req_data['GRP_ID'],
1686
			'context' => $this->_req_data['context'],
1687
			'action' => 'edit_message_template'
1688
			);
1689
		$go_back_url = parent::add_query_args_and_nonce( $query_args, $this->_admin_base_url );
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (add_query_args_and_nonce() instead of _preview_message()). Are you sure this is correct? If so, you might want to change this to $this->add_query_args_and_nonce().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
1690
		$preview_button = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit', 'event_espresso') . '</a>';
1691
		$message_types = $this->get_installed_message_types();
1692
		$active_messenger = $this->_message_resource_manager->get_active_messenger( $this->_req_data['messenger'] );
1693
		$active_messenger_label = $active_messenger instanceof EE_messenger
1694
			? ucwords( $active_messenger->label['singular'] )
1695
			: esc_html__( 'Unknown Messenger', 'event_espresso' );
1696
		//let's provide a helpful title for context
1697
		$preview_title = sprintf(
1698
			__( 'Viewing Preview for %s %s Message Template', 'event_espresso' ),
1699
			$active_messenger_label,
1700
			ucwords( $message_types[ $this->_req_data[ 'message_type' ] ]->label[ 'singular' ] )
1701
		);
1702
		//setup display of preview.
1703
		$this->_admin_page_title = $preview_title;
1704
		$this->_template_args['admin_page_content'] = $preview_button . '<br />' .stripslashes($preview);
1705
		$this->_template_args['data']['force_json'] = true;
1706
		return '';
1707
	}
1708
1709
1710
1711
1712
	/**
1713
	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
1714
	 * gets called automatically.
1715
	 *
1716
	 * @since 4.5.0
1717
	 *
1718
	 * @return string
1719
	 */
1720
	protected function _display_preview_message() {
1721
		$this->display_admin_page_with_no_sidebar();
1722
	}
1723
1724
1725
1726
1727
	/**
1728
	 * registers metaboxes that should show up on the "edit_message_template" page
1729
	 *
1730
	 * @access protected
1731
	 * @return void
1732
	 */
1733
	protected function _register_edit_meta_boxes() {
1734
		add_meta_box( 'mtp_valid_shortcodes', __('Valid Shortcodes', 'event_espresso'), array( $this, 'shortcode_meta_box' ), $this->_current_screen->id, 'side', 'default' );
1735
		add_meta_box( 'mtp_extra_actions', __('Extra Actions', 'event_espresso'), array( $this, 'extra_actions_meta_box' ), $this->_current_screen->id, 'side', 'high' );
1736
		add_meta_box( 'mtp_templates', __('Template Styles', 'event_espresso'), array( $this, 'template_pack_meta_box' ), $this->_current_screen->id, 'side', 'high' );
1737
	}
1738
1739
1740
1741
	/**
1742
	 * metabox content for all template pack and variation selection.
1743
	 *
1744
	 * @since 4.5.0
1745
	 *
1746
	 * @return string
1747
	 */
1748
	public function template_pack_meta_box() {
1749
		$this->_set_message_template_group();
1750
1751
		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
1752
1753
		$tp_select_values = array();
1754
1755
		foreach ( $tp_collection as $tp ) {
1756
			//only include template packs that support this messenger and message type!
1757
			$supports = $tp->get_supports();
1758
			if (
1759
				! isset( $supports[ $this->_message_template_group->messenger() ] )
1760
				|| ! in_array(
1761
					$this->_message_template_group->message_type(),
1762
					$supports[ $this->_message_template_group->messenger() ]
1763
				)
1764
			) {
1765
				//not supported
1766
				continue;
1767
			}
1768
1769
			$tp_select_values[] = array(
1770
				'text' => $tp->label,
1771
				'id' => $tp->dbref
1772
				);
1773
		}
1774
1775
		//if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by the default template pack.  This still allows for the odd template pack to override.
1776
		if ( empty( $tp_select_values ) ) {
1777
			$tp_select_values[] = array(
1778
				'text' => __('Default', 'event_espresso'),
1779
				'id' => 'default'
1780
			);
1781
		}
1782
1783
		//setup variation select values for the currently selected template.
1784
		$variations = $this->_message_template_group->get_template_pack()->get_variations(
1785
			$this->_message_template_group->messenger(),
1786
			$this->_message_template_group->message_type()
1787
		);
1788
		$variations_select_values = array();
1789
		foreach ( $variations as $variation => $label ) {
1790
			$variations_select_values[] = array(
1791
				'text' => $label,
1792
				'id' => $variation
1793
			);
1794
		}
1795
1796
		$template_pack_labels= $this->_message_template_group->messenger_obj()->get_supports_labels();
1797
1798
		$template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$template_args was never initialized. Although not strictly required by PHP, it is generally a good practice to add $template_args = 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...
1799
			'MTP_template_pack',
1800
			$tp_select_values,
1801
			$this->_message_template_group->get_template_pack_name()
1802
		);
1803
		$template_args['variations_selector'] = EEH_Form_Fields::select_input(
1804
			'MTP_template_variation',
1805
			$variations_select_values,
1806
			$this->_message_template_group->get_template_pack_variation()
1807
		);
1808
		$template_args['template_pack_label'] = $template_pack_labels->template_pack;
1809
		$template_args['template_variation_label'] = $template_pack_labels->template_variation;
1810
		$template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
1811
		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1812
1813
		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1814
1815
		EEH_Template::display_template( $template, $template_args );
1816
	}
1817
1818
1819
1820
	/**
1821
	 * This meta box holds any extra actions related to Message Templates
1822
	 * For now, this includes Resetting templates to defaults and sending a test email.
1823
	 *
1824
	 * @access  public
1825
	 * @return void
1826
	 */
1827
	public function extra_actions_meta_box() {
1828
		$template_form_fields = array();
1829
1830
		$extra_args = array(
1831
			'msgr' => $this->_message_template_group->messenger(),
1832
			'mt' => $this->_message_template_group->message_type(),
1833
			'GRP_ID' => $this->_message_template_group->GRP_ID()
1834
			);
1835
1836
		$button = $this->get_action_link_or_button(
1837
			'reset_to_default',
1838
			'reset',
1839
			$extra_args,
1840
			'button-primary reset-default-button'
1841
		);
1842
		//test button
1843
		//first we need to see if there are any fields
1844
		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
1845
1846
		if ( !empty( $fields ) ) {
1847
			//yup there be fields
1848
			foreach ( $fields as $field => $config ) {
1849
				$field_id = $this->_message_template_group->messenger() . '_' . $field;
1850
				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
1851
				$default = isset( $config['default'] ) ? $config['default'] : '';
1852
				$default = isset( $config['value'] ) ? $config['value'] : $default;
1853
1854
				//if type is hidden and the value is empty something may have gone wrong so let's correct with the defaults
1855
				$fix = $config['input'] == 'hidden' && isset($existing[$field]) && empty($existing[$field]) ? $default : '';
1856
				$existing[$field] = isset( $existing[$field] ) && empty( $fix ) ? $existing[$field] : $fix;
1857
1858
				$template_form_fields[$field_id] = array(
1859
					'name' => 'test_settings_fld[' . $field . ']',
1860
					'label' => $config['label'],
1861
					'input' => $config['input'],
1862
					'type' => $config['type'],
1863
					'required' => $config['required'],
1864
					'validation' => $config['validation'],
1865
					'value' => isset( $existing[$field] ) ? $existing[$field] : $default,
1866
					'css_class' => $config['css_class'],
1867
					'options' => isset( $config['options'] ) ? $config['options'] : array(),
1868
					'default' => $default,
1869
					'format' => $config['format']
1870
					);
1871
			}
1872
		}
1873
1874
		$test_settings_fields = !empty( $template_form_fields)
1875
			? $this->_generate_admin_form_fields( $template_form_fields, 'string', 'ee_tst_settings_flds' )
0 ignored issues
show
Documentation introduced by
'ee_tst_settings_flds' is of type string, but the function expects a false|array.

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...
1876
			: '';
1877
1878
		$test_settings_html = '';
1879
		//print out $test_settings_fields
1880
		if ( !empty( $test_settings_fields ) ) {
1881
			echo $test_settings_fields;
1882
			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" name="test_button" value="' . __('Test Send', 'event_espresso') . '" /><div style="clear:both"></div>';
1883
		}
1884
1885
		//and button
1886
		echo $test_settings_html . '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>' . '<div class="publishing-action alignright resetbutton">' . $button . '</div><div style="clear:both"></div>';
1887
	}
1888
1889
1890
1891
1892
	/**
1893
     * This returns the shortcode selector skeleton for a given context and field.
1894
     *
1895
     * @since 4.9.rc.000
1896
     *
1897
	 * @param string $field  The name of the field retrieving shortcodes for.
1898
     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
1899
     * @return string
1900
    */
1901
	protected function _get_shortcode_selector( $field, $linked_input_id ) {
1902
		$template_args = array(
1903
			'shortcodes' => $this->_get_shortcodes( array( $field ), true ),
1904
			'fieldname' => $field,
1905
			'linked_input_id' => $linked_input_id
1906
		);
1907
		return EEH_Template::display_template( EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php', $template_args, true );
1908
	}
1909
1910
1911
	/**
1912
	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
1913
	 * page)
1914
	 *
1915
	 * @access public
1916
	 * @return void
1917
	 */
1918
	public function shortcode_meta_box() {
1919
		$shortcodes = $this->_get_shortcodes(array(), false); //just make sure shortcodes property is set
1920
		//$messenger = $this->_message_template_group->messenger_obj();
1921
		//now let's set the content depending on the status of the shortcodes array
1922
		if ( empty( $shortcodes ) ) {
1923
			$content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
1924
			echo $content;
1925
		} else {
1926
			//$alt = 0;
1927
			?>
1928
			<div style="float:right; margin-top:10px"><?php echo $this->_get_help_tab_link('message_template_shortcodes'); ?></div><p class="small-text"><?php printf( __('You can view the shortcodes usable in your template by clicking the %s icon next to each field.', 'event_espresso' ), '<span class="dashicons dashicons-menu"></span>' ); ?></p>
1929
			<?php
1930
		}
1931
1932
1933
	}
1934
1935
1936
	/**
1937
	 * used to set the $_shortcodes property for when its needed elsewhere.
1938
	 *
1939
	 * @access protected
1940
	 * @return void
1941
	 */
1942
	protected function _set_shortcodes() {
1943
1944
		//no need to run this if the property is already set
1945
		if ( !empty($this->_shortcodes ) ) {return;}
1946
1947
		$this->_shortcodes = $this->_get_shortcodes();
1948
	}
1949
1950
1951
1952
1953
1954
	/**
1955
	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
1956
	 * property)
1957
	 *
1958
	 * @access  protected
1959
	 *
1960
	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes for.
1961
	 *                        Defaults to all (for the given context)
1962
	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
1963
	 *
1964
	 * @return array          Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is true
1965
	 *                       just an array of shortcode/label pairs.
1966
	 */
1967
	protected function _get_shortcodes( $fields = array(), $merged = true ) {
1968
		$this->_set_message_template_group();
1969
1970
		//we need the messenger and message template to retrieve the valid shortcodes array.
1971
		$GRP_ID = isset( $this->_req_data['id'] ) && !empty( $this->_req_data['id'] ) ? absint( $this->_req_data['id'] ) : false;
1972
		$context = isset( $this->_req_data['context'] ) ? $this->_req_data['context'] : key( $this->_message_template_group->contexts_config() );
1973
1974
		return !empty($GRP_ID) ? $this->_message_template_group->get_shortcodes( $context, $fields, $merged ) : array();
1975
	}
1976
1977
1978
1979
	/**
1980
	 * This sets the _message_template property (containing the called message_template object)
1981
	 *
1982
	 * @access protected
1983
	 * @return  void
1984
	 */
1985
	protected function _set_message_template_group() {
1986
1987
		if ( !empty( $this->_message_template_group ) )
1988
			{return;} //get out if this is already set.
1989
1990
		$GRP_ID =  ! empty( $this->_req_data['GRP_ID'] ) ? absint( $this->_req_data['GRP_ID'] ) : false;
1991
		$GRP_ID = empty( $GRP_ID ) && ! empty( $this->_req_data['id'] ) ? $this->_req_data['id'] : $GRP_ID;
1992
1993
		//let's get the message templates
1994
		$MTP = EEM_Message_Template_Group::instance();
1995
1996
		if ( empty($GRP_ID) )
1997
			{$this->_message_template_group = $MTP->create_default_object();}
0 ignored issues
show
Documentation Bug introduced by
It seems like $MTP->create_default_object() can also be of type object<EE_Base_Class>. However, the property $_message_template_group is declared as type object<EE_Message_Template_Group>. 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...
1998
		else
1999
			{$this->_message_template_group = $MTP->get_one_by_ID( $GRP_ID );}
0 ignored issues
show
Documentation Bug introduced by
It seems like $MTP->get_one_by_ID($GRP_ID) can also be of type object<EE_Base_Class>. However, the property $_message_template_group is declared as type object<EE_Message_Template_Group>. 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...
2000
2001
		$this->_template_pack = $this->_message_template_group->get_template_pack();
0 ignored issues
show
Documentation Bug introduced by
The method get_template_pack does not exist on object<EE_Base_Class>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2002
		$this->_variation = $this->_message_template_group->get_template_pack_variation();
0 ignored issues
show
Documentation Bug introduced by
The method get_template_pack_variation does not exist on object<EE_Base_Class>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2003
2004
	}
2005
2006
2007
2008
2009
	/**
2010
	 * sets up a context switcher for edit forms
2011
	 *
2012
	 * @access  protected
2013
	 *
2014
	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2015
	 * @param array $args various things the context switcher needs.
2016
	 *
2017
	 */
2018
	protected function _set_context_switcher( EE_Message_Template_Group $template_group_object, $args) {
2019
		$context_details = $template_group_object->contexts_config();
2020
		$context_label = $template_group_object->context_label();
2021
		ob_start();
2022
		?>
2023
		<div class="ee-msg-switcher-container">
2024
			<form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2025
				<?php
2026
					foreach ( $args as $name => $value ) {
2027
						if ( $name == 'context' || empty($value) || $name == 'extra' ) {continue;}
2028
						?>
2029
						<input type="hidden" name="<?php echo $name; ?>" value = "<?php echo $value; ?>" />
2030
						<?php
2031
					}
2032
					//setup nonce_url
2033
					wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2034
				?>
2035
				<select name="context">
2036
					<?php
2037
					$context_templates = $template_group_object->context_templates();
2038
					if ( is_array($context_templates) ) :
2039
							foreach ( $context_templates as $context => $template_fields ) :
2040
								$checked = ($context == $args['context']) ? 'selected="selected"' : '';
2041
					?>
2042
					<option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2043
						<?php echo $context_details[$context]['label']; ?>
2044
					</option>
2045
					<?php endforeach; endif; ?>
2046
				</select>
2047
				<?php $button_text = sprintf( __('Switch %s', 'event_espresso'), ucwords($context_label['label']) ); ?>
2048
				<input id="submit-msg-context-switcher-sbmt" class="button-secondary" type="submit" value="<?php echo $button_text; ?>">
2049
			</form>
2050
			<?php echo $args['extra']; ?>
2051
		</div> <!-- end .ee-msg-switcher-container -->
2052
		<?php
2053
		$output = ob_get_contents();
2054
		ob_clean();
2055
		$this->_context_switcher = $output;
2056
	}
2057
2058
2059
2060
2061
2062
2063
	/**
2064
	 * utility for sanitizing new values coming in.
2065
	 * Note: this is only used when updating a context.
2066
	 *
2067
	 * @access protected
2068
	 *
2069
	 * @param int $index This helps us know which template field to select from the request array.
2070
	 *
2071
	 * @return array
2072
	 */
2073
	protected function _set_message_template_column_values($index) {
2074
		if ( is_array($this->_req_data['MTP_template_fields'][$index]['content'] ) ) {
2075
			foreach ( $this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value ) {
0 ignored issues
show
Bug introduced by
The expression $this->_req_data['MTP_te...ds'][$index]['content'] of type string is not traversable.
Loading history...
2076
				$this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2077
			}
2078
		} /*else {
2079
			$this->_req_data['MTP_template_fields'][$index]['content'] = $this->_req_data['MTP_template_fields'][$index]['content'];
2080
		}*/
2081
2082
2083
		$set_column_values = array(
2084
			'MTP_ID'             => absint( $this->_req_data[ 'MTP_template_fields' ][ $index ][ 'MTP_ID' ] ),
2085
			'GRP_ID'             => absint( $this->_req_data[ 'GRP_ID' ] ),
2086
			'MTP_user_id'        => absint( $this->_req_data[ 'MTP_user_id' ] ),
2087
			'MTP_messenger'      => strtolower( $this->_req_data[ 'MTP_messenger' ] ),
2088
			'MTP_message_type'   => strtolower( $this->_req_data[ 'MTP_message_type' ] ),
2089
			'MTP_template_field' => strtolower( $this->_req_data[ 'MTP_template_fields' ][ $index ][ 'name' ] ),
2090
			'MTP_context'        => strtolower( $this->_req_data[ 'MTP_context' ] ),
2091
			'MTP_content'        => $this->_req_data[ 'MTP_template_fields' ][ $index ][ 'content' ],
2092
			'MTP_is_global'      => isset( $this->_req_data[ 'MTP_is_global' ] )
2093
				? absint( $this->_req_data[ 'MTP_is_global' ] )
2094
				: 0,
2095
			'MTP_is_override'    => isset( $this->_req_data[ 'MTP_is_override' ] )
2096
				? absint( $this->_req_data[ 'MTP_is_override' ] )
2097
				: 0,
2098
			'MTP_deleted'        => absint( $this->_req_data[ 'MTP_deleted' ] ),
2099
			'MTP_is_active'      => absint( $this->_req_data[ 'MTP_is_active' ] )
2100
		);
2101
2102
2103
		return $set_column_values;
2104
	}
2105
2106
2107
2108
2109
2110
2111
	protected function _insert_or_update_message_template($new = false ) {
2112
2113
		do_action ( 'AHEE_log', __FILE__, __FUNCTION__, '');
2114
		$success = 0;
2115
		$override = false;
2116
2117
		//setup notices description
2118
		$messenger = ! empty( $this->_req_data['MTP_messenger'] )
2119
			? ucwords( str_replace( '_', ' ', $this->_req_data['MTP_messenger'] ) )
2120
			: false;
2121
2122
		$message_type = ! empty( $this->_req_data['MTP_message_type'] )
2123
			? ucwords( str_replace( '_', ' ', $this->_req_data['MTP_message_type'] ) )
2124
			: false;
2125
2126
		$context = ! empty( $this->_req_data['MTP_context'] )
2127
			? ucwords( str_replace( '_', ' ', $this->_req_data['MTP_context'] ) )
2128
			: false;
2129
2130
		$item_desc = $messenger ? $messenger . ' ' . $message_type . ' ' . $context . ' ' : '';
2131
		$item_desc .= 'Message Template';
2132
		$query_args = array();
2133
		$edit_array = array();
2134
		$action_desc = '';
2135
2136
		//if this is "new" then we need to generate the default contexts for the selected messenger/message_type for user to edit.
2137
		if ( $new ) {
2138
			$GRP_ID = !empty( $this->_req_data['GRP_ID'] ) ? $this->_req_data['GRP_ID'] : 0;
2139
			if ( $edit_array = $this->_generate_new_templates($messenger, $message_type, $GRP_ID ) ) {
0 ignored issues
show
Security Bug introduced by
It seems like $messenger defined by !empty($this->_req_data[...P_messenger'])) : false on line 2118 can also be of type false; however, Messages_Admin_Page::_generate_new_templates() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
Documentation introduced by
$message_type is of type string|false, but the function expects a array.

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...
2140
				if ( empty($edit_array) ) {
2141
					$success = 0;
2142
				} else {
2143
					$success = 1;
2144
					$edit_array = $edit_array[0];
2145
					$query_args = array(
2146
						'id' => $edit_array['GRP_ID'],
2147
						'context' => $edit_array['MTP_context'],
2148
						'action' => 'edit_message_template'
2149
						);
2150
				}
2151
			}
2152
			$action_desc = 'created';
2153
		} else {
2154
			$MTPG = EEM_Message_Template_Group::instance();
2155
			$MTP = EEM_Message_Template::instance();
2156
2157
2158
			//run update for each template field in displayed context
2159
			if ( !isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'] ) ) {
2160
				EE_Error::add_error(
2161
					__('There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.', 'event_espresso'),
2162
					__FILE__, __FUNCTION__, __LINE__
2163
				);
2164
				$success = 0;
2165
2166
			} else {
2167
				//first validate all fields!
2168
				$validates = $MTPG->validate($this->_req_data['MTP_template_fields'], $this->_req_data['MTP_context'],  $this->_req_data['MTP_messenger'], $this->_req_data['MTP_message_type']);
0 ignored issues
show
Documentation introduced by
$this->_req_data['MTP_template_fields'] is of type string, but the function expects a array.

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...
2169
2170
				//if $validate returned error messages (i.e. is_array()) then we need to process them and setup an appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.  WE need to make sure there is no actual error messages in validates.
2171
				if ( is_array($validates) && !empty($validates) ) {
2172
					//add the transient so when the form loads we know which fields to highlight
2173
					$this->_add_transient( 'edit_message_template', $validates );
2174
2175
					$success = 0;
2176
2177
					//setup notices
2178
					foreach ( $validates as $field => $error ) {
2179
						if ( isset($error['msg'] ) ) {
2180
							EE_Error::add_error( $error['msg'], __FILE__, __FUNCTION__, __LINE__ );
2181
						}
2182
					}
2183
2184
				} else {
2185
					$set_column_values = array();
2186
					foreach ( $this->_req_data['MTP_template_fields'] as $template_field => $content ) {
0 ignored issues
show
Bug introduced by
The expression $this->_req_data['MTP_template_fields'] of type string is not traversable.
Loading history...
2187
						$set_column_values = $this->_set_message_template_column_values($template_field);
2188
2189
						$where_cols_n_values = array(
2190
							'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2191
						);
2192
2193
						$message_template_fields = array(
2194
							'GRP_ID' => $set_column_values['GRP_ID'],
2195
							'MTP_template_field' => $set_column_values['MTP_template_field'],
2196
							'MTP_context' => $set_column_values['MTP_context'],
2197
							'MTP_content' => $set_column_values['MTP_content']
2198
						);
2199
						if ( $updated = $MTP->update( $message_template_fields, array( $where_cols_n_values ) ) ) {
2200
							if ( $updated === false ) {
2201
								EE_Error::add_error(
2202
									sprintf(
2203
										__( '%s field was NOT updated for some reason', 'event_espresso' ),
2204
										$template_field
2205
									),
2206
									__FILE__, __FUNCTION__, __LINE__
2207
								);
2208
							} else {
2209
								$success = 1;
2210
							}
2211
						}
2212
						$action_desc = 'updated';
2213
					}
2214
2215
					//we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2216
					$mtpg_fields = array(
2217
						'MTP_user_id'      => $set_column_values[ 'MTP_user_id' ],
2218
						'MTP_messenger'    => $set_column_values[ 'MTP_messenger' ],
2219
						'MTP_message_type' => $set_column_values[ 'MTP_message_type' ],
2220
						'MTP_is_global'    => $set_column_values[ 'MTP_is_global' ],
2221
						'MTP_is_override'  => $set_column_values[ 'MTP_is_override' ],
2222
						'MTP_deleted'      => $set_column_values[ 'MTP_deleted' ],
2223
						'MTP_is_active'    => $set_column_values[ 'MTP_is_active' ],
2224
						'MTP_name'         => ! empty( $this->_req_data[ 'ee_msg_non_global_fields' ][ 'MTP_name' ] )
2225
							? $this->_req_data[ 'ee_msg_non_global_fields' ][ 'MTP_name' ]
2226
							: '',
2227
						'MTP_description'  => ! empty( $this->_req_data[ 'ee_msg_non_global_fields' ][ 'MTP_description' ] )
2228
							? $this->_req_data[ 'ee_msg_non_global_fields' ][ 'MTP_description' ]
2229
							: ''
2230
					);
2231
2232
					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID'] );
2233
					$updated = $MTPG->update( $mtpg_fields, array($mtpg_where) );
2234
2235
					if ( $updated === false ) {
2236
						EE_Error::add_error(
2237
							sprintf(
2238
								__( 'The Message Template Group (%d) was NOT updated for some reason', 'event_espresso' ),
2239
								$set_column_values[ 'GRP_ID' ]
2240
							),
2241
							__FILE__, __FUNCTION__, __LINE__
2242
						);
2243
					} else {
2244
						//k now we need to ensure the template_pack and template_variation fields are set.
2245
						$template_pack = ! empty( $this->_req_data['MTP_template_pack' ] )
2246
							? $this->_req_data['MTP_template_pack']
2247
							: 'default';
2248
2249
						$template_variation = ! empty( $this->_req_data['MTP_template_variation'] )
2250
							? $this->_req_data['MTP_template_variation']
2251
							: 'default';
2252
2253
						$mtpg_obj = $MTPG->get_one_by_ID( $set_column_values['GRP_ID'] );
2254
						if ( $mtpg_obj instanceof EE_Message_Template_Group ) {
2255
							$mtpg_obj->set_template_pack_name( $template_pack );
2256
							$mtpg_obj->set_template_pack_variation( $template_variation );
2257
						}
2258
						$success = 1;
2259
					}
2260
				}
2261
			}
2262
2263
		}
2264
2265
		//we return things differently if doing ajax
2266
		if ( defined('DOING_AJAX') && DOING_AJAX ) {
2267
			$this->_template_args['success'] = $success;
2268
			$this->_template_args['error'] = ! $success ? true : false;
2269
			$this->_template_args['content'] = '';
2270
			$this->_template_args['data'] = array(
2271
				'grpID' => $edit_array['GRP_ID'],
2272
				'templateName' => $edit_array['template_name']
2273
				);
2274
			if ( $success ) {
2275
				EE_Error::overwrite_success();
2276
				EE_Error::add_success( __('The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.', 'event_espresso') );
2277
			}
2278
2279
			$this->_return_json();
2280
		}
2281
2282
2283
		//was a test send triggered?
2284
		if ( isset( $this->_req_data['test_button'] ) ) {
2285
			EE_Error::overwrite_success();
2286
			$this->_do_test_send( $this->_req_data['MTP_context'],  $this->_req_data['MTP_messenger'], $this->_req_data['MTP_message_type'] );
2287
			$override = true;
2288
		}
2289
2290
		if ( empty( $query_args ) ) {
2291
			$query_args = array(
2292
				'id' => $this->_req_data['GRP_ID'],
2293
				'context' => $this->_req_data['MTP_context'],
2294
				'action' => 'edit_message_template'
2295
				);
2296
		}
2297
2298
		$this->_redirect_after_action( $success, $item_desc, $action_desc, $query_args, $override );
2299
	}
2300
2301
2302
2303
2304
	/**
2305
	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
2306
	 *
2307
	 * @param  string $context      what context being tested
2308
	 * @param  string $messenger  	messenger being tested
2309
	 * @param  string $message_type message type being tested
2310
	 *
2311
	 */
2312
	protected function _do_test_send( $context, $messenger, $message_type ) {
2313
		//set things up for preview
2314
		$this->_req_data['messenger'] = $messenger;
2315
		$this->_req_data['message_type'] = $message_type;
2316
		$this->_req_data['context'] = $context;
2317
		$this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID'] ) ? $this->_req_data['GRP_ID'] : '';
2318
		$active_messenger = $this->_message_resource_manager->get_active_messenger( $messenger );
2319
2320
		//let's save any existing fields that might be required by the messenger
2321
		if (
2322
			isset( $this->_req_data['test_settings_fld'] )
2323
			&& $active_messenger instanceof EE_messenger
2324
		) {
2325
			$active_messenger->set_existing_test_settings( $this->_req_data['test_settings_fld'] );
2326
		}
2327
2328
		$success = $this->_preview_message(true);
2329
2330
		if ( $success ) {
2331
			EE_Error::add_success( __('Test message sent', 'event_espresso') );
2332
		} else {
2333
			EE_Error::add_error( __('The test message was not sent', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
2334
		}
2335
	}
2336
2337
2338
2339
	/**
2340
	 * _generate_new_templates
2341
	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
2342
	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
2343
	 * for the event.
2344
	 *
2345
	 *
2346
	 * @param  string $messenger     the messenger we are generating templates for
2347
	 * @param array   $message_types array of message types that the templates are generated for.
2348
	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to indicate
2349
	 *                               the message_template_group being used as the base.
2350
	 *
2351
	 * @param bool    $global
2352
	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
2353
	 *                               encountering problems.
2354
	 * @throws \EE_Error
2355
	 */
2356
	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false) {
2357
2358
		//if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we just don't generate any templates.
2359
		if ( empty( $message_types ) ) {
2360
			return true;
2361
		}
2362
2363
		return EEH_MSG_Template::generate_new_templates( $messenger, $message_types, $GRP_ID, $global );
2364
	}
2365
2366
2367
2368
2369
2370
	/**
2371
	 * [_trash_or_restore_message_template]
2372
	 *
2373
	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
2374
	 * @param boolean $all whether this is going to trash/restore all contexts within a template group (TRUE) OR just
2375
	 *                     an individual context (FALSE).
2376
	 *
2377
	 * @return void
2378
	 */
2379
	protected function _trash_or_restore_message_template($trash = true, $all = false ) {
2380
		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
2381
		$MTP = EEM_Message_Template_Group::instance();
2382
2383
		$success = 1;
2384
2385
		//incoming GRP_IDs
2386
		if ( $all ) {
2387
			//Checkboxes
2388
			if ( !empty( $this->_req_data['checkbox'] ) && is_array($this->_req_data['checkbox'] ) ) {
2389
				//if array has more than one element then success message should be plural.
2390
				//todo: what about nonce?
2391
				$success = count( $this->_req_data['checkbox'] ) > 1 ? 2 : 1;
2392
2393
				//cycle through checkboxes
2394
				while ( list( $GRP_ID, $value ) = each ($this->_req_data['checkbox']) ) {
0 ignored issues
show
Unused Code introduced by
The assignment to $value is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
2395
					$trashed_or_restored = $trash ? $MTP->delete_by_ID( $GRP_ID ) : $MTP->restore_by_ID( $GRP_ID );
2396
					if ( ! $trashed_or_restored ) {
2397
						$success = 0;
2398
					}
2399
				}
2400
			} else {
2401
				//grab single GRP_ID and handle
2402
				$GRP_ID = isset( $this->_req_data['id'] ) ? absint($this->_req_data['id']) : 0;
2403
				if ( ! empty( $GRP_ID ) ) {
2404
					$trashed_or_restored = $trash ? $MTP->delete_by_ID( $GRP_ID ) : $MTP->restore_by_ID( $GRP_ID );
2405
					if ( ! $trashed_or_restored ) {
2406
						$success = 0;
2407
					}
2408
				} else {
2409
					$success = 0;
2410
				}
2411
			}
2412
2413
		}
2414
2415
		$action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2416
2417
		$action_desc = !empty( $this->_req_data['template_switch'] ) ? __('switched') : $action_desc;
2418
2419
		$item_desc = $all ? _n('Message Template Group', 'Message Template Groups', $success, 'event_espresso') : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
2420
2421
		$item_desc = !empty( $this->_req_data['template_switch'] ) ? _n('template', 'templates', $success, 'event_espresso') : $item_desc;
2422
2423
		$this->_redirect_after_action( $success, $item_desc, $action_desc, array() );
2424
2425
	}
2426
2427
2428
2429
2430
2431
2432
2433
	/**
2434
	 * [_delete_message_template]
2435
	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
2436
	 * @return void
2437
	 */
2438
	protected function _delete_message_template() {
2439
		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
2440
2441
		//checkboxes
2442
		if ( !empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'] ) ) {
2443
			//if array has more than one element then success message should be plural
2444
			$success = count( $this->_req_data['checkbox'] ) > 1 ? 2 : 1;
2445
2446
			//cycle through bulk action checkboxes
2447
			while ( list( $GRP_ID, $value ) = each($this->_req_data['checkbox'] ) ) {
0 ignored issues
show
Unused Code introduced by
The assignment to $value is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
2448
				$success = $this->_delete_mtp_permanently( $GRP_ID );
2449
			}
2450
		} else {
2451
			//grab single grp_id and delete
2452
			$GRP_ID = absint($this->_req_data['id'] );
2453
			$success = $this->_delete_mtp_permanently( $GRP_ID );
2454
		}
2455
2456
		$this->_redirect_after_action( $success, 'Message Templates', 'deleted', array() );
2457
2458
	}
2459
2460
2461
2462
2463
	/**
2464
	 * helper for permanently deleting a mtP group and all related message_templates
2465
	 *
2466
	 * @param  int    $GRP_ID The group being deleted
2467
	 * @param  bool $include_group whether to delete the Message Template Group as well.
2468
	 *
2469
	 * @return bool        boolean to indicate the success of the deletes or not.
2470
	 */
2471
	private function _delete_mtp_permanently( $GRP_ID, $include_group = true ) {
2472
		$success = 1;
2473
		$MTPG = EEM_Message_Template_Group::instance();
2474
		//first let's GET this group
2475
		$MTG = $MTPG->get_one_by_ID( $GRP_ID );
2476
		//then delete permanently all the related Message Templates
2477
		$deleted = $MTG->delete_related_permanently( 'Message_Template' );
2478
2479
		if ( $deleted === 0 )
2480
			{$success = 0;}
2481
2482
		//now delete permanently this particular group
2483
2484
		if ( $include_group && ! $MTG->delete_permanently() ) {
2485
			$success = 0;
2486
		}
2487
		return $success;
2488
	}
2489
2490
2491
2492
2493
2494
2495
2496
	/**
2497
	 * 	_learn_more_about_message_templates_link
2498
	*	@access protected
2499
	*	@return string
2500
	*/
2501
	protected function _learn_more_about_message_templates_link() {
2502
		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works', 'event_espresso') . '</a>';
2503
	}
2504
2505
2506
2507
2508
2509
2510
	/**
2511
	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
2512
	 * ajax and other routes.
2513
	 * @return void
2514
	 */
2515
	protected function _settings() {
2516
2517
2518
		$this->_set_m_mt_settings();
2519
2520
		$selected_messenger = isset( $this->_req_data['selected_messenger'] ) ? $this->_req_data['selected_messenger'] : 'email';
2521
2522
		//let's setup the messenger tabs
2523
		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links( $this->_m_mt_settings['messenger_tabs'], 'messenger_links', '|', $selected_messenger );
2524
		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
2525
		$this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
2526
2527
		$this->display_admin_page_with_sidebar();
2528
2529
	}
2530
2531
2532
2533
2534
	/**
2535
	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
2536
	 *
2537
	 * @access protected
2538
	 * @return void
2539
	 */
2540
	protected function _set_m_mt_settings() {
2541
		//first if this is already set then lets get out no need to regenerate data.
2542
		if ( !empty($this->_m_mt_settings) ) {
2543
			return;
2544
		}
2545
2546
		//$selected_messenger = isset( $this->_req_data['selected_messenger'] ) ? $this->_req_data['selected_messenger'] : 'email';
2547
2548
		//get all installed messengers and message_types
2549
		/** @type EE_messenger[] $messengers */
2550
		$messengers = $this->_message_resource_manager->installed_messengers();
2551
		/** @type EE_message_type[] $message_types */
2552
		$message_types = $this->_message_resource_manager->installed_message_types();
2553
2554
2555
		//assemble the array for the _tab_text_links helper
2556
2557
		foreach ( $messengers as $messenger ) {
2558
			$this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
2559
				'label' => ucwords($messenger->label['singular']),
2560
				'class' => $this->_message_resource_manager->is_messenger_active( $messenger->name ) ? 'messenger-active' : '',
2561
				'href' => $messenger->name,
2562
				'title' => __('Modify this Messenger', 'event_espresso'),
2563
				'slug' => $messenger->name,
2564
				'obj' => $messenger
2565
			);
2566
2567
2568
			$message_types_for_messenger = $messenger->get_valid_message_types();
2569
2570
			foreach ( $message_types as $message_type ) {
2571
				//first we need to verify that this message type is valid with this messenger. Cause if it isn't then it shouldn't show in either the inactive OR active metabox.
2572
				if ( ! in_array( $message_type->name, $message_types_for_messenger ) ) {
2573
					continue;
2574
				}
2575
2576
				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger( $messenger->name, $message_type->name ) ? 'active' : 'inactive';
2577
2578
				$this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2579
					'label'    => ucwords( $message_type->label[ 'singular' ] ),
2580
					'class'    => 'message-type-' . $a_or_i,
2581
					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2582
					'mt_nonce' => wp_create_nonce( $message_type->name . '_nonce' ),
2583
					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2584
					'title'    => $a_or_i == 'active'
2585
						? __( 'Drag this message type to the Inactive window to deactivate', 'event_espresso' )
2586
						: __( 'Drag this message type to the messenger to activate', 'event_espresso' ),
2587
					'content'  => $a_or_i == 'active'
2588
						? $this->_message_type_settings_content( $message_type, $messenger, true )
2589
						: $this->_message_type_settings_content( $message_type, $messenger ),
2590
					'slug'     => $message_type->name,
2591
					'active'   => $a_or_i == 'active' ? true : false,
2592
					'obj'      => $message_type
2593
				);
2594
			}
2595
		}
2596
	}
2597
2598
2599
	/**
2600
	 * This just prepares the content for the message type settings
2601
	 *
2602
	 * @param  object  $message_type The message type object
2603
	 * @param  object  $messenger    The messenger object
2604
	 * @param  boolean $active       Whether the message type is active or not
2605
	 *
2606
	 * @return string                html output for the content
2607
	 */
2608
	protected function _message_type_settings_content( $message_type, $messenger, $active = false ) {
2609
		//get message type fields
2610
		$fields = $message_type->get_admin_settings_fields();
2611
		$settings_template_args['template_form_fields']= '';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$settings_template_args was never initialized. Although not strictly required by PHP, it is generally a good practice to add $settings_template_args = 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...
2612
2613
		if ( !empty( $fields ) && $active ) {
2614
2615
			$existing_settings = $message_type->get_existing_admin_settings( $messenger->name );
2616
2617
			foreach( $fields as $fldname => $fldprops ) {
2618
				$field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2619
				$template_form_field[$field_id] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$template_form_field was never initialized. Although not strictly required by PHP, it is generally a good practice to add $template_form_field = 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...
2620
					'name' => 'message_type_settings[' . $fldname . ']',
2621
					'label' => $fldprops['label'],
2622
					'input' => $fldprops['field_type'],
2623
					'type' => $fldprops['value_type'],
2624
					'required' => $fldprops['required'],
2625
					'validation' => $fldprops['validation'],
2626
					'value' => isset( $existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2627
					'options' => isset( $fldprops['options'] ) ? $fldprops['options'] : array(),
2628
					'default' => isset( $existing_settings[$fldname] ) ? $existing_settings[$fldname] : $fldprops['default'],
2629
					'css_class' => 'no-drag',
2630
					'format' => $fldprops['format']
2631
				);
2632
			}
2633
2634
2635
			$settings_template_args['template_form_fields'] = !empty($template_form_field) ? $this->_generate_admin_form_fields( $template_form_field, 'string', 'ee_mt_activate_form' ) : '';
0 ignored issues
show
Documentation introduced by
'ee_mt_activate_form' is of type string, but the function expects a false|array.

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...
2636
		}
2637
2638
		$settings_template_args['description'] = $message_type->description;
2639
		//we also need some hidden fields
2640
			$settings_template_args['hidden_fields'] = array(
2641
				'message_type_settings[messenger]' => array(
2642
					'type' => 'hidden',
2643
					'value' => $messenger->name
2644
					),
2645
				'message_type_settings[message_type]' => array(
2646
					'type' => 'hidden',
2647
					'value' => $message_type->name
2648
					),
2649
				'type' => array(
2650
					'type' => 'hidden',
2651
					'value' => 'message_type'
2652
					)
2653
				);
2654
2655
		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields( $settings_template_args['hidden_fields'], 'array' );
2656
		$settings_template_args['show_form'] = empty( $settings_template_args['template_form_fields'] ) ? ' hidden' : '';
2657
2658
2659
2660
		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2661
		$content = EEH_Template::display_template( $template, $settings_template_args, true );
2662
		return $content;
2663
	}
2664
2665
2666
2667
	/**
2668
	 * Generate all the metaboxes for the message types and register them for the messages settings page.
2669
	 *
2670
	 * @access protected
2671
	 * @return void
2672
	 */
2673
	protected function _messages_settings_metaboxes() {
2674
		$this->_set_m_mt_settings();
2675
		$m_boxes = $mt_boxes = array();
2676
		$m_template_args = $mt_template_args = array();
2677
2678
		$selected_messenger = isset( $this->_req_data['selected_messenger'] ) ? $this->_req_data['selected_messenger'] : 'email';
2679
2680
		if ( isset( $this->_m_mt_settings[ 'messenger_tabs' ] ) ) {
2681
			foreach ( $this->_m_mt_settings[ 'messenger_tabs' ] as $messenger => $tab_array ) {
2682
				$hide_on_message = $this->_message_resource_manager->is_messenger_active( $messenger ) ? '' : 'hidden';
2683
				$hide_off_message = $this->_message_resource_manager->is_messenger_active( $messenger ) ? 'hidden' : '';
2684
				//messenger meta boxes
2685
				$active = $selected_messenger == $messenger ? true : false;
2686
				$active_mt_tabs = isset( $this->_m_mt_settings[ 'message_type_tabs' ][ $messenger ][ 'active' ] )
2687
				? $this->_m_mt_settings[ 'message_type_tabs' ][ $messenger ][ 'active' ]
2688
				: '';
2689
				$m_boxes[ $messenger . '_a_box' ] = sprintf(
2690
				__( '%s Settings', 'event_espresso' ),
2691
				$tab_array[ 'label' ]
2692
				);
2693
				$m_template_args[ $messenger . '_a_box' ] = array(
2694
				'active_message_types'   => ! empty( $active_mt_tabs ) ? $this->_get_mt_tabs( $active_mt_tabs ) : '',
2695
				'inactive_message_types' => isset( $this->_m_mt_settings[ 'message_type_tabs' ][ $messenger ][ 'inactive' ] )
2696
				? $this->_get_mt_tabs( $this->_m_mt_settings[ 'message_type_tabs' ][ $messenger ][ 'inactive' ] )
2697
				: '',
2698
				'content'                => $this->_get_messenger_box_content( $tab_array[ 'obj' ] ),
2699
				'hidden'                 => $active ? '' : ' hidden',
2700
				'hide_on_message'        => $hide_on_message,
2701
				'messenger'              => $messenger,
2702
				'active'                 => $active
2703
				);
2704
				// message type meta boxes
2705
				// (which is really just the inactive container for each messenger
2706
				// showing inactive message types for that messenger)
2707
				$mt_boxes[ $messenger . '_i_box' ] = __( 'Inactive Message Types', 'event_espresso' );
2708
				$mt_template_args[ $messenger . '_i_box' ] = array(
2709
				'active_message_types'   => ! empty( $active_mt_tabs ) ? $this->_get_mt_tabs( $active_mt_tabs ) : '',
2710
				'inactive_message_types' => isset( $this->_m_mt_settings[ 'message_type_tabs' ][ $messenger ][ 'inactive' ] )
2711
				? $this->_get_mt_tabs( $this->_m_mt_settings[ 'message_type_tabs' ][ $messenger ][ 'inactive' ] )
2712
				: '',
2713
				'hidden'                 => $active ? '' : ' hidden',
2714
				'hide_on_message'        => $hide_on_message,
2715
				'hide_off_message'       => $hide_off_message,
2716
				'messenger'              => $messenger,
2717
				'active'                 => $active
2718
				);
2719
			}
2720
		}
2721
2722
2723
		//register messenger metaboxes
2724
		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2725 View Code Duplication
		foreach ( $m_boxes as $box => $label ) {
2726
			$callback_args = array( 'template_path' => $m_template_path, 'template_args' => $m_template_args[$box] );
2727
			$msgr = str_replace( '_a_box', '', $box );
2728
			add_meta_box(
2729
				'espresso_' . $msgr . '_settings',
2730
				$label,
2731
				create_function(
0 ignored issues
show
Security Best Practice introduced by
The use of create_function is highly discouraged, better use a closure.

create_function can pose a great security vulnerability as it is similar to eval, and could be used for arbitrary code execution. We highly recommend to use a closure instead.

// Instead of
$function = create_function('$a, $b', 'return $a + $b');

// Better use
$function = function($a, $b) { return $a + $b; }
Loading history...
2732
					'$post, $metabox',
2733
					'echo EEH_Template::display_template( $metabox["args"]["template_path"], $metabox["args"]["template_args"], TRUE );'
2734
				),
2735
				$this->_current_screen_id,
0 ignored issues
show
Bug introduced by
The property _current_screen_id does not seem to exist. Did you mean _current_screen?

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...
2736
				'normal',
2737
				'high',
2738
				$callback_args
2739
			);
2740
		}
2741
2742
		//register message type metaboxes
2743
		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2744 View Code Duplication
		foreach ( $mt_boxes as $box => $label ) {
2745
			$callback_args = array(
2746
				'template_path' => $mt_template_path, 'template_args' => $mt_template_args[ $box ]
2747
			);
2748
			$mt = str_replace( '_i_box', '', $box );
2749
			add_meta_box(
2750
				'espresso_' . $mt . '_inactive_mts',
2751
				$label,
2752
				create_function(
0 ignored issues
show
Security Best Practice introduced by
The use of create_function is highly discouraged, better use a closure.

create_function can pose a great security vulnerability as it is similar to eval, and could be used for arbitrary code execution. We highly recommend to use a closure instead.

// Instead of
$function = create_function('$a, $b', 'return $a + $b');

// Better use
$function = function($a, $b) { return $a + $b; }
Loading history...
2753
					'$post, $metabox',
2754
					'echo EEH_Template::display_template( $metabox["args"]["template_path"], $metabox["args"]["template_args"], TRUE );'
2755
				),
2756
				$this->_current_screen_id,
0 ignored issues
show
Bug introduced by
The property _current_screen_id does not seem to exist. Did you mean _current_screen?

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...
2757
				'side',
2758
				'high',
2759
				$callback_args
2760
			);
2761
		}
2762
2763
	}
2764
2765
2766
	/**
2767
	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
2768
	 *
2769
	 * @param  array $tab_array  This is an array of message type tab details used to generate the tabs
2770
	 *
2771
	 * @return string            html formatted tabs
2772
	 */
2773
	protected function _get_mt_tabs( $tab_array ) {
2774
		$tab_array = (array) $tab_array;
2775
		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
2776
		$tabs = '';
2777
2778
		foreach ( $tab_array as $tab ) {
2779
			$tabs .=  EEH_Template::display_template( $template, $tab, true );
2780
		}
2781
2782
		return $tabs;
2783
	}
2784
2785
2786
2787
2788
	/**
2789
	 * This prepares the content of the messenger meta box admin settings
2790
	 *
2791
	 * @param  EE_messenger $messenger The messenger we're setting up content for
2792
	 *
2793
	 * @return string            html formatted content
2794
	 */
2795
	protected function _get_messenger_box_content( EE_messenger $messenger ) {
2796
2797
		$fields = $messenger->get_admin_settings_fields();
2798
		$settings_template_args['template_form_fields'] = '';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$settings_template_args was never initialized. Although not strictly required by PHP, it is generally a good practice to add $settings_template_args = 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...
2799
2800
		//is $messenger active?
2801
		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active( $messenger->name );
2802
2803
2804
		if ( ! empty( $fields ) ) {
2805
2806
			$existing_settings = $messenger->get_existing_admin_settings();
2807
2808
			foreach( $fields as $fldname => $fldprops ) {
2809
				$field_id = $messenger->name . '-' . $fldname;
2810
				$template_form_field[$field_id] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$template_form_field was never initialized. Although not strictly required by PHP, it is generally a good practice to add $template_form_field = 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...
2811
					'name' => 'messenger_settings[' . $field_id . ']',
2812
					'label' => $fldprops['label'],
2813
					'input' => $fldprops['field_type'],
2814
					'type' => $fldprops['value_type'],
2815
					'required' => $fldprops['required'],
2816
					'validation' => $fldprops['validation'],
2817
					'value' => isset( $existing_settings[$field_id])
2818
						? $existing_settings[$field_id]
2819
						: $fldprops['default'],
2820
					'css_class' => '',
2821
					'format' => $fldprops['format']
2822
					);
2823
			}
2824
2825
2826
			$settings_template_args['template_form_fields'] = !empty($template_form_field)
2827
				? $this->_generate_admin_form_fields( $template_form_field, 'string', 'ee_m_activate_form' )
0 ignored issues
show
Documentation introduced by
'ee_m_activate_form' is of type string, but the function expects a false|array.

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...
2828
				: '';
2829
		}
2830
2831
		//we also need some hidden fields
2832
		$settings_template_args['hidden_fields'] = array(
2833
			'messenger_settings[messenger]' => array(
2834
				'type' => 'hidden',
2835
				'value' => $messenger->name
2836
				),
2837
			'type' => array(
2838
				'type' => 'hidden',
2839
				'value' => 'messenger'
2840
				)
2841
			);
2842
2843
		//make sure any active message types that are existing are included in the hidden fields
2844
		if ( isset( $this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] ) ) {
2845
			foreach ( $this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values ) {
2846
				$settings_template_args['hidden_fields']['messenger_settings[message_types]['.$mt.']'] = array(
2847
						'type' => 'hidden',
2848
						'value' => $mt
2849
					);
2850
			}
2851
		}
2852
		$settings_template_args[ 'hidden_fields' ] = $this->_generate_admin_form_fields(
2853
			$settings_template_args[ 'hidden_fields' ],
2854
			'array'
2855
		);
2856
		$active = $this->_message_resource_manager->is_messenger_active( $messenger->name );
2857
2858
		$settings_template_args['messenger'] = $messenger->name;
2859
		$settings_template_args['description'] = $messenger->description;
2860
		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
2861
2862
2863
		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active( $messenger->name )
2864
			? $settings_template_args['show_hide_edit_form']
2865
			: ' hidden';
2866
2867
		$settings_template_args['show_hide_edit_form'] = empty( $settings_template_args['template_form_fields'] )
2868
			? ' hidden'
2869
			: $settings_template_args['show_hide_edit_form'];
2870
2871
2872
		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
2873
		$settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
2874
		$settings_template_args['on_off_status'] = $active ? true : false;
2875
		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
2876
		$content = EEH_Template::display_template( $template, $settings_template_args, true);
2877
		return $content;
2878
	}
2879
2880
2881
2882
2883
	/**
2884
	 * used by ajax on the messages settings page to activate|deactivate the messenger
2885
	 */
2886
	public function activate_messenger_toggle() {
2887
		$success = true;
2888
		$this->_prep_default_response_for_messenger_or_message_type_toggle();
2889
		//let's check that we have required data
2890
		if ( !isset( $this->_req_data[ 'messenger' ] ) ) {
2891
			EE_Error::add_error(
2892
				__( 'Messenger name needed to toggle activation. None given', 'event_espresso' ),
2893
				__FILE__,
2894
				__FUNCTION__,
2895
				__LINE__
2896
			);
2897
			$success = false;
2898
		}
2899
2900
		//do a nonce check here since we're not arriving via a normal route
2901
		$nonce = isset($this->_req_data[ 'activate_nonce' ]) ? sanitize_text_field( $this->_req_data[ 'activate_nonce'] ) : '';
2902
		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
2903
2904
		$this->_verify_nonce( $nonce, $nonce_ref );
2905
2906
2907
2908
		if ( !isset( $this->_req_data[ 'status' ])) {
2909
			EE_Error::add_error(
2910
				__(
2911
					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
2912
					'event_espresso'
2913
				),
2914
				__FILE__,
2915
				__FUNCTION__,
2916
				__LINE__
2917
			);
2918
			$success = false;
2919
		}
2920
2921
		//do check to verify we have a valid status.
2922
		$status = $this->_req_data['status'];
2923
2924 View Code Duplication
		if ( $status != 'off' && $status != 'on' ) {
2925
			EE_Error::add_error(
2926
				sprintf(
2927
					__( 'The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso' ),
2928
					$this->_req_data[ 'status' ]
2929
				),
2930
				__FILE__,
2931
				__FUNCTION__,
2932
				__LINE__
2933
			);
2934
			$success = false;
2935
		}
2936
2937
		if ( $success ) {
2938
			//made it here?  Stop dawdling then!!
2939
			$success = $status == 'off'
2940
				? $this->_deactivate_messenger( $this->_req_data['messenger'] )
2941
				: $this->_activate_messenger( $this->_req_data['messenger'] );
2942
		}
2943
2944
		$this->_template_args['success'] = $success;
2945
2946
		//no special instructions so let's just do the json return (which should automatically do all the special stuff).
2947
		$this->_return_json();
2948
2949
	}
2950
2951
2952
2953
2954
2955
	/**
2956
	 * used by ajax from the messages settings page to activate|deactivate a message type
2957
	 *
2958
	 */
2959
	public function activate_mt_toggle() {
2960
		$success = true;
2961
		$this->_prep_default_response_for_messenger_or_message_type_toggle();
2962
2963
		//let's make sure we have the necessary data
2964
		if ( ! isset( $this->_req_data[ 'message_type' ] ) ) {
2965
			EE_Error::add_error(
2966
				__('Message Type name needed to toggle activation. None given', 'event_espresso'),
2967
				__FILE__, __FUNCTION__, __LINE__
2968
			);
2969
			$success = false;
2970
		}
2971
2972
		if ( ! isset( $this->_req_data[ 'messenger' ] ) ) {
2973
			EE_Error::add_error(
2974
				__('Messenger name needed to toggle activation. None given', 'event_espresso'),
2975
				__FILE__, __FUNCTION__, __LINE__
2976
			);
2977
			$success = false;
2978
		}
2979
2980
		if ( ! isset( $this->_req_data[ 'status' ])) {
2981
			EE_Error::add_error(
2982
				__('Messenger status needed to know whether activation or deactivation is happening. No status is given', 'event_espresso'),
2983
				__FILE__, __FUNCTION__, __LINE__
2984
			);
2985
			$success = false;
2986
		}
2987
2988
2989
		//do check to verify we have a valid status.
2990
		$status = $this->_req_data['status'];
2991
2992 View Code Duplication
		if ( $status != 'activate' && $status != 'deactivate' ) {
2993
			EE_Error::add_error(
2994
				sprintf(
2995
					__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
2996
					$this->_req_data['status']
2997
				),
2998
				__FILE__, __FUNCTION__, __LINE__
2999
			);
3000
			$success = false;
3001
		}
3002
3003
3004
		//do a nonce check here since we're not arriving via a normal route
3005
		$nonce = isset( $this->_req_data['mt_nonce'] ) ? sanitize_text_field( $this->_req_data['mt_nonce'] ) : '';
3006
		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3007
3008
		$this->_verify_nonce( $nonce, $nonce_ref );
3009
3010
		if ( $success ) {
3011
			//made it here? um, what are you waiting for then?
3012
			$success = $status == 'deactivate'
3013
				? $this->_deactivate_message_type_for_messenger( $this->_req_data['messenger'], $this->_req_data['message_type'] )
3014
				: $this->_activate_message_type_for_messenger( $this->_req_data['messenger'], $this->_req_data['message_type'] );
3015
		}
3016
3017
		$this->_template_args['success'] = $success;
3018
		$this->_return_json();
3019
	}
3020
3021
3022
	/**
3023
	 * Takes care of processing activating a messenger and preparing the appropriate response.
3024
	 *
3025
	 * @param string $messenger_name The name of the messenger being activated
3026
	 * @return bool
3027
	 */
3028
	protected function _activate_messenger( $messenger_name ) {
3029
		/** @var EE_messenger $active_messenger  This will be present because it can't be toggled if it isn't*/
3030
		$active_messenger = $this->_message_resource_manager->get_messenger( $messenger_name );
3031
		$message_types_to_activate = $active_messenger instanceof EE_Messenger ? $active_messenger->get_default_message_types() : array();
3032
3033
		//ensure is active
3034
		$this->_message_resource_manager->activate_messenger( $messenger_name, $message_types_to_activate );
3035
3036
		//set response_data for reload
3037
		foreach( $message_types_to_activate as $message_type_name ) {
3038
			/** @var EE_message_type $message_type */
3039
			$message_type = $this->_message_resource_manager->get_message_type( $message_type_name );
3040 View Code Duplication
			if ( $this->_message_resource_manager->is_message_type_active_for_messenger( $messenger_name, $message_type_name )
3041
			     && $message_type instanceof EE_message_type
3042
			) {
3043
				$this->_template_args['data']['active_mts'][] = $message_type_name;
3044
				if ( $message_type->get_admin_settings_fields() ) {
3045
					$this->_template_args['data']['mt_reload'][] = $message_type_name;
3046
				}
3047
			}
3048
		}
3049
3050
		//add success message for activating messenger
3051
		return $this->_setup_response_message_for_activating_messenger_with_message_types( $active_messenger );
3052
3053
	}
3054
3055
3056
	/**
3057
	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
3058
	 *
3059
	 * @param string $messenger_name The name of the messenger being activated
3060
	 * @return bool
3061
	 */
3062
	protected function _deactivate_messenger( $messenger_name ) {
3063
		/** @var EE_messenger $active_messenger  This will be present because it can't be toggled if it isn't*/
3064
		$active_messenger = $this->_message_resource_manager->get_messenger( $messenger_name );
3065
		$this->_message_resource_manager->deactivate_messenger( $messenger_name );
3066
		return $this->_setup_response_message_for_deactivating_messenger_with_message_types( $active_messenger );
3067
	}
3068
3069
3070
	/**
3071
	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
3072
	 *
3073
	 * @param string $messenger_name  The name of the messenger the message type is being activated for.
3074
	 * @param string $message_type_name  The name of the message type being activated for the messenger
3075
	 * @return bool
3076
	 */
3077
	protected function _activate_message_type_for_messenger( $messenger_name, $message_type_name ) {
3078
		/** @var EE_messenger $active_messenger  This will be present because it can't be toggled if it isn't*/
3079
		$active_messenger = $this->_message_resource_manager->get_messenger( $messenger_name );
3080
		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't*/
3081
		$message_type_to_activate = $this->_message_resource_manager->get_message_type( $message_type_name );
3082
3083
		//ensure is active
3084
		$this->_message_resource_manager->activate_messenger( $messenger_name, $message_type_name );
0 ignored issues
show
Documentation introduced by
$message_type_name is of type string, but the function expects a array.

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...
3085
3086
		//set response for load
3087 View Code Duplication
		if ( $this->_message_resource_manager->is_message_type_active_for_messenger( $messenger_name, $message_type_name ) ) {
3088
			$this->_template_args['data']['active_mts'][] = $message_type_name;
3089
			if ( $message_type_to_activate->get_admin_settings_fields() ) {
3090
				$this->_template_args['data']['mt_reload'][] = $message_type_name;
3091
			}
3092
		}
3093
		return $this->_setup_response_message_for_activating_messenger_with_message_types( $active_messenger, $message_type_to_activate );
3094
	}
3095
3096
3097
3098
	/**
3099
	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
3100
	 *
3101
	 * @param string $messenger_name  The name of the messenger the message type is being deactivated for.
3102
	 * @param string $message_type_name  The name of the message type being deactivated for the messenger
3103
	 * @return bool
3104
	 */
3105
	protected function _deactivate_message_type_for_messenger( $messenger_name, $message_type_name ) {
3106
		/** @var EE_messenger $active_messenger  This will be present because it can't be toggled if it isn't*/
3107
		$active_messenger = $this->_message_resource_manager->get_messenger( $messenger_name );
3108
		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't*/
3109
		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type( $message_type_name );
3110
		$this->_message_resource_manager->deactivate_message_type_for_messenger( $message_type_name, $messenger_name );
3111
		return $this->_setup_response_message_for_deactivating_messenger_with_message_types( $active_messenger, $message_type_to_deactivate );
3112
	}
3113
3114
3115
3116
3117
3118
	/**
3119
	 * This just initializes the defaults for activating messenger and message type responses.
3120
	 */
3121
	protected function _prep_default_response_for_messenger_or_message_type_toggle() {
3122
		$this->_template_args['data']['active_mts'] = array();
3123
		$this->_template_args['data']['mt_reload'] = array();
3124
	}
3125
3126
3127
3128
	/**
3129
	 * Setup appropriate response for activating a messenger and/or message types
3130
	 *
3131
	 * @param EE_messenger         $messenger
3132
	 * @param EE_message_type|null $message_type
3133
	 *
3134
	 * @return bool
3135
	 * @throws EE_Error
3136
	 */
3137
	protected function _setup_response_message_for_activating_messenger_with_message_types(
3138
		$messenger,
3139
		EE_Message_Type $message_type = null
3140
	) {
3141
		//if $messenger isn't a valid messenger object then get out.
3142
		if ( ! $messenger instanceof EE_Messenger ) {
3143
			EE_Error::add_error(
3144
				__( 'The messenger being activated is not a valid messenger', 'event_espresso' ),
3145
				__FILE__,
3146
				__FUNCTION__,
3147
				__LINE__
3148
			);
3149
			return false;
3150
		}
3151
		//activated
3152
		if ( $this->_template_args['data']['active_mts'] ) {
3153
			EE_Error::overwrite_success();
3154
			//activated a message type with the messenger
3155
			if ( $message_type instanceof EE_message_type ) {
3156
				EE_Error::add_success(
3157
					sprintf(
3158
						__('%s message type has been successfully activated with the %s messenger', 'event_espresso'),
3159
						ucwords( $message_type->label['singular'] ),
3160
						ucwords( $messenger->label['singular'] )
3161
					)
3162
				);
3163
3164
				//if message type was invoice then let's make sure we activate the invoice payment method.
3165
				if ( $message_type->name == 'invoice' ) {
3166
					EE_Registry::instance()->load_lib( 'Payment_Method_Manager' );
3167
					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type( 'Invoice' );
3168
					if ( $pm instanceof EE_Payment_Method ) {
3169
						EE_Error::add_attention( __('Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.', 'event_espresso' ) );
3170
					}
3171
				}
3172
			//just toggles the entire messenger
3173
			} else {
3174
				EE_Error::add_success(
3175
					sprintf(
3176
						__( '%s messenger has been successfully activated', 'event_espresso' ),
3177
						ucwords( $messenger->label[ 'singular' ] )
3178
					)
3179
				);
3180
			}
3181
			return true;
3182
3183
		//possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
3184
		//message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
3185
		//in which case we just give a success message for the messenger being successfully activated.
3186
		} else {
3187
			if ( ! $messenger->get_default_message_types() ) {
3188
				//messenger doesn't have any default message types so still a success.
3189
				EE_Error::add_success(
3190
					sprintf(
3191
						__('%s messenger was successfully activated.', 'event_espresso' ),
3192
						ucwords( $messenger->label['singular'] )
3193
						)
3194
				);
3195
				return true;
3196
			} else {
3197
				EE_Error::add_error(
3198
					$message_type instanceof EE_message_type
3199
						? sprintf(
3200
						__( '%s message type was not successfully activated with the %s messenger', 'event_espresso' ),
3201
						ucwords( $message_type->label['singular'] ),
3202
						ucwords( $messenger->label['singular'] )
3203
					)
3204
						: sprintf(
3205
						__( '%s messenger was not successfully activated', 'event_espresso' ),
3206
						ucwords( $messenger->label['singular'] )
3207
					),
3208
					__FILE__,
3209
					__FUNCTION__,
3210
					__LINE__
3211
				);
3212
3213
				return false;
3214
			}
3215
		}
3216
	}
3217
3218
3219
	/**
3220
	 * This sets up the appropriate response for deactivating a messenger and/or message type.
3221
	 *
3222
	 * @param EE_messenger         $messenger
3223
	 * @param EE_message_type|null $message_type
3224
	 *
3225
	 * @return bool
3226
	 */
3227
	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
3228
		$messenger,
3229
		EE_message_type $message_type = null
3230
	) {
3231
		EE_Error::overwrite_success();
3232
3233
		//if $messenger isn't a valid messenger object then get out.
3234
		if ( ! $messenger instanceof EE_Messenger ) {
3235
			EE_Error::add_error(
3236
				__( 'The messenger being deactivated is not a valid messenger', 'event_espresso' ),
3237
				__FILE__,
3238
				__FUNCTION__,
3239
				__LINE__
3240
			);
3241
			return false;
3242
		}
3243
3244
		if ( $message_type instanceof EE_message_type ) {
3245
			$message_type_name = $message_type->name;
3246
			EE_Error::add_success(
3247
				sprintf(
3248
					__('%s message type has been successfully deactivated for the %s messenger.', 'event_espresso'),
3249
					ucwords( $message_type->label['singular'] ),
3250
					ucwords ( $messenger->label['singular'] )
3251
				)
3252
			);
3253
		} else {
3254
			$message_type_name = '';
3255
			EE_Error::add_success(
3256
				sprintf(
3257
					__('%s messenger has been successfully deactivated.', 'event_espresso'),
3258
					ucwords( $messenger->label['singular'] )
3259
				)
3260
			);
3261
		}
3262
3263
		//if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
3264
		if ( $messenger->name == 'html'  || $message_type_name == 'invoice') {
3265
			EE_Registry::instance()->load_lib( 'Payment_Method_Manager' );
3266
			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method( 'invoice' );
3267
			if ( $count_updated > 0 ) {
3268
				$msg = $message_type_name == 'invoice'
3269
					? __('Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.', 'event_espresso' )
3270
					: __('Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.', 'event_espresso' );
3271
				EE_Error::add_attention( $msg );
3272
			}
3273
		}
3274
		return true;
3275
	}
3276
3277
3278
	/**
3279
	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
3280
	 */
3281
	public function update_mt_form() {
3282
		if ( !isset( $this->_req_data['messenger'] ) || !isset( $this->_req_data['message_type'] ) ) {
3283
			EE_Error::add_error( __('Require message type or messenger to send an updated form'), __FILE__, __FUNCTION__, __LINE__ );
3284
			$this->_return_json();
3285
		}
3286
3287
		$message_types = $this->get_installed_message_types();
3288
3289
		$message_type = $message_types[ $this->_req_data['message_type'] ];
3290
		$messenger = $this->_message_resource_manager->get_active_messenger( $this->_req_data['messenger'] );
3291
3292
		$content = $this->_message_type_settings_content ( $message_type, $messenger, true );
0 ignored issues
show
Bug introduced by
It seems like $messenger defined by $this->_message_resource..._req_data['messenger']) on line 3290 can be null; however, Messages_Admin_Page::_me...type_settings_content() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
3293
		$this->_template_args['success'] = true;
3294
		$this->_template_args['content'] = $content;
3295
		$this->_return_json();
3296
	}
3297
3298
3299
3300
3301
	/**
3302
	 * this handles saving the settings for a messenger or message type
3303
	 *
3304
	 */
3305
	public function save_settings() {
3306
		if ( !isset( $this->_req_data['type'] ) ) {
3307
			EE_Error::add_error(__('Cannot save settings because type is unknown (messenger settings or messsage type settings?)', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__ );
3308
			$this->_template_args['error'] = true;
3309
			$this->_return_json();
3310
		}
3311
3312
3313
		if ( $this->_req_data['type'] == 'messenger' ) {
3314
			$settings = $this->_req_data['messenger_settings']; //this should be an array.
3315
			$messenger = $settings['messenger'];
3316
			//let's setup the settings data
3317 View Code Duplication
			foreach ( $settings as $key => $value ) {
3318
				switch ( $key ) {
3319
					case 'messenger' :
3320
						unset( $settings['messenger'] );
3321
						break;
3322
					case 'message_types' :
3323
						unset( $settings['message_types'] );
3324
						break;
3325
					default :
3326
						$settings[$key] = $value;
3327
						break;
3328
				}
3329
			}
3330
			$this->_message_resource_manager->add_settings_for_messenger( $messenger, $settings );
3331
		}
3332
3333
		else if ( $this->_req_data['type'] == 'message_type' ) {
3334
			$settings = $this->_req_data['message_type_settings'];
3335
			$messenger = $settings['messenger'];
3336
			$message_type = $settings['message_type'];
3337
3338 View Code Duplication
			foreach ( $settings as $key => $value ) {
3339
				switch ( $key ) {
3340
					case 'messenger' :
3341
						unset( $settings['messenger'] );
3342
						break;
3343
					case 'message_type' :
3344
						unset( $settings['message_type'] );
3345
						break;
3346
					default :
3347
						$settings[$key] = $value;
3348
						break;
3349
				}
3350
			}
3351
3352
			$this->_message_resource_manager->add_settings_for_message_type( $messenger, $message_type, $settings );
3353
		}
3354
3355
		//okay we should have the data all setup.  Now we just update!
3356
		$success = $this->_message_resource_manager->update_active_messengers_option();
3357
3358
		if ( $success ) {
3359
			EE_Error::add_success( __('Settings updated', 'event_espresso') );
3360
		} else {
3361
			EE_Error::add_error( __('Settings did not get updated', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__ );
3362
		}
3363
3364
		$this->_template_args['success'] = $success;
3365
		$this->_return_json();
3366
	}
3367
3368
3369
3370
3371
	/**  EE MESSAGE PROCESSING ACTIONS **/
3372
3373
3374
3375
	/**
3376
	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
3377
     * However, this does not send immediately, it just queues for sending.
3378
     *
3379
     * @since 4.9.0
3380
     */
3381
	protected function _generate_now() {
3382
		$msg_ids = $this->_get_msg_ids_from_request();
3383
		EED_Messages::generate_now( $msg_ids );
3384
		$this->_redirect_after_action( false, '', '', array(), true );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

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...
3385
	}
3386
3387
3388
3389
	/**
3390
	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that are
3391
     * EEM_Message::status_resend or EEM_Message::status_idle
3392
     *
3393
     * @since 4.9.0
3394
     *
3395
     */
3396
	protected function _generate_and_send_now() {
3397
		$this->_generate_now();
3398
		$this->_send_now();
3399
		$this->_redirect_after_action( false, '', '', array(), true );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

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...
3400
	}
3401
3402
3403
3404
3405
3406
	/**
3407
	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
3408
     *
3409
     * @since 4.9.0
3410
     */
3411
	protected function _queue_for_resending() {
3412
		$msg_ids = $this->_get_msg_ids_from_request();
3413
		EED_Messages::queue_for_resending( $msg_ids );
3414
		$this->_redirect_after_action( false, '', '', array(), true );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

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...
3415
	}
3416
3417
3418
3419
3420
	/**
3421
	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
3422
     *
3423
     *  @since 4.9.0
3424
     */
3425
	protected function _send_now() {
3426
		$msg_ids = $this->_get_msg_ids_from_request();
3427
		EED_Messages::send_now( $msg_ids );
3428
		$this->_redirect_after_action( false, '', '', array(), true );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

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...
3429
	}
3430
3431
3432
3433
3434
	/**
3435
	 * Deletes EE_messages for IDs in the request.
3436
     *
3437
     * @since 4.9.0
3438
     */
3439
	protected function _delete_ee_messages() {
3440
		$msg_ids = $this->_get_msg_ids_from_request();
3441
		$deleted_count = 0;
3442
		foreach ( $msg_ids as $msg_id ) {
3443
			if ( EEM_Message::instance()->delete_by_ID( $msg_id ) ) {
3444
				$deleted_count++;
3445
			}
3446
		}
3447
		if ( $deleted_count ) {
3448
			$this->_redirect_after_action(
3449
				true,
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a integer.

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...
3450
				_n( 'message', 'messages', $deleted_count, 'event_espresso' ),
3451
				__('deleted', 'event_espresso')
3452
			);
3453
		} else {
3454
			EE_Error::add_error(
3455
				_n( 'The message was not deleted.', 'The messages were not deleted', count( $msg_ids ), 'event_espresso' ),
3456
				__FILE__, __FUNCTION__, __LINE__
3457
			);
3458
			$this->_redirect_after_action( false, '', '', array(), true );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

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...
3459
		}
3460
	}
3461
3462
3463
3464
3465
	/**
3466
	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
3467
     *  @since 4.9.0
3468
     *  @return array
3469
     */
3470
	protected function _get_msg_ids_from_request() {
3471
		if ( ! isset( $this->_req_data['MSG_ID'] ) ) {
3472
			return array();
3473
		}
3474
		return is_array( $this->_req_data['MSG_ID'] ) ? array_keys( $this->_req_data['MSG_ID'] ) : array( $this->_req_data['MSG_ID'] );
3475
	}
3476
3477
3478
}
3479