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