Completed
Branch BUG/fix-named-parameter (9583b7)
by
unknown
05:28 queued 03:29
created
admin_pages/messages/Messages_Admin_Page.core.php 1 patch
Indentation   +4541 added lines, -4541 removed lines patch added patch discarded remove patch
@@ -19,2642 +19,2642 @@  discard block
 block discarded – undo
19 19
 class Messages_Admin_Page extends EE_Admin_Page
20 20
 {
21 21
 
22
-    /**
23
-     * @type EE_Message_Resource_Manager $_message_resource_manager
24
-     */
25
-    protected $_message_resource_manager;
26
-
27
-    /**
28
-     * @type string $_active_message_type_name
29
-     */
30
-    protected $_active_message_type_name = '';
31
-
32
-    /**
33
-     * @type EE_messenger $_active_messenger
34
-     */
35
-    protected $_active_messenger;
36
-    protected $_activate_state;
37
-    protected $_activate_meta_box_type;
38
-    protected $_current_message_meta_box;
39
-    protected $_current_message_meta_box_object;
40
-    protected $_context_switcher;
41
-    protected $_shortcodes = array();
42
-    protected $_active_messengers = array();
43
-    protected $_active_message_types = array();
44
-
45
-    /**
46
-     * @var EE_Message_Template_Group $_message_template_group
47
-     */
48
-    protected $_message_template_group;
49
-    protected $_m_mt_settings = array();
50
-
51
-
52
-    /**
53
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
-     * IF there is no group then it gets automatically set to the Default template pack.
55
-     *
56
-     * @since 4.5.0
57
-     *
58
-     * @var EE_Messages_Template_Pack
59
-     */
60
-    protected $_template_pack;
61
-
62
-
63
-    /**
64
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
-     * group is.  If there is no group then it automatically gets set to default.
66
-     *
67
-     * @since 4.5.0
68
-     *
69
-     * @var string
70
-     */
71
-    protected $_variation;
72
-
73
-
74
-    /**
75
-     * @param bool $routing
76
-     * @throws EE_Error
77
-     */
78
-    public function __construct($routing = true)
79
-    {
80
-        // make sure messages autoloader is running
81
-        EED_Messages::set_autoloaders();
82
-        parent::__construct($routing);
83
-    }
84
-
85
-
86
-    protected function _init_page_props()
87
-    {
88
-        $this->page_slug = EE_MSG_PG_SLUG;
89
-        $this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
-        $this->_admin_base_url = EE_MSG_ADMIN_URL;
91
-        $this->_admin_base_path = EE_MSG_ADMIN;
92
-
93
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
-            : array();
95
-
96
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
-        $this->_load_message_resource_manager();
98
-    }
99
-
100
-
101
-    /**
102
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
-     *
104
-     * @throws EE_Error
105
-     * @throws InvalidDataTypeException
106
-     * @throws InvalidInterfaceException
107
-     * @throws InvalidArgumentException
108
-     * @throws ReflectionException
109
-     */
110
-    protected function _load_message_resource_manager()
111
-    {
112
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
-    }
114
-
115
-
116
-    /**
117
-     * @deprecated 4.9.9.rc.014
118
-     * @return array
119
-     * @throws EE_Error
120
-     * @throws InvalidArgumentException
121
-     * @throws InvalidDataTypeException
122
-     * @throws InvalidInterfaceException
123
-     */
124
-    public function get_messengers_for_list_table()
125
-    {
126
-        EE_Error::doing_it_wrong(
127
-            __METHOD__,
128
-            sprintf(
129
-                esc_html__(
130
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
-                    'event_espresso'
132
-                ),
133
-                'Messages_Admin_Page::get_messengers_select_input()'
134
-            ),
135
-            '4.9.9.rc.014'
136
-        );
137
-
138
-        $m_values = array();
139
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
-        // setup messengers for selects
141
-        $i = 1;
142
-        foreach ($active_messengers as $active_messenger) {
143
-            if ($active_messenger instanceof EE_Message) {
144
-                $m_values[ $i ]['id'] = $active_messenger->messenger();
145
-                $m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
-                $i++;
147
-            }
148
-        }
149
-
150
-        return $m_values;
151
-    }
152
-
153
-
154
-    /**
155
-     * @deprecated 4.9.9.rc.014
156
-     * @return array
157
-     * @throws EE_Error
158
-     * @throws InvalidArgumentException
159
-     * @throws InvalidDataTypeException
160
-     * @throws InvalidInterfaceException
161
-     */
162
-    public function get_message_types_for_list_table()
163
-    {
164
-        EE_Error::doing_it_wrong(
165
-            __METHOD__,
166
-            sprintf(
167
-                esc_html__(
168
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
-                    'event_espresso'
170
-                ),
171
-                'Messages_Admin_Page::get_message_types_select_input()'
172
-            ),
173
-            '4.9.9.rc.014'
174
-        );
175
-
176
-        $mt_values = array();
177
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
-        $i = 1;
179
-        foreach ($active_messages as $active_message) {
180
-            if ($active_message instanceof EE_Message) {
181
-                $mt_values[ $i ]['id'] = $active_message->message_type();
182
-                $mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
-                $i++;
184
-            }
185
-        }
186
-
187
-        return $mt_values;
188
-    }
189
-
190
-
191
-    /**
192
-     * @deprecated 4.9.9.rc.014
193
-     * @return array
194
-     * @throws EE_Error
195
-     * @throws InvalidArgumentException
196
-     * @throws InvalidDataTypeException
197
-     * @throws InvalidInterfaceException
198
-     */
199
-    public function get_contexts_for_message_types_for_list_table()
200
-    {
201
-        EE_Error::doing_it_wrong(
202
-            __METHOD__,
203
-            sprintf(
204
-                esc_html__(
205
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
-                    'event_espresso'
207
-                ),
208
-                'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
-            ),
210
-            '4.9.9.rc.014'
211
-        );
212
-
213
-        $contexts = array();
214
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
-        foreach ($active_message_contexts as $active_message) {
216
-            if ($active_message instanceof EE_Message) {
217
-                $message_type = $active_message->message_type_object();
218
-                if ($message_type instanceof EE_message_type) {
219
-                    $message_type_contexts = $message_type->get_contexts();
220
-                    foreach ($message_type_contexts as $context => $context_details) {
221
-                        $contexts[ $context ] = $context_details['label'];
222
-                    }
223
-                }
224
-            }
225
-        }
226
-
227
-        return $contexts;
228
-    }
229
-
230
-
231
-    /**
232
-     * Generate select input with provided messenger options array.
233
-     *
234
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
-     *                                 labels.
236
-     * @return string
237
-     * @throws EE_Error
238
-     */
239
-    public function get_messengers_select_input($messenger_options)
240
-    {
241
-        // if empty or just one value then just return an empty string
242
-        if (empty($messenger_options)
243
-            || ! is_array($messenger_options)
244
-            || count($messenger_options) === 1
245
-        ) {
246
-            return '';
247
-        }
248
-        // merge in default
249
-        $messenger_options = array_merge(
250
-            array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
-            $messenger_options
252
-        );
253
-        $input = new EE_Select_Input(
254
-            $messenger_options,
255
-            array(
256
-                'html_name'  => 'ee_messenger_filter_by',
257
-                'html_id'    => 'ee_messenger_filter_by',
258
-                'html_class' => 'wide',
259
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
-                    : 'none_selected',
262
-            )
263
-        );
264
-
265
-        return $input->get_html_for_input();
266
-    }
267
-
268
-
269
-    /**
270
-     * Generate select input with provided message type options array.
271
-     *
272
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
-     *                                    message type labels
274
-     * @return string
275
-     * @throws EE_Error
276
-     */
277
-    public function get_message_types_select_input($message_type_options)
278
-    {
279
-        // if empty or count of options is 1 then just return an empty string
280
-        if (empty($message_type_options)
281
-            || ! is_array($message_type_options)
282
-            || count($message_type_options) === 1
283
-        ) {
284
-            return '';
285
-        }
286
-        // merge in default
287
-        $message_type_options = array_merge(
288
-            array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
-            $message_type_options
290
-        );
291
-        $input = new EE_Select_Input(
292
-            $message_type_options,
293
-            array(
294
-                'html_name'  => 'ee_message_type_filter_by',
295
-                'html_id'    => 'ee_message_type_filter_by',
296
-                'html_class' => 'wide',
297
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
-                    : 'none_selected',
300
-            )
301
-        );
302
-
303
-        return $input->get_html_for_input();
304
-    }
305
-
306
-
307
-    /**
308
-     * Generate select input with provide message type contexts array.
309
-     *
310
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
-     *                               context label.
312
-     * @return string
313
-     * @throws EE_Error
314
-     */
315
-    public function get_contexts_for_message_types_select_input($context_options)
316
-    {
317
-        // if empty or count of options is one then just return empty string
318
-        if (empty($context_options)
319
-            || ! is_array($context_options)
320
-            || count($context_options) === 1
321
-        ) {
322
-            return '';
323
-        }
324
-        // merge in default
325
-        $context_options = array_merge(
326
-            array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
-            $context_options
328
-        );
329
-        $input = new EE_Select_Input(
330
-            $context_options,
331
-            array(
332
-                'html_name'  => 'ee_context_filter_by',
333
-                'html_id'    => 'ee_context_filter_by',
334
-                'html_class' => 'wide',
335
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
336
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
337
-                    : 'none_selected',
338
-            )
339
-        );
340
-
341
-        return $input->get_html_for_input();
342
-    }
343
-
344
-
345
-    protected function _ajax_hooks()
346
-    {
347
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
-        add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
-    }
354
-
355
-
356
-    protected function _define_page_props()
357
-    {
358
-        $this->_admin_page_title = $this->page_label;
359
-        $this->_labels = array(
360
-            'buttons'    => array(
361
-                'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
-                'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
-                'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
-            ),
365
-            'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
-        );
367
-    }
368
-
369
-
370
-    /**
371
-     *        an array for storing key => value pairs of request actions and their corresponding methods
372
-     *
373
-     * @access protected
374
-     * @return void
375
-     */
376
-    protected function _set_page_routes()
377
-    {
378
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
-            ? $this->_req_data['GRP_ID']
380
-            : 0;
381
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
-            ? $this->_req_data['id']
383
-            : $grp_id;
384
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
-            ? $this->_req_data['MSG_ID']
386
-            : 0;
387
-
388
-        $this->_page_routes = array(
389
-            'default'                          => array(
390
-                'func'       => '_message_queue_list_table',
391
-                'capability' => 'ee_read_global_messages',
392
-            ),
393
-            'global_mtps'                      => array(
394
-                'func'       => '_ee_default_messages_overview_list_table',
395
-                'capability' => 'ee_read_global_messages',
396
-            ),
397
-            'custom_mtps'                      => array(
398
-                'func'       => '_custom_mtps_preview',
399
-                'capability' => 'ee_read_messages',
400
-            ),
401
-            'add_new_message_template'         => array(
402
-                'func'       => '_add_message_template',
403
-                'capability' => 'ee_edit_messages',
404
-                'noheader'   => true,
405
-            ),
406
-            'edit_message_template'            => array(
407
-                'func'       => '_edit_message_template',
408
-                'capability' => 'ee_edit_message',
409
-                'obj_id'     => $grp_id,
410
-            ),
411
-            'preview_message'                  => array(
412
-                'func'               => '_preview_message',
413
-                'capability'         => 'ee_read_message',
414
-                'obj_id'             => $grp_id,
415
-                'noheader'           => true,
416
-                'headers_sent_route' => 'display_preview_message',
417
-            ),
418
-            'display_preview_message'          => array(
419
-                'func'       => '_display_preview_message',
420
-                'capability' => 'ee_read_message',
421
-                'obj_id'     => $grp_id,
422
-            ),
423
-            'insert_message_template'          => array(
424
-                'func'       => '_insert_or_update_message_template',
425
-                'capability' => 'ee_edit_messages',
426
-                'args'       => array('new' => true),
427
-                'noheader'   => true,
428
-            ),
429
-            'update_message_template'          => array(
430
-                'func'       => '_insert_or_update_message_template',
431
-                'capability' => 'ee_edit_message',
432
-                'obj_id'     => $grp_id,
433
-                'args'       => array('new' => false),
434
-                'noheader'   => true,
435
-            ),
436
-            'trash_message_template'           => array(
437
-                'func'       => '_trash_or_restore_message_template',
438
-                'capability' => 'ee_delete_message',
439
-                'obj_id'     => $grp_id,
440
-                'args'       => array('trash' => true, 'all' => true),
441
-                'noheader'   => true,
442
-            ),
443
-            'trash_message_template_context'   => array(
444
-                'func'       => '_trash_or_restore_message_template',
445
-                'capability' => 'ee_delete_message',
446
-                'obj_id'     => $grp_id,
447
-                'args'       => array('trash' => true),
448
-                'noheader'   => true,
449
-            ),
450
-            'restore_message_template'         => array(
451
-                'func'       => '_trash_or_restore_message_template',
452
-                'capability' => 'ee_delete_message',
453
-                'obj_id'     => $grp_id,
454
-                'args'       => array('trash' => false, 'all' => true),
455
-                'noheader'   => true,
456
-            ),
457
-            'restore_message_template_context' => array(
458
-                'func'       => '_trash_or_restore_message_template',
459
-                'capability' => 'ee_delete_message',
460
-                'obj_id'     => $grp_id,
461
-                'args'       => array('trash' => false),
462
-                'noheader'   => true,
463
-            ),
464
-            'delete_message_template'          => array(
465
-                'func'       => '_delete_message_template',
466
-                'capability' => 'ee_delete_message',
467
-                'obj_id'     => $grp_id,
468
-                'noheader'   => true,
469
-            ),
470
-            'reset_to_default'                 => array(
471
-                'func'       => '_reset_to_default_template',
472
-                'capability' => 'ee_edit_message',
473
-                'obj_id'     => $grp_id,
474
-                'noheader'   => true,
475
-            ),
476
-            'settings'                         => array(
477
-                'func'       => '_settings',
478
-                'capability' => 'manage_options',
479
-            ),
480
-            'update_global_settings'           => array(
481
-                'func'       => '_update_global_settings',
482
-                'capability' => 'manage_options',
483
-                'noheader'   => true,
484
-            ),
485
-            'generate_now'                     => array(
486
-                'func'       => '_generate_now',
487
-                'capability' => 'ee_send_message',
488
-                'noheader'   => true,
489
-            ),
490
-            'generate_and_send_now'            => array(
491
-                'func'       => '_generate_and_send_now',
492
-                'capability' => 'ee_send_message',
493
-                'noheader'   => true,
494
-            ),
495
-            'queue_for_resending'              => array(
496
-                'func'       => '_queue_for_resending',
497
-                'capability' => 'ee_send_message',
498
-                'noheader'   => true,
499
-            ),
500
-            'send_now'                         => array(
501
-                'func'       => '_send_now',
502
-                'capability' => 'ee_send_message',
503
-                'noheader'   => true,
504
-            ),
505
-            'delete_ee_message'                => array(
506
-                'func'       => '_delete_ee_messages',
507
-                'capability' => 'ee_delete_messages',
508
-                'noheader'   => true,
509
-            ),
510
-            'delete_ee_messages'               => array(
511
-                'func'       => '_delete_ee_messages',
512
-                'capability' => 'ee_delete_messages',
513
-                'noheader'   => true,
514
-                'obj_id'     => $msg_id,
515
-            ),
516
-        );
517
-    }
518
-
519
-
520
-    protected function _set_page_config()
521
-    {
522
-        $this->_page_config = array(
523
-            'default'                  => array(
524
-                'nav'           => array(
525
-                    'label' => esc_html__('Message Activity', 'event_espresso'),
526
-                    'order' => 10,
527
-                ),
528
-                'list_table'    => 'EE_Message_List_Table',
529
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
-                'require_nonce' => false,
531
-            ),
532
-            'global_mtps'              => array(
533
-                'nav'           => array(
534
-                    'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
-                    'order' => 20,
536
-                ),
537
-                'list_table'    => 'Messages_Template_List_Table',
538
-                'help_tabs'     => array(
539
-                    'messages_overview_help_tab'                                => array(
540
-                        'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
-                        'filename' => 'messages_overview',
542
-                    ),
543
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
544
-                        'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
-                        'filename' => 'messages_overview_table_column_headings',
546
-                    ),
547
-                    'messages_overview_messages_filters_help_tab'               => array(
548
-                        'title'    => esc_html__('Message Filters', 'event_espresso'),
549
-                        'filename' => 'messages_overview_filters',
550
-                    ),
551
-                    'messages_overview_messages_views_help_tab'                 => array(
552
-                        'title'    => esc_html__('Message Views', 'event_espresso'),
553
-                        'filename' => 'messages_overview_views',
554
-                    ),
555
-                    'message_overview_message_types_help_tab'                   => array(
556
-                        'title'    => esc_html__('Message Types', 'event_espresso'),
557
-                        'filename' => 'messages_overview_types',
558
-                    ),
559
-                    'messages_overview_messengers_help_tab'                     => array(
560
-                        'title'    => esc_html__('Messengers', 'event_espresso'),
561
-                        'filename' => 'messages_overview_messengers',
562
-                    ),
563
-                ),
564
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
565
-                // 'help_tour'     => array('Messages_Overview_Help_Tour'),
566
-                'require_nonce' => false,
567
-            ),
568
-            'custom_mtps'              => array(
569
-                'nav'           => array(
570
-                    'label' => esc_html__('Custom Message Templates', 'event_espresso'),
571
-                    'order' => 30,
572
-                ),
573
-                'help_tabs'     => array(),
574
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
575
-                // 'help_tour'     => array(),
576
-                'require_nonce' => false,
577
-            ),
578
-            'add_new_message_template' => array(
579
-                'nav'           => array(
580
-                    'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
581
-                    'order'      => 5,
582
-                    'persistent' => false,
583
-                ),
584
-                'require_nonce' => false,
585
-            ),
586
-            'edit_message_template'    => array(
587
-                'labels'        => array(
588
-                    'buttons'    => array(
589
-                        'reset' => esc_html__('Reset Templates', 'event_espresso'),
590
-                    ),
591
-                    'publishbox' => esc_html__('Update Actions', 'event_espresso'),
592
-                ),
593
-                'nav'           => array(
594
-                    'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
595
-                    'order'      => 5,
596
-                    'persistent' => false,
597
-                    'url'        => '',
598
-                ),
599
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
600
-                'has_metaboxes' => true,
601
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
602
-                // 'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
603
-                'help_tabs'     => array(
604
-                    'edit_message_template'            => array(
605
-                        'title'    => esc_html__('Message Template Editor', 'event_espresso'),
606
-                        'callback' => 'edit_message_template_help_tab',
607
-                    ),
608
-                    'message_templates_help_tab'       => array(
609
-                        'title'    => esc_html__('Message Templates', 'event_espresso'),
610
-                        'filename' => 'messages_templates',
611
-                    ),
612
-                    'message_template_shortcodes'      => array(
613
-                        'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
614
-                        'callback' => 'message_template_shortcodes_help_tab',
615
-                    ),
616
-                    'message_preview_help_tab'         => array(
617
-                        'title'    => esc_html__('Message Preview', 'event_espresso'),
618
-                        'filename' => 'messages_preview',
619
-                    ),
620
-                    'messages_overview_other_help_tab' => array(
621
-                        'title'    => esc_html__('Messages Other', 'event_espresso'),
622
-                        'filename' => 'messages_overview_other',
623
-                    ),
624
-                ),
625
-                'require_nonce' => false,
626
-            ),
627
-            'display_preview_message'  => array(
628
-                'nav'           => array(
629
-                    'label'      => esc_html__('Message Preview', 'event_espresso'),
630
-                    'order'      => 5,
631
-                    'url'        => '',
632
-                    'persistent' => false,
633
-                ),
634
-                'help_tabs'     => array(
635
-                    'preview_message' => array(
636
-                        'title'    => esc_html__('About Previews', 'event_espresso'),
637
-                        'callback' => 'preview_message_help_tab',
638
-                    ),
639
-                ),
640
-                'require_nonce' => false,
641
-            ),
642
-            'settings'                 => array(
643
-                'nav'           => array(
644
-                    'label' => esc_html__('Settings', 'event_espresso'),
645
-                    'order' => 40,
646
-                ),
647
-                'metaboxes'     => array('_messages_settings_metaboxes'),
648
-                'help_tabs'     => array(
649
-                    'messages_settings_help_tab'               => array(
650
-                        'title'    => esc_html__('Messages Settings', 'event_espresso'),
651
-                        'filename' => 'messages_settings',
652
-                    ),
653
-                    'messages_settings_message_types_help_tab' => array(
654
-                        'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
655
-                        'filename' => 'messages_settings_message_types',
656
-                    ),
657
-                    'messages_settings_messengers_help_tab'    => array(
658
-                        'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
659
-                        'filename' => 'messages_settings_messengers',
660
-                    ),
661
-                ),
662
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
663
-                // 'help_tour'     => array('Messages_Settings_Help_Tour'),
664
-                'require_nonce' => false,
665
-            ),
666
-        );
667
-    }
668
-
669
-
670
-    protected function _add_screen_options()
671
-    {
672
-        // todo
673
-    }
674
-
675
-
676
-    protected function _add_screen_options_global_mtps()
677
-    {
678
-        /**
679
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
680
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
681
-         */
682
-        $page_title = $this->_admin_page_title;
683
-        $this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
684
-        $this->_per_page_screen_option();
685
-        $this->_admin_page_title = $page_title;
686
-    }
687
-
688
-
689
-    protected function _add_screen_options_default()
690
-    {
691
-        $this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
692
-        $this->_per_page_screen_option();
693
-    }
694
-
695
-
696
-    // none of the below group are currently used for Messages
697
-    protected function _add_feature_pointers()
698
-    {
699
-    }
700
-
701
-    public function admin_init()
702
-    {
703
-    }
704
-
705
-    public function admin_notices()
706
-    {
707
-    }
708
-
709
-    public function admin_footer_scripts()
710
-    {
711
-    }
712
-
713
-
714
-    public function messages_help_tab()
715
-    {
716
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
717
-    }
718
-
719
-
720
-    public function messengers_help_tab()
721
-    {
722
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
723
-    }
724
-
725
-
726
-    public function message_types_help_tab()
727
-    {
728
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
729
-    }
730
-
731
-
732
-    public function messages_overview_help_tab()
733
-    {
734
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
735
-    }
736
-
737
-
738
-    public function message_templates_help_tab()
739
-    {
740
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
741
-    }
742
-
743
-
744
-    public function edit_message_template_help_tab()
745
-    {
746
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
747
-                        . esc_attr__('Editor Title', 'event_espresso')
748
-                        . '" />';
749
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
750
-                        . esc_attr__('Context Switcher and Preview', 'event_espresso')
751
-                        . '" />';
752
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
753
-                        . esc_attr__('Message Template Form Fields', 'event_espresso')
754
-                        . '" />';
755
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
756
-                        . esc_attr__('Shortcodes Metabox', 'event_espresso')
757
-                        . '" />';
758
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
759
-                        . esc_attr__('Publish Metabox', 'event_espresso')
760
-                        . '" />';
761
-        EEH_Template::display_template(
762
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
763
-            $args
764
-        );
765
-    }
766
-
767
-
768
-    public function message_template_shortcodes_help_tab()
769
-    {
770
-        $this->_set_shortcodes();
771
-        $args['shortcodes'] = $this->_shortcodes;
772
-        EEH_Template::display_template(
773
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
774
-            $args
775
-        );
776
-    }
777
-
778
-
779
-    public function preview_message_help_tab()
780
-    {
781
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
782
-    }
783
-
784
-
785
-    public function settings_help_tab()
786
-    {
787
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
788
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
789
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
790
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
791
-        $args['img3'] = '<div class="switch">'
792
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
793
-                        . ' type="checkbox" checked="checked">'
794
-                        . '<label for="ee-on-off-toggle-on"></label>'
795
-                        . '</div>';
796
-        $args['img4'] = '<div class="switch">'
797
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
798
-                        . ' type="checkbox">'
799
-                        . '<label for="ee-on-off-toggle-on"></label>'
800
-                        . '</div>';
801
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
802
-    }
803
-
804
-
805
-    public function load_scripts_styles()
806
-    {
807
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
808
-        wp_enqueue_style('espresso_ee_msg');
809
-
810
-        wp_register_script(
811
-            'ee-messages-settings',
812
-            EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
813
-            array('jquery-ui-droppable', 'ee-serialize-full-array'),
814
-            EVENT_ESPRESSO_VERSION,
815
-            true
816
-        );
817
-        wp_register_script(
818
-            'ee-msg-list-table-js',
819
-            EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
820
-            array('ee-dialog'),
821
-            EVENT_ESPRESSO_VERSION
822
-        );
823
-    }
824
-
825
-
826
-    public function load_scripts_styles_default()
827
-    {
828
-        wp_enqueue_script('ee-msg-list-table-js');
829
-    }
830
-
831
-
832
-    public function wp_editor_css($mce_css)
833
-    {
834
-        // if we're on the edit_message_template route
835
-        if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
836
-            $message_type_name = $this->_active_message_type_name;
837
-
838
-            // we're going to REPLACE the existing mce css
839
-            // we need to get the css file location from the active messenger
840
-            $mce_css = $this->_active_messenger->get_variation(
841
-                $this->_template_pack,
842
-                $message_type_name,
843
-                true,
844
-                'wpeditor',
845
-                $this->_variation
846
-            );
847
-        }
848
-
849
-        return $mce_css;
850
-    }
851
-
852
-
853
-    public function load_scripts_styles_edit_message_template()
854
-    {
855
-
856
-        $this->_set_shortcodes();
857
-
858
-        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
859
-            esc_html__(
860
-                '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.',
861
-                'event_espresso'
862
-            ),
863
-            $this->_message_template_group->messenger_obj()->label['singular'],
864
-            $this->_message_template_group->message_type_obj()->label['singular']
865
-        );
866
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
867
-            '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?',
868
-            'event_espresso'
869
-        );
870
-        EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
871
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
872
-            'event_espresso'
873
-        );
874
-
875
-        wp_register_script(
876
-            'ee_msgs_edit_js',
877
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
878
-            array('jquery'),
879
-            EVENT_ESPRESSO_VERSION
880
-        );
881
-
882
-        wp_enqueue_script('ee_admin_js');
883
-        wp_enqueue_script('ee_msgs_edit_js');
884
-
885
-        // add in special css for tiny_mce
886
-        add_filter('mce_css', array($this, 'wp_editor_css'));
887
-    }
888
-
889
-
890
-    public function load_scripts_styles_display_preview_message()
891
-    {
892
-
893
-        $this->_set_message_template_group();
894
-
895
-        if (isset($this->_req_data['messenger'])) {
896
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
897
-                $this->_req_data['messenger']
898
-            );
899
-        }
900
-
901
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
902
-
903
-
904
-        wp_enqueue_style(
905
-            'espresso_preview_css',
906
-            $this->_active_messenger->get_variation(
907
-                $this->_template_pack,
908
-                $message_type_name,
909
-                true,
910
-                'preview',
911
-                $this->_variation
912
-            )
913
-        );
914
-    }
915
-
916
-
917
-    public function load_scripts_styles_settings()
918
-    {
919
-        wp_register_style(
920
-            'ee-message-settings',
921
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
922
-            array(),
923
-            EVENT_ESPRESSO_VERSION
924
-        );
925
-        wp_enqueue_style('ee-text-links');
926
-        wp_enqueue_style('ee-message-settings');
927
-        wp_enqueue_script('ee-messages-settings');
928
-    }
929
-
930
-
931
-    /**
932
-     * set views array for List Table
933
-     */
934
-    public function _set_list_table_views_global_mtps()
935
-    {
936
-        $this->_views = array(
937
-            'in_use' => array(
938
-                'slug'  => 'in_use',
939
-                'label' => esc_html__('In Use', 'event_espresso'),
940
-                'count' => 0,
941
-            ),
942
-        );
943
-    }
944
-
945
-
946
-    /**
947
-     * Set views array for the Custom Template List Table
948
-     */
949
-    public function _set_list_table_views_custom_mtps()
950
-    {
951
-        $this->_set_list_table_views_global_mtps();
952
-        $this->_views['in_use']['bulk_action'] = array(
953
-            'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
954
-        );
955
-    }
956
-
957
-
958
-    /**
959
-     * set views array for message queue list table
960
-     *
961
-     * @throws InvalidDataTypeException
962
-     * @throws InvalidInterfaceException
963
-     * @throws InvalidArgumentException
964
-     * @throws EE_Error
965
-     * @throws ReflectionException
966
-     */
967
-    public function _set_list_table_views_default()
968
-    {
969
-        EE_Registry::instance()->load_helper('Template');
970
-
971
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
972
-            'ee_send_message',
973
-            'message_list_table_bulk_actions'
974
-        )
975
-            ? array(
976
-                'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
977
-                'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
978
-                'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
979
-                'send_now'              => esc_html__('Send Now', 'event_espresso'),
980
-            )
981
-            : array();
982
-
983
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
984
-            'ee_delete_messages',
985
-            'message_list_table_bulk_actions'
986
-        )
987
-            ? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
988
-            : array();
989
-
990
-
991
-        $this->_views = array(
992
-            'all' => array(
993
-                'slug'        => 'all',
994
-                'label'       => esc_html__('All', 'event_espresso'),
995
-                'count'       => 0,
996
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
997
-            ),
998
-        );
999
-
1000
-
1001
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
1002
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
1003
-                continue;
1004
-            }
1005
-            $status_bulk_actions = $common_bulk_actions;
1006
-            // unset bulk actions not applying to status
1007
-            if (! empty($status_bulk_actions)) {
1008
-                switch ($status) {
1009
-                    case EEM_Message::status_idle:
1010
-                    case EEM_Message::status_resend:
1011
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1012
-                        break;
1013
-
1014
-                    case EEM_Message::status_failed:
1015
-                    case EEM_Message::status_debug_only:
1016
-                    case EEM_Message::status_messenger_executing:
1017
-                        $status_bulk_actions = array();
1018
-                        break;
1019
-
1020
-                    case EEM_Message::status_incomplete:
1021
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1022
-                        break;
1023
-
1024
-                    case EEM_Message::status_retry:
1025
-                    case EEM_Message::status_sent:
1026
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1027
-                        break;
1028
-                }
1029
-            }
1030
-
1031
-            // skip adding messenger executing status to views because it will be included with the Failed view.
1032
-            if ($status === EEM_Message::status_messenger_executing) {
1033
-                continue;
1034
-            }
1035
-
1036
-            $this->_views[ strtolower($status) ] = array(
1037
-                'slug'        => strtolower($status),
1038
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1039
-                'count'       => 0,
1040
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1041
-            );
1042
-        }
1043
-    }
1044
-
1045
-
1046
-    protected function _ee_default_messages_overview_list_table()
1047
-    {
1048
-        $this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1049
-        $this->display_admin_list_table_page_with_no_sidebar();
1050
-    }
1051
-
1052
-
1053
-    protected function _message_queue_list_table()
1054
-    {
1055
-        $this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1056
-        $this->_template_args['per_column'] = 6;
1057
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1058
-        $this->_template_args['before_list_table'] = '<h3>'
1059
-                                                     . EEM_Message::instance()->get_pretty_label_for_results()
1060
-                                                     . '</h3>';
1061
-        $this->display_admin_list_table_page_with_no_sidebar();
1062
-    }
1063
-
1064
-
1065
-    protected function _message_legend_items()
1066
-    {
1067
-
1068
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
1069
-        $action_items = array();
1070
-
1071
-        foreach ($action_css_classes as $action_item => $action_details) {
1072
-            if ($action_item === 'see_notifications_for') {
1073
-                continue;
1074
-            }
1075
-            $action_items[ $action_item ] = array(
1076
-                'class' => $action_details['css_class'],
1077
-                'desc'  => $action_details['label'],
1078
-            );
1079
-        }
1080
-
1081
-        /** @type array $status_items status legend setup */
1082
-        $status_items = array(
1083
-            'sent_status'                => array(
1084
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1085
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1086
-            ),
1087
-            'idle_status'                => array(
1088
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1089
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1090
-            ),
1091
-            'failed_status'              => array(
1092
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1093
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1094
-            ),
1095
-            'messenger_executing_status' => array(
1096
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1097
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1098
-            ),
1099
-            'resend_status'              => array(
1100
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1101
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1102
-            ),
1103
-            'incomplete_status'          => array(
1104
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1105
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1106
-            ),
1107
-            'retry_status'               => array(
1108
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1109
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1110
-            ),
1111
-        );
1112
-        if (EEM_Message::debug()) {
1113
-            $status_items['debug_only_status'] = array(
1114
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1115
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1116
-            );
1117
-        }
1118
-
1119
-        return array_merge($action_items, $status_items);
1120
-    }
1121
-
1122
-
1123
-    protected function _custom_mtps_preview()
1124
-    {
1125
-        $this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1126
-        $this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1127
-                                               . ' alt="' . esc_attr__(
1128
-                                                   'Preview Custom Message Templates screenshot',
1129
-                                                   'event_espresso'
1130
-                                               ) . '" />';
1131
-        $this->_template_args['preview_text'] = '<strong>'
1132
-                                                . esc_html__(
1133
-                                                    'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1134
-                                                    'event_espresso'
1135
-                                                )
1136
-                                                . '</strong>';
1137
-
1138
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1139
-    }
1140
-
1141
-
1142
-    /**
1143
-     * get_message_templates
1144
-     * This gets all the message templates for listing on the overview list.
1145
-     *
1146
-     * @access public
1147
-     * @param int    $perpage the amount of templates groups to show per page
1148
-     * @param string $type    the current _view we're getting templates for
1149
-     * @param bool   $count   return count?
1150
-     * @param bool   $all     disregard any paging info (get all data);
1151
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1152
-     * @return array
1153
-     * @throws EE_Error
1154
-     * @throws InvalidArgumentException
1155
-     * @throws InvalidDataTypeException
1156
-     * @throws InvalidInterfaceException
1157
-     */
1158
-    public function get_message_templates(
1159
-        $perpage = 10,
1160
-        $type = 'in_use',
1161
-        $count = false,
1162
-        $all = false,
1163
-        $global = true
1164
-    ) {
1165
-
1166
-        $MTP = EEM_Message_Template_Group::instance();
1167
-
1168
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1169
-        $orderby = $this->_req_data['orderby'];
1170
-
1171
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1172
-            ? $this->_req_data['order']
1173
-            : 'ASC';
1174
-
1175
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1176
-            ? $this->_req_data['paged']
1177
-            : 1;
1178
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1179
-            ? $this->_req_data['perpage']
1180
-            : $perpage;
1181
-
1182
-        $offset = ($current_page - 1) * $per_page;
1183
-        $limit = $all ? null : array($offset, $per_page);
1184
-
1185
-
1186
-        // options will match what is in the _views array property
1187
-        switch ($type) {
1188
-            case 'in_use':
1189
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1190
-                break;
1191
-            default:
1192
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1193
-        }
1194
-
1195
-        return $templates;
1196
-    }
1197
-
1198
-
1199
-    /**
1200
-     * filters etc might need a list of installed message_types
1201
-     *
1202
-     * @return array an array of message type objects
1203
-     */
1204
-    public function get_installed_message_types()
1205
-    {
1206
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1207
-        $installed = array();
1208
-
1209
-        foreach ($installed_message_types as $message_type) {
1210
-            $installed[ $message_type->name ] = $message_type;
1211
-        }
1212
-
1213
-        return $installed;
1214
-    }
1215
-
1216
-
1217
-    /**
1218
-     * _add_message_template
1219
-     *
1220
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1221
-     *
1222
-     * @param string $message_type
1223
-     * @param string $messenger
1224
-     * @param string $GRP_ID
1225
-     *
1226
-     * @throws EE_error
1227
-     */
1228
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1229
-    {
1230
-        // set values override any request data
1231
-        $message_type = ! empty($message_type) ? $message_type : '';
1232
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1233
-            ? $this->_req_data['message_type']
1234
-            : $message_type;
1235
-
1236
-        $messenger = ! empty($messenger) ? $messenger : '';
1237
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1238
-            ? $this->_req_data['messenger']
1239
-            : $messenger;
1240
-
1241
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1242
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1243
-
1244
-        // we need messenger and message type.  They should be coming from the event editor. If not here then return error
1245
-        if (empty($message_type) || empty($messenger)) {
1246
-            throw new EE_Error(
1247
-                esc_html__(
1248
-                    'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1249
-                    'event_espresso'
1250
-                )
1251
-            );
1252
-        }
1253
-
1254
-        // we need the GRP_ID for the template being used as the base for the new template
1255
-        if (empty($GRP_ID)) {
1256
-            throw new EE_Error(
1257
-                esc_html__(
1258
-                    'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1259
-                    'event_espresso'
1260
-                )
1261
-            );
1262
-        }
1263
-
1264
-        // let's just make sure the template gets generated!
1265
-
1266
-        // we need to reassign some variables for what the insert is expecting
1267
-        $this->_req_data['MTP_messenger'] = $messenger;
1268
-        $this->_req_data['MTP_message_type'] = $message_type;
1269
-        $this->_req_data['GRP_ID'] = $GRP_ID;
1270
-        $this->_insert_or_update_message_template(true);
1271
-    }
1272
-
1273
-
1274
-    /**
1275
-     * public wrapper for the _add_message_template method
1276
-     *
1277
-     * @param string $message_type     message type slug
1278
-     * @param string $messenger        messenger slug
1279
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1280
-     *                                 off of.
1281
-     * @throws EE_error
1282
-     */
1283
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1284
-    {
1285
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1286
-    }
1287
-
1288
-
1289
-    /**
1290
-     * _edit_message_template
1291
-     *
1292
-     * @access protected
1293
-     * @return void
1294
-     * @throws InvalidIdentifierException
1295
-     * @throws DomainException
1296
-     * @throws EE_Error
1297
-     * @throws InvalidArgumentException
1298
-     * @throws ReflectionException
1299
-     * @throws InvalidDataTypeException
1300
-     * @throws InvalidInterfaceException
1301
-     */
1302
-    protected function _edit_message_template()
1303
-    {
1304
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1305
-        $template_fields = '';
1306
-        $sidebar_fields = '';
1307
-        // we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1308
-        // valid html in the templates.
1309
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1310
-
1311
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1312
-            ? absint($this->_req_data['id'])
1313
-            : false;
1314
-
1315
-        $EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
1316
-        ? absint($this->_req_data['evt_id'])
1317
-        : false;
1318
-
1319
-        $this->_set_shortcodes(); // this also sets the _message_template property.
1320
-        $message_template_group = $this->_message_template_group;
1321
-        $c_label = $message_template_group->context_label();
1322
-        $c_config = $message_template_group->contexts_config();
1323
-
1324
-        reset($c_config);
1325
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1326
-            ? strtolower($this->_req_data['context'])
1327
-            : key($c_config);
1328
-
1329
-
1330
-        if (empty($GRP_ID)) {
1331
-            $action = 'insert_message_template';
1332
-            $edit_message_template_form_url = add_query_arg(
1333
-                array('action' => $action, 'noheader' => true),
1334
-                EE_MSG_ADMIN_URL
1335
-            );
1336
-        } else {
1337
-            $action = 'update_message_template';
1338
-            $edit_message_template_form_url = add_query_arg(
1339
-                array('action' => $action, 'noheader' => true),
1340
-                EE_MSG_ADMIN_URL
1341
-            );
1342
-        }
1343
-
1344
-        // set active messenger for this view
1345
-        $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1346
-            $message_template_group->messenger()
1347
-        );
1348
-        $this->_active_message_type_name = $message_template_group->message_type();
1349
-
1350
-
1351
-        // Do we have any validation errors?
1352
-        $validators = $this->_get_transient();
1353
-        $v_fields = ! empty($validators) ? array_keys($validators) : array();
1354
-
1355
-
1356
-        // we need to assemble the title from Various details
1357
-        $context_label = sprintf(
1358
-            esc_html__('(%s %s)', 'event_espresso'),
1359
-            $c_config[ $context ]['label'],
1360
-            ucwords($c_label['label'])
1361
-        );
1362
-
1363
-        $title = sprintf(
1364
-            esc_html__(' %s %s Template %s', 'event_espresso'),
1365
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1366
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1367
-            $context_label
1368
-        );
1369
-
1370
-        $this->_template_args['GRP_ID'] = $GRP_ID;
1371
-        $this->_template_args['message_template'] = $message_template_group;
1372
-        $this->_template_args['is_extra_fields'] = false;
1373
-
1374
-
1375
-        // let's get EEH_MSG_Template so we can get template form fields
1376
-        $template_field_structure = EEH_MSG_Template::get_fields(
1377
-            $message_template_group->messenger(),
1378
-            $message_template_group->message_type()
1379
-        );
1380
-
1381
-        if (! $template_field_structure) {
1382
-            $template_field_structure = false;
1383
-            $template_fields = esc_html__(
1384
-                'There was an error in assembling the fields for this display (you should see an error message)',
1385
-                'event_espresso'
1386
-            );
1387
-        }
1388
-
1389
-
1390
-        $message_templates = $message_template_group->context_templates();
1391
-
1392
-
1393
-        // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1394
-        // will get handled in the "extra" array.
1395
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1396
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1397
-                unset($template_field_structure[ $context ][ $reference_field ]);
1398
-            }
1399
-        }
1400
-
1401
-        // let's loop through the template_field_structure and actually assemble the input fields!
1402
-        if (! empty($template_field_structure)) {
1403
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1404
-                // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1405
-                // the extra array and reset them.
1406
-                if ($template_field === 'extra') {
1407
-                    $this->_template_args['is_extra_fields'] = true;
1408
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1409
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1410
-                        $content = $message_template instanceof EE_Message_Template
1411
-                            ? $message_template->get('MTP_content')
1412
-                            : '';
1413
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1414
-                            // let's verify if we need this extra field via the shortcodes parameter.
1415
-                            $continue = false;
1416
-                            if (isset($extra_array['shortcodes_required'])) {
1417
-                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1418
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1419
-                                        $continue = true;
1420
-                                    }
1421
-                                }
1422
-                                if ($continue) {
1423
-                                    continue;
1424
-                                }
1425
-                            }
1426
-
1427
-                            $field_id = $reference_field
1428
-                                        . '-'
1429
-                                        . $extra_field
1430
-                                        . '-content';
1431
-                            $template_form_fields[ $field_id ] = $extra_array;
1432
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1433
-                                                                         . $reference_field
1434
-                                                                         . '][content]['
1435
-                                                                         . $extra_field . ']';
1436
-                            $css_class = isset($extra_array['css_class'])
1437
-                                ? $extra_array['css_class']
1438
-                                : '';
1439
-
1440
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1441
-                                                                              && in_array($extra_field, $v_fields, true)
1442
-                                                                              &&
1443
-                                                                              (
1444
-                                                                                  is_array($validators[ $extra_field ])
1445
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1446
-                                                                              )
1447
-                                ? 'validate-error ' . $css_class
1448
-                                : $css_class;
1449
-
1450
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1451
-                                                                          && isset($content[ $extra_field ])
1452
-                                ? $content[ $extra_field ]
1453
-                                : '';
1454
-
1455
-                            // do we have a validation error?  if we do then let's use that value instead
1456
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1457
-                                ? $validators[ $extra_field ]['value']
1458
-                                : $template_form_fields[ $field_id ]['value'];
1459
-
1460
-
1461
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1462
-
1463
-                            // shortcode selector
1464
-                            $field_name_to_use = $extra_field === 'main'
1465
-                                ? 'content'
1466
-                                : $extra_field;
1467
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1468
-                                $field_name_to_use,
1469
-                                $field_id
1470
-                            );
1471
-
1472
-                            if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1473
-                                // we want to decode the entities
1474
-                                $template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1475
-                            }/**/
1476
-                        }
1477
-                        $templatefield_MTP_id = $reference_field . '-MTP_ID';
1478
-                        $templatefield_templatename_id = $reference_field . '-name';
1479
-
1480
-                        $template_form_fields[ $templatefield_MTP_id ] = array(
1481
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1482
-                            'label'      => null,
1483
-                            'input'      => 'hidden',
1484
-                            'type'       => 'int',
1485
-                            'required'   => false,
1486
-                            'validation' => false,
1487
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1488
-                            'css_class'  => '',
1489
-                            'format'     => '%d',
1490
-                            'db-col'     => 'MTP_ID',
1491
-                        );
1492
-
1493
-                        $template_form_fields[ $templatefield_templatename_id ] = array(
1494
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1495
-                            'label'      => null,
1496
-                            'input'      => 'hidden',
1497
-                            'type'       => 'string',
1498
-                            'required'   => false,
1499
-                            'validation' => true,
1500
-                            'value'      => $reference_field,
1501
-                            'css_class'  => '',
1502
-                            'format'     => '%s',
1503
-                            'db-col'     => 'MTP_template_field',
1504
-                        );
1505
-                    }
1506
-                    continue; // skip the next stuff, we got the necessary fields here for this dataset.
1507
-                } else {
1508
-                    $field_id = $template_field . '-content';
1509
-                    $template_form_fields[ $field_id ] = $field_setup_array;
1510
-                    $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1511
-                    $message_template = isset($message_templates[ $context ][ $template_field ])
1512
-                        ? $message_templates[ $context ][ $template_field ]
1513
-                        : null;
1514
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1515
-                                                                  && is_array($message_templates[ $context ])
1516
-                                                                  && $message_template instanceof EE_Message_Template
1517
-                        ? $message_template->get('MTP_content')
1518
-                        : '';
1519
-
1520
-                    // do we have a validator error for this field?  if we do then we'll use that value instead
1521
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1522
-                        ? $validators[ $template_field ]['value']
1523
-                        : $template_form_fields[ $field_id ]['value'];
1524
-
1525
-
1526
-                    $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1527
-                    $css_class = isset($field_setup_array['css_class'])
1528
-                        ? $field_setup_array['css_class']
1529
-                        : '';
1530
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1531
-                                                                      && in_array($template_field, $v_fields, true)
1532
-                                                                      && isset($validators[ $template_field ]['msg'])
1533
-                        ? 'validate-error ' . $css_class
1534
-                        : $css_class;
1535
-
1536
-                    // shortcode selector
1537
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1538
-                        $template_field,
1539
-                        $field_id
1540
-                    );
1541
-                }
1542
-
1543
-                // k took care of content field(s) now let's take care of others.
1544
-
1545
-                $templatefield_MTP_id = $template_field . '-MTP_ID';
1546
-                $templatefield_field_templatename_id = $template_field . '-name';
1547
-
1548
-                // foreach template field there are actually two form fields created
1549
-                $template_form_fields[ $templatefield_MTP_id ] = array(
1550
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1551
-                    'label'      => null,
1552
-                    'input'      => 'hidden',
1553
-                    'type'       => 'int',
1554
-                    'required'   => false,
1555
-                    'validation' => true,
1556
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1557
-                    'css_class'  => '',
1558
-                    'format'     => '%d',
1559
-                    'db-col'     => 'MTP_ID',
1560
-                );
1561
-
1562
-                $template_form_fields[ $templatefield_field_templatename_id ] = array(
1563
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1564
-                    'label'      => null,
1565
-                    'input'      => 'hidden',
1566
-                    'type'       => 'string',
1567
-                    'required'   => false,
1568
-                    'validation' => true,
1569
-                    'value'      => $template_field,
1570
-                    'css_class'  => '',
1571
-                    'format'     => '%s',
1572
-                    'db-col'     => 'MTP_template_field',
1573
-                );
1574
-            }
1575
-
1576
-            // add other fields
1577
-            $template_form_fields['ee-msg-current-context'] = array(
1578
-                'name'       => 'MTP_context',
1579
-                'label'      => null,
1580
-                'input'      => 'hidden',
1581
-                'type'       => 'string',
1582
-                'required'   => false,
1583
-                'validation' => true,
1584
-                'value'      => $context,
1585
-                'css_class'  => '',
1586
-                'format'     => '%s',
1587
-                'db-col'     => 'MTP_context',
1588
-            );
1589
-
1590
-            $template_form_fields['ee-msg-grp-id'] = array(
1591
-                'name'       => 'GRP_ID',
1592
-                'label'      => null,
1593
-                'input'      => 'hidden',
1594
-                'type'       => 'int',
1595
-                'required'   => false,
1596
-                'validation' => true,
1597
-                'value'      => $GRP_ID,
1598
-                'css_class'  => '',
1599
-                'format'     => '%d',
1600
-                'db-col'     => 'GRP_ID',
1601
-            );
1602
-
1603
-            $template_form_fields['ee-msg-messenger'] = array(
1604
-                'name'       => 'MTP_messenger',
1605
-                'label'      => null,
1606
-                'input'      => 'hidden',
1607
-                'type'       => 'string',
1608
-                'required'   => false,
1609
-                'validation' => true,
1610
-                'value'      => $message_template_group->messenger(),
1611
-                'css_class'  => '',
1612
-                'format'     => '%s',
1613
-                'db-col'     => 'MTP_messenger',
1614
-            );
1615
-
1616
-            $template_form_fields['ee-msg-message-type'] = array(
1617
-                'name'       => 'MTP_message_type',
1618
-                'label'      => null,
1619
-                'input'      => 'hidden',
1620
-                'type'       => 'string',
1621
-                'required'   => false,
1622
-                'validation' => true,
1623
-                'value'      => $message_template_group->message_type(),
1624
-                'css_class'  => '',
1625
-                'format'     => '%s',
1626
-                'db-col'     => 'MTP_message_type',
1627
-            );
1628
-
1629
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1630
-                'name'       => 'MTP_is_global',
1631
-                'label'      => esc_html__('Global Template', 'event_espresso'),
1632
-                'input'      => 'hidden',
1633
-                'type'       => 'int',
1634
-                'required'   => false,
1635
-                'validation' => true,
1636
-                'value'      => $message_template_group->get('MTP_is_global'),
1637
-                'css_class'  => '',
1638
-                'format'     => '%d',
1639
-                'db-col'     => 'MTP_is_global',
1640
-            );
1641
-
1642
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1643
-                'name'       => 'MTP_is_override',
1644
-                'label'      => esc_html__('Override all custom', 'event_espresso'),
1645
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1646
-                'type'       => 'int',
1647
-                'required'   => false,
1648
-                'validation' => true,
1649
-                'value'      => $message_template_group->get('MTP_is_override'),
1650
-                'css_class'  => '',
1651
-                'format'     => '%d',
1652
-                'db-col'     => 'MTP_is_override',
1653
-            );
1654
-
1655
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1656
-                'name'       => 'MTP_is_active',
1657
-                'label'      => esc_html__('Active Template', 'event_espresso'),
1658
-                'input'      => 'hidden',
1659
-                'type'       => 'int',
1660
-                'required'   => false,
1661
-                'validation' => true,
1662
-                'value'      => $message_template_group->is_active(),
1663
-                'css_class'  => '',
1664
-                'format'     => '%d',
1665
-                'db-col'     => 'MTP_is_active',
1666
-            );
1667
-
1668
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1669
-                'name'       => 'MTP_deleted',
1670
-                'label'      => null,
1671
-                'input'      => 'hidden',
1672
-                'type'       => 'int',
1673
-                'required'   => false,
1674
-                'validation' => true,
1675
-                'value'      => $message_template_group->get('MTP_deleted'),
1676
-                'css_class'  => '',
1677
-                'format'     => '%d',
1678
-                'db-col'     => 'MTP_deleted',
1679
-            );
1680
-            $sidebar_form_fields['ee-msg-author'] = array(
1681
-                'name'       => 'MTP_user_id',
1682
-                'label'      => esc_html__('Author', 'event_espresso'),
1683
-                'input'      => 'hidden',
1684
-                'type'       => 'int',
1685
-                'required'   => false,
1686
-                'validation' => false,
1687
-                'value'      => $message_template_group->user(),
1688
-                'format'     => '%d',
1689
-                'db-col'     => 'MTP_user_id',
1690
-            );
1691
-
1692
-            $sidebar_form_fields['ee-msg-route'] = array(
1693
-                'name'  => 'action',
1694
-                'input' => 'hidden',
1695
-                'type'  => 'string',
1696
-                'value' => $action,
1697
-            );
1698
-
1699
-            $sidebar_form_fields['ee-msg-id'] = array(
1700
-                'name'  => 'id',
1701
-                'input' => 'hidden',
1702
-                'type'  => 'int',
1703
-                'value' => $GRP_ID,
1704
-            );
1705
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1706
-                'name'  => $action . '_nonce',
1707
-                'input' => 'hidden',
1708
-                'type'  => 'string',
1709
-                'value' => wp_create_nonce($action . '_nonce'),
1710
-            );
1711
-
1712
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1713
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1714
-                    'name'  => 'template_switch',
1715
-                    'input' => 'hidden',
1716
-                    'type'  => 'int',
1717
-                    'value' => 1,
1718
-                );
1719
-            }
1720
-
1721
-
1722
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1723
-            $sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1724
-        } //end if ( !empty($template_field_structure) )
1725
-
1726
-        // set extra content for publish box
1727
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1728
-        $this->_set_publish_post_box_vars(
1729
-            'id',
1730
-            $GRP_ID,
1731
-            false,
1732
-            add_query_arg(
1733
-                array('action' => 'global_mtps'),
1734
-                $this->_admin_base_url
1735
-            )
1736
-        );
1737
-
1738
-        // add preview button
1739
-        $preview_url = parent::add_query_args_and_nonce(
1740
-            array(
1741
-                'message_type' => $message_template_group->message_type(),
1742
-                'messenger'    => $message_template_group->messenger(),
1743
-                'context'      => $context,
1744
-                'GRP_ID'       => $GRP_ID,
1745
-                'evt_id'       => $EVT_ID,
1746
-                'action'       => 'preview_message',
1747
-            ),
1748
-            $this->_admin_base_url
1749
-        );
1750
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1751
-                          . esc_html__('Preview', 'event_espresso')
1752
-                          . '</a>';
1753
-
1754
-
1755
-        // setup context switcher
1756
-        $context_switcher_args = array(
1757
-            'page'    => 'espresso_messages',
1758
-            'action'  => 'edit_message_template',
1759
-            'id'      => $GRP_ID,
1760
-            'evt_id'  => $EVT_ID,
1761
-            'context' => $context,
1762
-            'extra'   => $preview_button,
1763
-        );
1764
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1765
-
1766
-
1767
-        // main box
1768
-        $this->_template_args['template_fields'] = $template_fields;
1769
-        $this->_template_args['sidebar_box_id'] = 'details';
1770
-        $this->_template_args['action'] = $action;
1771
-        $this->_template_args['context'] = $context;
1772
-        $this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1773
-        $this->_template_args['learn_more_about_message_templates_link'] =
1774
-            $this->_learn_more_about_message_templates_link();
1775
-
1776
-
1777
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1778
-        $this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1779
-            $message_template_group,
1780
-            $context,
1781
-            $context_label
1782
-        );
1783
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1784
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1785
-
1786
-        $this->_template_path = $this->_template_args['GRP_ID']
1787
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1788
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1789
-
1790
-        // send along EE_Message_Template_Group object for further template use.
1791
-        $this->_template_args['MTP'] = $message_template_group;
1792
-
1793
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1794
-            $this->_template_path,
1795
-            $this->_template_args,
1796
-            true
1797
-        );
1798
-
1799
-
1800
-        // finally, let's set the admin_page title
1801
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1802
-
1803
-
1804
-        // we need to take care of setting the shortcodes property for use elsewhere.
1805
-        $this->_set_shortcodes();
1806
-
1807
-
1808
-        // final template wrapper
1809
-        $this->display_admin_page_with_sidebar();
1810
-    }
1811
-
1812
-
1813
-    public function filter_tinymce_init($mceInit, $editor_id)
1814
-    {
1815
-        return $mceInit;
1816
-    }
1817
-
1818
-
1819
-    public function add_context_switcher()
1820
-    {
1821
-        return $this->_context_switcher;
1822
-    }
1823
-
1824
-
1825
-    /**
1826
-     * Adds the activation/deactivation toggle for the message template context.
1827
-     *
1828
-     * @param EE_Message_Template_Group $message_template_group
1829
-     * @param string                    $context
1830
-     * @param string                    $context_label
1831
-     * @return string
1832
-     * @throws DomainException
1833
-     * @throws EE_Error
1834
-     * @throws InvalidIdentifierException
1835
-     */
1836
-    protected function add_active_context_element(
1837
-        EE_Message_Template_Group $message_template_group,
1838
-        $context,
1839
-        $context_label
1840
-    ) {
1841
-        $template_args = array(
1842
-            'context'                   => $context,
1843
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1844
-            'is_active'                 => $message_template_group->is_context_active($context),
1845
-            'on_off_action'             => $message_template_group->is_context_active($context)
1846
-                ? 'context-off'
1847
-                : 'context-on',
1848
-            'context_label'             => str_replace(array('(', ')'), '', $context_label),
1849
-            'message_template_group_id' => $message_template_group->ID(),
1850
-        );
1851
-        return EEH_Template::display_template(
1852
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1853
-            $template_args,
1854
-            true
1855
-        );
1856
-    }
1857
-
1858
-
1859
-    /**
1860
-     * Ajax callback for `toggle_context_template` ajax action.
1861
-     * Handles toggling the message context on or off.
1862
-     *
1863
-     * @throws EE_Error
1864
-     * @throws InvalidArgumentException
1865
-     * @throws InvalidDataTypeException
1866
-     * @throws InvalidIdentifierException
1867
-     * @throws InvalidInterfaceException
1868
-     */
1869
-    public function toggle_context_template()
1870
-    {
1871
-        $success = true;
1872
-        // check for required data
1873
-        if (! isset(
1874
-            $this->_req_data['message_template_group_id'],
1875
-            $this->_req_data['context'],
1876
-            $this->_req_data['status']
1877
-        )) {
1878
-            EE_Error::add_error(
1879
-                esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1880
-                __FILE__,
1881
-                __FUNCTION__,
1882
-                __LINE__
1883
-            );
1884
-            $success = false;
1885
-        }
1886
-
1887
-        $nonce = isset($this->_req_data['toggle_context_nonce'])
1888
-            ? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1889
-            : '';
1890
-        $nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1891
-        $this->_verify_nonce($nonce, $nonce_ref);
1892
-        $status = $this->_req_data['status'];
1893
-        if ($status !== 'off' && $status !== 'on') {
1894
-            EE_Error::add_error(
1895
-                sprintf(
1896
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1897
-                    $this->_req_data['status']
1898
-                ),
1899
-                __FILE__,
1900
-                __FUNCTION__,
1901
-                __LINE__
1902
-            );
1903
-            $success = false;
1904
-        }
1905
-        $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1906
-            $this->_req_data['message_template_group_id']
1907
-        );
1908
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1909
-            EE_Error::add_error(
1910
-                sprintf(
1911
-                    esc_html__(
1912
-                        'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1913
-                        'event_espresso'
1914
-                    ),
1915
-                    $this->_req_data['message_template_group_id'],
1916
-                    'EE_Message_Template_Group'
1917
-                ),
1918
-                __FILE__,
1919
-                __FUNCTION__,
1920
-                __LINE__
1921
-            );
1922
-            $success = false;
1923
-        }
1924
-        if ($success) {
1925
-            $success = $status === 'off'
1926
-                ? $message_template_group->deactivate_context($this->_req_data['context'])
1927
-                : $message_template_group->activate_context($this->_req_data['context']);
1928
-        }
1929
-        $this->_template_args['success'] = $success;
1930
-        $this->_return_json();
1931
-    }
1932
-
1933
-
1934
-    public function _add_form_element_before()
1935
-    {
1936
-        return '<form method="post" action="'
1937
-               . $this->_template_args["edit_message_template_form_url"]
1938
-               . '" id="ee-msg-edit-frm">';
1939
-    }
1940
-
1941
-    public function _add_form_element_after()
1942
-    {
1943
-        return '</form>';
1944
-    }
1945
-
1946
-
1947
-    /**
1948
-     * This executes switching the template pack for a message template.
1949
-     *
1950
-     * @since 4.5.0
1951
-     * @throws EE_Error
1952
-     * @throws InvalidDataTypeException
1953
-     * @throws InvalidInterfaceException
1954
-     * @throws InvalidArgumentException
1955
-     * @throws ReflectionException
1956
-     */
1957
-    public function switch_template_pack()
1958
-    {
1959
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1960
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1961
-
1962
-        // verify we have needed values.
1963
-        if (empty($GRP_ID) || empty($template_pack)) {
1964
-            $this->_template_args['error'] = true;
1965
-            EE_Error::add_error(
1966
-                esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1967
-                __FILE__,
1968
-                __FUNCTION__,
1969
-                __LINE__
1970
-            );
1971
-        } else {
1972
-            // get template, set the new template_pack and then reset to default
1973
-            /** @type EE_Message_Template_Group $message_template_group */
1974
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1975
-
1976
-            $message_template_group->set_template_pack_name($template_pack);
1977
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1978
-            $this->_req_data['mt'] = $message_template_group->message_type();
1979
-
1980
-            $query_args = $this->_reset_to_default_template();
1981
-
1982
-            if (empty($query_args['id'])) {
1983
-                EE_Error::add_error(
1984
-                    esc_html__(
1985
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1986
-                        'event_espresso'
1987
-                    ),
1988
-                    __FILE__,
1989
-                    __FUNCTION__,
1990
-                    __LINE__
1991
-                );
1992
-                $this->_template_args['error'] = true;
1993
-            } else {
1994
-                $template_label = $message_template_group->get_template_pack()->label;
1995
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1996
-                EE_Error::add_success(
1997
-                    sprintf(
1998
-                        esc_html__(
1999
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
2000
-                            'event_espresso'
2001
-                        ),
2002
-                        $template_label,
2003
-                        $template_pack_labels->template_pack
2004
-                    )
2005
-                );
2006
-                // generate the redirect url for js.
2007
-                $url = self::add_query_args_and_nonce(
2008
-                    $query_args,
2009
-                    $this->_admin_base_url
2010
-                );
2011
-                $this->_template_args['data']['redirect_url'] = $url;
2012
-                $this->_template_args['success'] = true;
2013
-            }
2014
-
2015
-            $this->_return_json();
2016
-        }
2017
-    }
2018
-
2019
-
2020
-    /**
2021
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2022
-     * they want.
2023
-     *
2024
-     * @access protected
2025
-     * @return array|null
2026
-     * @throws EE_Error
2027
-     * @throws InvalidArgumentException
2028
-     * @throws InvalidDataTypeException
2029
-     * @throws InvalidInterfaceException
2030
-     */
2031
-    protected function _reset_to_default_template()
2032
-    {
2033
-
2034
-        $templates = array();
2035
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2036
-        // we need to make sure we've got the info we need.
2037
-        if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2038
-            EE_Error::add_error(
2039
-                esc_html__(
2040
-                    '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.',
2041
-                    'event_espresso'
2042
-                ),
2043
-                __FILE__,
2044
-                __FUNCTION__,
2045
-                __LINE__
2046
-            );
2047
-        }
2048
-
2049
-        // all templates will be reset to whatever the defaults are
2050
-        // for the global template matching the messenger and message type.
2051
-        $success = ! empty($GRP_ID) ? true : false;
2052
-
2053
-        if ($success) {
2054
-            // let's first determine if the incoming template is a global template,
2055
-            // if it isn't then we need to get the global template matching messenger and message type.
2056
-            // $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2057
-
2058
-
2059
-            // note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2060
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
2061
-
2062
-            if ($success) {
2063
-                // if successfully deleted, lets generate the new ones.
2064
-                // Note. We set GLOBAL to true, because resets on ANY template
2065
-                // will use the related global template defaults for regeneration.
2066
-                // This means that if a custom template is reset it resets to whatever the related global template is.
2067
-                // HOWEVER, we DO keep the template pack and template variation set
2068
-                // for the current custom template when resetting.
2069
-                $templates = $this->_generate_new_templates(
2070
-                    $this->_req_data['msgr'],
2071
-                    $this->_req_data['mt'],
2072
-                    $GRP_ID,
2073
-                    true
2074
-                );
2075
-            }
2076
-        }
2077
-
2078
-        // any error messages?
2079
-        if (! $success) {
2080
-            EE_Error::add_error(
2081
-                esc_html__(
2082
-                    'Something went wrong with deleting existing templates. Unable to reset to default',
2083
-                    'event_espresso'
2084
-                ),
2085
-                __FILE__,
2086
-                __FUNCTION__,
2087
-                __LINE__
2088
-            );
2089
-        }
2090
-
2091
-        // all good, let's add a success message!
2092
-        if ($success && ! empty($templates)) {
2093
-            // the info for the template we generated is the first element in the returned array
2094
-            // $templates = $templates[0];
2095
-            EE_Error::overwrite_success();
2096
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2097
-        }
2098
-
2099
-
2100
-        $query_args = array(
2101
-            'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2102
-            'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2103
-            'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2104
-        );
2105
-
2106
-        // if called via ajax then we return query args otherwise redirect
2107
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2108
-            return $query_args;
2109
-        } else {
2110
-            $this->_redirect_after_action(false, '', '', $query_args, true);
2111
-
2112
-            return null;
2113
-        }
2114
-    }
2115
-
2116
-
2117
-    /**
2118
-     * Retrieve and set the message preview for display.
2119
-     *
2120
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2121
-     * @return string
2122
-     * @throws ReflectionException
2123
-     * @throws EE_Error
2124
-     * @throws InvalidArgumentException
2125
-     * @throws InvalidDataTypeException
2126
-     * @throws InvalidInterfaceException
2127
-     */
2128
-    public function _preview_message($send = false)
2129
-    {
2130
-        // first make sure we've got the necessary parameters
2131
-        if (! isset(
2132
-            $this->_req_data['message_type'],
2133
-            $this->_req_data['messenger'],
2134
-            $this->_req_data['messenger'],
2135
-            $this->_req_data['GRP_ID']
2136
-        )) {
2137
-            EE_Error::add_error(
2138
-                esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2139
-                __FILE__,
2140
-                __FUNCTION__,
2141
-                __LINE__
2142
-            );
2143
-        }
2144
-
2145
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
22
+	/**
23
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
24
+	 */
25
+	protected $_message_resource_manager;
26
+
27
+	/**
28
+	 * @type string $_active_message_type_name
29
+	 */
30
+	protected $_active_message_type_name = '';
31
+
32
+	/**
33
+	 * @type EE_messenger $_active_messenger
34
+	 */
35
+	protected $_active_messenger;
36
+	protected $_activate_state;
37
+	protected $_activate_meta_box_type;
38
+	protected $_current_message_meta_box;
39
+	protected $_current_message_meta_box_object;
40
+	protected $_context_switcher;
41
+	protected $_shortcodes = array();
42
+	protected $_active_messengers = array();
43
+	protected $_active_message_types = array();
44
+
45
+	/**
46
+	 * @var EE_Message_Template_Group $_message_template_group
47
+	 */
48
+	protected $_message_template_group;
49
+	protected $_m_mt_settings = array();
50
+
51
+
52
+	/**
53
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
+	 * IF there is no group then it gets automatically set to the Default template pack.
55
+	 *
56
+	 * @since 4.5.0
57
+	 *
58
+	 * @var EE_Messages_Template_Pack
59
+	 */
60
+	protected $_template_pack;
61
+
62
+
63
+	/**
64
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
+	 * group is.  If there is no group then it automatically gets set to default.
66
+	 *
67
+	 * @since 4.5.0
68
+	 *
69
+	 * @var string
70
+	 */
71
+	protected $_variation;
72
+
73
+
74
+	/**
75
+	 * @param bool $routing
76
+	 * @throws EE_Error
77
+	 */
78
+	public function __construct($routing = true)
79
+	{
80
+		// make sure messages autoloader is running
81
+		EED_Messages::set_autoloaders();
82
+		parent::__construct($routing);
83
+	}
84
+
85
+
86
+	protected function _init_page_props()
87
+	{
88
+		$this->page_slug = EE_MSG_PG_SLUG;
89
+		$this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
+		$this->_admin_base_url = EE_MSG_ADMIN_URL;
91
+		$this->_admin_base_path = EE_MSG_ADMIN;
92
+
93
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
+			: array();
95
+
96
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
+		$this->_load_message_resource_manager();
98
+	}
99
+
100
+
101
+	/**
102
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
+	 *
104
+	 * @throws EE_Error
105
+	 * @throws InvalidDataTypeException
106
+	 * @throws InvalidInterfaceException
107
+	 * @throws InvalidArgumentException
108
+	 * @throws ReflectionException
109
+	 */
110
+	protected function _load_message_resource_manager()
111
+	{
112
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
+	}
114
+
115
+
116
+	/**
117
+	 * @deprecated 4.9.9.rc.014
118
+	 * @return array
119
+	 * @throws EE_Error
120
+	 * @throws InvalidArgumentException
121
+	 * @throws InvalidDataTypeException
122
+	 * @throws InvalidInterfaceException
123
+	 */
124
+	public function get_messengers_for_list_table()
125
+	{
126
+		EE_Error::doing_it_wrong(
127
+			__METHOD__,
128
+			sprintf(
129
+				esc_html__(
130
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
+					'event_espresso'
132
+				),
133
+				'Messages_Admin_Page::get_messengers_select_input()'
134
+			),
135
+			'4.9.9.rc.014'
136
+		);
137
+
138
+		$m_values = array();
139
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
+		// setup messengers for selects
141
+		$i = 1;
142
+		foreach ($active_messengers as $active_messenger) {
143
+			if ($active_messenger instanceof EE_Message) {
144
+				$m_values[ $i ]['id'] = $active_messenger->messenger();
145
+				$m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
+				$i++;
147
+			}
148
+		}
149
+
150
+		return $m_values;
151
+	}
152
+
153
+
154
+	/**
155
+	 * @deprecated 4.9.9.rc.014
156
+	 * @return array
157
+	 * @throws EE_Error
158
+	 * @throws InvalidArgumentException
159
+	 * @throws InvalidDataTypeException
160
+	 * @throws InvalidInterfaceException
161
+	 */
162
+	public function get_message_types_for_list_table()
163
+	{
164
+		EE_Error::doing_it_wrong(
165
+			__METHOD__,
166
+			sprintf(
167
+				esc_html__(
168
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
+					'event_espresso'
170
+				),
171
+				'Messages_Admin_Page::get_message_types_select_input()'
172
+			),
173
+			'4.9.9.rc.014'
174
+		);
175
+
176
+		$mt_values = array();
177
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
+		$i = 1;
179
+		foreach ($active_messages as $active_message) {
180
+			if ($active_message instanceof EE_Message) {
181
+				$mt_values[ $i ]['id'] = $active_message->message_type();
182
+				$mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
+				$i++;
184
+			}
185
+		}
186
+
187
+		return $mt_values;
188
+	}
189
+
190
+
191
+	/**
192
+	 * @deprecated 4.9.9.rc.014
193
+	 * @return array
194
+	 * @throws EE_Error
195
+	 * @throws InvalidArgumentException
196
+	 * @throws InvalidDataTypeException
197
+	 * @throws InvalidInterfaceException
198
+	 */
199
+	public function get_contexts_for_message_types_for_list_table()
200
+	{
201
+		EE_Error::doing_it_wrong(
202
+			__METHOD__,
203
+			sprintf(
204
+				esc_html__(
205
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
+					'event_espresso'
207
+				),
208
+				'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
+			),
210
+			'4.9.9.rc.014'
211
+		);
212
+
213
+		$contexts = array();
214
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
+		foreach ($active_message_contexts as $active_message) {
216
+			if ($active_message instanceof EE_Message) {
217
+				$message_type = $active_message->message_type_object();
218
+				if ($message_type instanceof EE_message_type) {
219
+					$message_type_contexts = $message_type->get_contexts();
220
+					foreach ($message_type_contexts as $context => $context_details) {
221
+						$contexts[ $context ] = $context_details['label'];
222
+					}
223
+				}
224
+			}
225
+		}
226
+
227
+		return $contexts;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Generate select input with provided messenger options array.
233
+	 *
234
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
+	 *                                 labels.
236
+	 * @return string
237
+	 * @throws EE_Error
238
+	 */
239
+	public function get_messengers_select_input($messenger_options)
240
+	{
241
+		// if empty or just one value then just return an empty string
242
+		if (empty($messenger_options)
243
+			|| ! is_array($messenger_options)
244
+			|| count($messenger_options) === 1
245
+		) {
246
+			return '';
247
+		}
248
+		// merge in default
249
+		$messenger_options = array_merge(
250
+			array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
+			$messenger_options
252
+		);
253
+		$input = new EE_Select_Input(
254
+			$messenger_options,
255
+			array(
256
+				'html_name'  => 'ee_messenger_filter_by',
257
+				'html_id'    => 'ee_messenger_filter_by',
258
+				'html_class' => 'wide',
259
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
+					: 'none_selected',
262
+			)
263
+		);
264
+
265
+		return $input->get_html_for_input();
266
+	}
267
+
268
+
269
+	/**
270
+	 * Generate select input with provided message type options array.
271
+	 *
272
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
+	 *                                    message type labels
274
+	 * @return string
275
+	 * @throws EE_Error
276
+	 */
277
+	public function get_message_types_select_input($message_type_options)
278
+	{
279
+		// if empty or count of options is 1 then just return an empty string
280
+		if (empty($message_type_options)
281
+			|| ! is_array($message_type_options)
282
+			|| count($message_type_options) === 1
283
+		) {
284
+			return '';
285
+		}
286
+		// merge in default
287
+		$message_type_options = array_merge(
288
+			array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
+			$message_type_options
290
+		);
291
+		$input = new EE_Select_Input(
292
+			$message_type_options,
293
+			array(
294
+				'html_name'  => 'ee_message_type_filter_by',
295
+				'html_id'    => 'ee_message_type_filter_by',
296
+				'html_class' => 'wide',
297
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
+					: 'none_selected',
300
+			)
301
+		);
302
+
303
+		return $input->get_html_for_input();
304
+	}
305
+
306
+
307
+	/**
308
+	 * Generate select input with provide message type contexts array.
309
+	 *
310
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
+	 *                               context label.
312
+	 * @return string
313
+	 * @throws EE_Error
314
+	 */
315
+	public function get_contexts_for_message_types_select_input($context_options)
316
+	{
317
+		// if empty or count of options is one then just return empty string
318
+		if (empty($context_options)
319
+			|| ! is_array($context_options)
320
+			|| count($context_options) === 1
321
+		) {
322
+			return '';
323
+		}
324
+		// merge in default
325
+		$context_options = array_merge(
326
+			array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
+			$context_options
328
+		);
329
+		$input = new EE_Select_Input(
330
+			$context_options,
331
+			array(
332
+				'html_name'  => 'ee_context_filter_by',
333
+				'html_id'    => 'ee_context_filter_by',
334
+				'html_class' => 'wide',
335
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
336
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
337
+					: 'none_selected',
338
+			)
339
+		);
340
+
341
+		return $input->get_html_for_input();
342
+	}
343
+
344
+
345
+	protected function _ajax_hooks()
346
+	{
347
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
+		add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
+	}
354
+
355
+
356
+	protected function _define_page_props()
357
+	{
358
+		$this->_admin_page_title = $this->page_label;
359
+		$this->_labels = array(
360
+			'buttons'    => array(
361
+				'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
+				'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
+				'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
+			),
365
+			'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
+		);
367
+	}
368
+
369
+
370
+	/**
371
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
372
+	 *
373
+	 * @access protected
374
+	 * @return void
375
+	 */
376
+	protected function _set_page_routes()
377
+	{
378
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
+			? $this->_req_data['GRP_ID']
380
+			: 0;
381
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
+			? $this->_req_data['id']
383
+			: $grp_id;
384
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
+			? $this->_req_data['MSG_ID']
386
+			: 0;
387
+
388
+		$this->_page_routes = array(
389
+			'default'                          => array(
390
+				'func'       => '_message_queue_list_table',
391
+				'capability' => 'ee_read_global_messages',
392
+			),
393
+			'global_mtps'                      => array(
394
+				'func'       => '_ee_default_messages_overview_list_table',
395
+				'capability' => 'ee_read_global_messages',
396
+			),
397
+			'custom_mtps'                      => array(
398
+				'func'       => '_custom_mtps_preview',
399
+				'capability' => 'ee_read_messages',
400
+			),
401
+			'add_new_message_template'         => array(
402
+				'func'       => '_add_message_template',
403
+				'capability' => 'ee_edit_messages',
404
+				'noheader'   => true,
405
+			),
406
+			'edit_message_template'            => array(
407
+				'func'       => '_edit_message_template',
408
+				'capability' => 'ee_edit_message',
409
+				'obj_id'     => $grp_id,
410
+			),
411
+			'preview_message'                  => array(
412
+				'func'               => '_preview_message',
413
+				'capability'         => 'ee_read_message',
414
+				'obj_id'             => $grp_id,
415
+				'noheader'           => true,
416
+				'headers_sent_route' => 'display_preview_message',
417
+			),
418
+			'display_preview_message'          => array(
419
+				'func'       => '_display_preview_message',
420
+				'capability' => 'ee_read_message',
421
+				'obj_id'     => $grp_id,
422
+			),
423
+			'insert_message_template'          => array(
424
+				'func'       => '_insert_or_update_message_template',
425
+				'capability' => 'ee_edit_messages',
426
+				'args'       => array('new' => true),
427
+				'noheader'   => true,
428
+			),
429
+			'update_message_template'          => array(
430
+				'func'       => '_insert_or_update_message_template',
431
+				'capability' => 'ee_edit_message',
432
+				'obj_id'     => $grp_id,
433
+				'args'       => array('new' => false),
434
+				'noheader'   => true,
435
+			),
436
+			'trash_message_template'           => array(
437
+				'func'       => '_trash_or_restore_message_template',
438
+				'capability' => 'ee_delete_message',
439
+				'obj_id'     => $grp_id,
440
+				'args'       => array('trash' => true, 'all' => true),
441
+				'noheader'   => true,
442
+			),
443
+			'trash_message_template_context'   => array(
444
+				'func'       => '_trash_or_restore_message_template',
445
+				'capability' => 'ee_delete_message',
446
+				'obj_id'     => $grp_id,
447
+				'args'       => array('trash' => true),
448
+				'noheader'   => true,
449
+			),
450
+			'restore_message_template'         => array(
451
+				'func'       => '_trash_or_restore_message_template',
452
+				'capability' => 'ee_delete_message',
453
+				'obj_id'     => $grp_id,
454
+				'args'       => array('trash' => false, 'all' => true),
455
+				'noheader'   => true,
456
+			),
457
+			'restore_message_template_context' => array(
458
+				'func'       => '_trash_or_restore_message_template',
459
+				'capability' => 'ee_delete_message',
460
+				'obj_id'     => $grp_id,
461
+				'args'       => array('trash' => false),
462
+				'noheader'   => true,
463
+			),
464
+			'delete_message_template'          => array(
465
+				'func'       => '_delete_message_template',
466
+				'capability' => 'ee_delete_message',
467
+				'obj_id'     => $grp_id,
468
+				'noheader'   => true,
469
+			),
470
+			'reset_to_default'                 => array(
471
+				'func'       => '_reset_to_default_template',
472
+				'capability' => 'ee_edit_message',
473
+				'obj_id'     => $grp_id,
474
+				'noheader'   => true,
475
+			),
476
+			'settings'                         => array(
477
+				'func'       => '_settings',
478
+				'capability' => 'manage_options',
479
+			),
480
+			'update_global_settings'           => array(
481
+				'func'       => '_update_global_settings',
482
+				'capability' => 'manage_options',
483
+				'noheader'   => true,
484
+			),
485
+			'generate_now'                     => array(
486
+				'func'       => '_generate_now',
487
+				'capability' => 'ee_send_message',
488
+				'noheader'   => true,
489
+			),
490
+			'generate_and_send_now'            => array(
491
+				'func'       => '_generate_and_send_now',
492
+				'capability' => 'ee_send_message',
493
+				'noheader'   => true,
494
+			),
495
+			'queue_for_resending'              => array(
496
+				'func'       => '_queue_for_resending',
497
+				'capability' => 'ee_send_message',
498
+				'noheader'   => true,
499
+			),
500
+			'send_now'                         => array(
501
+				'func'       => '_send_now',
502
+				'capability' => 'ee_send_message',
503
+				'noheader'   => true,
504
+			),
505
+			'delete_ee_message'                => array(
506
+				'func'       => '_delete_ee_messages',
507
+				'capability' => 'ee_delete_messages',
508
+				'noheader'   => true,
509
+			),
510
+			'delete_ee_messages'               => array(
511
+				'func'       => '_delete_ee_messages',
512
+				'capability' => 'ee_delete_messages',
513
+				'noheader'   => true,
514
+				'obj_id'     => $msg_id,
515
+			),
516
+		);
517
+	}
518
+
519
+
520
+	protected function _set_page_config()
521
+	{
522
+		$this->_page_config = array(
523
+			'default'                  => array(
524
+				'nav'           => array(
525
+					'label' => esc_html__('Message Activity', 'event_espresso'),
526
+					'order' => 10,
527
+				),
528
+				'list_table'    => 'EE_Message_List_Table',
529
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
+				'require_nonce' => false,
531
+			),
532
+			'global_mtps'              => array(
533
+				'nav'           => array(
534
+					'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
+					'order' => 20,
536
+				),
537
+				'list_table'    => 'Messages_Template_List_Table',
538
+				'help_tabs'     => array(
539
+					'messages_overview_help_tab'                                => array(
540
+						'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
+						'filename' => 'messages_overview',
542
+					),
543
+					'messages_overview_messages_table_column_headings_help_tab' => array(
544
+						'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
+						'filename' => 'messages_overview_table_column_headings',
546
+					),
547
+					'messages_overview_messages_filters_help_tab'               => array(
548
+						'title'    => esc_html__('Message Filters', 'event_espresso'),
549
+						'filename' => 'messages_overview_filters',
550
+					),
551
+					'messages_overview_messages_views_help_tab'                 => array(
552
+						'title'    => esc_html__('Message Views', 'event_espresso'),
553
+						'filename' => 'messages_overview_views',
554
+					),
555
+					'message_overview_message_types_help_tab'                   => array(
556
+						'title'    => esc_html__('Message Types', 'event_espresso'),
557
+						'filename' => 'messages_overview_types',
558
+					),
559
+					'messages_overview_messengers_help_tab'                     => array(
560
+						'title'    => esc_html__('Messengers', 'event_espresso'),
561
+						'filename' => 'messages_overview_messengers',
562
+					),
563
+				),
564
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
565
+				// 'help_tour'     => array('Messages_Overview_Help_Tour'),
566
+				'require_nonce' => false,
567
+			),
568
+			'custom_mtps'              => array(
569
+				'nav'           => array(
570
+					'label' => esc_html__('Custom Message Templates', 'event_espresso'),
571
+					'order' => 30,
572
+				),
573
+				'help_tabs'     => array(),
574
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
575
+				// 'help_tour'     => array(),
576
+				'require_nonce' => false,
577
+			),
578
+			'add_new_message_template' => array(
579
+				'nav'           => array(
580
+					'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
581
+					'order'      => 5,
582
+					'persistent' => false,
583
+				),
584
+				'require_nonce' => false,
585
+			),
586
+			'edit_message_template'    => array(
587
+				'labels'        => array(
588
+					'buttons'    => array(
589
+						'reset' => esc_html__('Reset Templates', 'event_espresso'),
590
+					),
591
+					'publishbox' => esc_html__('Update Actions', 'event_espresso'),
592
+				),
593
+				'nav'           => array(
594
+					'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
595
+					'order'      => 5,
596
+					'persistent' => false,
597
+					'url'        => '',
598
+				),
599
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
600
+				'has_metaboxes' => true,
601
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
602
+				// 'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
603
+				'help_tabs'     => array(
604
+					'edit_message_template'            => array(
605
+						'title'    => esc_html__('Message Template Editor', 'event_espresso'),
606
+						'callback' => 'edit_message_template_help_tab',
607
+					),
608
+					'message_templates_help_tab'       => array(
609
+						'title'    => esc_html__('Message Templates', 'event_espresso'),
610
+						'filename' => 'messages_templates',
611
+					),
612
+					'message_template_shortcodes'      => array(
613
+						'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
614
+						'callback' => 'message_template_shortcodes_help_tab',
615
+					),
616
+					'message_preview_help_tab'         => array(
617
+						'title'    => esc_html__('Message Preview', 'event_espresso'),
618
+						'filename' => 'messages_preview',
619
+					),
620
+					'messages_overview_other_help_tab' => array(
621
+						'title'    => esc_html__('Messages Other', 'event_espresso'),
622
+						'filename' => 'messages_overview_other',
623
+					),
624
+				),
625
+				'require_nonce' => false,
626
+			),
627
+			'display_preview_message'  => array(
628
+				'nav'           => array(
629
+					'label'      => esc_html__('Message Preview', 'event_espresso'),
630
+					'order'      => 5,
631
+					'url'        => '',
632
+					'persistent' => false,
633
+				),
634
+				'help_tabs'     => array(
635
+					'preview_message' => array(
636
+						'title'    => esc_html__('About Previews', 'event_espresso'),
637
+						'callback' => 'preview_message_help_tab',
638
+					),
639
+				),
640
+				'require_nonce' => false,
641
+			),
642
+			'settings'                 => array(
643
+				'nav'           => array(
644
+					'label' => esc_html__('Settings', 'event_espresso'),
645
+					'order' => 40,
646
+				),
647
+				'metaboxes'     => array('_messages_settings_metaboxes'),
648
+				'help_tabs'     => array(
649
+					'messages_settings_help_tab'               => array(
650
+						'title'    => esc_html__('Messages Settings', 'event_espresso'),
651
+						'filename' => 'messages_settings',
652
+					),
653
+					'messages_settings_message_types_help_tab' => array(
654
+						'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
655
+						'filename' => 'messages_settings_message_types',
656
+					),
657
+					'messages_settings_messengers_help_tab'    => array(
658
+						'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
659
+						'filename' => 'messages_settings_messengers',
660
+					),
661
+				),
662
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
663
+				// 'help_tour'     => array('Messages_Settings_Help_Tour'),
664
+				'require_nonce' => false,
665
+			),
666
+		);
667
+	}
668
+
669
+
670
+	protected function _add_screen_options()
671
+	{
672
+		// todo
673
+	}
674
+
675
+
676
+	protected function _add_screen_options_global_mtps()
677
+	{
678
+		/**
679
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
680
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
681
+		 */
682
+		$page_title = $this->_admin_page_title;
683
+		$this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
684
+		$this->_per_page_screen_option();
685
+		$this->_admin_page_title = $page_title;
686
+	}
687
+
688
+
689
+	protected function _add_screen_options_default()
690
+	{
691
+		$this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
692
+		$this->_per_page_screen_option();
693
+	}
694
+
695
+
696
+	// none of the below group are currently used for Messages
697
+	protected function _add_feature_pointers()
698
+	{
699
+	}
700
+
701
+	public function admin_init()
702
+	{
703
+	}
704
+
705
+	public function admin_notices()
706
+	{
707
+	}
708
+
709
+	public function admin_footer_scripts()
710
+	{
711
+	}
712
+
713
+
714
+	public function messages_help_tab()
715
+	{
716
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
717
+	}
718
+
719
+
720
+	public function messengers_help_tab()
721
+	{
722
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
723
+	}
724
+
725
+
726
+	public function message_types_help_tab()
727
+	{
728
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
729
+	}
730
+
731
+
732
+	public function messages_overview_help_tab()
733
+	{
734
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
735
+	}
736
+
737
+
738
+	public function message_templates_help_tab()
739
+	{
740
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
741
+	}
742
+
743
+
744
+	public function edit_message_template_help_tab()
745
+	{
746
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
747
+						. esc_attr__('Editor Title', 'event_espresso')
748
+						. '" />';
749
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
750
+						. esc_attr__('Context Switcher and Preview', 'event_espresso')
751
+						. '" />';
752
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
753
+						. esc_attr__('Message Template Form Fields', 'event_espresso')
754
+						. '" />';
755
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
756
+						. esc_attr__('Shortcodes Metabox', 'event_espresso')
757
+						. '" />';
758
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
759
+						. esc_attr__('Publish Metabox', 'event_espresso')
760
+						. '" />';
761
+		EEH_Template::display_template(
762
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
763
+			$args
764
+		);
765
+	}
766
+
767
+
768
+	public function message_template_shortcodes_help_tab()
769
+	{
770
+		$this->_set_shortcodes();
771
+		$args['shortcodes'] = $this->_shortcodes;
772
+		EEH_Template::display_template(
773
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
774
+			$args
775
+		);
776
+	}
777
+
778
+
779
+	public function preview_message_help_tab()
780
+	{
781
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
782
+	}
783
+
784
+
785
+	public function settings_help_tab()
786
+	{
787
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
788
+						. '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
789
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
790
+						. '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
791
+		$args['img3'] = '<div class="switch">'
792
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
793
+						. ' type="checkbox" checked="checked">'
794
+						. '<label for="ee-on-off-toggle-on"></label>'
795
+						. '</div>';
796
+		$args['img4'] = '<div class="switch">'
797
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
798
+						. ' type="checkbox">'
799
+						. '<label for="ee-on-off-toggle-on"></label>'
800
+						. '</div>';
801
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
802
+	}
803
+
804
+
805
+	public function load_scripts_styles()
806
+	{
807
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
808
+		wp_enqueue_style('espresso_ee_msg');
809
+
810
+		wp_register_script(
811
+			'ee-messages-settings',
812
+			EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
813
+			array('jquery-ui-droppable', 'ee-serialize-full-array'),
814
+			EVENT_ESPRESSO_VERSION,
815
+			true
816
+		);
817
+		wp_register_script(
818
+			'ee-msg-list-table-js',
819
+			EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
820
+			array('ee-dialog'),
821
+			EVENT_ESPRESSO_VERSION
822
+		);
823
+	}
824
+
825
+
826
+	public function load_scripts_styles_default()
827
+	{
828
+		wp_enqueue_script('ee-msg-list-table-js');
829
+	}
830
+
831
+
832
+	public function wp_editor_css($mce_css)
833
+	{
834
+		// if we're on the edit_message_template route
835
+		if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
836
+			$message_type_name = $this->_active_message_type_name;
837
+
838
+			// we're going to REPLACE the existing mce css
839
+			// we need to get the css file location from the active messenger
840
+			$mce_css = $this->_active_messenger->get_variation(
841
+				$this->_template_pack,
842
+				$message_type_name,
843
+				true,
844
+				'wpeditor',
845
+				$this->_variation
846
+			);
847
+		}
848
+
849
+		return $mce_css;
850
+	}
851
+
852
+
853
+	public function load_scripts_styles_edit_message_template()
854
+	{
855
+
856
+		$this->_set_shortcodes();
857
+
858
+		EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
859
+			esc_html__(
860
+				'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.',
861
+				'event_espresso'
862
+			),
863
+			$this->_message_template_group->messenger_obj()->label['singular'],
864
+			$this->_message_template_group->message_type_obj()->label['singular']
865
+		);
866
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
867
+			'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?',
868
+			'event_espresso'
869
+		);
870
+		EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
871
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
872
+			'event_espresso'
873
+		);
874
+
875
+		wp_register_script(
876
+			'ee_msgs_edit_js',
877
+			EE_MSG_ASSETS_URL . 'ee_message_editor.js',
878
+			array('jquery'),
879
+			EVENT_ESPRESSO_VERSION
880
+		);
881
+
882
+		wp_enqueue_script('ee_admin_js');
883
+		wp_enqueue_script('ee_msgs_edit_js');
884
+
885
+		// add in special css for tiny_mce
886
+		add_filter('mce_css', array($this, 'wp_editor_css'));
887
+	}
888
+
889
+
890
+	public function load_scripts_styles_display_preview_message()
891
+	{
892
+
893
+		$this->_set_message_template_group();
894
+
895
+		if (isset($this->_req_data['messenger'])) {
896
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
897
+				$this->_req_data['messenger']
898
+			);
899
+		}
900
+
901
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
902
+
903
+
904
+		wp_enqueue_style(
905
+			'espresso_preview_css',
906
+			$this->_active_messenger->get_variation(
907
+				$this->_template_pack,
908
+				$message_type_name,
909
+				true,
910
+				'preview',
911
+				$this->_variation
912
+			)
913
+		);
914
+	}
915
+
916
+
917
+	public function load_scripts_styles_settings()
918
+	{
919
+		wp_register_style(
920
+			'ee-message-settings',
921
+			EE_MSG_ASSETS_URL . 'ee_message_settings.css',
922
+			array(),
923
+			EVENT_ESPRESSO_VERSION
924
+		);
925
+		wp_enqueue_style('ee-text-links');
926
+		wp_enqueue_style('ee-message-settings');
927
+		wp_enqueue_script('ee-messages-settings');
928
+	}
929
+
930
+
931
+	/**
932
+	 * set views array for List Table
933
+	 */
934
+	public function _set_list_table_views_global_mtps()
935
+	{
936
+		$this->_views = array(
937
+			'in_use' => array(
938
+				'slug'  => 'in_use',
939
+				'label' => esc_html__('In Use', 'event_espresso'),
940
+				'count' => 0,
941
+			),
942
+		);
943
+	}
944
+
945
+
946
+	/**
947
+	 * Set views array for the Custom Template List Table
948
+	 */
949
+	public function _set_list_table_views_custom_mtps()
950
+	{
951
+		$this->_set_list_table_views_global_mtps();
952
+		$this->_views['in_use']['bulk_action'] = array(
953
+			'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
954
+		);
955
+	}
956
+
957
+
958
+	/**
959
+	 * set views array for message queue list table
960
+	 *
961
+	 * @throws InvalidDataTypeException
962
+	 * @throws InvalidInterfaceException
963
+	 * @throws InvalidArgumentException
964
+	 * @throws EE_Error
965
+	 * @throws ReflectionException
966
+	 */
967
+	public function _set_list_table_views_default()
968
+	{
969
+		EE_Registry::instance()->load_helper('Template');
970
+
971
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
972
+			'ee_send_message',
973
+			'message_list_table_bulk_actions'
974
+		)
975
+			? array(
976
+				'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
977
+				'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
978
+				'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
979
+				'send_now'              => esc_html__('Send Now', 'event_espresso'),
980
+			)
981
+			: array();
982
+
983
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
984
+			'ee_delete_messages',
985
+			'message_list_table_bulk_actions'
986
+		)
987
+			? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
988
+			: array();
989
+
990
+
991
+		$this->_views = array(
992
+			'all' => array(
993
+				'slug'        => 'all',
994
+				'label'       => esc_html__('All', 'event_espresso'),
995
+				'count'       => 0,
996
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
997
+			),
998
+		);
999
+
1000
+
1001
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
1002
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
1003
+				continue;
1004
+			}
1005
+			$status_bulk_actions = $common_bulk_actions;
1006
+			// unset bulk actions not applying to status
1007
+			if (! empty($status_bulk_actions)) {
1008
+				switch ($status) {
1009
+					case EEM_Message::status_idle:
1010
+					case EEM_Message::status_resend:
1011
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1012
+						break;
1013
+
1014
+					case EEM_Message::status_failed:
1015
+					case EEM_Message::status_debug_only:
1016
+					case EEM_Message::status_messenger_executing:
1017
+						$status_bulk_actions = array();
1018
+						break;
1019
+
1020
+					case EEM_Message::status_incomplete:
1021
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1022
+						break;
1023
+
1024
+					case EEM_Message::status_retry:
1025
+					case EEM_Message::status_sent:
1026
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1027
+						break;
1028
+				}
1029
+			}
1030
+
1031
+			// skip adding messenger executing status to views because it will be included with the Failed view.
1032
+			if ($status === EEM_Message::status_messenger_executing) {
1033
+				continue;
1034
+			}
1035
+
1036
+			$this->_views[ strtolower($status) ] = array(
1037
+				'slug'        => strtolower($status),
1038
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1039
+				'count'       => 0,
1040
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1041
+			);
1042
+		}
1043
+	}
1044
+
1045
+
1046
+	protected function _ee_default_messages_overview_list_table()
1047
+	{
1048
+		$this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1049
+		$this->display_admin_list_table_page_with_no_sidebar();
1050
+	}
1051
+
1052
+
1053
+	protected function _message_queue_list_table()
1054
+	{
1055
+		$this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1056
+		$this->_template_args['per_column'] = 6;
1057
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1058
+		$this->_template_args['before_list_table'] = '<h3>'
1059
+													 . EEM_Message::instance()->get_pretty_label_for_results()
1060
+													 . '</h3>';
1061
+		$this->display_admin_list_table_page_with_no_sidebar();
1062
+	}
1063
+
1064
+
1065
+	protected function _message_legend_items()
1066
+	{
1067
+
1068
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
1069
+		$action_items = array();
1070
+
1071
+		foreach ($action_css_classes as $action_item => $action_details) {
1072
+			if ($action_item === 'see_notifications_for') {
1073
+				continue;
1074
+			}
1075
+			$action_items[ $action_item ] = array(
1076
+				'class' => $action_details['css_class'],
1077
+				'desc'  => $action_details['label'],
1078
+			);
1079
+		}
1080
+
1081
+		/** @type array $status_items status legend setup */
1082
+		$status_items = array(
1083
+			'sent_status'                => array(
1084
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1085
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1086
+			),
1087
+			'idle_status'                => array(
1088
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1089
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1090
+			),
1091
+			'failed_status'              => array(
1092
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1093
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1094
+			),
1095
+			'messenger_executing_status' => array(
1096
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1097
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1098
+			),
1099
+			'resend_status'              => array(
1100
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1101
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1102
+			),
1103
+			'incomplete_status'          => array(
1104
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1105
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1106
+			),
1107
+			'retry_status'               => array(
1108
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1109
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1110
+			),
1111
+		);
1112
+		if (EEM_Message::debug()) {
1113
+			$status_items['debug_only_status'] = array(
1114
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1115
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1116
+			);
1117
+		}
1118
+
1119
+		return array_merge($action_items, $status_items);
1120
+	}
1121
+
1122
+
1123
+	protected function _custom_mtps_preview()
1124
+	{
1125
+		$this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1126
+		$this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1127
+											   . ' alt="' . esc_attr__(
1128
+												   'Preview Custom Message Templates screenshot',
1129
+												   'event_espresso'
1130
+											   ) . '" />';
1131
+		$this->_template_args['preview_text'] = '<strong>'
1132
+												. esc_html__(
1133
+													'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1134
+													'event_espresso'
1135
+												)
1136
+												. '</strong>';
1137
+
1138
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1139
+	}
1140
+
1141
+
1142
+	/**
1143
+	 * get_message_templates
1144
+	 * This gets all the message templates for listing on the overview list.
1145
+	 *
1146
+	 * @access public
1147
+	 * @param int    $perpage the amount of templates groups to show per page
1148
+	 * @param string $type    the current _view we're getting templates for
1149
+	 * @param bool   $count   return count?
1150
+	 * @param bool   $all     disregard any paging info (get all data);
1151
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1152
+	 * @return array
1153
+	 * @throws EE_Error
1154
+	 * @throws InvalidArgumentException
1155
+	 * @throws InvalidDataTypeException
1156
+	 * @throws InvalidInterfaceException
1157
+	 */
1158
+	public function get_message_templates(
1159
+		$perpage = 10,
1160
+		$type = 'in_use',
1161
+		$count = false,
1162
+		$all = false,
1163
+		$global = true
1164
+	) {
1165
+
1166
+		$MTP = EEM_Message_Template_Group::instance();
1167
+
1168
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1169
+		$orderby = $this->_req_data['orderby'];
1170
+
1171
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1172
+			? $this->_req_data['order']
1173
+			: 'ASC';
1174
+
1175
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1176
+			? $this->_req_data['paged']
1177
+			: 1;
1178
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1179
+			? $this->_req_data['perpage']
1180
+			: $perpage;
1181
+
1182
+		$offset = ($current_page - 1) * $per_page;
1183
+		$limit = $all ? null : array($offset, $per_page);
1184
+
1185
+
1186
+		// options will match what is in the _views array property
1187
+		switch ($type) {
1188
+			case 'in_use':
1189
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1190
+				break;
1191
+			default:
1192
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1193
+		}
1194
+
1195
+		return $templates;
1196
+	}
1197
+
1198
+
1199
+	/**
1200
+	 * filters etc might need a list of installed message_types
1201
+	 *
1202
+	 * @return array an array of message type objects
1203
+	 */
1204
+	public function get_installed_message_types()
1205
+	{
1206
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1207
+		$installed = array();
1208
+
1209
+		foreach ($installed_message_types as $message_type) {
1210
+			$installed[ $message_type->name ] = $message_type;
1211
+		}
1212
+
1213
+		return $installed;
1214
+	}
1215
+
1216
+
1217
+	/**
1218
+	 * _add_message_template
1219
+	 *
1220
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1221
+	 *
1222
+	 * @param string $message_type
1223
+	 * @param string $messenger
1224
+	 * @param string $GRP_ID
1225
+	 *
1226
+	 * @throws EE_error
1227
+	 */
1228
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1229
+	{
1230
+		// set values override any request data
1231
+		$message_type = ! empty($message_type) ? $message_type : '';
1232
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1233
+			? $this->_req_data['message_type']
1234
+			: $message_type;
1235
+
1236
+		$messenger = ! empty($messenger) ? $messenger : '';
1237
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1238
+			? $this->_req_data['messenger']
1239
+			: $messenger;
1240
+
1241
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1242
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1243
+
1244
+		// we need messenger and message type.  They should be coming from the event editor. If not here then return error
1245
+		if (empty($message_type) || empty($messenger)) {
1246
+			throw new EE_Error(
1247
+				esc_html__(
1248
+					'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1249
+					'event_espresso'
1250
+				)
1251
+			);
1252
+		}
1253
+
1254
+		// we need the GRP_ID for the template being used as the base for the new template
1255
+		if (empty($GRP_ID)) {
1256
+			throw new EE_Error(
1257
+				esc_html__(
1258
+					'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1259
+					'event_espresso'
1260
+				)
1261
+			);
1262
+		}
1263
+
1264
+		// let's just make sure the template gets generated!
1265
+
1266
+		// we need to reassign some variables for what the insert is expecting
1267
+		$this->_req_data['MTP_messenger'] = $messenger;
1268
+		$this->_req_data['MTP_message_type'] = $message_type;
1269
+		$this->_req_data['GRP_ID'] = $GRP_ID;
1270
+		$this->_insert_or_update_message_template(true);
1271
+	}
1272
+
1273
+
1274
+	/**
1275
+	 * public wrapper for the _add_message_template method
1276
+	 *
1277
+	 * @param string $message_type     message type slug
1278
+	 * @param string $messenger        messenger slug
1279
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1280
+	 *                                 off of.
1281
+	 * @throws EE_error
1282
+	 */
1283
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1284
+	{
1285
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1286
+	}
1287
+
1288
+
1289
+	/**
1290
+	 * _edit_message_template
1291
+	 *
1292
+	 * @access protected
1293
+	 * @return void
1294
+	 * @throws InvalidIdentifierException
1295
+	 * @throws DomainException
1296
+	 * @throws EE_Error
1297
+	 * @throws InvalidArgumentException
1298
+	 * @throws ReflectionException
1299
+	 * @throws InvalidDataTypeException
1300
+	 * @throws InvalidInterfaceException
1301
+	 */
1302
+	protected function _edit_message_template()
1303
+	{
1304
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1305
+		$template_fields = '';
1306
+		$sidebar_fields = '';
1307
+		// we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1308
+		// valid html in the templates.
1309
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1310
+
1311
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1312
+			? absint($this->_req_data['id'])
1313
+			: false;
1314
+
1315
+		$EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
1316
+		? absint($this->_req_data['evt_id'])
1317
+		: false;
1318
+
1319
+		$this->_set_shortcodes(); // this also sets the _message_template property.
1320
+		$message_template_group = $this->_message_template_group;
1321
+		$c_label = $message_template_group->context_label();
1322
+		$c_config = $message_template_group->contexts_config();
1323
+
1324
+		reset($c_config);
1325
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1326
+			? strtolower($this->_req_data['context'])
1327
+			: key($c_config);
1328
+
1329
+
1330
+		if (empty($GRP_ID)) {
1331
+			$action = 'insert_message_template';
1332
+			$edit_message_template_form_url = add_query_arg(
1333
+				array('action' => $action, 'noheader' => true),
1334
+				EE_MSG_ADMIN_URL
1335
+			);
1336
+		} else {
1337
+			$action = 'update_message_template';
1338
+			$edit_message_template_form_url = add_query_arg(
1339
+				array('action' => $action, 'noheader' => true),
1340
+				EE_MSG_ADMIN_URL
1341
+			);
1342
+		}
1343
+
1344
+		// set active messenger for this view
1345
+		$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1346
+			$message_template_group->messenger()
1347
+		);
1348
+		$this->_active_message_type_name = $message_template_group->message_type();
1349
+
1350
+
1351
+		// Do we have any validation errors?
1352
+		$validators = $this->_get_transient();
1353
+		$v_fields = ! empty($validators) ? array_keys($validators) : array();
1354
+
1355
+
1356
+		// we need to assemble the title from Various details
1357
+		$context_label = sprintf(
1358
+			esc_html__('(%s %s)', 'event_espresso'),
1359
+			$c_config[ $context ]['label'],
1360
+			ucwords($c_label['label'])
1361
+		);
1362
+
1363
+		$title = sprintf(
1364
+			esc_html__(' %s %s Template %s', 'event_espresso'),
1365
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1366
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1367
+			$context_label
1368
+		);
1369
+
1370
+		$this->_template_args['GRP_ID'] = $GRP_ID;
1371
+		$this->_template_args['message_template'] = $message_template_group;
1372
+		$this->_template_args['is_extra_fields'] = false;
1373
+
1374
+
1375
+		// let's get EEH_MSG_Template so we can get template form fields
1376
+		$template_field_structure = EEH_MSG_Template::get_fields(
1377
+			$message_template_group->messenger(),
1378
+			$message_template_group->message_type()
1379
+		);
1380
+
1381
+		if (! $template_field_structure) {
1382
+			$template_field_structure = false;
1383
+			$template_fields = esc_html__(
1384
+				'There was an error in assembling the fields for this display (you should see an error message)',
1385
+				'event_espresso'
1386
+			);
1387
+		}
1388
+
1389
+
1390
+		$message_templates = $message_template_group->context_templates();
1391
+
1392
+
1393
+		// if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1394
+		// will get handled in the "extra" array.
1395
+		if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1396
+			foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1397
+				unset($template_field_structure[ $context ][ $reference_field ]);
1398
+			}
1399
+		}
1400
+
1401
+		// let's loop through the template_field_structure and actually assemble the input fields!
1402
+		if (! empty($template_field_structure)) {
1403
+			foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1404
+				// if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1405
+				// the extra array and reset them.
1406
+				if ($template_field === 'extra') {
1407
+					$this->_template_args['is_extra_fields'] = true;
1408
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1409
+						$message_template = $message_templates[ $context ][ $reference_field ];
1410
+						$content = $message_template instanceof EE_Message_Template
1411
+							? $message_template->get('MTP_content')
1412
+							: '';
1413
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1414
+							// let's verify if we need this extra field via the shortcodes parameter.
1415
+							$continue = false;
1416
+							if (isset($extra_array['shortcodes_required'])) {
1417
+								foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1418
+									if (! array_key_exists($shortcode, $this->_shortcodes)) {
1419
+										$continue = true;
1420
+									}
1421
+								}
1422
+								if ($continue) {
1423
+									continue;
1424
+								}
1425
+							}
1426
+
1427
+							$field_id = $reference_field
1428
+										. '-'
1429
+										. $extra_field
1430
+										. '-content';
1431
+							$template_form_fields[ $field_id ] = $extra_array;
1432
+							$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1433
+																		 . $reference_field
1434
+																		 . '][content]['
1435
+																		 . $extra_field . ']';
1436
+							$css_class = isset($extra_array['css_class'])
1437
+								? $extra_array['css_class']
1438
+								: '';
1439
+
1440
+							$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1441
+																			  && in_array($extra_field, $v_fields, true)
1442
+																			  &&
1443
+																			  (
1444
+																				  is_array($validators[ $extra_field ])
1445
+																				  && isset($validators[ $extra_field ]['msg'])
1446
+																			  )
1447
+								? 'validate-error ' . $css_class
1448
+								: $css_class;
1449
+
1450
+							$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1451
+																		  && isset($content[ $extra_field ])
1452
+								? $content[ $extra_field ]
1453
+								: '';
1454
+
1455
+							// do we have a validation error?  if we do then let's use that value instead
1456
+							$template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1457
+								? $validators[ $extra_field ]['value']
1458
+								: $template_form_fields[ $field_id ]['value'];
1459
+
1460
+
1461
+							$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1462
+
1463
+							// shortcode selector
1464
+							$field_name_to_use = $extra_field === 'main'
1465
+								? 'content'
1466
+								: $extra_field;
1467
+							$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1468
+								$field_name_to_use,
1469
+								$field_id
1470
+							);
1471
+
1472
+							if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1473
+								// we want to decode the entities
1474
+								$template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1475
+							}/**/
1476
+						}
1477
+						$templatefield_MTP_id = $reference_field . '-MTP_ID';
1478
+						$templatefield_templatename_id = $reference_field . '-name';
1479
+
1480
+						$template_form_fields[ $templatefield_MTP_id ] = array(
1481
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1482
+							'label'      => null,
1483
+							'input'      => 'hidden',
1484
+							'type'       => 'int',
1485
+							'required'   => false,
1486
+							'validation' => false,
1487
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1488
+							'css_class'  => '',
1489
+							'format'     => '%d',
1490
+							'db-col'     => 'MTP_ID',
1491
+						);
1492
+
1493
+						$template_form_fields[ $templatefield_templatename_id ] = array(
1494
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1495
+							'label'      => null,
1496
+							'input'      => 'hidden',
1497
+							'type'       => 'string',
1498
+							'required'   => false,
1499
+							'validation' => true,
1500
+							'value'      => $reference_field,
1501
+							'css_class'  => '',
1502
+							'format'     => '%s',
1503
+							'db-col'     => 'MTP_template_field',
1504
+						);
1505
+					}
1506
+					continue; // skip the next stuff, we got the necessary fields here for this dataset.
1507
+				} else {
1508
+					$field_id = $template_field . '-content';
1509
+					$template_form_fields[ $field_id ] = $field_setup_array;
1510
+					$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1511
+					$message_template = isset($message_templates[ $context ][ $template_field ])
1512
+						? $message_templates[ $context ][ $template_field ]
1513
+						: null;
1514
+					$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1515
+																  && is_array($message_templates[ $context ])
1516
+																  && $message_template instanceof EE_Message_Template
1517
+						? $message_template->get('MTP_content')
1518
+						: '';
1519
+
1520
+					// do we have a validator error for this field?  if we do then we'll use that value instead
1521
+					$template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1522
+						? $validators[ $template_field ]['value']
1523
+						: $template_form_fields[ $field_id ]['value'];
1524
+
1525
+
1526
+					$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1527
+					$css_class = isset($field_setup_array['css_class'])
1528
+						? $field_setup_array['css_class']
1529
+						: '';
1530
+					$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1531
+																	  && in_array($template_field, $v_fields, true)
1532
+																	  && isset($validators[ $template_field ]['msg'])
1533
+						? 'validate-error ' . $css_class
1534
+						: $css_class;
1535
+
1536
+					// shortcode selector
1537
+					$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1538
+						$template_field,
1539
+						$field_id
1540
+					);
1541
+				}
1542
+
1543
+				// k took care of content field(s) now let's take care of others.
1544
+
1545
+				$templatefield_MTP_id = $template_field . '-MTP_ID';
1546
+				$templatefield_field_templatename_id = $template_field . '-name';
1547
+
1548
+				// foreach template field there are actually two form fields created
1549
+				$template_form_fields[ $templatefield_MTP_id ] = array(
1550
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1551
+					'label'      => null,
1552
+					'input'      => 'hidden',
1553
+					'type'       => 'int',
1554
+					'required'   => false,
1555
+					'validation' => true,
1556
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1557
+					'css_class'  => '',
1558
+					'format'     => '%d',
1559
+					'db-col'     => 'MTP_ID',
1560
+				);
1561
+
1562
+				$template_form_fields[ $templatefield_field_templatename_id ] = array(
1563
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1564
+					'label'      => null,
1565
+					'input'      => 'hidden',
1566
+					'type'       => 'string',
1567
+					'required'   => false,
1568
+					'validation' => true,
1569
+					'value'      => $template_field,
1570
+					'css_class'  => '',
1571
+					'format'     => '%s',
1572
+					'db-col'     => 'MTP_template_field',
1573
+				);
1574
+			}
1575
+
1576
+			// add other fields
1577
+			$template_form_fields['ee-msg-current-context'] = array(
1578
+				'name'       => 'MTP_context',
1579
+				'label'      => null,
1580
+				'input'      => 'hidden',
1581
+				'type'       => 'string',
1582
+				'required'   => false,
1583
+				'validation' => true,
1584
+				'value'      => $context,
1585
+				'css_class'  => '',
1586
+				'format'     => '%s',
1587
+				'db-col'     => 'MTP_context',
1588
+			);
1589
+
1590
+			$template_form_fields['ee-msg-grp-id'] = array(
1591
+				'name'       => 'GRP_ID',
1592
+				'label'      => null,
1593
+				'input'      => 'hidden',
1594
+				'type'       => 'int',
1595
+				'required'   => false,
1596
+				'validation' => true,
1597
+				'value'      => $GRP_ID,
1598
+				'css_class'  => '',
1599
+				'format'     => '%d',
1600
+				'db-col'     => 'GRP_ID',
1601
+			);
1602
+
1603
+			$template_form_fields['ee-msg-messenger'] = array(
1604
+				'name'       => 'MTP_messenger',
1605
+				'label'      => null,
1606
+				'input'      => 'hidden',
1607
+				'type'       => 'string',
1608
+				'required'   => false,
1609
+				'validation' => true,
1610
+				'value'      => $message_template_group->messenger(),
1611
+				'css_class'  => '',
1612
+				'format'     => '%s',
1613
+				'db-col'     => 'MTP_messenger',
1614
+			);
1615
+
1616
+			$template_form_fields['ee-msg-message-type'] = array(
1617
+				'name'       => 'MTP_message_type',
1618
+				'label'      => null,
1619
+				'input'      => 'hidden',
1620
+				'type'       => 'string',
1621
+				'required'   => false,
1622
+				'validation' => true,
1623
+				'value'      => $message_template_group->message_type(),
1624
+				'css_class'  => '',
1625
+				'format'     => '%s',
1626
+				'db-col'     => 'MTP_message_type',
1627
+			);
1628
+
1629
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1630
+				'name'       => 'MTP_is_global',
1631
+				'label'      => esc_html__('Global Template', 'event_espresso'),
1632
+				'input'      => 'hidden',
1633
+				'type'       => 'int',
1634
+				'required'   => false,
1635
+				'validation' => true,
1636
+				'value'      => $message_template_group->get('MTP_is_global'),
1637
+				'css_class'  => '',
1638
+				'format'     => '%d',
1639
+				'db-col'     => 'MTP_is_global',
1640
+			);
1641
+
1642
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1643
+				'name'       => 'MTP_is_override',
1644
+				'label'      => esc_html__('Override all custom', 'event_espresso'),
1645
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1646
+				'type'       => 'int',
1647
+				'required'   => false,
1648
+				'validation' => true,
1649
+				'value'      => $message_template_group->get('MTP_is_override'),
1650
+				'css_class'  => '',
1651
+				'format'     => '%d',
1652
+				'db-col'     => 'MTP_is_override',
1653
+			);
1654
+
1655
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1656
+				'name'       => 'MTP_is_active',
1657
+				'label'      => esc_html__('Active Template', 'event_espresso'),
1658
+				'input'      => 'hidden',
1659
+				'type'       => 'int',
1660
+				'required'   => false,
1661
+				'validation' => true,
1662
+				'value'      => $message_template_group->is_active(),
1663
+				'css_class'  => '',
1664
+				'format'     => '%d',
1665
+				'db-col'     => 'MTP_is_active',
1666
+			);
1667
+
1668
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1669
+				'name'       => 'MTP_deleted',
1670
+				'label'      => null,
1671
+				'input'      => 'hidden',
1672
+				'type'       => 'int',
1673
+				'required'   => false,
1674
+				'validation' => true,
1675
+				'value'      => $message_template_group->get('MTP_deleted'),
1676
+				'css_class'  => '',
1677
+				'format'     => '%d',
1678
+				'db-col'     => 'MTP_deleted',
1679
+			);
1680
+			$sidebar_form_fields['ee-msg-author'] = array(
1681
+				'name'       => 'MTP_user_id',
1682
+				'label'      => esc_html__('Author', 'event_espresso'),
1683
+				'input'      => 'hidden',
1684
+				'type'       => 'int',
1685
+				'required'   => false,
1686
+				'validation' => false,
1687
+				'value'      => $message_template_group->user(),
1688
+				'format'     => '%d',
1689
+				'db-col'     => 'MTP_user_id',
1690
+			);
1691
+
1692
+			$sidebar_form_fields['ee-msg-route'] = array(
1693
+				'name'  => 'action',
1694
+				'input' => 'hidden',
1695
+				'type'  => 'string',
1696
+				'value' => $action,
1697
+			);
1698
+
1699
+			$sidebar_form_fields['ee-msg-id'] = array(
1700
+				'name'  => 'id',
1701
+				'input' => 'hidden',
1702
+				'type'  => 'int',
1703
+				'value' => $GRP_ID,
1704
+			);
1705
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1706
+				'name'  => $action . '_nonce',
1707
+				'input' => 'hidden',
1708
+				'type'  => 'string',
1709
+				'value' => wp_create_nonce($action . '_nonce'),
1710
+			);
1711
+
1712
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1713
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1714
+					'name'  => 'template_switch',
1715
+					'input' => 'hidden',
1716
+					'type'  => 'int',
1717
+					'value' => 1,
1718
+				);
1719
+			}
1720
+
1721
+
1722
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1723
+			$sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1724
+		} //end if ( !empty($template_field_structure) )
1725
+
1726
+		// set extra content for publish box
1727
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1728
+		$this->_set_publish_post_box_vars(
1729
+			'id',
1730
+			$GRP_ID,
1731
+			false,
1732
+			add_query_arg(
1733
+				array('action' => 'global_mtps'),
1734
+				$this->_admin_base_url
1735
+			)
1736
+		);
1737
+
1738
+		// add preview button
1739
+		$preview_url = parent::add_query_args_and_nonce(
1740
+			array(
1741
+				'message_type' => $message_template_group->message_type(),
1742
+				'messenger'    => $message_template_group->messenger(),
1743
+				'context'      => $context,
1744
+				'GRP_ID'       => $GRP_ID,
1745
+				'evt_id'       => $EVT_ID,
1746
+				'action'       => 'preview_message',
1747
+			),
1748
+			$this->_admin_base_url
1749
+		);
1750
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1751
+						  . esc_html__('Preview', 'event_espresso')
1752
+						  . '</a>';
1753
+
1754
+
1755
+		// setup context switcher
1756
+		$context_switcher_args = array(
1757
+			'page'    => 'espresso_messages',
1758
+			'action'  => 'edit_message_template',
1759
+			'id'      => $GRP_ID,
1760
+			'evt_id'  => $EVT_ID,
1761
+			'context' => $context,
1762
+			'extra'   => $preview_button,
1763
+		);
1764
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1765
+
1766
+
1767
+		// main box
1768
+		$this->_template_args['template_fields'] = $template_fields;
1769
+		$this->_template_args['sidebar_box_id'] = 'details';
1770
+		$this->_template_args['action'] = $action;
1771
+		$this->_template_args['context'] = $context;
1772
+		$this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1773
+		$this->_template_args['learn_more_about_message_templates_link'] =
1774
+			$this->_learn_more_about_message_templates_link();
1775
+
1776
+
1777
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1778
+		$this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1779
+			$message_template_group,
1780
+			$context,
1781
+			$context_label
1782
+		);
1783
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1784
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1785
+
1786
+		$this->_template_path = $this->_template_args['GRP_ID']
1787
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1788
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1789
+
1790
+		// send along EE_Message_Template_Group object for further template use.
1791
+		$this->_template_args['MTP'] = $message_template_group;
1792
+
1793
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1794
+			$this->_template_path,
1795
+			$this->_template_args,
1796
+			true
1797
+		);
1798
+
1799
+
1800
+		// finally, let's set the admin_page title
1801
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1802
+
1803
+
1804
+		// we need to take care of setting the shortcodes property for use elsewhere.
1805
+		$this->_set_shortcodes();
1806
+
1807
+
1808
+		// final template wrapper
1809
+		$this->display_admin_page_with_sidebar();
1810
+	}
1811
+
1812
+
1813
+	public function filter_tinymce_init($mceInit, $editor_id)
1814
+	{
1815
+		return $mceInit;
1816
+	}
1817
+
1818
+
1819
+	public function add_context_switcher()
1820
+	{
1821
+		return $this->_context_switcher;
1822
+	}
1823
+
1824
+
1825
+	/**
1826
+	 * Adds the activation/deactivation toggle for the message template context.
1827
+	 *
1828
+	 * @param EE_Message_Template_Group $message_template_group
1829
+	 * @param string                    $context
1830
+	 * @param string                    $context_label
1831
+	 * @return string
1832
+	 * @throws DomainException
1833
+	 * @throws EE_Error
1834
+	 * @throws InvalidIdentifierException
1835
+	 */
1836
+	protected function add_active_context_element(
1837
+		EE_Message_Template_Group $message_template_group,
1838
+		$context,
1839
+		$context_label
1840
+	) {
1841
+		$template_args = array(
1842
+			'context'                   => $context,
1843
+			'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1844
+			'is_active'                 => $message_template_group->is_context_active($context),
1845
+			'on_off_action'             => $message_template_group->is_context_active($context)
1846
+				? 'context-off'
1847
+				: 'context-on',
1848
+			'context_label'             => str_replace(array('(', ')'), '', $context_label),
1849
+			'message_template_group_id' => $message_template_group->ID(),
1850
+		);
1851
+		return EEH_Template::display_template(
1852
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1853
+			$template_args,
1854
+			true
1855
+		);
1856
+	}
1857
+
1858
+
1859
+	/**
1860
+	 * Ajax callback for `toggle_context_template` ajax action.
1861
+	 * Handles toggling the message context on or off.
1862
+	 *
1863
+	 * @throws EE_Error
1864
+	 * @throws InvalidArgumentException
1865
+	 * @throws InvalidDataTypeException
1866
+	 * @throws InvalidIdentifierException
1867
+	 * @throws InvalidInterfaceException
1868
+	 */
1869
+	public function toggle_context_template()
1870
+	{
1871
+		$success = true;
1872
+		// check for required data
1873
+		if (! isset(
1874
+			$this->_req_data['message_template_group_id'],
1875
+			$this->_req_data['context'],
1876
+			$this->_req_data['status']
1877
+		)) {
1878
+			EE_Error::add_error(
1879
+				esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1880
+				__FILE__,
1881
+				__FUNCTION__,
1882
+				__LINE__
1883
+			);
1884
+			$success = false;
1885
+		}
1886
+
1887
+		$nonce = isset($this->_req_data['toggle_context_nonce'])
1888
+			? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1889
+			: '';
1890
+		$nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1891
+		$this->_verify_nonce($nonce, $nonce_ref);
1892
+		$status = $this->_req_data['status'];
1893
+		if ($status !== 'off' && $status !== 'on') {
1894
+			EE_Error::add_error(
1895
+				sprintf(
1896
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1897
+					$this->_req_data['status']
1898
+				),
1899
+				__FILE__,
1900
+				__FUNCTION__,
1901
+				__LINE__
1902
+			);
1903
+			$success = false;
1904
+		}
1905
+		$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1906
+			$this->_req_data['message_template_group_id']
1907
+		);
1908
+		if (! $message_template_group instanceof EE_Message_Template_Group) {
1909
+			EE_Error::add_error(
1910
+				sprintf(
1911
+					esc_html__(
1912
+						'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1913
+						'event_espresso'
1914
+					),
1915
+					$this->_req_data['message_template_group_id'],
1916
+					'EE_Message_Template_Group'
1917
+				),
1918
+				__FILE__,
1919
+				__FUNCTION__,
1920
+				__LINE__
1921
+			);
1922
+			$success = false;
1923
+		}
1924
+		if ($success) {
1925
+			$success = $status === 'off'
1926
+				? $message_template_group->deactivate_context($this->_req_data['context'])
1927
+				: $message_template_group->activate_context($this->_req_data['context']);
1928
+		}
1929
+		$this->_template_args['success'] = $success;
1930
+		$this->_return_json();
1931
+	}
1932
+
1933
+
1934
+	public function _add_form_element_before()
1935
+	{
1936
+		return '<form method="post" action="'
1937
+			   . $this->_template_args["edit_message_template_form_url"]
1938
+			   . '" id="ee-msg-edit-frm">';
1939
+	}
1940
+
1941
+	public function _add_form_element_after()
1942
+	{
1943
+		return '</form>';
1944
+	}
1945
+
1946
+
1947
+	/**
1948
+	 * This executes switching the template pack for a message template.
1949
+	 *
1950
+	 * @since 4.5.0
1951
+	 * @throws EE_Error
1952
+	 * @throws InvalidDataTypeException
1953
+	 * @throws InvalidInterfaceException
1954
+	 * @throws InvalidArgumentException
1955
+	 * @throws ReflectionException
1956
+	 */
1957
+	public function switch_template_pack()
1958
+	{
1959
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1960
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1961
+
1962
+		// verify we have needed values.
1963
+		if (empty($GRP_ID) || empty($template_pack)) {
1964
+			$this->_template_args['error'] = true;
1965
+			EE_Error::add_error(
1966
+				esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1967
+				__FILE__,
1968
+				__FUNCTION__,
1969
+				__LINE__
1970
+			);
1971
+		} else {
1972
+			// get template, set the new template_pack and then reset to default
1973
+			/** @type EE_Message_Template_Group $message_template_group */
1974
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1975
+
1976
+			$message_template_group->set_template_pack_name($template_pack);
1977
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1978
+			$this->_req_data['mt'] = $message_template_group->message_type();
1979
+
1980
+			$query_args = $this->_reset_to_default_template();
1981
+
1982
+			if (empty($query_args['id'])) {
1983
+				EE_Error::add_error(
1984
+					esc_html__(
1985
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1986
+						'event_espresso'
1987
+					),
1988
+					__FILE__,
1989
+					__FUNCTION__,
1990
+					__LINE__
1991
+				);
1992
+				$this->_template_args['error'] = true;
1993
+			} else {
1994
+				$template_label = $message_template_group->get_template_pack()->label;
1995
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1996
+				EE_Error::add_success(
1997
+					sprintf(
1998
+						esc_html__(
1999
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
2000
+							'event_espresso'
2001
+						),
2002
+						$template_label,
2003
+						$template_pack_labels->template_pack
2004
+					)
2005
+				);
2006
+				// generate the redirect url for js.
2007
+				$url = self::add_query_args_and_nonce(
2008
+					$query_args,
2009
+					$this->_admin_base_url
2010
+				);
2011
+				$this->_template_args['data']['redirect_url'] = $url;
2012
+				$this->_template_args['success'] = true;
2013
+			}
2014
+
2015
+			$this->_return_json();
2016
+		}
2017
+	}
2018
+
2019
+
2020
+	/**
2021
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2022
+	 * they want.
2023
+	 *
2024
+	 * @access protected
2025
+	 * @return array|null
2026
+	 * @throws EE_Error
2027
+	 * @throws InvalidArgumentException
2028
+	 * @throws InvalidDataTypeException
2029
+	 * @throws InvalidInterfaceException
2030
+	 */
2031
+	protected function _reset_to_default_template()
2032
+	{
2033
+
2034
+		$templates = array();
2035
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2036
+		// we need to make sure we've got the info we need.
2037
+		if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2038
+			EE_Error::add_error(
2039
+				esc_html__(
2040
+					'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.',
2041
+					'event_espresso'
2042
+				),
2043
+				__FILE__,
2044
+				__FUNCTION__,
2045
+				__LINE__
2046
+			);
2047
+		}
2048
+
2049
+		// all templates will be reset to whatever the defaults are
2050
+		// for the global template matching the messenger and message type.
2051
+		$success = ! empty($GRP_ID) ? true : false;
2052
+
2053
+		if ($success) {
2054
+			// let's first determine if the incoming template is a global template,
2055
+			// if it isn't then we need to get the global template matching messenger and message type.
2056
+			// $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2057
+
2058
+
2059
+			// note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2060
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
2061
+
2062
+			if ($success) {
2063
+				// if successfully deleted, lets generate the new ones.
2064
+				// Note. We set GLOBAL to true, because resets on ANY template
2065
+				// will use the related global template defaults for regeneration.
2066
+				// This means that if a custom template is reset it resets to whatever the related global template is.
2067
+				// HOWEVER, we DO keep the template pack and template variation set
2068
+				// for the current custom template when resetting.
2069
+				$templates = $this->_generate_new_templates(
2070
+					$this->_req_data['msgr'],
2071
+					$this->_req_data['mt'],
2072
+					$GRP_ID,
2073
+					true
2074
+				);
2075
+			}
2076
+		}
2077
+
2078
+		// any error messages?
2079
+		if (! $success) {
2080
+			EE_Error::add_error(
2081
+				esc_html__(
2082
+					'Something went wrong with deleting existing templates. Unable to reset to default',
2083
+					'event_espresso'
2084
+				),
2085
+				__FILE__,
2086
+				__FUNCTION__,
2087
+				__LINE__
2088
+			);
2089
+		}
2090
+
2091
+		// all good, let's add a success message!
2092
+		if ($success && ! empty($templates)) {
2093
+			// the info for the template we generated is the first element in the returned array
2094
+			// $templates = $templates[0];
2095
+			EE_Error::overwrite_success();
2096
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2097
+		}
2098
+
2099
+
2100
+		$query_args = array(
2101
+			'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2102
+			'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2103
+			'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2104
+		);
2105
+
2106
+		// if called via ajax then we return query args otherwise redirect
2107
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2108
+			return $query_args;
2109
+		} else {
2110
+			$this->_redirect_after_action(false, '', '', $query_args, true);
2111
+
2112
+			return null;
2113
+		}
2114
+	}
2115
+
2116
+
2117
+	/**
2118
+	 * Retrieve and set the message preview for display.
2119
+	 *
2120
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2121
+	 * @return string
2122
+	 * @throws ReflectionException
2123
+	 * @throws EE_Error
2124
+	 * @throws InvalidArgumentException
2125
+	 * @throws InvalidDataTypeException
2126
+	 * @throws InvalidInterfaceException
2127
+	 */
2128
+	public function _preview_message($send = false)
2129
+	{
2130
+		// first make sure we've got the necessary parameters
2131
+		if (! isset(
2132
+			$this->_req_data['message_type'],
2133
+			$this->_req_data['messenger'],
2134
+			$this->_req_data['messenger'],
2135
+			$this->_req_data['GRP_ID']
2136
+		)) {
2137
+			EE_Error::add_error(
2138
+				esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2139
+				__FILE__,
2140
+				__FUNCTION__,
2141
+				__LINE__
2142
+			);
2143
+		}
2144
+
2145
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2146 2146
         
2147
-        // if we have an evt_id set on the request, use it.
2148
-        $EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
2149
-        ? absint($this->_req_data['evt_id'])
2150
-        : false;
2151
-
2152
-
2153
-        // get the preview!
2154
-        $preview = EED_Messages::preview_message(
2155
-            $this->_req_data['message_type'],
2156
-            $this->_req_data['context'],
2157
-            $this->_req_data['messenger'],
2158
-            $send
2159
-        );
2160
-
2161
-        if ($send) {
2162
-            return $preview;
2163
-        }
2164
-
2165
-        // let's add a button to go back to the edit view
2166
-        $query_args = array(
2167
-            'id'      => $this->_req_data['GRP_ID'],
2168
-            'evt_id'  => $EVT_ID,
2169
-            'context' => $this->_req_data['context'],
2170
-            'action'  => 'edit_message_template',
2171
-        );
2172
-        $go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2173
-        $preview_button = '<a href="'
2174
-                          . $go_back_url
2175
-                          . '" class="button-secondary messages-preview-go-back-button">'
2176
-                          . esc_html__('Go Back to Edit', 'event_espresso')
2177
-                          . '</a>';
2178
-        $message_types = $this->get_installed_message_types();
2179
-        $active_messenger = $this->_message_resource_manager->get_active_messenger(
2180
-            $this->_req_data['messenger']
2181
-        );
2182
-        $active_messenger_label = $active_messenger instanceof EE_messenger
2183
-            ? ucwords($active_messenger->label['singular'])
2184
-            : esc_html__('Unknown Messenger', 'event_espresso');
2185
-        // let's provide a helpful title for context
2186
-        $preview_title = sprintf(
2187
-            esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2188
-            $active_messenger_label,
2189
-            ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2190
-        );
2191
-        if (empty($preview)) {
2192
-            $this->noEventsErrorMessage();
2193
-        }
2194
-        // setup display of preview.
2195
-        $this->_admin_page_title = $preview_title;
2196
-        $this->_template_args['admin_page_title'] = $preview_title;
2197
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2198
-        $this->_template_args['data']['force_json'] = true;
2199
-
2200
-        return '';
2201
-    }
2202
-
2203
-
2204
-    /**
2205
-     * Used to set an error if there are no events available for generating a preview/test send.
2206
-     *
2207
-     * @param bool $test_send  Whether the error should be generated for the context of a test send.
2208
-     */
2209
-    protected function noEventsErrorMessage($test_send = false)
2210
-    {
2211
-        $events_url = parent::add_query_args_and_nonce(
2212
-            array(
2213
-                'action' => 'default',
2214
-                'page'   => 'espresso_events',
2215
-            ),
2216
-            admin_url('admin.php')
2217
-        );
2218
-        $message = $test_send
2219
-            ? __(
2220
-                'A test message could not be sent for this message template because there are no events created yet. The preview system uses actual events for generating the test message. %1$sGo see your events%2$s!',
2221
-                'event_espresso'
2222
-            )
2223
-            : __(
2224
-                'There is no preview for this message template available because there are no events created yet. The preview system uses actual events for generating the preview. %1$sGo see your events%2$s!',
2225
-                'event_espresso'
2226
-            );
2227
-
2228
-        EE_Error::add_attention(
2229
-            sprintf(
2230
-                $message,
2231
-                "<a href='{$events_url}'>",
2232
-                '</a>'
2233
-            )
2234
-        );
2235
-    }
2236
-
2237
-
2238
-    /**
2239
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2240
-     * gets called automatically.
2241
-     *
2242
-     * @since 4.5.0
2243
-     *
2244
-     * @return string
2245
-     */
2246
-    protected function _display_preview_message()
2247
-    {
2248
-        $this->display_admin_page_with_no_sidebar();
2249
-    }
2250
-
2251
-
2252
-    /**
2253
-     * registers metaboxes that should show up on the "edit_message_template" page
2254
-     *
2255
-     * @access protected
2256
-     * @return void
2257
-     */
2258
-    protected function _register_edit_meta_boxes()
2259
-    {
2260
-        add_meta_box(
2261
-            'mtp_valid_shortcodes',
2262
-            esc_html__('Valid Shortcodes', 'event_espresso'),
2263
-            array($this, 'shortcode_meta_box'),
2264
-            $this->_current_screen->id,
2265
-            'side',
2266
-            'default'
2267
-        );
2268
-        add_meta_box(
2269
-            'mtp_extra_actions',
2270
-            esc_html__('Extra Actions', 'event_espresso'),
2271
-            array($this, 'extra_actions_meta_box'),
2272
-            $this->_current_screen->id,
2273
-            'side',
2274
-            'high'
2275
-        );
2276
-        add_meta_box(
2277
-            'mtp_templates',
2278
-            esc_html__('Template Styles', 'event_espresso'),
2279
-            array($this, 'template_pack_meta_box'),
2280
-            $this->_current_screen->id,
2281
-            'side',
2282
-            'high'
2283
-        );
2284
-    }
2285
-
2286
-
2287
-    /**
2288
-     * metabox content for all template pack and variation selection.
2289
-     *
2290
-     * @since 4.5.0
2291
-     * @return string
2292
-     * @throws DomainException
2293
-     * @throws EE_Error
2294
-     * @throws InvalidArgumentException
2295
-     * @throws ReflectionException
2296
-     * @throws InvalidDataTypeException
2297
-     * @throws InvalidInterfaceException
2298
-     */
2299
-    public function template_pack_meta_box()
2300
-    {
2301
-        $this->_set_message_template_group();
2302
-
2303
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
2304
-
2305
-        $tp_select_values = array();
2306
-
2307
-        foreach ($tp_collection as $tp) {
2308
-            // only include template packs that support this messenger and message type!
2309
-            $supports = $tp->get_supports();
2310
-            if (! isset($supports[ $this->_message_template_group->messenger() ])
2311
-                || ! in_array(
2312
-                    $this->_message_template_group->message_type(),
2313
-                    $supports[ $this->_message_template_group->messenger() ],
2314
-                    true
2315
-                )
2316
-            ) {
2317
-                // not supported
2318
-                continue;
2319
-            }
2320
-
2321
-            $tp_select_values[] = array(
2322
-                'text' => $tp->label,
2323
-                'id'   => $tp->dbref,
2324
-            );
2325
-        }
2326
-
2327
-        // if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2328
-        // the default template pack.  This still allows for the odd template pack to override.
2329
-        if (empty($tp_select_values)) {
2330
-            $tp_select_values[] = array(
2331
-                'text' => esc_html__('Default', 'event_espresso'),
2332
-                'id'   => 'default',
2333
-            );
2334
-        }
2335
-
2336
-        // setup variation select values for the currently selected template.
2337
-        $variations = $this->_message_template_group->get_template_pack()->get_variations(
2338
-            $this->_message_template_group->messenger(),
2339
-            $this->_message_template_group->message_type()
2340
-        );
2341
-        $variations_select_values = array();
2342
-        foreach ($variations as $variation => $label) {
2343
-            $variations_select_values[] = array(
2344
-                'text' => $label,
2345
-                'id'   => $variation,
2346
-            );
2347
-        }
2348
-
2349
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2350
-
2351
-        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2352
-            'MTP_template_pack',
2353
-            $tp_select_values,
2354
-            $this->_message_template_group->get_template_pack_name()
2355
-        );
2356
-        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
2357
-            'MTP_template_variation',
2358
-            $variations_select_values,
2359
-            $this->_message_template_group->get_template_pack_variation()
2360
-        );
2361
-        $template_args['template_pack_label'] = $template_pack_labels->template_pack;
2362
-        $template_args['template_variation_label'] = $template_pack_labels->template_variation;
2363
-        $template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2364
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2365
-
2366
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2367
-
2368
-        EEH_Template::display_template($template, $template_args);
2369
-    }
2370
-
2371
-
2372
-    /**
2373
-     * This meta box holds any extra actions related to Message Templates
2374
-     * For now, this includes Resetting templates to defaults and sending a test email.
2375
-     *
2376
-     * @access  public
2377
-     * @return void
2378
-     * @throws EE_Error
2379
-     */
2380
-    public function extra_actions_meta_box()
2381
-    {
2382
-        $template_form_fields = array();
2383
-
2384
-        $extra_args = array(
2385
-            'msgr'   => $this->_message_template_group->messenger(),
2386
-            'mt'     => $this->_message_template_group->message_type(),
2387
-            'GRP_ID' => $this->_message_template_group->GRP_ID(),
2388
-        );
2389
-        // first we need to see if there are any fields
2390
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2391
-
2392
-        if (! empty($fields)) {
2393
-            // yup there be fields
2394
-            foreach ($fields as $field => $config) {
2395
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2396
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2397
-                $default = isset($config['default']) ? $config['default'] : '';
2398
-                $default = isset($config['value']) ? $config['value'] : $default;
2399
-
2400
-                // if type is hidden and the value is empty
2401
-                // something may have gone wrong so let's correct with the defaults
2402
-                $fix = $config['input'] === 'hidden'
2403
-                       && isset($existing[ $field ])
2404
-                       && empty($existing[ $field ])
2405
-                    ? $default
2406
-                    : '';
2407
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2408
-                    ? $existing[ $field ]
2409
-                    : $fix;
2410
-
2411
-                $template_form_fields[ $field_id ] = array(
2412
-                    'name'       => 'test_settings_fld[' . $field . ']',
2413
-                    'label'      => $config['label'],
2414
-                    'input'      => $config['input'],
2415
-                    'type'       => $config['type'],
2416
-                    'required'   => $config['required'],
2417
-                    'validation' => $config['validation'],
2418
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2419
-                    'css_class'  => $config['css_class'],
2420
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2421
-                    'default'    => $default,
2422
-                    'format'     => $config['format'],
2423
-                );
2424
-            }
2425
-        }
2426
-
2427
-        $test_settings_fields = ! empty($template_form_fields)
2428
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2429
-            : '';
2430
-
2431
-        $test_settings_html = '';
2432
-        // print out $test_settings_fields
2433
-        if (! empty($test_settings_fields)) {
2434
-            echo $test_settings_fields;
2435
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2436
-            $test_settings_html .= 'name="test_button" value="';
2437
-            $test_settings_html .= esc_html__('Test Send', 'event_espresso');
2438
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2439
-        }
2440
-
2441
-        // and button
2442
-        $test_settings_html .= '<p>'
2443
-                               . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2444
-                               . '</p>';
2445
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2446
-        $test_settings_html .= $this->get_action_link_or_button(
2447
-            'reset_to_default',
2448
-            'reset',
2449
-            $extra_args,
2450
-            'button-primary reset-default-button'
2451
-        );
2452
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2453
-        echo $test_settings_html;
2454
-    }
2455
-
2456
-
2457
-    /**
2458
-     * This returns the shortcode selector skeleton for a given context and field.
2459
-     *
2460
-     * @since 4.9.rc.000
2461
-     * @param string $field           The name of the field retrieving shortcodes for.
2462
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2463
-     * @return string
2464
-     * @throws DomainException
2465
-     * @throws EE_Error
2466
-     * @throws InvalidArgumentException
2467
-     * @throws ReflectionException
2468
-     * @throws InvalidDataTypeException
2469
-     * @throws InvalidInterfaceException
2470
-     */
2471
-    protected function _get_shortcode_selector($field, $linked_input_id)
2472
-    {
2473
-        $template_args = array(
2474
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2475
-            'fieldname'       => $field,
2476
-            'linked_input_id' => $linked_input_id,
2477
-        );
2478
-
2479
-        return EEH_Template::display_template(
2480
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2481
-            $template_args,
2482
-            true
2483
-        );
2484
-    }
2485
-
2486
-
2487
-    /**
2488
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2489
-     * page)
2490
-     *
2491
-     * @access public
2492
-     * @return void
2493
-     * @throws EE_Error
2494
-     * @throws InvalidArgumentException
2495
-     * @throws ReflectionException
2496
-     * @throws InvalidDataTypeException
2497
-     * @throws InvalidInterfaceException
2498
-     */
2499
-    public function shortcode_meta_box()
2500
-    {
2501
-        $shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2502
-        // $messenger = $this->_message_template_group->messenger_obj();
2503
-        // now let's set the content depending on the status of the shortcodes array
2504
-        if (empty($shortcodes)) {
2505
-            $content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2506
-            echo $content;
2507
-        } else {
2508
-            // $alt = 0;
2509
-            ?>
2147
+		// if we have an evt_id set on the request, use it.
2148
+		$EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
2149
+		? absint($this->_req_data['evt_id'])
2150
+		: false;
2151
+
2152
+
2153
+		// get the preview!
2154
+		$preview = EED_Messages::preview_message(
2155
+			$this->_req_data['message_type'],
2156
+			$this->_req_data['context'],
2157
+			$this->_req_data['messenger'],
2158
+			$send
2159
+		);
2160
+
2161
+		if ($send) {
2162
+			return $preview;
2163
+		}
2164
+
2165
+		// let's add a button to go back to the edit view
2166
+		$query_args = array(
2167
+			'id'      => $this->_req_data['GRP_ID'],
2168
+			'evt_id'  => $EVT_ID,
2169
+			'context' => $this->_req_data['context'],
2170
+			'action'  => 'edit_message_template',
2171
+		);
2172
+		$go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2173
+		$preview_button = '<a href="'
2174
+						  . $go_back_url
2175
+						  . '" class="button-secondary messages-preview-go-back-button">'
2176
+						  . esc_html__('Go Back to Edit', 'event_espresso')
2177
+						  . '</a>';
2178
+		$message_types = $this->get_installed_message_types();
2179
+		$active_messenger = $this->_message_resource_manager->get_active_messenger(
2180
+			$this->_req_data['messenger']
2181
+		);
2182
+		$active_messenger_label = $active_messenger instanceof EE_messenger
2183
+			? ucwords($active_messenger->label['singular'])
2184
+			: esc_html__('Unknown Messenger', 'event_espresso');
2185
+		// let's provide a helpful title for context
2186
+		$preview_title = sprintf(
2187
+			esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2188
+			$active_messenger_label,
2189
+			ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2190
+		);
2191
+		if (empty($preview)) {
2192
+			$this->noEventsErrorMessage();
2193
+		}
2194
+		// setup display of preview.
2195
+		$this->_admin_page_title = $preview_title;
2196
+		$this->_template_args['admin_page_title'] = $preview_title;
2197
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2198
+		$this->_template_args['data']['force_json'] = true;
2199
+
2200
+		return '';
2201
+	}
2202
+
2203
+
2204
+	/**
2205
+	 * Used to set an error if there are no events available for generating a preview/test send.
2206
+	 *
2207
+	 * @param bool $test_send  Whether the error should be generated for the context of a test send.
2208
+	 */
2209
+	protected function noEventsErrorMessage($test_send = false)
2210
+	{
2211
+		$events_url = parent::add_query_args_and_nonce(
2212
+			array(
2213
+				'action' => 'default',
2214
+				'page'   => 'espresso_events',
2215
+			),
2216
+			admin_url('admin.php')
2217
+		);
2218
+		$message = $test_send
2219
+			? __(
2220
+				'A test message could not be sent for this message template because there are no events created yet. The preview system uses actual events for generating the test message. %1$sGo see your events%2$s!',
2221
+				'event_espresso'
2222
+			)
2223
+			: __(
2224
+				'There is no preview for this message template available because there are no events created yet. The preview system uses actual events for generating the preview. %1$sGo see your events%2$s!',
2225
+				'event_espresso'
2226
+			);
2227
+
2228
+		EE_Error::add_attention(
2229
+			sprintf(
2230
+				$message,
2231
+				"<a href='{$events_url}'>",
2232
+				'</a>'
2233
+			)
2234
+		);
2235
+	}
2236
+
2237
+
2238
+	/**
2239
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2240
+	 * gets called automatically.
2241
+	 *
2242
+	 * @since 4.5.0
2243
+	 *
2244
+	 * @return string
2245
+	 */
2246
+	protected function _display_preview_message()
2247
+	{
2248
+		$this->display_admin_page_with_no_sidebar();
2249
+	}
2250
+
2251
+
2252
+	/**
2253
+	 * registers metaboxes that should show up on the "edit_message_template" page
2254
+	 *
2255
+	 * @access protected
2256
+	 * @return void
2257
+	 */
2258
+	protected function _register_edit_meta_boxes()
2259
+	{
2260
+		add_meta_box(
2261
+			'mtp_valid_shortcodes',
2262
+			esc_html__('Valid Shortcodes', 'event_espresso'),
2263
+			array($this, 'shortcode_meta_box'),
2264
+			$this->_current_screen->id,
2265
+			'side',
2266
+			'default'
2267
+		);
2268
+		add_meta_box(
2269
+			'mtp_extra_actions',
2270
+			esc_html__('Extra Actions', 'event_espresso'),
2271
+			array($this, 'extra_actions_meta_box'),
2272
+			$this->_current_screen->id,
2273
+			'side',
2274
+			'high'
2275
+		);
2276
+		add_meta_box(
2277
+			'mtp_templates',
2278
+			esc_html__('Template Styles', 'event_espresso'),
2279
+			array($this, 'template_pack_meta_box'),
2280
+			$this->_current_screen->id,
2281
+			'side',
2282
+			'high'
2283
+		);
2284
+	}
2285
+
2286
+
2287
+	/**
2288
+	 * metabox content for all template pack and variation selection.
2289
+	 *
2290
+	 * @since 4.5.0
2291
+	 * @return string
2292
+	 * @throws DomainException
2293
+	 * @throws EE_Error
2294
+	 * @throws InvalidArgumentException
2295
+	 * @throws ReflectionException
2296
+	 * @throws InvalidDataTypeException
2297
+	 * @throws InvalidInterfaceException
2298
+	 */
2299
+	public function template_pack_meta_box()
2300
+	{
2301
+		$this->_set_message_template_group();
2302
+
2303
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
2304
+
2305
+		$tp_select_values = array();
2306
+
2307
+		foreach ($tp_collection as $tp) {
2308
+			// only include template packs that support this messenger and message type!
2309
+			$supports = $tp->get_supports();
2310
+			if (! isset($supports[ $this->_message_template_group->messenger() ])
2311
+				|| ! in_array(
2312
+					$this->_message_template_group->message_type(),
2313
+					$supports[ $this->_message_template_group->messenger() ],
2314
+					true
2315
+				)
2316
+			) {
2317
+				// not supported
2318
+				continue;
2319
+			}
2320
+
2321
+			$tp_select_values[] = array(
2322
+				'text' => $tp->label,
2323
+				'id'   => $tp->dbref,
2324
+			);
2325
+		}
2326
+
2327
+		// if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2328
+		// the default template pack.  This still allows for the odd template pack to override.
2329
+		if (empty($tp_select_values)) {
2330
+			$tp_select_values[] = array(
2331
+				'text' => esc_html__('Default', 'event_espresso'),
2332
+				'id'   => 'default',
2333
+			);
2334
+		}
2335
+
2336
+		// setup variation select values for the currently selected template.
2337
+		$variations = $this->_message_template_group->get_template_pack()->get_variations(
2338
+			$this->_message_template_group->messenger(),
2339
+			$this->_message_template_group->message_type()
2340
+		);
2341
+		$variations_select_values = array();
2342
+		foreach ($variations as $variation => $label) {
2343
+			$variations_select_values[] = array(
2344
+				'text' => $label,
2345
+				'id'   => $variation,
2346
+			);
2347
+		}
2348
+
2349
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2350
+
2351
+		$template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2352
+			'MTP_template_pack',
2353
+			$tp_select_values,
2354
+			$this->_message_template_group->get_template_pack_name()
2355
+		);
2356
+		$template_args['variations_selector'] = EEH_Form_Fields::select_input(
2357
+			'MTP_template_variation',
2358
+			$variations_select_values,
2359
+			$this->_message_template_group->get_template_pack_variation()
2360
+		);
2361
+		$template_args['template_pack_label'] = $template_pack_labels->template_pack;
2362
+		$template_args['template_variation_label'] = $template_pack_labels->template_variation;
2363
+		$template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2364
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2365
+
2366
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2367
+
2368
+		EEH_Template::display_template($template, $template_args);
2369
+	}
2370
+
2371
+
2372
+	/**
2373
+	 * This meta box holds any extra actions related to Message Templates
2374
+	 * For now, this includes Resetting templates to defaults and sending a test email.
2375
+	 *
2376
+	 * @access  public
2377
+	 * @return void
2378
+	 * @throws EE_Error
2379
+	 */
2380
+	public function extra_actions_meta_box()
2381
+	{
2382
+		$template_form_fields = array();
2383
+
2384
+		$extra_args = array(
2385
+			'msgr'   => $this->_message_template_group->messenger(),
2386
+			'mt'     => $this->_message_template_group->message_type(),
2387
+			'GRP_ID' => $this->_message_template_group->GRP_ID(),
2388
+		);
2389
+		// first we need to see if there are any fields
2390
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2391
+
2392
+		if (! empty($fields)) {
2393
+			// yup there be fields
2394
+			foreach ($fields as $field => $config) {
2395
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2396
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2397
+				$default = isset($config['default']) ? $config['default'] : '';
2398
+				$default = isset($config['value']) ? $config['value'] : $default;
2399
+
2400
+				// if type is hidden and the value is empty
2401
+				// something may have gone wrong so let's correct with the defaults
2402
+				$fix = $config['input'] === 'hidden'
2403
+					   && isset($existing[ $field ])
2404
+					   && empty($existing[ $field ])
2405
+					? $default
2406
+					: '';
2407
+				$existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2408
+					? $existing[ $field ]
2409
+					: $fix;
2410
+
2411
+				$template_form_fields[ $field_id ] = array(
2412
+					'name'       => 'test_settings_fld[' . $field . ']',
2413
+					'label'      => $config['label'],
2414
+					'input'      => $config['input'],
2415
+					'type'       => $config['type'],
2416
+					'required'   => $config['required'],
2417
+					'validation' => $config['validation'],
2418
+					'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2419
+					'css_class'  => $config['css_class'],
2420
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2421
+					'default'    => $default,
2422
+					'format'     => $config['format'],
2423
+				);
2424
+			}
2425
+		}
2426
+
2427
+		$test_settings_fields = ! empty($template_form_fields)
2428
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2429
+			: '';
2430
+
2431
+		$test_settings_html = '';
2432
+		// print out $test_settings_fields
2433
+		if (! empty($test_settings_fields)) {
2434
+			echo $test_settings_fields;
2435
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2436
+			$test_settings_html .= 'name="test_button" value="';
2437
+			$test_settings_html .= esc_html__('Test Send', 'event_espresso');
2438
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2439
+		}
2440
+
2441
+		// and button
2442
+		$test_settings_html .= '<p>'
2443
+							   . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2444
+							   . '</p>';
2445
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2446
+		$test_settings_html .= $this->get_action_link_or_button(
2447
+			'reset_to_default',
2448
+			'reset',
2449
+			$extra_args,
2450
+			'button-primary reset-default-button'
2451
+		);
2452
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2453
+		echo $test_settings_html;
2454
+	}
2455
+
2456
+
2457
+	/**
2458
+	 * This returns the shortcode selector skeleton for a given context and field.
2459
+	 *
2460
+	 * @since 4.9.rc.000
2461
+	 * @param string $field           The name of the field retrieving shortcodes for.
2462
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2463
+	 * @return string
2464
+	 * @throws DomainException
2465
+	 * @throws EE_Error
2466
+	 * @throws InvalidArgumentException
2467
+	 * @throws ReflectionException
2468
+	 * @throws InvalidDataTypeException
2469
+	 * @throws InvalidInterfaceException
2470
+	 */
2471
+	protected function _get_shortcode_selector($field, $linked_input_id)
2472
+	{
2473
+		$template_args = array(
2474
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2475
+			'fieldname'       => $field,
2476
+			'linked_input_id' => $linked_input_id,
2477
+		);
2478
+
2479
+		return EEH_Template::display_template(
2480
+			EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2481
+			$template_args,
2482
+			true
2483
+		);
2484
+	}
2485
+
2486
+
2487
+	/**
2488
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2489
+	 * page)
2490
+	 *
2491
+	 * @access public
2492
+	 * @return void
2493
+	 * @throws EE_Error
2494
+	 * @throws InvalidArgumentException
2495
+	 * @throws ReflectionException
2496
+	 * @throws InvalidDataTypeException
2497
+	 * @throws InvalidInterfaceException
2498
+	 */
2499
+	public function shortcode_meta_box()
2500
+	{
2501
+		$shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2502
+		// $messenger = $this->_message_template_group->messenger_obj();
2503
+		// now let's set the content depending on the status of the shortcodes array
2504
+		if (empty($shortcodes)) {
2505
+			$content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2506
+			echo $content;
2507
+		} else {
2508
+			// $alt = 0;
2509
+			?>
2510 2510
             <div style="float:right; margin-top:10px"><?php
2511
-                            echo $this->_get_help_tab_link('message_template_shortcodes');
2512
-                            ?></div>
2511
+							echo $this->_get_help_tab_link('message_template_shortcodes');
2512
+							?></div>
2513 2513
             <p class="small-text"><?php
2514
-                                  printf(
2515
-                                      esc_html__(
2516
-                                          'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2517
-                                          'event_espresso'
2518
-                                      ),
2519
-                                      '<span class="dashicons dashicons-menu"></span>'
2520
-                                  );
2521
-                                ?>
2514
+								  printf(
2515
+									  esc_html__(
2516
+										  'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2517
+										  'event_espresso'
2518
+									  ),
2519
+									  '<span class="dashicons dashicons-menu"></span>'
2520
+								  );
2521
+								?>
2522 2522
             </p>
2523 2523
             <?php
2524
-        }
2525
-    }
2526
-
2527
-
2528
-    /**
2529
-     * used to set the $_shortcodes property for when its needed elsewhere.
2530
-     *
2531
-     * @access protected
2532
-     * @return void
2533
-     * @throws EE_Error
2534
-     * @throws InvalidArgumentException
2535
-     * @throws ReflectionException
2536
-     * @throws InvalidDataTypeException
2537
-     * @throws InvalidInterfaceException
2538
-     */
2539
-    protected function _set_shortcodes()
2540
-    {
2541
-
2542
-        // no need to run this if the property is already set
2543
-        if (! empty($this->_shortcodes)) {
2544
-            return;
2545
-        }
2546
-
2547
-        $this->_shortcodes = $this->_get_shortcodes();
2548
-    }
2549
-
2550
-
2551
-    /**
2552
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2553
-     * property)
2554
-     *
2555
-     * @access  protected
2556
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2557
-     *                         for. Defaults to all (for the given context)
2558
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2559
-     * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2560
-     *                         true just an array of shortcode/label pairs.
2561
-     * @throws EE_Error
2562
-     * @throws InvalidArgumentException
2563
-     * @throws ReflectionException
2564
-     * @throws InvalidDataTypeException
2565
-     * @throws InvalidInterfaceException
2566
-     */
2567
-    protected function _get_shortcodes($fields = array(), $merged = true)
2568
-    {
2569
-        $this->_set_message_template_group();
2570
-
2571
-        // we need the messenger and message template to retrieve the valid shortcodes array.
2572
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2573
-            ? absint($this->_req_data['id'])
2574
-            : false;
2575
-        $context = isset($this->_req_data['context'])
2576
-            ? $this->_req_data['context']
2577
-            : key($this->_message_template_group->contexts_config());
2578
-
2579
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2580
-    }
2581
-
2582
-
2583
-    /**
2584
-     * This sets the _message_template property (containing the called message_template object)
2585
-     *
2586
-     * @access protected
2587
-     * @return void
2588
-     * @throws EE_Error
2589
-     * @throws InvalidArgumentException
2590
-     * @throws ReflectionException
2591
-     * @throws InvalidDataTypeException
2592
-     * @throws InvalidInterfaceException
2593
-     */
2594
-    protected function _set_message_template_group()
2595
-    {
2596
-
2597
-        if (! empty($this->_message_template_group)) {
2598
-            return;
2599
-        } //get out if this is already set.
2600
-
2601
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2602
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2603
-
2604
-        // let's get the message templates
2605
-        $MTP = EEM_Message_Template_Group::instance();
2606
-
2607
-        if (empty($GRP_ID)) {
2608
-            $this->_message_template_group = $MTP->create_default_object();
2609
-        } else {
2610
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2611
-        }
2612
-
2613
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2614
-        $this->_variation = $this->_message_template_group->get_template_pack_variation();
2615
-    }
2616
-
2617
-
2618
-    /**
2619
-     * sets up a context switcher for edit forms
2620
-     *
2621
-     * @access  protected
2622
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2623
-     * @param array                      $args                  various things the context switcher needs.
2624
-     * @throws EE_Error
2625
-     */
2626
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2627
-    {
2628
-        $context_details = $template_group_object->contexts_config();
2629
-        $context_label = $template_group_object->context_label();
2630
-        ob_start();
2631
-        ?>
2524
+		}
2525
+	}
2526
+
2527
+
2528
+	/**
2529
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2530
+	 *
2531
+	 * @access protected
2532
+	 * @return void
2533
+	 * @throws EE_Error
2534
+	 * @throws InvalidArgumentException
2535
+	 * @throws ReflectionException
2536
+	 * @throws InvalidDataTypeException
2537
+	 * @throws InvalidInterfaceException
2538
+	 */
2539
+	protected function _set_shortcodes()
2540
+	{
2541
+
2542
+		// no need to run this if the property is already set
2543
+		if (! empty($this->_shortcodes)) {
2544
+			return;
2545
+		}
2546
+
2547
+		$this->_shortcodes = $this->_get_shortcodes();
2548
+	}
2549
+
2550
+
2551
+	/**
2552
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2553
+	 * property)
2554
+	 *
2555
+	 * @access  protected
2556
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2557
+	 *                         for. Defaults to all (for the given context)
2558
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2559
+	 * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2560
+	 *                         true just an array of shortcode/label pairs.
2561
+	 * @throws EE_Error
2562
+	 * @throws InvalidArgumentException
2563
+	 * @throws ReflectionException
2564
+	 * @throws InvalidDataTypeException
2565
+	 * @throws InvalidInterfaceException
2566
+	 */
2567
+	protected function _get_shortcodes($fields = array(), $merged = true)
2568
+	{
2569
+		$this->_set_message_template_group();
2570
+
2571
+		// we need the messenger and message template to retrieve the valid shortcodes array.
2572
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2573
+			? absint($this->_req_data['id'])
2574
+			: false;
2575
+		$context = isset($this->_req_data['context'])
2576
+			? $this->_req_data['context']
2577
+			: key($this->_message_template_group->contexts_config());
2578
+
2579
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2580
+	}
2581
+
2582
+
2583
+	/**
2584
+	 * This sets the _message_template property (containing the called message_template object)
2585
+	 *
2586
+	 * @access protected
2587
+	 * @return void
2588
+	 * @throws EE_Error
2589
+	 * @throws InvalidArgumentException
2590
+	 * @throws ReflectionException
2591
+	 * @throws InvalidDataTypeException
2592
+	 * @throws InvalidInterfaceException
2593
+	 */
2594
+	protected function _set_message_template_group()
2595
+	{
2596
+
2597
+		if (! empty($this->_message_template_group)) {
2598
+			return;
2599
+		} //get out if this is already set.
2600
+
2601
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2602
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2603
+
2604
+		// let's get the message templates
2605
+		$MTP = EEM_Message_Template_Group::instance();
2606
+
2607
+		if (empty($GRP_ID)) {
2608
+			$this->_message_template_group = $MTP->create_default_object();
2609
+		} else {
2610
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2611
+		}
2612
+
2613
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2614
+		$this->_variation = $this->_message_template_group->get_template_pack_variation();
2615
+	}
2616
+
2617
+
2618
+	/**
2619
+	 * sets up a context switcher for edit forms
2620
+	 *
2621
+	 * @access  protected
2622
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2623
+	 * @param array                      $args                  various things the context switcher needs.
2624
+	 * @throws EE_Error
2625
+	 */
2626
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2627
+	{
2628
+		$context_details = $template_group_object->contexts_config();
2629
+		$context_label = $template_group_object->context_label();
2630
+		ob_start();
2631
+		?>
2632 2632
         <div class="ee-msg-switcher-container">
2633 2633
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2634 2634
                 <?php
2635
-                foreach ($args as $name => $value) {
2636
-                    if ($name === 'context' || empty($value) || $name === 'extra') {
2637
-                        continue;
2638
-                    }
2639
-                    ?>
2635
+				foreach ($args as $name => $value) {
2636
+					if ($name === 'context' || empty($value) || $name === 'extra') {
2637
+						continue;
2638
+					}
2639
+					?>
2640 2640
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2641 2641
                     <?php
2642
-                }
2643
-                // setup nonce_url
2644
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2645
-                ?>
2642
+				}
2643
+				// setup nonce_url
2644
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2645
+				?>
2646 2646
                 <select name="context">
2647 2647
                     <?php
2648
-                    $context_templates = $template_group_object->context_templates();
2649
-                    if (is_array($context_templates)) :
2650
-                        foreach ($context_templates as $context => $template_fields) :
2651
-                            $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2652
-                            ?>
2648
+					$context_templates = $template_group_object->context_templates();
2649
+					if (is_array($context_templates)) :
2650
+						foreach ($context_templates as $context => $template_fields) :
2651
+							$checked = ($context === $args['context']) ? 'selected="selected"' : '';
2652
+							?>
2653 2653
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2654 2654
                                 <?php echo $context_details[ $context ]['label']; ?>
2655 2655
                             </option>
2656 2656
                         <?php endforeach;
2657
-                    endif; ?>
2657
+					endif; ?>
2658 2658
                 </select>
2659 2659
                 <?php $button_text = sprintf(__('Switch %s', 'event_espresso'), ucwords($context_label['label'])); ?>
2660 2660
                 <input id="submit-msg-context-switcher-sbmt" class="button-secondary" type="submit"
@@ -2663,1925 +2663,1925 @@  discard block
 block discarded – undo
2663 2663
             <?php echo $args['extra']; ?>
2664 2664
         </div> <!-- end .ee-msg-switcher-container -->
2665 2665
         <?php
2666
-        $output = ob_get_contents();
2667
-        ob_clean();
2668
-        $this->_context_switcher = $output;
2669
-    }
2670
-
2671
-
2672
-    /**
2673
-     * utility for sanitizing new values coming in.
2674
-     * Note: this is only used when updating a context.
2675
-     *
2676
-     * @access protected
2677
-     *
2678
-     * @param int $index This helps us know which template field to select from the request array.
2679
-     *
2680
-     * @return array
2681
-     */
2682
-    protected function _set_message_template_column_values($index)
2683
-    {
2684
-        if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2685
-            foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2686
-                $this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2687
-            }
2688
-        }
2689
-
2690
-
2691
-        $set_column_values = array(
2692
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2693
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2694
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2695
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2696
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2697
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2698
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2699
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2700
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2701
-                ? absint($this->_req_data['MTP_is_global'])
2702
-                : 0,
2703
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2704
-                ? absint($this->_req_data['MTP_is_override'])
2705
-                : 0,
2706
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2707
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2708
-        );
2709
-
2710
-
2711
-        return $set_column_values;
2712
-    }
2713
-
2714
-
2715
-    protected function _insert_or_update_message_template($new = false)
2716
-    {
2717
-
2718
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2719
-        $success = 0;
2720
-        $override = false;
2721
-
2722
-        // setup notices description
2723
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2724
-
2725
-        // need the message type and messenger objects to be able to use the labels for the notices
2726
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2727
-        $messenger_label = $messenger_object instanceof EE_messenger
2728
-            ? ucwords($messenger_object->label['singular'])
2729
-            : '';
2730
-
2731
-        $message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2732
-            ? $this->_req_data['MTP_message_type']
2733
-            : '';
2734
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2735
-
2736
-        $message_type_label = $message_type_object instanceof EE_message_type
2737
-            ? ucwords($message_type_object->label['singular'])
2738
-            : '';
2739
-
2740
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2741
-            ? $this->_req_data['MTP_context']
2742
-            : '';
2743
-        $context = ucwords(str_replace('_', ' ', $context_slug));
2744
-
2745
-        $item_desc = $messenger_label && $message_type_label
2746
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2747
-            : '';
2748
-        $item_desc .= 'Message Template';
2749
-        $query_args = array();
2750
-        $edit_array = array();
2751
-        $action_desc = '';
2752
-
2753
-        // if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2754
-        // user to edit.
2755
-        if ($new) {
2756
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2757
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2758
-                if (empty($edit_array)) {
2759
-                    $success = 0;
2760
-                } else {
2761
-                    $success = 1;
2762
-                    $edit_array = $edit_array[0];
2763
-                    $query_args = array(
2764
-                        'id'      => $edit_array['GRP_ID'],
2765
-                        'context' => $edit_array['MTP_context'],
2766
-                        'action'  => 'edit_message_template',
2767
-                    );
2768
-                }
2769
-            }
2770
-            $action_desc = 'created';
2771
-        } else {
2772
-            $MTPG = EEM_Message_Template_Group::instance();
2773
-            $MTP = EEM_Message_Template::instance();
2774
-
2775
-
2776
-            // run update for each template field in displayed context
2777
-            if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2778
-                EE_Error::add_error(
2779
-                    esc_html__(
2780
-                        'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2781
-                        'event_espresso'
2782
-                    ),
2783
-                    __FILE__,
2784
-                    __FUNCTION__,
2785
-                    __LINE__
2786
-                );
2787
-                $success = 0;
2788
-            } else {
2789
-                // first validate all fields!
2790
-                // this filter allows client code to add its own validation to the template fields as well.
2791
-                // returning an empty array means everything passed validation.
2792
-                // errors in validation should be represented in an array with the following shape:
2793
-                // array(
2794
-                //   'fieldname' => array(
2795
-                //          'msg' => 'error message'
2796
-                //          'value' => 'value for field producing error'
2797
-                // )
2798
-                $custom_validation = (array) apply_filters(
2799
-                    'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2800
-                    array(),
2801
-                    $this->_req_data['MTP_template_fields'],
2802
-                    $context_slug,
2803
-                    $messenger_slug,
2804
-                    $message_type_slug
2805
-                );
2806
-
2807
-                $system_validation = $MTPG->validate(
2808
-                    $this->_req_data['MTP_template_fields'],
2809
-                    $context_slug,
2810
-                    $messenger_slug,
2811
-                    $message_type_slug
2812
-                );
2813
-
2814
-                $system_validation = ! is_array($system_validation) && $system_validation ? array()
2815
-                    : $system_validation;
2816
-                $validates = array_merge($custom_validation, $system_validation);
2817
-
2818
-                // if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2819
-                // appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2820
-                //  WE need to make sure there is no actual error messages in validates.
2821
-                if (is_array($validates) && ! empty($validates)) {
2822
-                    // add the transient so when the form loads we know which fields to highlight
2823
-                    $this->_add_transient('edit_message_template', $validates);
2824
-
2825
-                    $success = 0;
2826
-
2827
-                    // setup notices
2828
-                    foreach ($validates as $field => $error) {
2829
-                        if (isset($error['msg'])) {
2830
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2831
-                        }
2832
-                    }
2833
-                } else {
2834
-                    $set_column_values = array();
2835
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2836
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2837
-
2838
-                        $where_cols_n_values = array(
2839
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2840
-                        );
2841
-                        // if they aren't allowed to use all JS, restrict them to just posty-y tags
2842
-                        if (! current_user_can('unfiltered_html')) {
2843
-                            if (is_array($set_column_values['MTP_content'])) {
2844
-                                foreach ($set_column_values['MTP_content'] as $key => $value) {
2845
-                                    // remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2846
-                                    // only removes slashes from double-quotes, so attributes using single quotes always
2847
-                                    // appear invalid.) But currently the models expect slashed data, so after wp_kses
2848
-                                    // runs we need to re-slash the data. Sheesh. See
2849
-                                    // https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2850
-                                    $set_column_values['MTP_content'][ $key ] = addslashes(
2851
-                                        wp_kses(
2852
-                                            stripslashes($value),
2853
-                                            wp_kses_allowed_html('post')
2854
-                                        )
2855
-                                    );
2856
-                                }
2857
-                            } else {
2858
-                                $set_column_values['MTP_content'] = wp_kses(
2859
-                                    $set_column_values['MTP_content'],
2860
-                                    wp_kses_allowed_html('post')
2861
-                                );
2862
-                            }
2863
-                        }
2864
-                        $message_template_fields = array(
2865
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2866
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2867
-                            'MTP_context'        => $set_column_values['MTP_context'],
2868
-                            'MTP_content'        => $set_column_values['MTP_content'],
2869
-                        );
2870
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2871
-                            if ($updated === false) {
2872
-                                EE_Error::add_error(
2873
-                                    sprintf(
2874
-                                        esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2875
-                                        $template_field
2876
-                                    ),
2877
-                                    __FILE__,
2878
-                                    __FUNCTION__,
2879
-                                    __LINE__
2880
-                                );
2881
-                            } else {
2882
-                                $success = 1;
2883
-                            }
2884
-                        } else {
2885
-                            // only do this logic if we don't have a MTP_ID for this field
2886
-                            if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2887
-                                // this has already been through the template field validator and sanitized, so it will be
2888
-                                // safe to insert this field.  Why insert?  This typically happens when we introduce a new
2889
-                                // message template field in a messenger/message type and existing users don't have the
2890
-                                // default setup for it.
2891
-                                // @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2892
-                                $updated = $MTP->insert($message_template_fields);
2893
-                                if (! $updated || is_wp_error($updated)) {
2894
-                                    EE_Error::add_error(
2895
-                                        sprintf(
2896
-                                            esc_html__('%s field could not be updated.', 'event_espresso'),
2897
-                                            $template_field
2898
-                                        ),
2899
-                                        __FILE__,
2900
-                                        __FUNCTION__,
2901
-                                        __LINE__
2902
-                                    );
2903
-                                    $success = 0;
2904
-                                } else {
2905
-                                    $success = 1;
2906
-                                }
2907
-                            }
2908
-                        }
2909
-                        $action_desc = 'updated';
2910
-                    }
2911
-
2912
-                    // we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2913
-                    $mtpg_fields = array(
2914
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2915
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2916
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2917
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2918
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2919
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2920
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2921
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2922
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2923
-                            : '',
2924
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2925
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2926
-                            : '',
2927
-                    );
2928
-
2929
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2930
-                    $updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2931
-
2932
-                    if ($updated === false) {
2933
-                        EE_Error::add_error(
2934
-                            sprintf(
2935
-                                esc_html__(
2936
-                                    'The Message Template Group (%d) was NOT updated for some reason',
2937
-                                    'event_espresso'
2938
-                                ),
2939
-                                $set_column_values['GRP_ID']
2940
-                            ),
2941
-                            __FILE__,
2942
-                            __FUNCTION__,
2943
-                            __LINE__
2944
-                        );
2945
-                    } else {
2946
-                        // k now we need to ensure the template_pack and template_variation fields are set.
2947
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2948
-                            ? $this->_req_data['MTP_template_pack']
2949
-                            : 'default';
2950
-
2951
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2952
-                            ? $this->_req_data['MTP_template_variation']
2953
-                            : 'default';
2954
-
2955
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2956
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2957
-                            $mtpg_obj->set_template_pack_name($template_pack);
2958
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2959
-                        }
2960
-                        $success = 1;
2961
-                    }
2962
-                }
2963
-            }
2964
-        }
2965
-
2966
-        // we return things differently if doing ajax
2967
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2968
-            $this->_template_args['success'] = $success;
2969
-            $this->_template_args['error'] = ! $success ? true : false;
2970
-            $this->_template_args['content'] = '';
2971
-            $this->_template_args['data'] = array(
2972
-                'grpID'        => $edit_array['GRP_ID'],
2973
-                'templateName' => $edit_array['template_name'],
2974
-            );
2975
-            if ($success) {
2976
-                EE_Error::overwrite_success();
2977
-                EE_Error::add_success(
2978
-                    esc_html__(
2979
-                        '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.',
2980
-                        'event_espresso'
2981
-                    )
2982
-                );
2983
-            }
2984
-
2985
-            $this->_return_json();
2986
-        }
2987
-
2988
-
2989
-        // was a test send triggered?
2990
-        if (isset($this->_req_data['test_button'])) {
2991
-            EE_Error::overwrite_success();
2992
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2993
-            $override = true;
2994
-        }
2995
-
2996
-        if (empty($query_args)) {
2997
-            $query_args = array(
2998
-                'id'      => $this->_req_data['GRP_ID'],
2999
-                'context' => $context_slug,
3000
-                'action'  => 'edit_message_template',
3001
-            );
3002
-        }
3003
-
3004
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
3005
-    }
3006
-
3007
-
3008
-    /**
3009
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
3010
-     *
3011
-     * @param  string $context      what context being tested
3012
-     * @param  string $messenger    messenger being tested
3013
-     * @param  string $message_type message type being tested
3014
-     * @throws EE_Error
3015
-     * @throws InvalidArgumentException
3016
-     * @throws InvalidDataTypeException
3017
-     * @throws InvalidInterfaceException
3018
-     */
3019
-    protected function _do_test_send($context, $messenger, $message_type)
3020
-    {
3021
-        // set things up for preview
3022
-        $this->_req_data['messenger'] = $messenger;
3023
-        $this->_req_data['message_type'] = $message_type;
3024
-        $this->_req_data['context'] = $context;
3025
-        $this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
3026
-        $active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
3027
-
3028
-        // let's save any existing fields that might be required by the messenger
3029
-        if (isset($this->_req_data['test_settings_fld'])
3030
-            && $active_messenger instanceof EE_messenger
3031
-            && apply_filters(
3032
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3033
-                true,
3034
-                $this->_req_data['test_settings_fld'],
3035
-                $active_messenger
3036
-            )
3037
-        ) {
3038
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
3039
-        }
3040
-
3041
-        /**
3042
-         * Use filter to add additional controls on whether message can send or not
3043
-         */
3044
-        if (apply_filters(
3045
-            'FHEE__Messages_Admin_Page__do_test_send__can_send',
3046
-            true,
3047
-            $context,
3048
-            $this->_req_data,
3049
-            $messenger,
3050
-            $message_type
3051
-        )) {
3052
-            if (EEM_Event::instance()->count() > 0) {
3053
-                $success = $this->_preview_message(true);
3054
-                if ($success) {
3055
-                    EE_Error::add_success(__('Test message sent', 'event_espresso'));
3056
-                } else {
3057
-                    EE_Error::add_error(
3058
-                        esc_html__('The test message was not sent', 'event_espresso'),
3059
-                        __FILE__,
3060
-                        __FUNCTION__,
3061
-                        __LINE__
3062
-                    );
3063
-                }
3064
-            } else {
3065
-                $this->noEventsErrorMessage(true);
3066
-            }
3067
-        }
3068
-    }
3069
-
3070
-
3071
-    /**
3072
-     * _generate_new_templates
3073
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3074
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3075
-     * for the event.
3076
-     *
3077
-     *
3078
-     * @param  string $messenger     the messenger we are generating templates for
3079
-     * @param array   $message_types array of message types that the templates are generated for.
3080
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3081
-     *                               indicate the message_template_group being used as the base.
3082
-     *
3083
-     * @param bool    $global
3084
-     *
3085
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
3086
-     *                               encountering problems.
3087
-     * @throws EE_Error
3088
-     */
3089
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3090
-    {
3091
-
3092
-        // if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3093
-        // just don't generate any templates.
3094
-        if (empty($message_types)) {
3095
-            return true;
3096
-        }
3097
-
3098
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3099
-    }
3100
-
3101
-
3102
-    /**
3103
-     * [_trash_or_restore_message_template]
3104
-     *
3105
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3106
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3107
-     *                        an individual context (FALSE).
3108
-     * @return void
3109
-     * @throws EE_Error
3110
-     * @throws InvalidArgumentException
3111
-     * @throws InvalidDataTypeException
3112
-     * @throws InvalidInterfaceException
3113
-     */
3114
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
3115
-    {
3116
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3117
-        $MTP = EEM_Message_Template_Group::instance();
3118
-
3119
-        $success = 1;
3120
-
3121
-        // incoming GRP_IDs
3122
-        if ($all) {
3123
-            // Checkboxes
3124
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3125
-                // if array has more than one element then success message should be plural.
3126
-                // todo: what about nonce?
3127
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3128
-
3129
-                // cycle through checkboxes
3130
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3131
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3132
-                    if (! $trashed_or_restored) {
3133
-                        $success = 0;
3134
-                    }
3135
-                }
3136
-            } else {
3137
-                // grab single GRP_ID and handle
3138
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3139
-                if (! empty($GRP_ID)) {
3140
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3141
-                    if (! $trashed_or_restored) {
3142
-                        $success = 0;
3143
-                    }
3144
-                } else {
3145
-                    $success = 0;
3146
-                }
3147
-            }
3148
-        }
3149
-
3150
-        $action_desc = $trash
3151
-            ? esc_html__('moved to the trash', 'event_espresso')
3152
-            : esc_html__('restored', 'event_espresso');
3153
-
3154
-        $action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3155
-
3156
-        $item_desc = $all ? _n(
3157
-            'Message Template Group',
3158
-            'Message Template Groups',
3159
-            $success,
3160
-            'event_espresso'
3161
-        ) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3162
-
3163
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3164
-            'template',
3165
-            'templates',
3166
-            $success,
3167
-            'event_espresso'
3168
-        ) : $item_desc;
3169
-
3170
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
3171
-    }
3172
-
3173
-
3174
-    /**
3175
-     * [_delete_message_template]
3176
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3177
-     *
3178
-     * @return void
3179
-     * @throws EE_Error
3180
-     * @throws InvalidArgumentException
3181
-     * @throws InvalidDataTypeException
3182
-     * @throws InvalidInterfaceException
3183
-     */
3184
-    protected function _delete_message_template()
3185
-    {
3186
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3187
-
3188
-        // checkboxes
3189
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3190
-            // if array has more than one element then success message should be plural
3191
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3192
-
3193
-            // cycle through bulk action checkboxes
3194
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3195
-                $success = $this->_delete_mtp_permanently($GRP_ID);
3196
-            }
3197
-        } else {
3198
-            // grab single grp_id and delete
3199
-            $GRP_ID = absint($this->_req_data['id']);
3200
-            $success = $this->_delete_mtp_permanently($GRP_ID);
3201
-        }
3202
-
3203
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3204
-    }
3205
-
3206
-
3207
-    /**
3208
-     * helper for permanently deleting a mtP group and all related message_templates
3209
-     *
3210
-     * @param  int  $GRP_ID        The group being deleted
3211
-     * @param  bool $include_group whether to delete the Message Template Group as well.
3212
-     * @return bool boolean to indicate the success of the deletes or not.
3213
-     * @throws EE_Error
3214
-     * @throws InvalidArgumentException
3215
-     * @throws InvalidDataTypeException
3216
-     * @throws InvalidInterfaceException
3217
-     */
3218
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3219
-    {
3220
-        $success = 1;
3221
-        $MTPG = EEM_Message_Template_Group::instance();
3222
-        // first let's GET this group
3223
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
3224
-        // then delete permanently all the related Message Templates
3225
-        $deleted = $MTG->delete_related_permanently('Message_Template');
3226
-
3227
-        if ($deleted === 0) {
3228
-            $success = 0;
3229
-        }
3230
-
3231
-        // now delete permanently this particular group
3232
-
3233
-        if ($include_group && ! $MTG->delete_permanently()) {
3234
-            $success = 0;
3235
-        }
3236
-
3237
-        return $success;
3238
-    }
3239
-
3240
-
3241
-    /**
3242
-     *    _learn_more_about_message_templates_link
3243
-     *
3244
-     * @access protected
3245
-     * @return string
3246
-     */
3247
-    protected function _learn_more_about_message_templates_link()
3248
-    {
3249
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3250
-               . esc_html__('learn more about how message templates works', 'event_espresso')
3251
-               . '</a>';
3252
-    }
3253
-
3254
-
3255
-    /**
3256
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3257
-     * ajax and other routes.
3258
-     *
3259
-     * @return void
3260
-     * @throws DomainException
3261
-     */
3262
-    protected function _settings()
3263
-    {
3264
-
3265
-
3266
-        $this->_set_m_mt_settings();
3267
-
3268
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3269
-            ? $this->_req_data['selected_messenger']
3270
-            : 'email';
3271
-
3272
-        // let's setup the messenger tabs
3273
-        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3274
-            $this->_m_mt_settings['messenger_tabs'],
3275
-            'messenger_links',
3276
-            '|',
3277
-            $selected_messenger
3278
-        );
3279
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3280
-        $this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3281
-
3282
-        $this->display_admin_page_with_sidebar();
3283
-    }
3284
-
3285
-
3286
-    /**
3287
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3288
-     *
3289
-     * @access protected
3290
-     * @return void
3291
-     * @throws DomainException
3292
-     */
3293
-    protected function _set_m_mt_settings()
3294
-    {
3295
-        // first if this is already set then lets get out no need to regenerate data.
3296
-        if (! empty($this->_m_mt_settings)) {
3297
-            return;
3298
-        }
3299
-
3300
-        // get all installed messengers and message_types
3301
-        /** @type EE_messenger[] $messengers */
3302
-        $messengers = $this->_message_resource_manager->installed_messengers();
3303
-        /** @type EE_message_type[] $message_types */
3304
-        $message_types = $this->_message_resource_manager->installed_message_types();
3305
-
3306
-
3307
-        // assemble the array for the _tab_text_links helper
3308
-
3309
-        foreach ($messengers as $messenger) {
3310
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3311
-                'label' => ucwords($messenger->label['singular']),
3312
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3313
-                    ? 'messenger-active'
3314
-                    : '',
3315
-                'href'  => $messenger->name,
3316
-                'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3317
-                'slug'  => $messenger->name,
3318
-                'obj'   => $messenger,
3319
-            );
3320
-
3321
-
3322
-            $message_types_for_messenger = $messenger->get_valid_message_types();
3323
-
3324
-            foreach ($message_types as $message_type) {
3325
-                // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3326
-                // it shouldn't show in either the inactive OR active metabox.
3327
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3328
-                    continue;
3329
-                }
3330
-
3331
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3332
-                    $messenger->name,
3333
-                    $message_type->name
3334
-                )
3335
-                    ? 'active'
3336
-                    : 'inactive';
3337
-
3338
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3339
-                    'label'    => ucwords($message_type->label['singular']),
3340
-                    'class'    => 'message-type-' . $a_or_i,
3341
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3342
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3343
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3344
-                    'title'    => $a_or_i === 'active'
3345
-                        ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3346
-                        : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3347
-                    'content'  => $a_or_i === 'active'
3348
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
3349
-                        : $this->_message_type_settings_content($message_type, $messenger),
3350
-                    'slug'     => $message_type->name,
3351
-                    'active'   => $a_or_i === 'active',
3352
-                    'obj'      => $message_type,
3353
-                );
3354
-            }
3355
-        }
3356
-    }
3357
-
3358
-
3359
-    /**
3360
-     * This just prepares the content for the message type settings
3361
-     *
3362
-     * @param  EE_message_type $message_type The message type object
3363
-     * @param  EE_messenger    $messenger    The messenger object
3364
-     * @param  boolean         $active       Whether the message type is active or not
3365
-     * @return string html output for the content
3366
-     * @throws DomainException
3367
-     */
3368
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
3369
-    {
3370
-        // get message type fields
3371
-        $fields = $message_type->get_admin_settings_fields();
3372
-        $settings_template_args['template_form_fields'] = '';
3373
-
3374
-        if (! empty($fields) && $active) {
3375
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3376
-            foreach ($fields as $fldname => $fldprops) {
3377
-                $field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3378
-                $template_form_field[ $field_id ] = array(
3379
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3380
-                    'label'      => $fldprops['label'],
3381
-                    'input'      => $fldprops['field_type'],
3382
-                    'type'       => $fldprops['value_type'],
3383
-                    'required'   => $fldprops['required'],
3384
-                    'validation' => $fldprops['validation'],
3385
-                    'value'      => isset($existing_settings[ $fldname ])
3386
-                        ? $existing_settings[ $fldname ]
3387
-                        : $fldprops['default'],
3388
-                    'options'    => isset($fldprops['options'])
3389
-                        ? $fldprops['options']
3390
-                        : array(),
3391
-                    'default'    => isset($existing_settings[ $fldname ])
3392
-                        ? $existing_settings[ $fldname ]
3393
-                        : $fldprops['default'],
3394
-                    'css_class'  => 'no-drag',
3395
-                    'format'     => $fldprops['format'],
3396
-                );
3397
-            }
3398
-
3399
-
3400
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3401
-                ? $this->_generate_admin_form_fields(
3402
-                    $template_form_field,
3403
-                    'string',
3404
-                    'ee_mt_activate_form'
3405
-                )
3406
-                : '';
3407
-        }
3408
-
3409
-        $settings_template_args['description'] = $message_type->description;
3410
-        // we also need some hidden fields
3411
-        $settings_template_args['hidden_fields'] = array(
3412
-            'message_type_settings[messenger]'    => array(
3413
-                'type'  => 'hidden',
3414
-                'value' => $messenger->name,
3415
-            ),
3416
-            'message_type_settings[message_type]' => array(
3417
-                'type'  => 'hidden',
3418
-                'value' => $message_type->name,
3419
-            ),
3420
-            'type'                                => array(
3421
-                'type'  => 'hidden',
3422
-                'value' => 'message_type',
3423
-            ),
3424
-        );
3425
-
3426
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3427
-            $settings_template_args['hidden_fields'],
3428
-            'array'
3429
-        );
3430
-        $settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3431
-            ? ' hidden'
3432
-            : '';
3433
-
3434
-
3435
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3436
-        $content = EEH_Template::display_template($template, $settings_template_args, true);
3437
-
3438
-        return $content;
3439
-    }
3440
-
3441
-
3442
-    /**
3443
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
3444
-     *
3445
-     * @access protected
3446
-     * @return void
3447
-     * @throws DomainException
3448
-     */
3449
-    protected function _messages_settings_metaboxes()
3450
-    {
3451
-        $this->_set_m_mt_settings();
3452
-        $m_boxes = $mt_boxes = array();
3453
-        $m_template_args = $mt_template_args = array();
3454
-
3455
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3456
-            ? $this->_req_data['selected_messenger']
3457
-            : 'email';
3458
-
3459
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
3460
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3461
-                $hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3462
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3463
-                // messenger meta boxes
3464
-                $active = $selected_messenger === $messenger;
3465
-                $active_mt_tabs = isset(
3466
-                    $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3467
-                )
3468
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3469
-                    : '';
3470
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3471
-                    esc_html__('%s Settings', 'event_espresso'),
3472
-                    $tab_array['label']
3473
-                );
3474
-                $m_template_args[ $messenger . '_a_box' ] = array(
3475
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3476
-                    'inactive_message_types' => isset(
3477
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3478
-                    )
3479
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3480
-                        : '',
3481
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3482
-                    'hidden'                 => $active ? '' : ' hidden',
3483
-                    'hide_on_message'        => $hide_on_message,
3484
-                    'messenger'              => $messenger,
3485
-                    'active'                 => $active,
3486
-                );
3487
-                // message type meta boxes
3488
-                // (which is really just the inactive container for each messenger
3489
-                // showing inactive message types for that messenger)
3490
-                $mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3491
-                $mt_template_args[ $messenger . '_i_box' ] = array(
3492
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3493
-                    'inactive_message_types' => isset(
3494
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3495
-                    )
3496
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3497
-                        : '',
3498
-                    'hidden'                 => $active ? '' : ' hidden',
3499
-                    'hide_on_message'        => $hide_on_message,
3500
-                    'hide_off_message'       => $hide_off_message,
3501
-                    'messenger'              => $messenger,
3502
-                    'active'                 => $active,
3503
-                );
3504
-            }
3505
-        }
3506
-
3507
-
3508
-        // register messenger metaboxes
3509
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3510
-        foreach ($m_boxes as $box => $label) {
3511
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3512
-            $msgr = str_replace('_a_box', '', $box);
3513
-            add_meta_box(
3514
-                'espresso_' . $msgr . '_settings',
3515
-                $label,
3516
-                function ($post, $metabox) {
3517
-                    echo EEH_Template::display_template(
3518
-                        $metabox["args"]["template_path"],
3519
-                        $metabox["args"]["template_args"],
3520
-                        true
3521
-                    );
3522
-                },
3523
-                $this->_current_screen->id,
3524
-                'normal',
3525
-                'high',
3526
-                $callback_args
3527
-            );
3528
-        }
3529
-
3530
-        // register message type metaboxes
3531
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3532
-        foreach ($mt_boxes as $box => $label) {
3533
-            $callback_args = array(
3534
-                'template_path' => $mt_template_path,
3535
-                'template_args' => $mt_template_args[ $box ],
3536
-            );
3537
-            $mt = str_replace('_i_box', '', $box);
3538
-            add_meta_box(
3539
-                'espresso_' . $mt . '_inactive_mts',
3540
-                $label,
3541
-                function ($post, $metabox) {
3542
-                    echo EEH_Template::display_template(
3543
-                        $metabox["args"]["template_path"],
3544
-                        $metabox["args"]["template_args"],
3545
-                        true
3546
-                    );
3547
-                },
3548
-                $this->_current_screen->id,
3549
-                'side',
3550
-                'high',
3551
-                $callback_args
3552
-            );
3553
-        }
3554
-
3555
-        // register metabox for global messages settings but only when on the main site.  On single site installs this
3556
-        // will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3557
-        if (is_main_site()) {
3558
-            add_meta_box(
3559
-                'espresso_global_message_settings',
3560
-                esc_html__('Global Message Settings', 'event_espresso'),
3561
-                array($this, 'global_messages_settings_metabox_content'),
3562
-                $this->_current_screen->id,
3563
-                'normal',
3564
-                'low',
3565
-                array()
3566
-            );
3567
-        }
3568
-    }
3569
-
3570
-
3571
-    /**
3572
-     *  This generates the content for the global messages settings metabox.
3573
-     *
3574
-     * @return string
3575
-     * @throws EE_Error
3576
-     * @throws InvalidArgumentException
3577
-     * @throws ReflectionException
3578
-     * @throws InvalidDataTypeException
3579
-     * @throws InvalidInterfaceException
3580
-     */
3581
-    public function global_messages_settings_metabox_content()
3582
-    {
3583
-        $form = $this->_generate_global_settings_form();
3584
-        echo $form->form_open(
3585
-            $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3586
-            'POST'
3587
-        )
3588
-             . $form->get_html()
3589
-             . $form->form_close();
3590
-    }
3591
-
3592
-
3593
-    /**
3594
-     * This generates and returns the form object for the global messages settings.
3595
-     *
3596
-     * @return EE_Form_Section_Proper
3597
-     * @throws EE_Error
3598
-     * @throws InvalidArgumentException
3599
-     * @throws ReflectionException
3600
-     * @throws InvalidDataTypeException
3601
-     * @throws InvalidInterfaceException
3602
-     */
3603
-    protected function _generate_global_settings_form()
3604
-    {
3605
-        EE_Registry::instance()->load_helper('HTML');
3606
-        /** @var EE_Network_Core_Config $network_config */
3607
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3608
-
3609
-        return new EE_Form_Section_Proper(
3610
-            array(
3611
-                'name'            => 'global_messages_settings',
3612
-                'html_id'         => 'global_messages_settings',
3613
-                'html_class'      => 'form-table',
3614
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3615
-                'subsections'     => apply_filters(
3616
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3617
-                    array(
3618
-                        'do_messages_on_same_request' => new EE_Select_Input(
3619
-                            array(
3620
-                                true  => esc_html__("On the same request", "event_espresso"),
3621
-                                false => esc_html__("On a separate request", "event_espresso"),
3622
-                            ),
3623
-                            array(
3624
-                                'default'         => $network_config->do_messages_on_same_request,
3625
-                                'html_label_text' => esc_html__(
3626
-                                    'Generate and send all messages:',
3627
-                                    'event_espresso'
3628
-                                ),
3629
-                                'html_help_text'  => esc_html__(
3630
-                                    'By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3631
-                                    'event_espresso'
3632
-                                ),
3633
-                            )
3634
-                        ),
3635
-                        'delete_threshold'            => new EE_Select_Input(
3636
-                            array(
3637
-                                0  => esc_html__('Forever', 'event_espresso'),
3638
-                                3  => esc_html__('3 Months', 'event_espresso'),
3639
-                                6  => esc_html__('6 Months', 'event_espresso'),
3640
-                                9  => esc_html__('9 Months', 'event_espresso'),
3641
-                                12 => esc_html__('12 Months', 'event_espresso'),
3642
-                                24 => esc_html__('24 Months', 'event_espresso'),
3643
-                                36 => esc_html__('36 Months', 'event_espresso'),
3644
-                            ),
3645
-                            array(
3646
-                                'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3647
-                                'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3648
-                                'html_help_text'  => esc_html__(
3649
-                                    'You can control how long a record of processed messages is kept via this option.',
3650
-                                    'event_espresso'
3651
-                                ),
3652
-                            )
3653
-                        ),
3654
-                        'update_settings'             => new EE_Submit_Input(
3655
-                            array(
3656
-                                'default'         => esc_html__('Update', 'event_espresso'),
3657
-                                'html_label_text' => '&nbsp',
3658
-                            )
3659
-                        ),
3660
-                    )
3661
-                ),
3662
-            )
3663
-        );
3664
-    }
3665
-
3666
-
3667
-    /**
3668
-     * This handles updating the global settings set on the admin page.
3669
-     *
3670
-     * @throws EE_Error
3671
-     * @throws InvalidDataTypeException
3672
-     * @throws InvalidInterfaceException
3673
-     * @throws InvalidArgumentException
3674
-     * @throws ReflectionException
3675
-     */
3676
-    protected function _update_global_settings()
3677
-    {
3678
-        /** @var EE_Network_Core_Config $network_config */
3679
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3680
-        $messages_config = EE_Registry::instance()->CFG->messages;
3681
-        $form = $this->_generate_global_settings_form();
3682
-        if ($form->was_submitted()) {
3683
-            $form->receive_form_submission();
3684
-            if ($form->is_valid()) {
3685
-                $valid_data = $form->valid_data();
3686
-                foreach ($valid_data as $property => $value) {
3687
-                    $setter = 'set_' . $property;
3688
-                    if (method_exists($network_config, $setter)) {
3689
-                        $network_config->{$setter}($value);
3690
-                    } elseif (property_exists($network_config, $property)
3691
-                        && $network_config->{$property} !== $value
3692
-                    ) {
3693
-                        $network_config->{$property} = $value;
3694
-                    } elseif (property_exists($messages_config, $property)
3695
-                        && $messages_config->{$property} !== $value
3696
-                    ) {
3697
-                        $messages_config->{$property} = $value;
3698
-                    }
3699
-                }
3700
-                // only update if the form submission was valid!
3701
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3702
-                EE_Registry::instance()->CFG->update_espresso_config();
3703
-                EE_Error::overwrite_success();
3704
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3705
-            }
3706
-        }
3707
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3708
-    }
3709
-
3710
-
3711
-    /**
3712
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3713
-     *
3714
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3715
-     * @return string html formatted tabs
3716
-     * @throws DomainException
3717
-     */
3718
-    protected function _get_mt_tabs($tab_array)
3719
-    {
3720
-        $tab_array = (array) $tab_array;
3721
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3722
-        $tabs = '';
3723
-
3724
-        foreach ($tab_array as $tab) {
3725
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3726
-        }
3727
-
3728
-        return $tabs;
3729
-    }
3730
-
3731
-
3732
-    /**
3733
-     * This prepares the content of the messenger meta box admin settings
3734
-     *
3735
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3736
-     * @return string html formatted content
3737
-     * @throws DomainException
3738
-     */
3739
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3740
-    {
3741
-
3742
-        $fields = $messenger->get_admin_settings_fields();
3743
-        $settings_template_args['template_form_fields'] = '';
3744
-
3745
-        // is $messenger active?
3746
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3747
-
3748
-
3749
-        if (! empty($fields)) {
3750
-            $existing_settings = $messenger->get_existing_admin_settings();
3751
-
3752
-            foreach ($fields as $fldname => $fldprops) {
3753
-                $field_id = $messenger->name . '-' . $fldname;
3754
-                $template_form_field[ $field_id ] = array(
3755
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3756
-                    'label'      => $fldprops['label'],
3757
-                    'input'      => $fldprops['field_type'],
3758
-                    'type'       => $fldprops['value_type'],
3759
-                    'required'   => $fldprops['required'],
3760
-                    'validation' => $fldprops['validation'],
3761
-                    'value'      => isset($existing_settings[ $field_id ])
3762
-                        ? $existing_settings[ $field_id ]
3763
-                        : $fldprops['default'],
3764
-                    'css_class'  => '',
3765
-                    'format'     => $fldprops['format'],
3766
-                );
3767
-            }
3768
-
3769
-
3770
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3771
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3772
-                : '';
3773
-        }
3774
-
3775
-        // we also need some hidden fields
3776
-        $settings_template_args['hidden_fields'] = array(
3777
-            'messenger_settings[messenger]' => array(
3778
-                'type'  => 'hidden',
3779
-                'value' => $messenger->name,
3780
-            ),
3781
-            'type'                          => array(
3782
-                'type'  => 'hidden',
3783
-                'value' => 'messenger',
3784
-            ),
3785
-        );
3786
-
3787
-        // make sure any active message types that are existing are included in the hidden fields
3788
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3789
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3790
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3791
-                    'type'  => 'hidden',
3792
-                    'value' => $mt,
3793
-                );
3794
-            }
3795
-        }
3796
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3797
-            $settings_template_args['hidden_fields'],
3798
-            'array'
3799
-        );
3800
-        $active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3801
-
3802
-        $settings_template_args['messenger'] = $messenger->name;
3803
-        $settings_template_args['description'] = $messenger->description;
3804
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3805
-
3806
-
3807
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3808
-            $messenger->name
3809
-        )
3810
-            ? $settings_template_args['show_hide_edit_form']
3811
-            : ' hidden';
3812
-
3813
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3814
-            ? ' hidden'
3815
-            : $settings_template_args['show_hide_edit_form'];
3816
-
3817
-
3818
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3819
-        $settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3820
-        $settings_template_args['on_off_status'] = $active ? true : false;
3821
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3822
-        $content = EEH_Template::display_template(
3823
-            $template,
3824
-            $settings_template_args,
3825
-            true
3826
-        );
3827
-
3828
-        return $content;
3829
-    }
3830
-
3831
-
3832
-    /**
3833
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3834
-     *
3835
-     * @throws DomainException
3836
-     * @throws EE_Error
3837
-     * @throws InvalidDataTypeException
3838
-     * @throws InvalidInterfaceException
3839
-     * @throws InvalidArgumentException
3840
-     * @throws ReflectionException
3841
-     */
3842
-    public function activate_messenger_toggle()
3843
-    {
3844
-        $success = true;
3845
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3846
-        // let's check that we have required data
3847
-        if (! isset($this->_req_data['messenger'])) {
3848
-            EE_Error::add_error(
3849
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3850
-                __FILE__,
3851
-                __FUNCTION__,
3852
-                __LINE__
3853
-            );
3854
-            $success = false;
3855
-        }
3856
-
3857
-        // do a nonce check here since we're not arriving via a normal route
3858
-        $nonce = isset($this->_req_data['activate_nonce'])
3859
-            ? sanitize_text_field($this->_req_data['activate_nonce'])
3860
-            : '';
3861
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3862
-
3863
-        $this->_verify_nonce($nonce, $nonce_ref);
3864
-
3865
-
3866
-        if (! isset($this->_req_data['status'])) {
3867
-            EE_Error::add_error(
3868
-                esc_html__(
3869
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3870
-                    'event_espresso'
3871
-                ),
3872
-                __FILE__,
3873
-                __FUNCTION__,
3874
-                __LINE__
3875
-            );
3876
-            $success = false;
3877
-        }
3878
-
3879
-        // do check to verify we have a valid status.
3880
-        $status = $this->_req_data['status'];
3881
-
3882
-        if ($status !== 'off' && $status !== 'on') {
3883
-            EE_Error::add_error(
3884
-                sprintf(
3885
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3886
-                    $this->_req_data['status']
3887
-                ),
3888
-                __FILE__,
3889
-                __FUNCTION__,
3890
-                __LINE__
3891
-            );
3892
-            $success = false;
3893
-        }
3894
-
3895
-        if ($success) {
3896
-            // made it here?  Stop dawdling then!!
3897
-            $success = $status === 'off'
3898
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3899
-                : $this->_activate_messenger($this->_req_data['messenger']);
3900
-        }
3901
-
3902
-        $this->_template_args['success'] = $success;
3903
-
3904
-        // no special instructions so let's just do the json return (which should automatically do all the special stuff).
3905
-        $this->_return_json();
3906
-    }
3907
-
3908
-
3909
-    /**
3910
-     * used by ajax from the messages settings page to activate|deactivate a message type
3911
-     *
3912
-     * @throws DomainException
3913
-     * @throws EE_Error
3914
-     * @throws ReflectionException
3915
-     * @throws InvalidDataTypeException
3916
-     * @throws InvalidInterfaceException
3917
-     * @throws InvalidArgumentException
3918
-     */
3919
-    public function activate_mt_toggle()
3920
-    {
3921
-        $success = true;
3922
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3923
-
3924
-        // let's make sure we have the necessary data
3925
-        if (! isset($this->_req_data['message_type'])) {
3926
-            EE_Error::add_error(
3927
-                esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3928
-                __FILE__,
3929
-                __FUNCTION__,
3930
-                __LINE__
3931
-            );
3932
-            $success = false;
3933
-        }
3934
-
3935
-        if (! isset($this->_req_data['messenger'])) {
3936
-            EE_Error::add_error(
3937
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3938
-                __FILE__,
3939
-                __FUNCTION__,
3940
-                __LINE__
3941
-            );
3942
-            $success = false;
3943
-        }
3944
-
3945
-        if (! isset($this->_req_data['status'])) {
3946
-            EE_Error::add_error(
3947
-                esc_html__(
3948
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3949
-                    'event_espresso'
3950
-                ),
3951
-                __FILE__,
3952
-                __FUNCTION__,
3953
-                __LINE__
3954
-            );
3955
-            $success = false;
3956
-        }
3957
-
3958
-
3959
-        // do check to verify we have a valid status.
3960
-        $status = $this->_req_data['status'];
3961
-
3962
-        if ($status !== 'activate' && $status !== 'deactivate') {
3963
-            EE_Error::add_error(
3964
-                sprintf(
3965
-                    esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3966
-                    $this->_req_data['status']
3967
-                ),
3968
-                __FILE__,
3969
-                __FUNCTION__,
3970
-                __LINE__
3971
-            );
3972
-            $success = false;
3973
-        }
3974
-
3975
-
3976
-        // do a nonce check here since we're not arriving via a normal route
3977
-        $nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3978
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3979
-
3980
-        $this->_verify_nonce($nonce, $nonce_ref);
3981
-
3982
-        if ($success) {
3983
-            // made it here? um, what are you waiting for then?
3984
-            $success = $status === 'deactivate'
3985
-                ? $this->_deactivate_message_type_for_messenger(
3986
-                    $this->_req_data['messenger'],
3987
-                    $this->_req_data['message_type']
3988
-                )
3989
-                : $this->_activate_message_type_for_messenger(
3990
-                    $this->_req_data['messenger'],
3991
-                    $this->_req_data['message_type']
3992
-                );
3993
-        }
3994
-
3995
-        $this->_template_args['success'] = $success;
3996
-        $this->_return_json();
3997
-    }
3998
-
3999
-
4000
-    /**
4001
-     * Takes care of processing activating a messenger and preparing the appropriate response.
4002
-     *
4003
-     * @param string $messenger_name The name of the messenger being activated
4004
-     * @return bool
4005
-     * @throws DomainException
4006
-     * @throws EE_Error
4007
-     * @throws InvalidArgumentException
4008
-     * @throws ReflectionException
4009
-     * @throws InvalidDataTypeException
4010
-     * @throws InvalidInterfaceException
4011
-     */
4012
-    protected function _activate_messenger($messenger_name)
4013
-    {
4014
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4015
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4016
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger
4017
-            ? $active_messenger->get_default_message_types()
4018
-            : array();
4019
-
4020
-        // ensure is active
4021
-        $this->_message_resource_manager->activate_messenger($active_messenger, $message_types_to_activate);
4022
-
4023
-        // set response_data for reload
4024
-        foreach ($message_types_to_activate as $message_type_name) {
4025
-            /** @var EE_message_type $message_type */
4026
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4027
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4028
-                $messenger_name,
4029
-                $message_type_name
4030
-            )
4031
-                && $message_type instanceof EE_message_type
4032
-            ) {
4033
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
4034
-                if ($message_type->get_admin_settings_fields()) {
4035
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
4036
-                }
4037
-            }
4038
-        }
4039
-
4040
-        // add success message for activating messenger
4041
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4042
-    }
4043
-
4044
-
4045
-    /**
4046
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
4047
-     *
4048
-     * @param string $messenger_name The name of the messenger being activated
4049
-     * @return bool
4050
-     * @throws DomainException
4051
-     * @throws EE_Error
4052
-     * @throws InvalidArgumentException
4053
-     * @throws ReflectionException
4054
-     * @throws InvalidDataTypeException
4055
-     * @throws InvalidInterfaceException
4056
-     */
4057
-    protected function _deactivate_messenger($messenger_name)
4058
-    {
4059
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4060
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4061
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
4062
-
4063
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4064
-    }
4065
-
4066
-
4067
-    /**
4068
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4069
-     *
4070
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
4071
-     * @param string $message_type_name The name of the message type being activated for the messenger
4072
-     * @return bool
4073
-     * @throws DomainException
4074
-     * @throws EE_Error
4075
-     * @throws InvalidArgumentException
4076
-     * @throws ReflectionException
4077
-     * @throws InvalidDataTypeException
4078
-     * @throws InvalidInterfaceException
4079
-     */
4080
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4081
-    {
4082
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4083
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4084
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4085
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4086
-
4087
-        // ensure is active
4088
-        $this->_message_resource_manager->activate_messenger($active_messenger, $message_type_name);
4089
-
4090
-        // set response for load
4091
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4092
-            $messenger_name,
4093
-            $message_type_name
4094
-        )
4095
-        ) {
4096
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
4097
-            if ($message_type_to_activate->get_admin_settings_fields()) {
4098
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
4099
-            }
4100
-        }
4101
-
4102
-        return $this->_setup_response_message_for_activating_messenger_with_message_types(
4103
-            $active_messenger,
4104
-            $message_type_to_activate
4105
-        );
4106
-    }
4107
-
4108
-
4109
-    /**
4110
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4111
-     *
4112
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4113
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
4114
-     * @return bool
4115
-     * @throws DomainException
4116
-     * @throws EE_Error
4117
-     * @throws InvalidArgumentException
4118
-     * @throws ReflectionException
4119
-     * @throws InvalidDataTypeException
4120
-     * @throws InvalidInterfaceException
4121
-     */
4122
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4123
-    {
4124
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4125
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4126
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4127
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4128
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4129
-
4130
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4131
-            $active_messenger,
4132
-            $message_type_to_deactivate
4133
-        );
4134
-    }
4135
-
4136
-
4137
-    /**
4138
-     * This just initializes the defaults for activating messenger and message type responses.
4139
-     */
4140
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
4141
-    {
4142
-        $this->_template_args['data']['active_mts'] = array();
4143
-        $this->_template_args['data']['mt_reload'] = array();
4144
-    }
4145
-
4146
-
4147
-    /**
4148
-     * Setup appropriate response for activating a messenger and/or message types
4149
-     *
4150
-     * @param EE_messenger         $messenger
4151
-     * @param EE_message_type|null $message_type
4152
-     * @return bool
4153
-     * @throws DomainException
4154
-     * @throws EE_Error
4155
-     * @throws InvalidArgumentException
4156
-     * @throws ReflectionException
4157
-     * @throws InvalidDataTypeException
4158
-     * @throws InvalidInterfaceException
4159
-     */
4160
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
4161
-        $messenger,
4162
-        EE_Message_Type $message_type = null
4163
-    ) {
4164
-        // if $messenger isn't a valid messenger object then get out.
4165
-        if (! $messenger instanceof EE_Messenger) {
4166
-            EE_Error::add_error(
4167
-                esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4168
-                __FILE__,
4169
-                __FUNCTION__,
4170
-                __LINE__
4171
-            );
4172
-
4173
-            return false;
4174
-        }
4175
-        // activated
4176
-        if ($this->_template_args['data']['active_mts']) {
4177
-            EE_Error::overwrite_success();
4178
-            // activated a message type with the messenger
4179
-            if ($message_type instanceof EE_message_type) {
4180
-                EE_Error::add_success(
4181
-                    sprintf(
4182
-                        esc_html__(
4183
-                            '%s message type has been successfully activated with the %s messenger',
4184
-                            'event_espresso'
4185
-                        ),
4186
-                        ucwords($message_type->label['singular']),
4187
-                        ucwords($messenger->label['singular'])
4188
-                    )
4189
-                );
4190
-
4191
-                // if message type was invoice then let's make sure we activate the invoice payment method.
4192
-                if ($message_type->name === 'invoice') {
4193
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
4194
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4195
-                    if ($pm instanceof EE_Payment_Method) {
4196
-                        EE_Error::add_attention(
4197
-                            esc_html__(
4198
-                                '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.',
4199
-                                'event_espresso'
4200
-                            )
4201
-                        );
4202
-                    }
4203
-                }
4204
-                // just toggles the entire messenger
4205
-            } else {
4206
-                EE_Error::add_success(
4207
-                    sprintf(
4208
-                        esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4209
-                        ucwords($messenger->label['singular'])
4210
-                    )
4211
-                );
4212
-            }
4213
-
4214
-            return true;
4215
-
4216
-            // possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4217
-            // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4218
-            // in which case we just give a success message for the messenger being successfully activated.
4219
-        } else {
4220
-            if (! $messenger->get_default_message_types()) {
4221
-                // messenger doesn't have any default message types so still a success.
4222
-                EE_Error::add_success(
4223
-                    sprintf(
4224
-                        esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4225
-                        ucwords($messenger->label['singular'])
4226
-                    )
4227
-                );
4228
-
4229
-                return true;
4230
-            } else {
4231
-                EE_Error::add_error(
4232
-                    $message_type instanceof EE_message_type
4233
-                        ? sprintf(
4234
-                            esc_html__(
4235
-                                '%s message type was not successfully activated with the %s messenger',
4236
-                                'event_espresso'
4237
-                            ),
4238
-                            ucwords($message_type->label['singular']),
4239
-                            ucwords($messenger->label['singular'])
4240
-                        )
4241
-                        : sprintf(
4242
-                            esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4243
-                            ucwords($messenger->label['singular'])
4244
-                        ),
4245
-                    __FILE__,
4246
-                    __FUNCTION__,
4247
-                    __LINE__
4248
-                );
4249
-
4250
-                return false;
4251
-            }
4252
-        }
4253
-    }
4254
-
4255
-
4256
-    /**
4257
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
4258
-     *
4259
-     * @param EE_messenger         $messenger
4260
-     * @param EE_message_type|null $message_type
4261
-     * @return bool
4262
-     * @throws DomainException
4263
-     * @throws EE_Error
4264
-     * @throws InvalidArgumentException
4265
-     * @throws ReflectionException
4266
-     * @throws InvalidDataTypeException
4267
-     * @throws InvalidInterfaceException
4268
-     */
4269
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4270
-        $messenger,
4271
-        EE_message_type $message_type = null
4272
-    ) {
4273
-        EE_Error::overwrite_success();
4274
-
4275
-        // if $messenger isn't a valid messenger object then get out.
4276
-        if (! $messenger instanceof EE_Messenger) {
4277
-            EE_Error::add_error(
4278
-                esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4279
-                __FILE__,
4280
-                __FUNCTION__,
4281
-                __LINE__
4282
-            );
4283
-
4284
-            return false;
4285
-        }
4286
-
4287
-        if ($message_type instanceof EE_message_type) {
4288
-            $message_type_name = $message_type->name;
4289
-            EE_Error::add_success(
4290
-                sprintf(
4291
-                    esc_html__(
4292
-                        '%s message type has been successfully deactivated for the %s messenger.',
4293
-                        'event_espresso'
4294
-                    ),
4295
-                    ucwords($message_type->label['singular']),
4296
-                    ucwords($messenger->label['singular'])
4297
-                )
4298
-            );
4299
-        } else {
4300
-            $message_type_name = '';
4301
-            EE_Error::add_success(
4302
-                sprintf(
4303
-                    esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4304
-                    ucwords($messenger->label['singular'])
4305
-                )
4306
-            );
4307
-        }
4308
-
4309
-        // if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4310
-        if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4311
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
4312
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4313
-            if ($count_updated > 0) {
4314
-                $msg = $message_type_name === 'invoice'
4315
-                    ? esc_html__(
4316
-                        '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.',
4317
-                        'event_espresso'
4318
-                    )
4319
-                    : esc_html__(
4320
-                        '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.',
4321
-                        'event_espresso'
4322
-                    );
4323
-                EE_Error::add_attention($msg);
4324
-            }
4325
-        }
4326
-
4327
-        return true;
4328
-    }
4329
-
4330
-
4331
-    /**
4332
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4333
-     *
4334
-     * @throws DomainException
4335
-     */
4336
-    public function update_mt_form()
4337
-    {
4338
-        if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4339
-            EE_Error::add_error(
4340
-                esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4341
-                __FILE__,
4342
-                __FUNCTION__,
4343
-                __LINE__
4344
-            );
4345
-            $this->_return_json();
4346
-        }
4347
-
4348
-        $message_types = $this->get_installed_message_types();
4349
-
4350
-        $message_type = $message_types[ $this->_req_data['message_type'] ];
4351
-        $messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4352
-
4353
-        $content = $this->_message_type_settings_content(
4354
-            $message_type,
4355
-            $messenger,
4356
-            true
4357
-        );
4358
-        $this->_template_args['success'] = true;
4359
-        $this->_template_args['content'] = $content;
4360
-        $this->_return_json();
4361
-    }
4362
-
4363
-
4364
-    /**
4365
-     * this handles saving the settings for a messenger or message type
4366
-     *
4367
-     */
4368
-    public function save_settings()
4369
-    {
4370
-        if (! isset($this->_req_data['type'])) {
4371
-            EE_Error::add_error(
4372
-                esc_html__(
4373
-                    'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4374
-                    'event_espresso'
4375
-                ),
4376
-                __FILE__,
4377
-                __FUNCTION__,
4378
-                __LINE__
4379
-            );
4380
-            $this->_template_args['error'] = true;
4381
-            $this->_return_json();
4382
-        }
4383
-
4384
-
4385
-        if ($this->_req_data['type'] === 'messenger') {
4386
-            // this should be an array.
4387
-            $settings = $this->_req_data['messenger_settings'];
4388
-            $messenger = $settings['messenger'];
4389
-            // let's setup the settings data
4390
-            foreach ($settings as $key => $value) {
4391
-                switch ($key) {
4392
-                    case 'messenger':
4393
-                        unset($settings['messenger']);
4394
-                        break;
4395
-                    case 'message_types':
4396
-                        unset($settings['message_types']);
4397
-                        break;
4398
-                    default:
4399
-                        $settings[ $key ] = $value;
4400
-                        break;
4401
-                }
4402
-            }
4403
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4404
-        } elseif ($this->_req_data['type'] === 'message_type') {
4405
-            $settings = $this->_req_data['message_type_settings'];
4406
-            $messenger = $settings['messenger'];
4407
-            $message_type = $settings['message_type'];
4408
-
4409
-            foreach ($settings as $key => $value) {
4410
-                switch ($key) {
4411
-                    case 'messenger':
4412
-                        unset($settings['messenger']);
4413
-                        break;
4414
-                    case 'message_type':
4415
-                        unset($settings['message_type']);
4416
-                        break;
4417
-                    default:
4418
-                        $settings[ $key ] = $value;
4419
-                        break;
4420
-                }
4421
-            }
4422
-
4423
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4424
-        }
4425
-
4426
-        // okay we should have the data all setup.  Now we just update!
4427
-        $success = $this->_message_resource_manager->update_active_messengers_option();
4428
-
4429
-        if ($success) {
4430
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
4431
-        } else {
4432
-            EE_Error::add_error(
4433
-                esc_html__(
4434
-                    'Settings did not get updated',
4435
-                    'event_espresso'
4436
-                ),
4437
-                __FILE__,
4438
-                __FUNCTION__,
4439
-                __LINE__
4440
-            );
4441
-        }
4442
-
4443
-        $this->_template_args['success'] = $success;
4444
-        $this->_return_json();
4445
-    }
4446
-
4447
-
4448
-
4449
-
4450
-    /**  EE MESSAGE PROCESSING ACTIONS **/
4451
-
4452
-
4453
-    /**
4454
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4455
-     * However, this does not send immediately, it just queues for sending.
4456
-     *
4457
-     * @since 4.9.0
4458
-     * @throws EE_Error
4459
-     * @throws InvalidDataTypeException
4460
-     * @throws InvalidInterfaceException
4461
-     * @throws InvalidArgumentException
4462
-     * @throws ReflectionException
4463
-     */
4464
-    protected function _generate_now()
4465
-    {
4466
-        EED_Messages::generate_now($this->_get_msg_ids_from_request());
4467
-        $this->_redirect_after_action(false, '', '', array(), true);
4468
-    }
4469
-
4470
-
4471
-    /**
4472
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4473
-     * are EEM_Message::status_resend or EEM_Message::status_idle
4474
-     *
4475
-     * @since 4.9.0
4476
-     * @throws EE_Error
4477
-     * @throws InvalidDataTypeException
4478
-     * @throws InvalidInterfaceException
4479
-     * @throws InvalidArgumentException
4480
-     * @throws ReflectionException
4481
-     */
4482
-    protected function _generate_and_send_now()
4483
-    {
4484
-        EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4485
-        $this->_redirect_after_action(false, '', '', array(), true);
4486
-    }
4487
-
4488
-
4489
-    /**
4490
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4491
-     *
4492
-     * @since 4.9.0
4493
-     * @throws EE_Error
4494
-     * @throws InvalidDataTypeException
4495
-     * @throws InvalidInterfaceException
4496
-     * @throws InvalidArgumentException
4497
-     * @throws ReflectionException
4498
-     */
4499
-    protected function _queue_for_resending()
4500
-    {
4501
-        EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4502
-        $this->_redirect_after_action(false, '', '', array(), true);
4503
-    }
4504
-
4505
-
4506
-    /**
4507
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4508
-     *
4509
-     * @since 4.9.0
4510
-     * @throws EE_Error
4511
-     * @throws InvalidDataTypeException
4512
-     * @throws InvalidInterfaceException
4513
-     * @throws InvalidArgumentException
4514
-     * @throws ReflectionException
4515
-     */
4516
-    protected function _send_now()
4517
-    {
4518
-        EED_Messages::send_now($this->_get_msg_ids_from_request());
4519
-        $this->_redirect_after_action(false, '', '', array(), true);
4520
-    }
4521
-
4522
-
4523
-    /**
4524
-     * Deletes EE_messages for IDs in the request.
4525
-     *
4526
-     * @since 4.9.0
4527
-     * @throws EE_Error
4528
-     * @throws InvalidDataTypeException
4529
-     * @throws InvalidInterfaceException
4530
-     * @throws InvalidArgumentException
4531
-     */
4532
-    protected function _delete_ee_messages()
4533
-    {
4534
-        $msg_ids = $this->_get_msg_ids_from_request();
4535
-        $deleted_count = 0;
4536
-        foreach ($msg_ids as $msg_id) {
4537
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4538
-                $deleted_count++;
4539
-            }
4540
-        }
4541
-        if ($deleted_count) {
4542
-            EE_Error::add_success(
4543
-                esc_html(
4544
-                    _n(
4545
-                        'Message successfully deleted',
4546
-                        'Messages successfully deleted',
4547
-                        $deleted_count,
4548
-                        'event_espresso'
4549
-                    )
4550
-                )
4551
-            );
4552
-            $this->_redirect_after_action(
4553
-                false,
4554
-                '',
4555
-                '',
4556
-                array(),
4557
-                true
4558
-            );
4559
-        } else {
4560
-            EE_Error::add_error(
4561
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4562
-                __FILE__,
4563
-                __FUNCTION__,
4564
-                __LINE__
4565
-            );
4566
-            $this->_redirect_after_action(false, '', '', array(), true);
4567
-        }
4568
-    }
4569
-
4570
-
4571
-    /**
4572
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4573
-     *
4574
-     * @since 4.9.0
4575
-     * @return array
4576
-     */
4577
-    protected function _get_msg_ids_from_request()
4578
-    {
4579
-        if (! isset($this->_req_data['MSG_ID'])) {
4580
-            return array();
4581
-        }
4582
-
4583
-        return is_array($this->_req_data['MSG_ID'])
4584
-            ? array_keys($this->_req_data['MSG_ID'])
4585
-            : array($this->_req_data['MSG_ID']);
4586
-    }
2666
+		$output = ob_get_contents();
2667
+		ob_clean();
2668
+		$this->_context_switcher = $output;
2669
+	}
2670
+
2671
+
2672
+	/**
2673
+	 * utility for sanitizing new values coming in.
2674
+	 * Note: this is only used when updating a context.
2675
+	 *
2676
+	 * @access protected
2677
+	 *
2678
+	 * @param int $index This helps us know which template field to select from the request array.
2679
+	 *
2680
+	 * @return array
2681
+	 */
2682
+	protected function _set_message_template_column_values($index)
2683
+	{
2684
+		if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2685
+			foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2686
+				$this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2687
+			}
2688
+		}
2689
+
2690
+
2691
+		$set_column_values = array(
2692
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2693
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2694
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2695
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2696
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2697
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2698
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2699
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2700
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2701
+				? absint($this->_req_data['MTP_is_global'])
2702
+				: 0,
2703
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2704
+				? absint($this->_req_data['MTP_is_override'])
2705
+				: 0,
2706
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2707
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2708
+		);
2709
+
2710
+
2711
+		return $set_column_values;
2712
+	}
2713
+
2714
+
2715
+	protected function _insert_or_update_message_template($new = false)
2716
+	{
2717
+
2718
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2719
+		$success = 0;
2720
+		$override = false;
2721
+
2722
+		// setup notices description
2723
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2724
+
2725
+		// need the message type and messenger objects to be able to use the labels for the notices
2726
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2727
+		$messenger_label = $messenger_object instanceof EE_messenger
2728
+			? ucwords($messenger_object->label['singular'])
2729
+			: '';
2730
+
2731
+		$message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2732
+			? $this->_req_data['MTP_message_type']
2733
+			: '';
2734
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2735
+
2736
+		$message_type_label = $message_type_object instanceof EE_message_type
2737
+			? ucwords($message_type_object->label['singular'])
2738
+			: '';
2739
+
2740
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2741
+			? $this->_req_data['MTP_context']
2742
+			: '';
2743
+		$context = ucwords(str_replace('_', ' ', $context_slug));
2744
+
2745
+		$item_desc = $messenger_label && $message_type_label
2746
+			? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2747
+			: '';
2748
+		$item_desc .= 'Message Template';
2749
+		$query_args = array();
2750
+		$edit_array = array();
2751
+		$action_desc = '';
2752
+
2753
+		// if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2754
+		// user to edit.
2755
+		if ($new) {
2756
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2757
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2758
+				if (empty($edit_array)) {
2759
+					$success = 0;
2760
+				} else {
2761
+					$success = 1;
2762
+					$edit_array = $edit_array[0];
2763
+					$query_args = array(
2764
+						'id'      => $edit_array['GRP_ID'],
2765
+						'context' => $edit_array['MTP_context'],
2766
+						'action'  => 'edit_message_template',
2767
+					);
2768
+				}
2769
+			}
2770
+			$action_desc = 'created';
2771
+		} else {
2772
+			$MTPG = EEM_Message_Template_Group::instance();
2773
+			$MTP = EEM_Message_Template::instance();
2774
+
2775
+
2776
+			// run update for each template field in displayed context
2777
+			if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2778
+				EE_Error::add_error(
2779
+					esc_html__(
2780
+						'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2781
+						'event_espresso'
2782
+					),
2783
+					__FILE__,
2784
+					__FUNCTION__,
2785
+					__LINE__
2786
+				);
2787
+				$success = 0;
2788
+			} else {
2789
+				// first validate all fields!
2790
+				// this filter allows client code to add its own validation to the template fields as well.
2791
+				// returning an empty array means everything passed validation.
2792
+				// errors in validation should be represented in an array with the following shape:
2793
+				// array(
2794
+				//   'fieldname' => array(
2795
+				//          'msg' => 'error message'
2796
+				//          'value' => 'value for field producing error'
2797
+				// )
2798
+				$custom_validation = (array) apply_filters(
2799
+					'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2800
+					array(),
2801
+					$this->_req_data['MTP_template_fields'],
2802
+					$context_slug,
2803
+					$messenger_slug,
2804
+					$message_type_slug
2805
+				);
2806
+
2807
+				$system_validation = $MTPG->validate(
2808
+					$this->_req_data['MTP_template_fields'],
2809
+					$context_slug,
2810
+					$messenger_slug,
2811
+					$message_type_slug
2812
+				);
2813
+
2814
+				$system_validation = ! is_array($system_validation) && $system_validation ? array()
2815
+					: $system_validation;
2816
+				$validates = array_merge($custom_validation, $system_validation);
2817
+
2818
+				// if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2819
+				// appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2820
+				//  WE need to make sure there is no actual error messages in validates.
2821
+				if (is_array($validates) && ! empty($validates)) {
2822
+					// add the transient so when the form loads we know which fields to highlight
2823
+					$this->_add_transient('edit_message_template', $validates);
2824
+
2825
+					$success = 0;
2826
+
2827
+					// setup notices
2828
+					foreach ($validates as $field => $error) {
2829
+						if (isset($error['msg'])) {
2830
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2831
+						}
2832
+					}
2833
+				} else {
2834
+					$set_column_values = array();
2835
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2836
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2837
+
2838
+						$where_cols_n_values = array(
2839
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2840
+						);
2841
+						// if they aren't allowed to use all JS, restrict them to just posty-y tags
2842
+						if (! current_user_can('unfiltered_html')) {
2843
+							if (is_array($set_column_values['MTP_content'])) {
2844
+								foreach ($set_column_values['MTP_content'] as $key => $value) {
2845
+									// remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2846
+									// only removes slashes from double-quotes, so attributes using single quotes always
2847
+									// appear invalid.) But currently the models expect slashed data, so after wp_kses
2848
+									// runs we need to re-slash the data. Sheesh. See
2849
+									// https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2850
+									$set_column_values['MTP_content'][ $key ] = addslashes(
2851
+										wp_kses(
2852
+											stripslashes($value),
2853
+											wp_kses_allowed_html('post')
2854
+										)
2855
+									);
2856
+								}
2857
+							} else {
2858
+								$set_column_values['MTP_content'] = wp_kses(
2859
+									$set_column_values['MTP_content'],
2860
+									wp_kses_allowed_html('post')
2861
+								);
2862
+							}
2863
+						}
2864
+						$message_template_fields = array(
2865
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2866
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2867
+							'MTP_context'        => $set_column_values['MTP_context'],
2868
+							'MTP_content'        => $set_column_values['MTP_content'],
2869
+						);
2870
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2871
+							if ($updated === false) {
2872
+								EE_Error::add_error(
2873
+									sprintf(
2874
+										esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2875
+										$template_field
2876
+									),
2877
+									__FILE__,
2878
+									__FUNCTION__,
2879
+									__LINE__
2880
+								);
2881
+							} else {
2882
+								$success = 1;
2883
+							}
2884
+						} else {
2885
+							// only do this logic if we don't have a MTP_ID for this field
2886
+							if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2887
+								// this has already been through the template field validator and sanitized, so it will be
2888
+								// safe to insert this field.  Why insert?  This typically happens when we introduce a new
2889
+								// message template field in a messenger/message type and existing users don't have the
2890
+								// default setup for it.
2891
+								// @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2892
+								$updated = $MTP->insert($message_template_fields);
2893
+								if (! $updated || is_wp_error($updated)) {
2894
+									EE_Error::add_error(
2895
+										sprintf(
2896
+											esc_html__('%s field could not be updated.', 'event_espresso'),
2897
+											$template_field
2898
+										),
2899
+										__FILE__,
2900
+										__FUNCTION__,
2901
+										__LINE__
2902
+									);
2903
+									$success = 0;
2904
+								} else {
2905
+									$success = 1;
2906
+								}
2907
+							}
2908
+						}
2909
+						$action_desc = 'updated';
2910
+					}
2911
+
2912
+					// we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2913
+					$mtpg_fields = array(
2914
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2915
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2916
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2917
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2918
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2919
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2920
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2921
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2922
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2923
+							: '',
2924
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2925
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2926
+							: '',
2927
+					);
2928
+
2929
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2930
+					$updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2931
+
2932
+					if ($updated === false) {
2933
+						EE_Error::add_error(
2934
+							sprintf(
2935
+								esc_html__(
2936
+									'The Message Template Group (%d) was NOT updated for some reason',
2937
+									'event_espresso'
2938
+								),
2939
+								$set_column_values['GRP_ID']
2940
+							),
2941
+							__FILE__,
2942
+							__FUNCTION__,
2943
+							__LINE__
2944
+						);
2945
+					} else {
2946
+						// k now we need to ensure the template_pack and template_variation fields are set.
2947
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2948
+							? $this->_req_data['MTP_template_pack']
2949
+							: 'default';
2950
+
2951
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2952
+							? $this->_req_data['MTP_template_variation']
2953
+							: 'default';
2954
+
2955
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2956
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2957
+							$mtpg_obj->set_template_pack_name($template_pack);
2958
+							$mtpg_obj->set_template_pack_variation($template_variation);
2959
+						}
2960
+						$success = 1;
2961
+					}
2962
+				}
2963
+			}
2964
+		}
2965
+
2966
+		// we return things differently if doing ajax
2967
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2968
+			$this->_template_args['success'] = $success;
2969
+			$this->_template_args['error'] = ! $success ? true : false;
2970
+			$this->_template_args['content'] = '';
2971
+			$this->_template_args['data'] = array(
2972
+				'grpID'        => $edit_array['GRP_ID'],
2973
+				'templateName' => $edit_array['template_name'],
2974
+			);
2975
+			if ($success) {
2976
+				EE_Error::overwrite_success();
2977
+				EE_Error::add_success(
2978
+					esc_html__(
2979
+						'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.',
2980
+						'event_espresso'
2981
+					)
2982
+				);
2983
+			}
2984
+
2985
+			$this->_return_json();
2986
+		}
2987
+
2988
+
2989
+		// was a test send triggered?
2990
+		if (isset($this->_req_data['test_button'])) {
2991
+			EE_Error::overwrite_success();
2992
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2993
+			$override = true;
2994
+		}
2995
+
2996
+		if (empty($query_args)) {
2997
+			$query_args = array(
2998
+				'id'      => $this->_req_data['GRP_ID'],
2999
+				'context' => $context_slug,
3000
+				'action'  => 'edit_message_template',
3001
+			);
3002
+		}
3003
+
3004
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
3005
+	}
3006
+
3007
+
3008
+	/**
3009
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
3010
+	 *
3011
+	 * @param  string $context      what context being tested
3012
+	 * @param  string $messenger    messenger being tested
3013
+	 * @param  string $message_type message type being tested
3014
+	 * @throws EE_Error
3015
+	 * @throws InvalidArgumentException
3016
+	 * @throws InvalidDataTypeException
3017
+	 * @throws InvalidInterfaceException
3018
+	 */
3019
+	protected function _do_test_send($context, $messenger, $message_type)
3020
+	{
3021
+		// set things up for preview
3022
+		$this->_req_data['messenger'] = $messenger;
3023
+		$this->_req_data['message_type'] = $message_type;
3024
+		$this->_req_data['context'] = $context;
3025
+		$this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
3026
+		$active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
3027
+
3028
+		// let's save any existing fields that might be required by the messenger
3029
+		if (isset($this->_req_data['test_settings_fld'])
3030
+			&& $active_messenger instanceof EE_messenger
3031
+			&& apply_filters(
3032
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3033
+				true,
3034
+				$this->_req_data['test_settings_fld'],
3035
+				$active_messenger
3036
+			)
3037
+		) {
3038
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
3039
+		}
3040
+
3041
+		/**
3042
+		 * Use filter to add additional controls on whether message can send or not
3043
+		 */
3044
+		if (apply_filters(
3045
+			'FHEE__Messages_Admin_Page__do_test_send__can_send',
3046
+			true,
3047
+			$context,
3048
+			$this->_req_data,
3049
+			$messenger,
3050
+			$message_type
3051
+		)) {
3052
+			if (EEM_Event::instance()->count() > 0) {
3053
+				$success = $this->_preview_message(true);
3054
+				if ($success) {
3055
+					EE_Error::add_success(__('Test message sent', 'event_espresso'));
3056
+				} else {
3057
+					EE_Error::add_error(
3058
+						esc_html__('The test message was not sent', 'event_espresso'),
3059
+						__FILE__,
3060
+						__FUNCTION__,
3061
+						__LINE__
3062
+					);
3063
+				}
3064
+			} else {
3065
+				$this->noEventsErrorMessage(true);
3066
+			}
3067
+		}
3068
+	}
3069
+
3070
+
3071
+	/**
3072
+	 * _generate_new_templates
3073
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3074
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3075
+	 * for the event.
3076
+	 *
3077
+	 *
3078
+	 * @param  string $messenger     the messenger we are generating templates for
3079
+	 * @param array   $message_types array of message types that the templates are generated for.
3080
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3081
+	 *                               indicate the message_template_group being used as the base.
3082
+	 *
3083
+	 * @param bool    $global
3084
+	 *
3085
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
3086
+	 *                               encountering problems.
3087
+	 * @throws EE_Error
3088
+	 */
3089
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3090
+	{
3091
+
3092
+		// if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3093
+		// just don't generate any templates.
3094
+		if (empty($message_types)) {
3095
+			return true;
3096
+		}
3097
+
3098
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3099
+	}
3100
+
3101
+
3102
+	/**
3103
+	 * [_trash_or_restore_message_template]
3104
+	 *
3105
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3106
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3107
+	 *                        an individual context (FALSE).
3108
+	 * @return void
3109
+	 * @throws EE_Error
3110
+	 * @throws InvalidArgumentException
3111
+	 * @throws InvalidDataTypeException
3112
+	 * @throws InvalidInterfaceException
3113
+	 */
3114
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
3115
+	{
3116
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3117
+		$MTP = EEM_Message_Template_Group::instance();
3118
+
3119
+		$success = 1;
3120
+
3121
+		// incoming GRP_IDs
3122
+		if ($all) {
3123
+			// Checkboxes
3124
+			if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3125
+				// if array has more than one element then success message should be plural.
3126
+				// todo: what about nonce?
3127
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3128
+
3129
+				// cycle through checkboxes
3130
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3131
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3132
+					if (! $trashed_or_restored) {
3133
+						$success = 0;
3134
+					}
3135
+				}
3136
+			} else {
3137
+				// grab single GRP_ID and handle
3138
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3139
+				if (! empty($GRP_ID)) {
3140
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3141
+					if (! $trashed_or_restored) {
3142
+						$success = 0;
3143
+					}
3144
+				} else {
3145
+					$success = 0;
3146
+				}
3147
+			}
3148
+		}
3149
+
3150
+		$action_desc = $trash
3151
+			? esc_html__('moved to the trash', 'event_espresso')
3152
+			: esc_html__('restored', 'event_espresso');
3153
+
3154
+		$action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3155
+
3156
+		$item_desc = $all ? _n(
3157
+			'Message Template Group',
3158
+			'Message Template Groups',
3159
+			$success,
3160
+			'event_espresso'
3161
+		) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3162
+
3163
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3164
+			'template',
3165
+			'templates',
3166
+			$success,
3167
+			'event_espresso'
3168
+		) : $item_desc;
3169
+
3170
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
3171
+	}
3172
+
3173
+
3174
+	/**
3175
+	 * [_delete_message_template]
3176
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3177
+	 *
3178
+	 * @return void
3179
+	 * @throws EE_Error
3180
+	 * @throws InvalidArgumentException
3181
+	 * @throws InvalidDataTypeException
3182
+	 * @throws InvalidInterfaceException
3183
+	 */
3184
+	protected function _delete_message_template()
3185
+	{
3186
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3187
+
3188
+		// checkboxes
3189
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3190
+			// if array has more than one element then success message should be plural
3191
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3192
+
3193
+			// cycle through bulk action checkboxes
3194
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3195
+				$success = $this->_delete_mtp_permanently($GRP_ID);
3196
+			}
3197
+		} else {
3198
+			// grab single grp_id and delete
3199
+			$GRP_ID = absint($this->_req_data['id']);
3200
+			$success = $this->_delete_mtp_permanently($GRP_ID);
3201
+		}
3202
+
3203
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3204
+	}
3205
+
3206
+
3207
+	/**
3208
+	 * helper for permanently deleting a mtP group and all related message_templates
3209
+	 *
3210
+	 * @param  int  $GRP_ID        The group being deleted
3211
+	 * @param  bool $include_group whether to delete the Message Template Group as well.
3212
+	 * @return bool boolean to indicate the success of the deletes or not.
3213
+	 * @throws EE_Error
3214
+	 * @throws InvalidArgumentException
3215
+	 * @throws InvalidDataTypeException
3216
+	 * @throws InvalidInterfaceException
3217
+	 */
3218
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3219
+	{
3220
+		$success = 1;
3221
+		$MTPG = EEM_Message_Template_Group::instance();
3222
+		// first let's GET this group
3223
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
3224
+		// then delete permanently all the related Message Templates
3225
+		$deleted = $MTG->delete_related_permanently('Message_Template');
3226
+
3227
+		if ($deleted === 0) {
3228
+			$success = 0;
3229
+		}
3230
+
3231
+		// now delete permanently this particular group
3232
+
3233
+		if ($include_group && ! $MTG->delete_permanently()) {
3234
+			$success = 0;
3235
+		}
3236
+
3237
+		return $success;
3238
+	}
3239
+
3240
+
3241
+	/**
3242
+	 *    _learn_more_about_message_templates_link
3243
+	 *
3244
+	 * @access protected
3245
+	 * @return string
3246
+	 */
3247
+	protected function _learn_more_about_message_templates_link()
3248
+	{
3249
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3250
+			   . esc_html__('learn more about how message templates works', 'event_espresso')
3251
+			   . '</a>';
3252
+	}
3253
+
3254
+
3255
+	/**
3256
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3257
+	 * ajax and other routes.
3258
+	 *
3259
+	 * @return void
3260
+	 * @throws DomainException
3261
+	 */
3262
+	protected function _settings()
3263
+	{
3264
+
3265
+
3266
+		$this->_set_m_mt_settings();
3267
+
3268
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3269
+			? $this->_req_data['selected_messenger']
3270
+			: 'email';
3271
+
3272
+		// let's setup the messenger tabs
3273
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3274
+			$this->_m_mt_settings['messenger_tabs'],
3275
+			'messenger_links',
3276
+			'|',
3277
+			$selected_messenger
3278
+		);
3279
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3280
+		$this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3281
+
3282
+		$this->display_admin_page_with_sidebar();
3283
+	}
3284
+
3285
+
3286
+	/**
3287
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3288
+	 *
3289
+	 * @access protected
3290
+	 * @return void
3291
+	 * @throws DomainException
3292
+	 */
3293
+	protected function _set_m_mt_settings()
3294
+	{
3295
+		// first if this is already set then lets get out no need to regenerate data.
3296
+		if (! empty($this->_m_mt_settings)) {
3297
+			return;
3298
+		}
3299
+
3300
+		// get all installed messengers and message_types
3301
+		/** @type EE_messenger[] $messengers */
3302
+		$messengers = $this->_message_resource_manager->installed_messengers();
3303
+		/** @type EE_message_type[] $message_types */
3304
+		$message_types = $this->_message_resource_manager->installed_message_types();
3305
+
3306
+
3307
+		// assemble the array for the _tab_text_links helper
3308
+
3309
+		foreach ($messengers as $messenger) {
3310
+			$this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3311
+				'label' => ucwords($messenger->label['singular']),
3312
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3313
+					? 'messenger-active'
3314
+					: '',
3315
+				'href'  => $messenger->name,
3316
+				'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3317
+				'slug'  => $messenger->name,
3318
+				'obj'   => $messenger,
3319
+			);
3320
+
3321
+
3322
+			$message_types_for_messenger = $messenger->get_valid_message_types();
3323
+
3324
+			foreach ($message_types as $message_type) {
3325
+				// first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3326
+				// it shouldn't show in either the inactive OR active metabox.
3327
+				if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3328
+					continue;
3329
+				}
3330
+
3331
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3332
+					$messenger->name,
3333
+					$message_type->name
3334
+				)
3335
+					? 'active'
3336
+					: 'inactive';
3337
+
3338
+				$this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3339
+					'label'    => ucwords($message_type->label['singular']),
3340
+					'class'    => 'message-type-' . $a_or_i,
3341
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3342
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3343
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3344
+					'title'    => $a_or_i === 'active'
3345
+						? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3346
+						: esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3347
+					'content'  => $a_or_i === 'active'
3348
+						? $this->_message_type_settings_content($message_type, $messenger, true)
3349
+						: $this->_message_type_settings_content($message_type, $messenger),
3350
+					'slug'     => $message_type->name,
3351
+					'active'   => $a_or_i === 'active',
3352
+					'obj'      => $message_type,
3353
+				);
3354
+			}
3355
+		}
3356
+	}
3357
+
3358
+
3359
+	/**
3360
+	 * This just prepares the content for the message type settings
3361
+	 *
3362
+	 * @param  EE_message_type $message_type The message type object
3363
+	 * @param  EE_messenger    $messenger    The messenger object
3364
+	 * @param  boolean         $active       Whether the message type is active or not
3365
+	 * @return string html output for the content
3366
+	 * @throws DomainException
3367
+	 */
3368
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
3369
+	{
3370
+		// get message type fields
3371
+		$fields = $message_type->get_admin_settings_fields();
3372
+		$settings_template_args['template_form_fields'] = '';
3373
+
3374
+		if (! empty($fields) && $active) {
3375
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3376
+			foreach ($fields as $fldname => $fldprops) {
3377
+				$field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3378
+				$template_form_field[ $field_id ] = array(
3379
+					'name'       => 'message_type_settings[' . $fldname . ']',
3380
+					'label'      => $fldprops['label'],
3381
+					'input'      => $fldprops['field_type'],
3382
+					'type'       => $fldprops['value_type'],
3383
+					'required'   => $fldprops['required'],
3384
+					'validation' => $fldprops['validation'],
3385
+					'value'      => isset($existing_settings[ $fldname ])
3386
+						? $existing_settings[ $fldname ]
3387
+						: $fldprops['default'],
3388
+					'options'    => isset($fldprops['options'])
3389
+						? $fldprops['options']
3390
+						: array(),
3391
+					'default'    => isset($existing_settings[ $fldname ])
3392
+						? $existing_settings[ $fldname ]
3393
+						: $fldprops['default'],
3394
+					'css_class'  => 'no-drag',
3395
+					'format'     => $fldprops['format'],
3396
+				);
3397
+			}
3398
+
3399
+
3400
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3401
+				? $this->_generate_admin_form_fields(
3402
+					$template_form_field,
3403
+					'string',
3404
+					'ee_mt_activate_form'
3405
+				)
3406
+				: '';
3407
+		}
3408
+
3409
+		$settings_template_args['description'] = $message_type->description;
3410
+		// we also need some hidden fields
3411
+		$settings_template_args['hidden_fields'] = array(
3412
+			'message_type_settings[messenger]'    => array(
3413
+				'type'  => 'hidden',
3414
+				'value' => $messenger->name,
3415
+			),
3416
+			'message_type_settings[message_type]' => array(
3417
+				'type'  => 'hidden',
3418
+				'value' => $message_type->name,
3419
+			),
3420
+			'type'                                => array(
3421
+				'type'  => 'hidden',
3422
+				'value' => 'message_type',
3423
+			),
3424
+		);
3425
+
3426
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3427
+			$settings_template_args['hidden_fields'],
3428
+			'array'
3429
+		);
3430
+		$settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3431
+			? ' hidden'
3432
+			: '';
3433
+
3434
+
3435
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3436
+		$content = EEH_Template::display_template($template, $settings_template_args, true);
3437
+
3438
+		return $content;
3439
+	}
3440
+
3441
+
3442
+	/**
3443
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
3444
+	 *
3445
+	 * @access protected
3446
+	 * @return void
3447
+	 * @throws DomainException
3448
+	 */
3449
+	protected function _messages_settings_metaboxes()
3450
+	{
3451
+		$this->_set_m_mt_settings();
3452
+		$m_boxes = $mt_boxes = array();
3453
+		$m_template_args = $mt_template_args = array();
3454
+
3455
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3456
+			? $this->_req_data['selected_messenger']
3457
+			: 'email';
3458
+
3459
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
3460
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3461
+				$hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3462
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3463
+				// messenger meta boxes
3464
+				$active = $selected_messenger === $messenger;
3465
+				$active_mt_tabs = isset(
3466
+					$this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3467
+				)
3468
+					? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3469
+					: '';
3470
+				$m_boxes[ $messenger . '_a_box' ] = sprintf(
3471
+					esc_html__('%s Settings', 'event_espresso'),
3472
+					$tab_array['label']
3473
+				);
3474
+				$m_template_args[ $messenger . '_a_box' ] = array(
3475
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3476
+					'inactive_message_types' => isset(
3477
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3478
+					)
3479
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3480
+						: '',
3481
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3482
+					'hidden'                 => $active ? '' : ' hidden',
3483
+					'hide_on_message'        => $hide_on_message,
3484
+					'messenger'              => $messenger,
3485
+					'active'                 => $active,
3486
+				);
3487
+				// message type meta boxes
3488
+				// (which is really just the inactive container for each messenger
3489
+				// showing inactive message types for that messenger)
3490
+				$mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3491
+				$mt_template_args[ $messenger . '_i_box' ] = array(
3492
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3493
+					'inactive_message_types' => isset(
3494
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3495
+					)
3496
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3497
+						: '',
3498
+					'hidden'                 => $active ? '' : ' hidden',
3499
+					'hide_on_message'        => $hide_on_message,
3500
+					'hide_off_message'       => $hide_off_message,
3501
+					'messenger'              => $messenger,
3502
+					'active'                 => $active,
3503
+				);
3504
+			}
3505
+		}
3506
+
3507
+
3508
+		// register messenger metaboxes
3509
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3510
+		foreach ($m_boxes as $box => $label) {
3511
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3512
+			$msgr = str_replace('_a_box', '', $box);
3513
+			add_meta_box(
3514
+				'espresso_' . $msgr . '_settings',
3515
+				$label,
3516
+				function ($post, $metabox) {
3517
+					echo EEH_Template::display_template(
3518
+						$metabox["args"]["template_path"],
3519
+						$metabox["args"]["template_args"],
3520
+						true
3521
+					);
3522
+				},
3523
+				$this->_current_screen->id,
3524
+				'normal',
3525
+				'high',
3526
+				$callback_args
3527
+			);
3528
+		}
3529
+
3530
+		// register message type metaboxes
3531
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3532
+		foreach ($mt_boxes as $box => $label) {
3533
+			$callback_args = array(
3534
+				'template_path' => $mt_template_path,
3535
+				'template_args' => $mt_template_args[ $box ],
3536
+			);
3537
+			$mt = str_replace('_i_box', '', $box);
3538
+			add_meta_box(
3539
+				'espresso_' . $mt . '_inactive_mts',
3540
+				$label,
3541
+				function ($post, $metabox) {
3542
+					echo EEH_Template::display_template(
3543
+						$metabox["args"]["template_path"],
3544
+						$metabox["args"]["template_args"],
3545
+						true
3546
+					);
3547
+				},
3548
+				$this->_current_screen->id,
3549
+				'side',
3550
+				'high',
3551
+				$callback_args
3552
+			);
3553
+		}
3554
+
3555
+		// register metabox for global messages settings but only when on the main site.  On single site installs this
3556
+		// will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3557
+		if (is_main_site()) {
3558
+			add_meta_box(
3559
+				'espresso_global_message_settings',
3560
+				esc_html__('Global Message Settings', 'event_espresso'),
3561
+				array($this, 'global_messages_settings_metabox_content'),
3562
+				$this->_current_screen->id,
3563
+				'normal',
3564
+				'low',
3565
+				array()
3566
+			);
3567
+		}
3568
+	}
3569
+
3570
+
3571
+	/**
3572
+	 *  This generates the content for the global messages settings metabox.
3573
+	 *
3574
+	 * @return string
3575
+	 * @throws EE_Error
3576
+	 * @throws InvalidArgumentException
3577
+	 * @throws ReflectionException
3578
+	 * @throws InvalidDataTypeException
3579
+	 * @throws InvalidInterfaceException
3580
+	 */
3581
+	public function global_messages_settings_metabox_content()
3582
+	{
3583
+		$form = $this->_generate_global_settings_form();
3584
+		echo $form->form_open(
3585
+			$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3586
+			'POST'
3587
+		)
3588
+			 . $form->get_html()
3589
+			 . $form->form_close();
3590
+	}
3591
+
3592
+
3593
+	/**
3594
+	 * This generates and returns the form object for the global messages settings.
3595
+	 *
3596
+	 * @return EE_Form_Section_Proper
3597
+	 * @throws EE_Error
3598
+	 * @throws InvalidArgumentException
3599
+	 * @throws ReflectionException
3600
+	 * @throws InvalidDataTypeException
3601
+	 * @throws InvalidInterfaceException
3602
+	 */
3603
+	protected function _generate_global_settings_form()
3604
+	{
3605
+		EE_Registry::instance()->load_helper('HTML');
3606
+		/** @var EE_Network_Core_Config $network_config */
3607
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3608
+
3609
+		return new EE_Form_Section_Proper(
3610
+			array(
3611
+				'name'            => 'global_messages_settings',
3612
+				'html_id'         => 'global_messages_settings',
3613
+				'html_class'      => 'form-table',
3614
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3615
+				'subsections'     => apply_filters(
3616
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3617
+					array(
3618
+						'do_messages_on_same_request' => new EE_Select_Input(
3619
+							array(
3620
+								true  => esc_html__("On the same request", "event_espresso"),
3621
+								false => esc_html__("On a separate request", "event_espresso"),
3622
+							),
3623
+							array(
3624
+								'default'         => $network_config->do_messages_on_same_request,
3625
+								'html_label_text' => esc_html__(
3626
+									'Generate and send all messages:',
3627
+									'event_espresso'
3628
+								),
3629
+								'html_help_text'  => esc_html__(
3630
+									'By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3631
+									'event_espresso'
3632
+								),
3633
+							)
3634
+						),
3635
+						'delete_threshold'            => new EE_Select_Input(
3636
+							array(
3637
+								0  => esc_html__('Forever', 'event_espresso'),
3638
+								3  => esc_html__('3 Months', 'event_espresso'),
3639
+								6  => esc_html__('6 Months', 'event_espresso'),
3640
+								9  => esc_html__('9 Months', 'event_espresso'),
3641
+								12 => esc_html__('12 Months', 'event_espresso'),
3642
+								24 => esc_html__('24 Months', 'event_espresso'),
3643
+								36 => esc_html__('36 Months', 'event_espresso'),
3644
+							),
3645
+							array(
3646
+								'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3647
+								'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3648
+								'html_help_text'  => esc_html__(
3649
+									'You can control how long a record of processed messages is kept via this option.',
3650
+									'event_espresso'
3651
+								),
3652
+							)
3653
+						),
3654
+						'update_settings'             => new EE_Submit_Input(
3655
+							array(
3656
+								'default'         => esc_html__('Update', 'event_espresso'),
3657
+								'html_label_text' => '&nbsp',
3658
+							)
3659
+						),
3660
+					)
3661
+				),
3662
+			)
3663
+		);
3664
+	}
3665
+
3666
+
3667
+	/**
3668
+	 * This handles updating the global settings set on the admin page.
3669
+	 *
3670
+	 * @throws EE_Error
3671
+	 * @throws InvalidDataTypeException
3672
+	 * @throws InvalidInterfaceException
3673
+	 * @throws InvalidArgumentException
3674
+	 * @throws ReflectionException
3675
+	 */
3676
+	protected function _update_global_settings()
3677
+	{
3678
+		/** @var EE_Network_Core_Config $network_config */
3679
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3680
+		$messages_config = EE_Registry::instance()->CFG->messages;
3681
+		$form = $this->_generate_global_settings_form();
3682
+		if ($form->was_submitted()) {
3683
+			$form->receive_form_submission();
3684
+			if ($form->is_valid()) {
3685
+				$valid_data = $form->valid_data();
3686
+				foreach ($valid_data as $property => $value) {
3687
+					$setter = 'set_' . $property;
3688
+					if (method_exists($network_config, $setter)) {
3689
+						$network_config->{$setter}($value);
3690
+					} elseif (property_exists($network_config, $property)
3691
+						&& $network_config->{$property} !== $value
3692
+					) {
3693
+						$network_config->{$property} = $value;
3694
+					} elseif (property_exists($messages_config, $property)
3695
+						&& $messages_config->{$property} !== $value
3696
+					) {
3697
+						$messages_config->{$property} = $value;
3698
+					}
3699
+				}
3700
+				// only update if the form submission was valid!
3701
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3702
+				EE_Registry::instance()->CFG->update_espresso_config();
3703
+				EE_Error::overwrite_success();
3704
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3705
+			}
3706
+		}
3707
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3708
+	}
3709
+
3710
+
3711
+	/**
3712
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3713
+	 *
3714
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3715
+	 * @return string html formatted tabs
3716
+	 * @throws DomainException
3717
+	 */
3718
+	protected function _get_mt_tabs($tab_array)
3719
+	{
3720
+		$tab_array = (array) $tab_array;
3721
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3722
+		$tabs = '';
3723
+
3724
+		foreach ($tab_array as $tab) {
3725
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3726
+		}
3727
+
3728
+		return $tabs;
3729
+	}
3730
+
3731
+
3732
+	/**
3733
+	 * This prepares the content of the messenger meta box admin settings
3734
+	 *
3735
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3736
+	 * @return string html formatted content
3737
+	 * @throws DomainException
3738
+	 */
3739
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3740
+	{
3741
+
3742
+		$fields = $messenger->get_admin_settings_fields();
3743
+		$settings_template_args['template_form_fields'] = '';
3744
+
3745
+		// is $messenger active?
3746
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3747
+
3748
+
3749
+		if (! empty($fields)) {
3750
+			$existing_settings = $messenger->get_existing_admin_settings();
3751
+
3752
+			foreach ($fields as $fldname => $fldprops) {
3753
+				$field_id = $messenger->name . '-' . $fldname;
3754
+				$template_form_field[ $field_id ] = array(
3755
+					'name'       => 'messenger_settings[' . $field_id . ']',
3756
+					'label'      => $fldprops['label'],
3757
+					'input'      => $fldprops['field_type'],
3758
+					'type'       => $fldprops['value_type'],
3759
+					'required'   => $fldprops['required'],
3760
+					'validation' => $fldprops['validation'],
3761
+					'value'      => isset($existing_settings[ $field_id ])
3762
+						? $existing_settings[ $field_id ]
3763
+						: $fldprops['default'],
3764
+					'css_class'  => '',
3765
+					'format'     => $fldprops['format'],
3766
+				);
3767
+			}
3768
+
3769
+
3770
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3771
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3772
+				: '';
3773
+		}
3774
+
3775
+		// we also need some hidden fields
3776
+		$settings_template_args['hidden_fields'] = array(
3777
+			'messenger_settings[messenger]' => array(
3778
+				'type'  => 'hidden',
3779
+				'value' => $messenger->name,
3780
+			),
3781
+			'type'                          => array(
3782
+				'type'  => 'hidden',
3783
+				'value' => 'messenger',
3784
+			),
3785
+		);
3786
+
3787
+		// make sure any active message types that are existing are included in the hidden fields
3788
+		if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3789
+			foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3790
+				$settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3791
+					'type'  => 'hidden',
3792
+					'value' => $mt,
3793
+				);
3794
+			}
3795
+		}
3796
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3797
+			$settings_template_args['hidden_fields'],
3798
+			'array'
3799
+		);
3800
+		$active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3801
+
3802
+		$settings_template_args['messenger'] = $messenger->name;
3803
+		$settings_template_args['description'] = $messenger->description;
3804
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3805
+
3806
+
3807
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3808
+			$messenger->name
3809
+		)
3810
+			? $settings_template_args['show_hide_edit_form']
3811
+			: ' hidden';
3812
+
3813
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3814
+			? ' hidden'
3815
+			: $settings_template_args['show_hide_edit_form'];
3816
+
3817
+
3818
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3819
+		$settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3820
+		$settings_template_args['on_off_status'] = $active ? true : false;
3821
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3822
+		$content = EEH_Template::display_template(
3823
+			$template,
3824
+			$settings_template_args,
3825
+			true
3826
+		);
3827
+
3828
+		return $content;
3829
+	}
3830
+
3831
+
3832
+	/**
3833
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3834
+	 *
3835
+	 * @throws DomainException
3836
+	 * @throws EE_Error
3837
+	 * @throws InvalidDataTypeException
3838
+	 * @throws InvalidInterfaceException
3839
+	 * @throws InvalidArgumentException
3840
+	 * @throws ReflectionException
3841
+	 */
3842
+	public function activate_messenger_toggle()
3843
+	{
3844
+		$success = true;
3845
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3846
+		// let's check that we have required data
3847
+		if (! isset($this->_req_data['messenger'])) {
3848
+			EE_Error::add_error(
3849
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3850
+				__FILE__,
3851
+				__FUNCTION__,
3852
+				__LINE__
3853
+			);
3854
+			$success = false;
3855
+		}
3856
+
3857
+		// do a nonce check here since we're not arriving via a normal route
3858
+		$nonce = isset($this->_req_data['activate_nonce'])
3859
+			? sanitize_text_field($this->_req_data['activate_nonce'])
3860
+			: '';
3861
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3862
+
3863
+		$this->_verify_nonce($nonce, $nonce_ref);
3864
+
3865
+
3866
+		if (! isset($this->_req_data['status'])) {
3867
+			EE_Error::add_error(
3868
+				esc_html__(
3869
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3870
+					'event_espresso'
3871
+				),
3872
+				__FILE__,
3873
+				__FUNCTION__,
3874
+				__LINE__
3875
+			);
3876
+			$success = false;
3877
+		}
3878
+
3879
+		// do check to verify we have a valid status.
3880
+		$status = $this->_req_data['status'];
3881
+
3882
+		if ($status !== 'off' && $status !== 'on') {
3883
+			EE_Error::add_error(
3884
+				sprintf(
3885
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3886
+					$this->_req_data['status']
3887
+				),
3888
+				__FILE__,
3889
+				__FUNCTION__,
3890
+				__LINE__
3891
+			);
3892
+			$success = false;
3893
+		}
3894
+
3895
+		if ($success) {
3896
+			// made it here?  Stop dawdling then!!
3897
+			$success = $status === 'off'
3898
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3899
+				: $this->_activate_messenger($this->_req_data['messenger']);
3900
+		}
3901
+
3902
+		$this->_template_args['success'] = $success;
3903
+
3904
+		// no special instructions so let's just do the json return (which should automatically do all the special stuff).
3905
+		$this->_return_json();
3906
+	}
3907
+
3908
+
3909
+	/**
3910
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3911
+	 *
3912
+	 * @throws DomainException
3913
+	 * @throws EE_Error
3914
+	 * @throws ReflectionException
3915
+	 * @throws InvalidDataTypeException
3916
+	 * @throws InvalidInterfaceException
3917
+	 * @throws InvalidArgumentException
3918
+	 */
3919
+	public function activate_mt_toggle()
3920
+	{
3921
+		$success = true;
3922
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3923
+
3924
+		// let's make sure we have the necessary data
3925
+		if (! isset($this->_req_data['message_type'])) {
3926
+			EE_Error::add_error(
3927
+				esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3928
+				__FILE__,
3929
+				__FUNCTION__,
3930
+				__LINE__
3931
+			);
3932
+			$success = false;
3933
+		}
3934
+
3935
+		if (! isset($this->_req_data['messenger'])) {
3936
+			EE_Error::add_error(
3937
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3938
+				__FILE__,
3939
+				__FUNCTION__,
3940
+				__LINE__
3941
+			);
3942
+			$success = false;
3943
+		}
3944
+
3945
+		if (! isset($this->_req_data['status'])) {
3946
+			EE_Error::add_error(
3947
+				esc_html__(
3948
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3949
+					'event_espresso'
3950
+				),
3951
+				__FILE__,
3952
+				__FUNCTION__,
3953
+				__LINE__
3954
+			);
3955
+			$success = false;
3956
+		}
3957
+
3958
+
3959
+		// do check to verify we have a valid status.
3960
+		$status = $this->_req_data['status'];
3961
+
3962
+		if ($status !== 'activate' && $status !== 'deactivate') {
3963
+			EE_Error::add_error(
3964
+				sprintf(
3965
+					esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3966
+					$this->_req_data['status']
3967
+				),
3968
+				__FILE__,
3969
+				__FUNCTION__,
3970
+				__LINE__
3971
+			);
3972
+			$success = false;
3973
+		}
3974
+
3975
+
3976
+		// do a nonce check here since we're not arriving via a normal route
3977
+		$nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3978
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3979
+
3980
+		$this->_verify_nonce($nonce, $nonce_ref);
3981
+
3982
+		if ($success) {
3983
+			// made it here? um, what are you waiting for then?
3984
+			$success = $status === 'deactivate'
3985
+				? $this->_deactivate_message_type_for_messenger(
3986
+					$this->_req_data['messenger'],
3987
+					$this->_req_data['message_type']
3988
+				)
3989
+				: $this->_activate_message_type_for_messenger(
3990
+					$this->_req_data['messenger'],
3991
+					$this->_req_data['message_type']
3992
+				);
3993
+		}
3994
+
3995
+		$this->_template_args['success'] = $success;
3996
+		$this->_return_json();
3997
+	}
3998
+
3999
+
4000
+	/**
4001
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
4002
+	 *
4003
+	 * @param string $messenger_name The name of the messenger being activated
4004
+	 * @return bool
4005
+	 * @throws DomainException
4006
+	 * @throws EE_Error
4007
+	 * @throws InvalidArgumentException
4008
+	 * @throws ReflectionException
4009
+	 * @throws InvalidDataTypeException
4010
+	 * @throws InvalidInterfaceException
4011
+	 */
4012
+	protected function _activate_messenger($messenger_name)
4013
+	{
4014
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4015
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4016
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger
4017
+			? $active_messenger->get_default_message_types()
4018
+			: array();
4019
+
4020
+		// ensure is active
4021
+		$this->_message_resource_manager->activate_messenger($active_messenger, $message_types_to_activate);
4022
+
4023
+		// set response_data for reload
4024
+		foreach ($message_types_to_activate as $message_type_name) {
4025
+			/** @var EE_message_type $message_type */
4026
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4027
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4028
+				$messenger_name,
4029
+				$message_type_name
4030
+			)
4031
+				&& $message_type instanceof EE_message_type
4032
+			) {
4033
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
4034
+				if ($message_type->get_admin_settings_fields()) {
4035
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
4036
+				}
4037
+			}
4038
+		}
4039
+
4040
+		// add success message for activating messenger
4041
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4042
+	}
4043
+
4044
+
4045
+	/**
4046
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
4047
+	 *
4048
+	 * @param string $messenger_name The name of the messenger being activated
4049
+	 * @return bool
4050
+	 * @throws DomainException
4051
+	 * @throws EE_Error
4052
+	 * @throws InvalidArgumentException
4053
+	 * @throws ReflectionException
4054
+	 * @throws InvalidDataTypeException
4055
+	 * @throws InvalidInterfaceException
4056
+	 */
4057
+	protected function _deactivate_messenger($messenger_name)
4058
+	{
4059
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4060
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4061
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
4062
+
4063
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4064
+	}
4065
+
4066
+
4067
+	/**
4068
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4069
+	 *
4070
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
4071
+	 * @param string $message_type_name The name of the message type being activated for the messenger
4072
+	 * @return bool
4073
+	 * @throws DomainException
4074
+	 * @throws EE_Error
4075
+	 * @throws InvalidArgumentException
4076
+	 * @throws ReflectionException
4077
+	 * @throws InvalidDataTypeException
4078
+	 * @throws InvalidInterfaceException
4079
+	 */
4080
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4081
+	{
4082
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4083
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4084
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4085
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4086
+
4087
+		// ensure is active
4088
+		$this->_message_resource_manager->activate_messenger($active_messenger, $message_type_name);
4089
+
4090
+		// set response for load
4091
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4092
+			$messenger_name,
4093
+			$message_type_name
4094
+		)
4095
+		) {
4096
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
4097
+			if ($message_type_to_activate->get_admin_settings_fields()) {
4098
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
4099
+			}
4100
+		}
4101
+
4102
+		return $this->_setup_response_message_for_activating_messenger_with_message_types(
4103
+			$active_messenger,
4104
+			$message_type_to_activate
4105
+		);
4106
+	}
4107
+
4108
+
4109
+	/**
4110
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4111
+	 *
4112
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4113
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
4114
+	 * @return bool
4115
+	 * @throws DomainException
4116
+	 * @throws EE_Error
4117
+	 * @throws InvalidArgumentException
4118
+	 * @throws ReflectionException
4119
+	 * @throws InvalidDataTypeException
4120
+	 * @throws InvalidInterfaceException
4121
+	 */
4122
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4123
+	{
4124
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4125
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4126
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4127
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4128
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4129
+
4130
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4131
+			$active_messenger,
4132
+			$message_type_to_deactivate
4133
+		);
4134
+	}
4135
+
4136
+
4137
+	/**
4138
+	 * This just initializes the defaults for activating messenger and message type responses.
4139
+	 */
4140
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
4141
+	{
4142
+		$this->_template_args['data']['active_mts'] = array();
4143
+		$this->_template_args['data']['mt_reload'] = array();
4144
+	}
4145
+
4146
+
4147
+	/**
4148
+	 * Setup appropriate response for activating a messenger and/or message types
4149
+	 *
4150
+	 * @param EE_messenger         $messenger
4151
+	 * @param EE_message_type|null $message_type
4152
+	 * @return bool
4153
+	 * @throws DomainException
4154
+	 * @throws EE_Error
4155
+	 * @throws InvalidArgumentException
4156
+	 * @throws ReflectionException
4157
+	 * @throws InvalidDataTypeException
4158
+	 * @throws InvalidInterfaceException
4159
+	 */
4160
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
4161
+		$messenger,
4162
+		EE_Message_Type $message_type = null
4163
+	) {
4164
+		// if $messenger isn't a valid messenger object then get out.
4165
+		if (! $messenger instanceof EE_Messenger) {
4166
+			EE_Error::add_error(
4167
+				esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4168
+				__FILE__,
4169
+				__FUNCTION__,
4170
+				__LINE__
4171
+			);
4172
+
4173
+			return false;
4174
+		}
4175
+		// activated
4176
+		if ($this->_template_args['data']['active_mts']) {
4177
+			EE_Error::overwrite_success();
4178
+			// activated a message type with the messenger
4179
+			if ($message_type instanceof EE_message_type) {
4180
+				EE_Error::add_success(
4181
+					sprintf(
4182
+						esc_html__(
4183
+							'%s message type has been successfully activated with the %s messenger',
4184
+							'event_espresso'
4185
+						),
4186
+						ucwords($message_type->label['singular']),
4187
+						ucwords($messenger->label['singular'])
4188
+					)
4189
+				);
4190
+
4191
+				// if message type was invoice then let's make sure we activate the invoice payment method.
4192
+				if ($message_type->name === 'invoice') {
4193
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
4194
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4195
+					if ($pm instanceof EE_Payment_Method) {
4196
+						EE_Error::add_attention(
4197
+							esc_html__(
4198
+								'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.',
4199
+								'event_espresso'
4200
+							)
4201
+						);
4202
+					}
4203
+				}
4204
+				// just toggles the entire messenger
4205
+			} else {
4206
+				EE_Error::add_success(
4207
+					sprintf(
4208
+						esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4209
+						ucwords($messenger->label['singular'])
4210
+					)
4211
+				);
4212
+			}
4213
+
4214
+			return true;
4215
+
4216
+			// possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4217
+			// message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4218
+			// in which case we just give a success message for the messenger being successfully activated.
4219
+		} else {
4220
+			if (! $messenger->get_default_message_types()) {
4221
+				// messenger doesn't have any default message types so still a success.
4222
+				EE_Error::add_success(
4223
+					sprintf(
4224
+						esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4225
+						ucwords($messenger->label['singular'])
4226
+					)
4227
+				);
4228
+
4229
+				return true;
4230
+			} else {
4231
+				EE_Error::add_error(
4232
+					$message_type instanceof EE_message_type
4233
+						? sprintf(
4234
+							esc_html__(
4235
+								'%s message type was not successfully activated with the %s messenger',
4236
+								'event_espresso'
4237
+							),
4238
+							ucwords($message_type->label['singular']),
4239
+							ucwords($messenger->label['singular'])
4240
+						)
4241
+						: sprintf(
4242
+							esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4243
+							ucwords($messenger->label['singular'])
4244
+						),
4245
+					__FILE__,
4246
+					__FUNCTION__,
4247
+					__LINE__
4248
+				);
4249
+
4250
+				return false;
4251
+			}
4252
+		}
4253
+	}
4254
+
4255
+
4256
+	/**
4257
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
4258
+	 *
4259
+	 * @param EE_messenger         $messenger
4260
+	 * @param EE_message_type|null $message_type
4261
+	 * @return bool
4262
+	 * @throws DomainException
4263
+	 * @throws EE_Error
4264
+	 * @throws InvalidArgumentException
4265
+	 * @throws ReflectionException
4266
+	 * @throws InvalidDataTypeException
4267
+	 * @throws InvalidInterfaceException
4268
+	 */
4269
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4270
+		$messenger,
4271
+		EE_message_type $message_type = null
4272
+	) {
4273
+		EE_Error::overwrite_success();
4274
+
4275
+		// if $messenger isn't a valid messenger object then get out.
4276
+		if (! $messenger instanceof EE_Messenger) {
4277
+			EE_Error::add_error(
4278
+				esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4279
+				__FILE__,
4280
+				__FUNCTION__,
4281
+				__LINE__
4282
+			);
4283
+
4284
+			return false;
4285
+		}
4286
+
4287
+		if ($message_type instanceof EE_message_type) {
4288
+			$message_type_name = $message_type->name;
4289
+			EE_Error::add_success(
4290
+				sprintf(
4291
+					esc_html__(
4292
+						'%s message type has been successfully deactivated for the %s messenger.',
4293
+						'event_espresso'
4294
+					),
4295
+					ucwords($message_type->label['singular']),
4296
+					ucwords($messenger->label['singular'])
4297
+				)
4298
+			);
4299
+		} else {
4300
+			$message_type_name = '';
4301
+			EE_Error::add_success(
4302
+				sprintf(
4303
+					esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4304
+					ucwords($messenger->label['singular'])
4305
+				)
4306
+			);
4307
+		}
4308
+
4309
+		// if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4310
+		if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4311
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
4312
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4313
+			if ($count_updated > 0) {
4314
+				$msg = $message_type_name === 'invoice'
4315
+					? esc_html__(
4316
+						'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.',
4317
+						'event_espresso'
4318
+					)
4319
+					: esc_html__(
4320
+						'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.',
4321
+						'event_espresso'
4322
+					);
4323
+				EE_Error::add_attention($msg);
4324
+			}
4325
+		}
4326
+
4327
+		return true;
4328
+	}
4329
+
4330
+
4331
+	/**
4332
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4333
+	 *
4334
+	 * @throws DomainException
4335
+	 */
4336
+	public function update_mt_form()
4337
+	{
4338
+		if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4339
+			EE_Error::add_error(
4340
+				esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4341
+				__FILE__,
4342
+				__FUNCTION__,
4343
+				__LINE__
4344
+			);
4345
+			$this->_return_json();
4346
+		}
4347
+
4348
+		$message_types = $this->get_installed_message_types();
4349
+
4350
+		$message_type = $message_types[ $this->_req_data['message_type'] ];
4351
+		$messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4352
+
4353
+		$content = $this->_message_type_settings_content(
4354
+			$message_type,
4355
+			$messenger,
4356
+			true
4357
+		);
4358
+		$this->_template_args['success'] = true;
4359
+		$this->_template_args['content'] = $content;
4360
+		$this->_return_json();
4361
+	}
4362
+
4363
+
4364
+	/**
4365
+	 * this handles saving the settings for a messenger or message type
4366
+	 *
4367
+	 */
4368
+	public function save_settings()
4369
+	{
4370
+		if (! isset($this->_req_data['type'])) {
4371
+			EE_Error::add_error(
4372
+				esc_html__(
4373
+					'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4374
+					'event_espresso'
4375
+				),
4376
+				__FILE__,
4377
+				__FUNCTION__,
4378
+				__LINE__
4379
+			);
4380
+			$this->_template_args['error'] = true;
4381
+			$this->_return_json();
4382
+		}
4383
+
4384
+
4385
+		if ($this->_req_data['type'] === 'messenger') {
4386
+			// this should be an array.
4387
+			$settings = $this->_req_data['messenger_settings'];
4388
+			$messenger = $settings['messenger'];
4389
+			// let's setup the settings data
4390
+			foreach ($settings as $key => $value) {
4391
+				switch ($key) {
4392
+					case 'messenger':
4393
+						unset($settings['messenger']);
4394
+						break;
4395
+					case 'message_types':
4396
+						unset($settings['message_types']);
4397
+						break;
4398
+					default:
4399
+						$settings[ $key ] = $value;
4400
+						break;
4401
+				}
4402
+			}
4403
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4404
+		} elseif ($this->_req_data['type'] === 'message_type') {
4405
+			$settings = $this->_req_data['message_type_settings'];
4406
+			$messenger = $settings['messenger'];
4407
+			$message_type = $settings['message_type'];
4408
+
4409
+			foreach ($settings as $key => $value) {
4410
+				switch ($key) {
4411
+					case 'messenger':
4412
+						unset($settings['messenger']);
4413
+						break;
4414
+					case 'message_type':
4415
+						unset($settings['message_type']);
4416
+						break;
4417
+					default:
4418
+						$settings[ $key ] = $value;
4419
+						break;
4420
+				}
4421
+			}
4422
+
4423
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4424
+		}
4425
+
4426
+		// okay we should have the data all setup.  Now we just update!
4427
+		$success = $this->_message_resource_manager->update_active_messengers_option();
4428
+
4429
+		if ($success) {
4430
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
4431
+		} else {
4432
+			EE_Error::add_error(
4433
+				esc_html__(
4434
+					'Settings did not get updated',
4435
+					'event_espresso'
4436
+				),
4437
+				__FILE__,
4438
+				__FUNCTION__,
4439
+				__LINE__
4440
+			);
4441
+		}
4442
+
4443
+		$this->_template_args['success'] = $success;
4444
+		$this->_return_json();
4445
+	}
4446
+
4447
+
4448
+
4449
+
4450
+	/**  EE MESSAGE PROCESSING ACTIONS **/
4451
+
4452
+
4453
+	/**
4454
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4455
+	 * However, this does not send immediately, it just queues for sending.
4456
+	 *
4457
+	 * @since 4.9.0
4458
+	 * @throws EE_Error
4459
+	 * @throws InvalidDataTypeException
4460
+	 * @throws InvalidInterfaceException
4461
+	 * @throws InvalidArgumentException
4462
+	 * @throws ReflectionException
4463
+	 */
4464
+	protected function _generate_now()
4465
+	{
4466
+		EED_Messages::generate_now($this->_get_msg_ids_from_request());
4467
+		$this->_redirect_after_action(false, '', '', array(), true);
4468
+	}
4469
+
4470
+
4471
+	/**
4472
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4473
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
4474
+	 *
4475
+	 * @since 4.9.0
4476
+	 * @throws EE_Error
4477
+	 * @throws InvalidDataTypeException
4478
+	 * @throws InvalidInterfaceException
4479
+	 * @throws InvalidArgumentException
4480
+	 * @throws ReflectionException
4481
+	 */
4482
+	protected function _generate_and_send_now()
4483
+	{
4484
+		EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4485
+		$this->_redirect_after_action(false, '', '', array(), true);
4486
+	}
4487
+
4488
+
4489
+	/**
4490
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4491
+	 *
4492
+	 * @since 4.9.0
4493
+	 * @throws EE_Error
4494
+	 * @throws InvalidDataTypeException
4495
+	 * @throws InvalidInterfaceException
4496
+	 * @throws InvalidArgumentException
4497
+	 * @throws ReflectionException
4498
+	 */
4499
+	protected function _queue_for_resending()
4500
+	{
4501
+		EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4502
+		$this->_redirect_after_action(false, '', '', array(), true);
4503
+	}
4504
+
4505
+
4506
+	/**
4507
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4508
+	 *
4509
+	 * @since 4.9.0
4510
+	 * @throws EE_Error
4511
+	 * @throws InvalidDataTypeException
4512
+	 * @throws InvalidInterfaceException
4513
+	 * @throws InvalidArgumentException
4514
+	 * @throws ReflectionException
4515
+	 */
4516
+	protected function _send_now()
4517
+	{
4518
+		EED_Messages::send_now($this->_get_msg_ids_from_request());
4519
+		$this->_redirect_after_action(false, '', '', array(), true);
4520
+	}
4521
+
4522
+
4523
+	/**
4524
+	 * Deletes EE_messages for IDs in the request.
4525
+	 *
4526
+	 * @since 4.9.0
4527
+	 * @throws EE_Error
4528
+	 * @throws InvalidDataTypeException
4529
+	 * @throws InvalidInterfaceException
4530
+	 * @throws InvalidArgumentException
4531
+	 */
4532
+	protected function _delete_ee_messages()
4533
+	{
4534
+		$msg_ids = $this->_get_msg_ids_from_request();
4535
+		$deleted_count = 0;
4536
+		foreach ($msg_ids as $msg_id) {
4537
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4538
+				$deleted_count++;
4539
+			}
4540
+		}
4541
+		if ($deleted_count) {
4542
+			EE_Error::add_success(
4543
+				esc_html(
4544
+					_n(
4545
+						'Message successfully deleted',
4546
+						'Messages successfully deleted',
4547
+						$deleted_count,
4548
+						'event_espresso'
4549
+					)
4550
+				)
4551
+			);
4552
+			$this->_redirect_after_action(
4553
+				false,
4554
+				'',
4555
+				'',
4556
+				array(),
4557
+				true
4558
+			);
4559
+		} else {
4560
+			EE_Error::add_error(
4561
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4562
+				__FILE__,
4563
+				__FUNCTION__,
4564
+				__LINE__
4565
+			);
4566
+			$this->_redirect_after_action(false, '', '', array(), true);
4567
+		}
4568
+	}
4569
+
4570
+
4571
+	/**
4572
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4573
+	 *
4574
+	 * @since 4.9.0
4575
+	 * @return array
4576
+	 */
4577
+	protected function _get_msg_ids_from_request()
4578
+	{
4579
+		if (! isset($this->_req_data['MSG_ID'])) {
4580
+			return array();
4581
+		}
4582
+
4583
+		return is_array($this->_req_data['MSG_ID'])
4584
+			? array_keys($this->_req_data['MSG_ID'])
4585
+			: array($this->_req_data['MSG_ID']);
4586
+	}
4587 4587
 }
Please login to merge, or discard this patch.