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