Completed
Branch FET/live-event-msg-preview (250d3a)
by
unknown
35:30 queued 27:19
created
admin_pages/messages/Messages_Admin_Page.core.php 1 patch
Indentation   +4533 added lines, -4533 removed lines patch added patch discarded remove patch
@@ -19,2633 +19,2633 @@  discard block
 block discarded – undo
19 19
 class Messages_Admin_Page extends EE_Admin_Page
20 20
 {
21 21
 
22
-    /**
23
-     * @type EE_Message_Resource_Manager $_message_resource_manager
24
-     */
25
-    protected $_message_resource_manager;
26
-
27
-    /**
28
-     * @type string $_active_message_type_name
29
-     */
30
-    protected $_active_message_type_name = '';
31
-
32
-    /**
33
-     * @type EE_messenger $_active_messenger
34
-     */
35
-    protected $_active_messenger;
36
-    protected $_activate_state;
37
-    protected $_activate_meta_box_type;
38
-    protected $_current_message_meta_box;
39
-    protected $_current_message_meta_box_object;
40
-    protected $_context_switcher;
41
-    protected $_shortcodes = array();
42
-    protected $_active_messengers = array();
43
-    protected $_active_message_types = array();
44
-
45
-    /**
46
-     * @var EE_Message_Template_Group $_message_template_group
47
-     */
48
-    protected $_message_template_group;
49
-    protected $_m_mt_settings = array();
50
-
51
-
52
-    /**
53
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
-     * IF there is no group then it gets automatically set to the Default template pack.
55
-     *
56
-     * @since 4.5.0
57
-     *
58
-     * @var EE_Messages_Template_Pack
59
-     */
60
-    protected $_template_pack;
61
-
62
-
63
-    /**
64
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
-     * group is.  If there is no group then it automatically gets set to default.
66
-     *
67
-     * @since 4.5.0
68
-     *
69
-     * @var string
70
-     */
71
-    protected $_variation;
72
-
73
-
74
-    /**
75
-     * @param bool $routing
76
-     * @throws EE_Error
77
-     */
78
-    public function __construct($routing = true)
79
-    {
80
-        // make sure messages autoloader is running
81
-        EED_Messages::set_autoloaders();
82
-        parent::__construct($routing);
83
-    }
84
-
85
-
86
-    protected function _init_page_props()
87
-    {
88
-        $this->page_slug = EE_MSG_PG_SLUG;
89
-        $this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
-        $this->_admin_base_url = EE_MSG_ADMIN_URL;
91
-        $this->_admin_base_path = EE_MSG_ADMIN;
92
-
93
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
-            : array();
95
-
96
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
-        $this->_load_message_resource_manager();
98
-    }
99
-
100
-
101
-    /**
102
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
-     *
104
-     * @throws EE_Error
105
-     * @throws InvalidDataTypeException
106
-     * @throws InvalidInterfaceException
107
-     * @throws InvalidArgumentException
108
-     * @throws ReflectionException
109
-     */
110
-    protected function _load_message_resource_manager()
111
-    {
112
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
-    }
114
-
115
-
116
-    /**
117
-     * @deprecated 4.9.9.rc.014
118
-     * @return array
119
-     * @throws EE_Error
120
-     * @throws InvalidArgumentException
121
-     * @throws InvalidDataTypeException
122
-     * @throws InvalidInterfaceException
123
-     */
124
-    public function get_messengers_for_list_table()
125
-    {
126
-        EE_Error::doing_it_wrong(
127
-            __METHOD__,
128
-            sprintf(
129
-                esc_html__(
130
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
-                    'event_espresso'
132
-                ),
133
-                'Messages_Admin_Page::get_messengers_select_input()'
134
-            ),
135
-            '4.9.9.rc.014'
136
-        );
137
-
138
-        $m_values = array();
139
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
-        // setup messengers for selects
141
-        $i = 1;
142
-        foreach ($active_messengers as $active_messenger) {
143
-            if ($active_messenger instanceof EE_Message) {
144
-                $m_values[ $i ]['id'] = $active_messenger->messenger();
145
-                $m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
-                $i++;
147
-            }
148
-        }
149
-
150
-        return $m_values;
151
-    }
152
-
153
-
154
-    /**
155
-     * @deprecated 4.9.9.rc.014
156
-     * @return array
157
-     * @throws EE_Error
158
-     * @throws InvalidArgumentException
159
-     * @throws InvalidDataTypeException
160
-     * @throws InvalidInterfaceException
161
-     */
162
-    public function get_message_types_for_list_table()
163
-    {
164
-        EE_Error::doing_it_wrong(
165
-            __METHOD__,
166
-            sprintf(
167
-                esc_html__(
168
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
-                    'event_espresso'
170
-                ),
171
-                'Messages_Admin_Page::get_message_types_select_input()'
172
-            ),
173
-            '4.9.9.rc.014'
174
-        );
175
-
176
-        $mt_values = array();
177
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
-        $i = 1;
179
-        foreach ($active_messages as $active_message) {
180
-            if ($active_message instanceof EE_Message) {
181
-                $mt_values[ $i ]['id'] = $active_message->message_type();
182
-                $mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
-                $i++;
184
-            }
185
-        }
186
-
187
-        return $mt_values;
188
-    }
189
-
190
-
191
-    /**
192
-     * @deprecated 4.9.9.rc.014
193
-     * @return array
194
-     * @throws EE_Error
195
-     * @throws InvalidArgumentException
196
-     * @throws InvalidDataTypeException
197
-     * @throws InvalidInterfaceException
198
-     */
199
-    public function get_contexts_for_message_types_for_list_table()
200
-    {
201
-        EE_Error::doing_it_wrong(
202
-            __METHOD__,
203
-            sprintf(
204
-                esc_html__(
205
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
-                    'event_espresso'
207
-                ),
208
-                'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
-            ),
210
-            '4.9.9.rc.014'
211
-        );
212
-
213
-        $contexts = array();
214
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
-        foreach ($active_message_contexts as $active_message) {
216
-            if ($active_message instanceof EE_Message) {
217
-                $message_type = $active_message->message_type_object();
218
-                if ($message_type instanceof EE_message_type) {
219
-                    $message_type_contexts = $message_type->get_contexts();
220
-                    foreach ($message_type_contexts as $context => $context_details) {
221
-                        $contexts[ $context ] = $context_details['label'];
222
-                    }
223
-                }
224
-            }
225
-        }
226
-
227
-        return $contexts;
228
-    }
229
-
230
-
231
-    /**
232
-     * Generate select input with provided messenger options array.
233
-     *
234
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
-     *                                 labels.
236
-     * @return string
237
-     * @throws EE_Error
238
-     */
239
-    public function get_messengers_select_input($messenger_options)
240
-    {
241
-        // if empty or just one value then just return an empty string
242
-        if (empty($messenger_options)
243
-            || ! is_array($messenger_options)
244
-            || count($messenger_options) === 1
245
-        ) {
246
-            return '';
247
-        }
248
-        // merge in default
249
-        $messenger_options = array_merge(
250
-            array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
-            $messenger_options
252
-        );
253
-        $input = new EE_Select_Input(
254
-            $messenger_options,
255
-            array(
256
-                'html_name'  => 'ee_messenger_filter_by',
257
-                'html_id'    => 'ee_messenger_filter_by',
258
-                'html_class' => 'wide',
259
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
-                    : 'none_selected',
262
-            )
263
-        );
264
-
265
-        return $input->get_html_for_input();
266
-    }
267
-
268
-
269
-    /**
270
-     * Generate select input with provided message type options array.
271
-     *
272
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
-     *                                    message type labels
274
-     * @return string
275
-     * @throws EE_Error
276
-     */
277
-    public function get_message_types_select_input($message_type_options)
278
-    {
279
-        // if empty or count of options is 1 then just return an empty string
280
-        if (empty($message_type_options)
281
-            || ! is_array($message_type_options)
282
-            || count($message_type_options) === 1
283
-        ) {
284
-            return '';
285
-        }
286
-        // merge in default
287
-        $message_type_options = array_merge(
288
-            array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
-            $message_type_options
290
-        );
291
-        $input = new EE_Select_Input(
292
-            $message_type_options,
293
-            array(
294
-                'html_name'  => 'ee_message_type_filter_by',
295
-                'html_id'    => 'ee_message_type_filter_by',
296
-                'html_class' => 'wide',
297
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
-                    : 'none_selected',
300
-            )
301
-        );
302
-
303
-        return $input->get_html_for_input();
304
-    }
305
-
306
-
307
-    /**
308
-     * Generate select input with provide message type contexts array.
309
-     *
310
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
-     *                               context label.
312
-     * @return string
313
-     * @throws EE_Error
314
-     */
315
-    public function get_contexts_for_message_types_select_input($context_options)
316
-    {
317
-        // if empty or count of options is one then just return empty string
318
-        if (empty($context_options)
319
-            || ! is_array($context_options)
320
-            || count($context_options) === 1
321
-        ) {
322
-            return '';
323
-        }
324
-        // merge in default
325
-        $context_options = array_merge(
326
-            array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
-            $context_options
328
-        );
329
-        $input = new EE_Select_Input(
330
-            $context_options,
331
-            array(
332
-                'html_name'  => 'ee_context_filter_by',
333
-                'html_id'    => 'ee_context_filter_by',
334
-                'html_class' => 'wide',
335
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
336
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
337
-                    : 'none_selected',
338
-            )
339
-        );
340
-
341
-        return $input->get_html_for_input();
342
-    }
343
-
344
-
345
-    protected function _ajax_hooks()
346
-    {
347
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
-        add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
-    }
354
-
355
-
356
-    protected function _define_page_props()
357
-    {
358
-        $this->_admin_page_title = $this->page_label;
359
-        $this->_labels = array(
360
-            'buttons'    => array(
361
-                'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
-                'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
-                'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
-            ),
365
-            'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
-        );
367
-    }
368
-
369
-
370
-    /**
371
-     *        an array for storing key => value pairs of request actions and their corresponding methods
372
-     *
373
-     * @access protected
374
-     * @return void
375
-     */
376
-    protected function _set_page_routes()
377
-    {
378
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
-            ? $this->_req_data['GRP_ID']
380
-            : 0;
381
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
-            ? $this->_req_data['id']
383
-            : $grp_id;
384
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
-            ? $this->_req_data['MSG_ID']
386
-            : 0;
387
-
388
-        $this->_page_routes = array(
389
-            'default'                          => array(
390
-                'func'       => '_message_queue_list_table',
391
-                'capability' => 'ee_read_global_messages',
392
-            ),
393
-            'global_mtps'                      => array(
394
-                'func'       => '_ee_default_messages_overview_list_table',
395
-                'capability' => 'ee_read_global_messages',
396
-            ),
397
-            'custom_mtps'                      => array(
398
-                'func'       => '_custom_mtps_preview',
399
-                'capability' => 'ee_read_messages',
400
-            ),
401
-            'add_new_message_template'         => array(
402
-                'func'       => '_add_message_template',
403
-                'capability' => 'ee_edit_messages',
404
-                'noheader'   => true,
405
-            ),
406
-            'edit_message_template'            => array(
407
-                'func'       => '_edit_message_template',
408
-                'capability' => 'ee_edit_message',
409
-                'obj_id'     => $grp_id,
410
-            ),
411
-            'preview_message'                  => array(
412
-                'func'               => '_preview_message',
413
-                'capability'         => 'ee_read_message',
414
-                'obj_id'             => $grp_id,
415
-                'noheader'           => true,
416
-                'headers_sent_route' => 'display_preview_message',
417
-            ),
418
-            'display_preview_message'          => array(
419
-                'func'       => '_display_preview_message',
420
-                'capability' => 'ee_read_message',
421
-                'obj_id'     => $grp_id,
422
-            ),
423
-            'insert_message_template'          => array(
424
-                'func'       => '_insert_or_update_message_template',
425
-                'capability' => 'ee_edit_messages',
426
-                'args'       => array('new_template' => true),
427
-                'noheader'   => true,
428
-            ),
429
-            'update_message_template'          => array(
430
-                'func'       => '_insert_or_update_message_template',
431
-                'capability' => 'ee_edit_message',
432
-                'obj_id'     => $grp_id,
433
-                'args'       => array('new_template' => false),
434
-                'noheader'   => true,
435
-            ),
436
-            'trash_message_template'           => array(
437
-                'func'       => '_trash_or_restore_message_template',
438
-                'capability' => 'ee_delete_message',
439
-                'obj_id'     => $grp_id,
440
-                'args'       => array('trash' => true, 'all' => true),
441
-                'noheader'   => true,
442
-            ),
443
-            'trash_message_template_context'   => array(
444
-                'func'       => '_trash_or_restore_message_template',
445
-                'capability' => 'ee_delete_message',
446
-                'obj_id'     => $grp_id,
447
-                'args'       => array('trash' => true),
448
-                'noheader'   => true,
449
-            ),
450
-            'restore_message_template'         => array(
451
-                'func'       => '_trash_or_restore_message_template',
452
-                'capability' => 'ee_delete_message',
453
-                'obj_id'     => $grp_id,
454
-                'args'       => array('trash' => false, 'all' => true),
455
-                'noheader'   => true,
456
-            ),
457
-            'restore_message_template_context' => array(
458
-                'func'       => '_trash_or_restore_message_template',
459
-                'capability' => 'ee_delete_message',
460
-                'obj_id'     => $grp_id,
461
-                'args'       => array('trash' => false),
462
-                'noheader'   => true,
463
-            ),
464
-            'delete_message_template'          => array(
465
-                'func'       => '_delete_message_template',
466
-                'capability' => 'ee_delete_message',
467
-                'obj_id'     => $grp_id,
468
-                'noheader'   => true,
469
-            ),
470
-            'reset_to_default'                 => array(
471
-                'func'       => '_reset_to_default_template',
472
-                'capability' => 'ee_edit_message',
473
-                'obj_id'     => $grp_id,
474
-                'noheader'   => true,
475
-            ),
476
-            'settings'                         => array(
477
-                'func'       => '_settings',
478
-                'capability' => 'manage_options',
479
-            ),
480
-            'update_global_settings'           => array(
481
-                'func'       => '_update_global_settings',
482
-                'capability' => 'manage_options',
483
-                'noheader'   => true,
484
-            ),
485
-            'generate_now'                     => array(
486
-                'func'       => '_generate_now',
487
-                'capability' => 'ee_send_message',
488
-                'noheader'   => true,
489
-            ),
490
-            'generate_and_send_now'            => array(
491
-                'func'       => '_generate_and_send_now',
492
-                'capability' => 'ee_send_message',
493
-                'noheader'   => true,
494
-            ),
495
-            'queue_for_resending'              => array(
496
-                'func'       => '_queue_for_resending',
497
-                'capability' => 'ee_send_message',
498
-                'noheader'   => true,
499
-            ),
500
-            'send_now'                         => array(
501
-                'func'       => '_send_now',
502
-                'capability' => 'ee_send_message',
503
-                'noheader'   => true,
504
-            ),
505
-            'delete_ee_message'                => array(
506
-                'func'       => '_delete_ee_messages',
507
-                'capability' => 'ee_delete_messages',
508
-                'noheader'   => true,
509
-            ),
510
-            'delete_ee_messages'               => array(
511
-                'func'       => '_delete_ee_messages',
512
-                'capability' => 'ee_delete_messages',
513
-                'noheader'   => true,
514
-                'obj_id'     => $msg_id,
515
-            ),
516
-        );
517
-    }
518
-
519
-
520
-    protected function _set_page_config()
521
-    {
522
-        $this->_page_config = array(
523
-            'default'                  => array(
524
-                'nav'           => array(
525
-                    'label' => esc_html__('Message Activity', 'event_espresso'),
526
-                    'order' => 10,
527
-                ),
528
-                'list_table'    => 'EE_Message_List_Table',
529
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
-                'require_nonce' => false,
531
-            ),
532
-            'global_mtps'              => array(
533
-                'nav'           => array(
534
-                    'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
-                    'order' => 20,
536
-                ),
537
-                'list_table'    => 'Messages_Template_List_Table',
538
-                'help_tabs'     => array(
539
-                    'messages_overview_help_tab'                                => array(
540
-                        'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
-                        'filename' => 'messages_overview',
542
-                    ),
543
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
544
-                        'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
-                        'filename' => 'messages_overview_table_column_headings',
546
-                    ),
547
-                    'messages_overview_messages_filters_help_tab'               => array(
548
-                        'title'    => esc_html__('Message Filters', 'event_espresso'),
549
-                        'filename' => 'messages_overview_filters',
550
-                    ),
551
-                    'messages_overview_messages_views_help_tab'                 => array(
552
-                        'title'    => esc_html__('Message Views', 'event_espresso'),
553
-                        'filename' => 'messages_overview_views',
554
-                    ),
555
-                    'message_overview_message_types_help_tab'                   => array(
556
-                        'title'    => esc_html__('Message Types', 'event_espresso'),
557
-                        'filename' => 'messages_overview_types',
558
-                    ),
559
-                    'messages_overview_messengers_help_tab'                     => array(
560
-                        'title'    => esc_html__('Messengers', 'event_espresso'),
561
-                        'filename' => 'messages_overview_messengers',
562
-                    ),
563
-                ),
564
-                'help_tour'     => array('Messages_Overview_Help_Tour'),
565
-                'require_nonce' => false,
566
-            ),
567
-            'custom_mtps'              => array(
568
-                'nav'           => array(
569
-                    'label' => esc_html__('Custom Message Templates', 'event_espresso'),
570
-                    'order' => 30,
571
-                ),
572
-                'help_tabs'     => array(),
573
-                'help_tour'     => array(),
574
-                'require_nonce' => false,
575
-            ),
576
-            'add_new_message_template' => array(
577
-                'nav'           => array(
578
-                    'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
579
-                    'order'      => 5,
580
-                    'persistent' => false,
581
-                ),
582
-                'require_nonce' => false,
583
-            ),
584
-            'edit_message_template'    => array(
585
-                'labels'        => array(
586
-                    'buttons'    => array(
587
-                        'reset' => esc_html__('Reset Templates', 'event_espresso'),
588
-                    ),
589
-                    'publishbox' => esc_html__('Update Actions', 'event_espresso'),
590
-                ),
591
-                'nav'           => array(
592
-                    'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
593
-                    'order'      => 5,
594
-                    'persistent' => false,
595
-                    'url'        => '',
596
-                ),
597
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
598
-                'has_metaboxes' => true,
599
-                'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
600
-                'help_tabs'     => array(
601
-                    'edit_message_template'            => array(
602
-                        'title'    => esc_html__('Message Template Editor', 'event_espresso'),
603
-                        'callback' => 'edit_message_template_help_tab',
604
-                    ),
605
-                    'message_templates_help_tab'       => array(
606
-                        'title'    => esc_html__('Message Templates', 'event_espresso'),
607
-                        'filename' => 'messages_templates',
608
-                    ),
609
-                    'message_template_shortcodes'      => array(
610
-                        'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
611
-                        'callback' => 'message_template_shortcodes_help_tab',
612
-                    ),
613
-                    'message_preview_help_tab'         => array(
614
-                        'title'    => esc_html__('Message Preview', 'event_espresso'),
615
-                        'filename' => 'messages_preview',
616
-                    ),
617
-                    'messages_overview_other_help_tab' => array(
618
-                        'title'    => esc_html__('Messages Other', 'event_espresso'),
619
-                        'filename' => 'messages_overview_other',
620
-                    ),
621
-                ),
622
-                'require_nonce' => false,
623
-            ),
624
-            'display_preview_message'  => array(
625
-                'nav'           => array(
626
-                    'label'      => esc_html__('Message Preview', 'event_espresso'),
627
-                    'order'      => 5,
628
-                    'url'        => '',
629
-                    'persistent' => false,
630
-                ),
631
-                'help_tabs'     => array(
632
-                    'preview_message' => array(
633
-                        'title'    => esc_html__('About Previews', 'event_espresso'),
634
-                        'callback' => 'preview_message_help_tab',
635
-                    ),
636
-                ),
637
-                'require_nonce' => false,
638
-            ),
639
-            'settings'                 => array(
640
-                'nav'           => array(
641
-                    'label' => esc_html__('Settings', 'event_espresso'),
642
-                    'order' => 40,
643
-                ),
644
-                'metaboxes'     => array('_messages_settings_metaboxes'),
645
-                'help_tabs'     => array(
646
-                    'messages_settings_help_tab'               => array(
647
-                        'title'    => esc_html__('Messages Settings', 'event_espresso'),
648
-                        'filename' => 'messages_settings',
649
-                    ),
650
-                    'messages_settings_message_types_help_tab' => array(
651
-                        'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
652
-                        'filename' => 'messages_settings_message_types',
653
-                    ),
654
-                    'messages_settings_messengers_help_tab'    => array(
655
-                        'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
656
-                        'filename' => 'messages_settings_messengers',
657
-                    ),
658
-                ),
659
-                'help_tour'     => array('Messages_Settings_Help_Tour'),
660
-                'require_nonce' => false,
661
-            ),
662
-        );
663
-    }
664
-
665
-
666
-    protected function _add_screen_options()
667
-    {
668
-        // todo
669
-    }
670
-
671
-
672
-    protected function _add_screen_options_global_mtps()
673
-    {
674
-        /**
675
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
676
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
677
-         */
678
-        $page_title = $this->_admin_page_title;
679
-        $this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
680
-        $this->_per_page_screen_option();
681
-        $this->_admin_page_title = $page_title;
682
-    }
683
-
684
-
685
-    protected function _add_screen_options_default()
686
-    {
687
-        $this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
688
-        $this->_per_page_screen_option();
689
-    }
690
-
691
-
692
-    // none of the below group are currently used for Messages
693
-    protected function _add_feature_pointers()
694
-    {
695
-    }
696
-
697
-    public function admin_init()
698
-    {
699
-    }
700
-
701
-    public function admin_notices()
702
-    {
703
-    }
704
-
705
-    public function admin_footer_scripts()
706
-    {
707
-    }
708
-
709
-
710
-    public function messages_help_tab()
711
-    {
712
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
713
-    }
714
-
715
-
716
-    public function messengers_help_tab()
717
-    {
718
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
719
-    }
720
-
721
-
722
-    public function message_types_help_tab()
723
-    {
724
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
725
-    }
726
-
727
-
728
-    public function messages_overview_help_tab()
729
-    {
730
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
731
-    }
732
-
733
-
734
-    public function message_templates_help_tab()
735
-    {
736
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
737
-    }
738
-
739
-
740
-    public function edit_message_template_help_tab()
741
-    {
742
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
743
-                        . esc_attr__('Editor Title', 'event_espresso')
744
-                        . '" />';
745
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
746
-                        . esc_attr__('Context Switcher and Preview', 'event_espresso')
747
-                        . '" />';
748
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
749
-                        . esc_attr__('Message Template Form Fields', 'event_espresso')
750
-                        . '" />';
751
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
752
-                        . esc_attr__('Shortcodes Metabox', 'event_espresso')
753
-                        . '" />';
754
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
755
-                        . esc_attr__('Publish Metabox', 'event_espresso')
756
-                        . '" />';
757
-        EEH_Template::display_template(
758
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
759
-            $args
760
-        );
761
-    }
762
-
763
-
764
-    public function message_template_shortcodes_help_tab()
765
-    {
766
-        $this->_set_shortcodes();
767
-        $args['shortcodes'] = $this->_shortcodes;
768
-        EEH_Template::display_template(
769
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
770
-            $args
771
-        );
772
-    }
773
-
774
-
775
-    public function preview_message_help_tab()
776
-    {
777
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
778
-    }
779
-
780
-
781
-    public function settings_help_tab()
782
-    {
783
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
784
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
785
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
786
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
787
-        $args['img3'] = '<div class="switch">'
788
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
789
-                        . ' type="checkbox" checked="checked">'
790
-                        . '<label for="ee-on-off-toggle-on"></label>'
791
-                        . '</div>';
792
-        $args['img4'] = '<div class="switch">'
793
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
794
-                        . ' type="checkbox">'
795
-                        . '<label for="ee-on-off-toggle-on"></label>'
796
-                        . '</div>';
797
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
798
-    }
799
-
800
-
801
-    public function load_scripts_styles()
802
-    {
803
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
804
-        wp_enqueue_style('espresso_ee_msg');
805
-
806
-        wp_register_script(
807
-            'ee-messages-settings',
808
-            EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
-            array('jquery-ui-droppable', 'ee-serialize-full-array'),
810
-            EVENT_ESPRESSO_VERSION,
811
-            true
812
-        );
813
-        wp_register_script(
814
-            'ee-msg-list-table-js',
815
-            EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
816
-            array('ee-dialog'),
817
-            EVENT_ESPRESSO_VERSION
818
-        );
819
-    }
820
-
821
-
822
-    public function load_scripts_styles_default()
823
-    {
824
-        wp_enqueue_script('ee-msg-list-table-js');
825
-    }
826
-
827
-
828
-    public function wp_editor_css($mce_css)
829
-    {
830
-        // if we're on the edit_message_template route
831
-        if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
832
-            $message_type_name = $this->_active_message_type_name;
833
-
834
-            // we're going to REPLACE the existing mce css
835
-            // we need to get the css file location from the active messenger
836
-            $mce_css = $this->_active_messenger->get_variation(
837
-                $this->_template_pack,
838
-                $message_type_name,
839
-                true,
840
-                'wpeditor',
841
-                $this->_variation
842
-            );
843
-        }
844
-
845
-        return $mce_css;
846
-    }
847
-
848
-
849
-    public function load_scripts_styles_edit_message_template()
850
-    {
851
-
852
-        $this->_set_shortcodes();
853
-
854
-        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
855
-            esc_html__(
856
-                '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.',
857
-                'event_espresso'
858
-            ),
859
-            $this->_message_template_group->messenger_obj()->label['singular'],
860
-            $this->_message_template_group->message_type_obj()->label['singular']
861
-        );
862
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
863
-            '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?',
864
-            'event_espresso'
865
-        );
866
-        EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
867
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
868
-            'event_espresso'
869
-        );
870
-
871
-        wp_register_script(
872
-            'ee_msgs_edit_js',
873
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
874
-            array('jquery'),
875
-            EVENT_ESPRESSO_VERSION
876
-        );
877
-
878
-        wp_enqueue_script('ee_admin_js');
879
-        wp_enqueue_script('ee_msgs_edit_js');
880
-
881
-        // add in special css for tiny_mce
882
-        add_filter('mce_css', array($this, 'wp_editor_css'));
883
-    }
884
-
885
-
886
-    public function load_scripts_styles_display_preview_message()
887
-    {
888
-
889
-        $this->_set_message_template_group();
890
-
891
-        if (isset($this->_req_data['messenger'])) {
892
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
893
-                $this->_req_data['messenger']
894
-            );
895
-        }
896
-
897
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
898
-
899
-
900
-        wp_enqueue_style(
901
-            'espresso_preview_css',
902
-            $this->_active_messenger->get_variation(
903
-                $this->_template_pack,
904
-                $message_type_name,
905
-                true,
906
-                'preview',
907
-                $this->_variation
908
-            )
909
-        );
910
-    }
911
-
912
-
913
-    public function load_scripts_styles_settings()
914
-    {
915
-        wp_register_style(
916
-            'ee-message-settings',
917
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
918
-            array(),
919
-            EVENT_ESPRESSO_VERSION
920
-        );
921
-        wp_enqueue_style('ee-text-links');
922
-        wp_enqueue_style('ee-message-settings');
923
-        wp_enqueue_script('ee-messages-settings');
924
-    }
925
-
926
-
927
-    /**
928
-     * set views array for List Table
929
-     */
930
-    public function _set_list_table_views_global_mtps()
931
-    {
932
-        $this->_views = array(
933
-            'in_use' => array(
934
-                'slug'  => 'in_use',
935
-                'label' => esc_html__('In Use', 'event_espresso'),
936
-                'count' => 0,
937
-            ),
938
-        );
939
-    }
940
-
941
-
942
-    /**
943
-     * Set views array for the Custom Template List Table
944
-     */
945
-    public function _set_list_table_views_custom_mtps()
946
-    {
947
-        $this->_set_list_table_views_global_mtps();
948
-        $this->_views['in_use']['bulk_action'] = array(
949
-            'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
950
-        );
951
-    }
952
-
953
-
954
-    /**
955
-     * set views array for message queue list table
956
-     *
957
-     * @throws InvalidDataTypeException
958
-     * @throws InvalidInterfaceException
959
-     * @throws InvalidArgumentException
960
-     * @throws EE_Error
961
-     * @throws ReflectionException
962
-     */
963
-    public function _set_list_table_views_default()
964
-    {
965
-        EE_Registry::instance()->load_helper('Template');
966
-
967
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
968
-            'ee_send_message',
969
-            'message_list_table_bulk_actions'
970
-        )
971
-            ? array(
972
-                'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
973
-                'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
974
-                'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
975
-                'send_now'              => esc_html__('Send Now', 'event_espresso'),
976
-            )
977
-            : array();
978
-
979
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
980
-            'ee_delete_messages',
981
-            'message_list_table_bulk_actions'
982
-        )
983
-            ? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
984
-            : array();
985
-
986
-
987
-        $this->_views = array(
988
-            'all' => array(
989
-                'slug'        => 'all',
990
-                'label'       => esc_html__('All', 'event_espresso'),
991
-                'count'       => 0,
992
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
993
-            ),
994
-        );
995
-
996
-
997
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
998
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
999
-                continue;
1000
-            }
1001
-            $status_bulk_actions = $common_bulk_actions;
1002
-            // unset bulk actions not applying to status
1003
-            if (! empty($status_bulk_actions)) {
1004
-                switch ($status) {
1005
-                    case EEM_Message::status_idle:
1006
-                    case EEM_Message::status_resend:
1007
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1008
-                        break;
1009
-
1010
-                    case EEM_Message::status_failed:
1011
-                    case EEM_Message::status_debug_only:
1012
-                    case EEM_Message::status_messenger_executing:
1013
-                        $status_bulk_actions = array();
1014
-                        break;
1015
-
1016
-                    case EEM_Message::status_incomplete:
1017
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1018
-                        break;
1019
-
1020
-                    case EEM_Message::status_retry:
1021
-                    case EEM_Message::status_sent:
1022
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1023
-                        break;
1024
-                }
1025
-            }
1026
-
1027
-            // skip adding messenger executing status to views because it will be included with the Failed view.
1028
-            if ($status === EEM_Message::status_messenger_executing) {
1029
-                continue;
1030
-            }
1031
-
1032
-            $this->_views[ strtolower($status) ] = array(
1033
-                'slug'        => strtolower($status),
1034
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1035
-                'count'       => 0,
1036
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1037
-            );
1038
-        }
1039
-    }
1040
-
1041
-
1042
-    protected function _ee_default_messages_overview_list_table()
1043
-    {
1044
-        $this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1045
-        $this->display_admin_list_table_page_with_no_sidebar();
1046
-    }
1047
-
1048
-
1049
-    protected function _message_queue_list_table()
1050
-    {
1051
-        $this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1052
-        $this->_template_args['per_column'] = 6;
1053
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1054
-        $this->_template_args['before_list_table'] = '<h3>'
1055
-                                                     . EEM_Message::instance()->get_pretty_label_for_results()
1056
-                                                     . '</h3>';
1057
-        $this->display_admin_list_table_page_with_no_sidebar();
1058
-    }
1059
-
1060
-
1061
-    protected function _message_legend_items()
1062
-    {
1063
-
1064
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
1065
-        $action_items = array();
1066
-
1067
-        foreach ($action_css_classes as $action_item => $action_details) {
1068
-            if ($action_item === 'see_notifications_for') {
1069
-                continue;
1070
-            }
1071
-            $action_items[ $action_item ] = array(
1072
-                'class' => $action_details['css_class'],
1073
-                'desc'  => $action_details['label'],
1074
-            );
1075
-        }
1076
-
1077
-        /** @type array $status_items status legend setup */
1078
-        $status_items = array(
1079
-            'sent_status'                => array(
1080
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1081
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1082
-            ),
1083
-            'idle_status'                => array(
1084
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1085
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1086
-            ),
1087
-            'failed_status'              => array(
1088
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1089
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1090
-            ),
1091
-            'messenger_executing_status' => array(
1092
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1093
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1094
-            ),
1095
-            'resend_status'              => array(
1096
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1097
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1098
-            ),
1099
-            'incomplete_status'          => array(
1100
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1101
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1102
-            ),
1103
-            'retry_status'               => array(
1104
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1105
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1106
-            ),
1107
-        );
1108
-        if (EEM_Message::debug()) {
1109
-            $status_items['debug_only_status'] = array(
1110
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1111
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1112
-            );
1113
-        }
1114
-
1115
-        return array_merge($action_items, $status_items);
1116
-    }
1117
-
1118
-
1119
-    protected function _custom_mtps_preview()
1120
-    {
1121
-        $this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1122
-        $this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1123
-                                               . ' alt="' . esc_attr__(
1124
-                                                   'Preview Custom Message Templates screenshot',
1125
-                                                   'event_espresso'
1126
-                                               ) . '" />';
1127
-        $this->_template_args['preview_text'] = '<strong>'
1128
-                                                . esc_html__(
1129
-                                                    '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.',
1130
-                                                    'event_espresso'
1131
-                                                )
1132
-                                                . '</strong>';
1133
-
1134
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1135
-    }
1136
-
1137
-
1138
-    /**
1139
-     * get_message_templates
1140
-     * This gets all the message templates for listing on the overview list.
1141
-     *
1142
-     * @access public
1143
-     * @param int    $perpage the amount of templates groups to show per page
1144
-     * @param string $type    the current _view we're getting templates for
1145
-     * @param bool   $count   return count?
1146
-     * @param bool   $all     disregard any paging info (get all data);
1147
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1148
-     * @return array
1149
-     * @throws EE_Error
1150
-     * @throws InvalidArgumentException
1151
-     * @throws InvalidDataTypeException
1152
-     * @throws InvalidInterfaceException
1153
-     */
1154
-    public function get_message_templates(
1155
-        $perpage = 10,
1156
-        $type = 'in_use',
1157
-        $count = false,
1158
-        $all = false,
1159
-        $global = true
1160
-    ) {
1161
-
1162
-        $MTP = EEM_Message_Template_Group::instance();
1163
-
1164
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1165
-        $orderby = $this->_req_data['orderby'];
1166
-
1167
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1168
-            ? $this->_req_data['order']
1169
-            : 'ASC';
1170
-
1171
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1172
-            ? $this->_req_data['paged']
1173
-            : 1;
1174
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1175
-            ? $this->_req_data['perpage']
1176
-            : $perpage;
1177
-
1178
-        $offset = ($current_page - 1) * $per_page;
1179
-        $limit = $all ? null : array($offset, $per_page);
1180
-
1181
-
1182
-        // options will match what is in the _views array property
1183
-        switch ($type) {
1184
-            case 'in_use':
1185
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1186
-                break;
1187
-            default:
1188
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1189
-        }
1190
-
1191
-        return $templates;
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * filters etc might need a list of installed message_types
1197
-     *
1198
-     * @return array an array of message type objects
1199
-     */
1200
-    public function get_installed_message_types()
1201
-    {
1202
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1203
-        $installed = array();
1204
-
1205
-        foreach ($installed_message_types as $message_type) {
1206
-            $installed[ $message_type->name ] = $message_type;
1207
-        }
1208
-
1209
-        return $installed;
1210
-    }
1211
-
1212
-
1213
-    /**
1214
-     * _add_message_template
1215
-     *
1216
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1217
-     *
1218
-     * @param string $message_type
1219
-     * @param string $messenger
1220
-     * @param string $GRP_ID
1221
-     *
1222
-     * @throws EE_error
1223
-     */
1224
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1225
-    {
1226
-        // set values override any request data
1227
-        $message_type = ! empty($message_type) ? $message_type : '';
1228
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1229
-            ? $this->_req_data['message_type']
1230
-            : $message_type;
1231
-
1232
-        $messenger = ! empty($messenger) ? $messenger : '';
1233
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1234
-            ? $this->_req_data['messenger']
1235
-            : $messenger;
1236
-
1237
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1238
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1239
-
1240
-        // we need messenger and message type.  They should be coming from the event editor. If not here then return error
1241
-        if (empty($message_type) || empty($messenger)) {
1242
-            throw new EE_Error(
1243
-                esc_html__(
1244
-                    'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1245
-                    'event_espresso'
1246
-                )
1247
-            );
1248
-        }
1249
-
1250
-        // we need the GRP_ID for the template being used as the base for the new template
1251
-        if (empty($GRP_ID)) {
1252
-            throw new EE_Error(
1253
-                esc_html__(
1254
-                    'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1255
-                    'event_espresso'
1256
-                )
1257
-            );
1258
-        }
1259
-
1260
-        // let's just make sure the template gets generated!
1261
-
1262
-        // we need to reassign some variables for what the insert is expecting
1263
-        $this->_req_data['MTP_messenger'] = $messenger;
1264
-        $this->_req_data['MTP_message_type'] = $message_type;
1265
-        $this->_req_data['GRP_ID'] = $GRP_ID;
1266
-        $this->_insert_or_update_message_template(true);
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * public wrapper for the _add_message_template method
1272
-     *
1273
-     * @param string $message_type     message type slug
1274
-     * @param string $messenger        messenger slug
1275
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1276
-     *                                 off of.
1277
-     * @throws EE_error
1278
-     */
1279
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1280
-    {
1281
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1282
-    }
1283
-
1284
-
1285
-    /**
1286
-     * _edit_message_template
1287
-     *
1288
-     * @access protected
1289
-     * @return void
1290
-     * @throws InvalidIdentifierException
1291
-     * @throws DomainException
1292
-     * @throws EE_Error
1293
-     * @throws InvalidArgumentException
1294
-     * @throws ReflectionException
1295
-     * @throws InvalidDataTypeException
1296
-     * @throws InvalidInterfaceException
1297
-     */
1298
-    protected function _edit_message_template()
1299
-    {
1300
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1301
-        $template_fields = '';
1302
-        $sidebar_fields = '';
1303
-        // we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1304
-        // valid html in the templates.
1305
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1306
-
1307
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1308
-            ? absint($this->_req_data['id'])
1309
-            : false;
1310
-
1311
-        $EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
1312
-        ? absint($this->_req_data['evt_id'])
1313
-        : false;
1314
-
1315
-        $this->_set_shortcodes(); // this also sets the _message_template property.
1316
-        $message_template_group = $this->_message_template_group;
1317
-        $c_label = $message_template_group->context_label();
1318
-        $c_config = $message_template_group->contexts_config();
1319
-
1320
-        reset($c_config);
1321
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1322
-            ? strtolower($this->_req_data['context'])
1323
-            : key($c_config);
1324
-
1325
-
1326
-        if (empty($GRP_ID)) {
1327
-            $action = 'insert_message_template';
1328
-            $edit_message_template_form_url = add_query_arg(
1329
-                array('action' => $action, 'noheader' => true),
1330
-                EE_MSG_ADMIN_URL
1331
-            );
1332
-        } else {
1333
-            $action = 'update_message_template';
1334
-            $edit_message_template_form_url = add_query_arg(
1335
-                array('action' => $action, 'noheader' => true),
1336
-                EE_MSG_ADMIN_URL
1337
-            );
1338
-        }
1339
-
1340
-        // set active messenger for this view
1341
-        $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1342
-            $message_template_group->messenger()
1343
-        );
1344
-        $this->_active_message_type_name = $message_template_group->message_type();
1345
-
1346
-
1347
-        // Do we have any validation errors?
1348
-        $validators = $this->_get_transient();
1349
-        $v_fields = ! empty($validators) ? array_keys($validators) : array();
1350
-
1351
-
1352
-        // we need to assemble the title from Various details
1353
-        $context_label = sprintf(
1354
-            esc_html__('(%s %s)', 'event_espresso'),
1355
-            $c_config[ $context ]['label'],
1356
-            ucwords($c_label['label'])
1357
-        );
1358
-
1359
-        $title = sprintf(
1360
-            esc_html__(' %s %s Template %s', 'event_espresso'),
1361
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1362
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1363
-            $context_label
1364
-        );
1365
-
1366
-        $this->_template_args['GRP_ID'] = $GRP_ID;
1367
-        $this->_template_args['message_template'] = $message_template_group;
1368
-        $this->_template_args['is_extra_fields'] = false;
1369
-
1370
-
1371
-        // let's get EEH_MSG_Template so we can get template form fields
1372
-        $template_field_structure = EEH_MSG_Template::get_fields(
1373
-            $message_template_group->messenger(),
1374
-            $message_template_group->message_type()
1375
-        );
1376
-
1377
-        if (! $template_field_structure) {
1378
-            $template_field_structure = false;
1379
-            $template_fields = esc_html__(
1380
-                'There was an error in assembling the fields for this display (you should see an error message)',
1381
-                'event_espresso'
1382
-            );
1383
-        }
1384
-
1385
-
1386
-        $message_templates = $message_template_group->context_templates();
1387
-
1388
-
1389
-        // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1390
-        // will get handled in the "extra" array.
1391
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1392
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1393
-                unset($template_field_structure[ $context ][ $reference_field ]);
1394
-            }
1395
-        }
1396
-
1397
-        // let's loop through the template_field_structure and actually assemble the input fields!
1398
-        if (! empty($template_field_structure)) {
1399
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1400
-                // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1401
-                // the extra array and reset them.
1402
-                if ($template_field === 'extra') {
1403
-                    $this->_template_args['is_extra_fields'] = true;
1404
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1405
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1406
-                        $content = $message_template instanceof EE_Message_Template
1407
-                            ? $message_template->get('MTP_content')
1408
-                            : '';
1409
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1410
-                            // let's verify if we need this extra field via the shortcodes parameter.
1411
-                            $continue = false;
1412
-                            if (isset($extra_array['shortcodes_required'])) {
1413
-                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1414
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1415
-                                        $continue = true;
1416
-                                    }
1417
-                                }
1418
-                                if ($continue) {
1419
-                                    continue;
1420
-                                }
1421
-                            }
1422
-
1423
-                            $field_id = $reference_field
1424
-                                        . '-'
1425
-                                        . $extra_field
1426
-                                        . '-content';
1427
-                            $template_form_fields[ $field_id ] = $extra_array;
1428
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1429
-                                                                         . $reference_field
1430
-                                                                         . '][content]['
1431
-                                                                         . $extra_field . ']';
1432
-                            $css_class = isset($extra_array['css_class'])
1433
-                                ? $extra_array['css_class']
1434
-                                : '';
1435
-
1436
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1437
-                                                                              && in_array($extra_field, $v_fields, true)
1438
-                                                                              &&
1439
-                                                                              (
1440
-                                                                                  is_array($validators[ $extra_field ])
1441
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1442
-                                                                              )
1443
-                                ? 'validate-error ' . $css_class
1444
-                                : $css_class;
1445
-
1446
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1447
-                                                                          && isset($content[ $extra_field ])
1448
-                                ? $content[ $extra_field ]
1449
-                                : '';
1450
-
1451
-                            // do we have a validation error?  if we do then let's use that value instead
1452
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1453
-                                ? $validators[ $extra_field ]['value']
1454
-                                : $template_form_fields[ $field_id ]['value'];
1455
-
1456
-
1457
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1458
-
1459
-                            // shortcode selector
1460
-                            $field_name_to_use = $extra_field === 'main'
1461
-                                ? 'content'
1462
-                                : $extra_field;
1463
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1464
-                                $field_name_to_use,
1465
-                                $field_id
1466
-                            );
1467
-
1468
-                            if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1469
-                                // we want to decode the entities
1470
-                                $template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1471
-                            }/**/
1472
-                        }
1473
-                        $templatefield_MTP_id = $reference_field . '-MTP_ID';
1474
-                        $templatefield_templatename_id = $reference_field . '-name';
1475
-
1476
-                        $template_form_fields[ $templatefield_MTP_id ] = array(
1477
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1478
-                            'label'      => null,
1479
-                            'input'      => 'hidden',
1480
-                            'type'       => 'int',
1481
-                            'required'   => false,
1482
-                            'validation' => false,
1483
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1484
-                            'css_class'  => '',
1485
-                            'format'     => '%d',
1486
-                            'db-col'     => 'MTP_ID',
1487
-                        );
1488
-
1489
-                        $template_form_fields[ $templatefield_templatename_id ] = array(
1490
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1491
-                            'label'      => null,
1492
-                            'input'      => 'hidden',
1493
-                            'type'       => 'string',
1494
-                            'required'   => false,
1495
-                            'validation' => true,
1496
-                            'value'      => $reference_field,
1497
-                            'css_class'  => '',
1498
-                            'format'     => '%s',
1499
-                            'db-col'     => 'MTP_template_field',
1500
-                        );
1501
-                    }
1502
-                    continue; // skip the next stuff, we got the necessary fields here for this dataset.
1503
-                } else {
1504
-                    $field_id = $template_field . '-content';
1505
-                    $template_form_fields[ $field_id ] = $field_setup_array;
1506
-                    $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1507
-                    $message_template = isset($message_templates[ $context ][ $template_field ])
1508
-                        ? $message_templates[ $context ][ $template_field ]
1509
-                        : null;
1510
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1511
-                                                                  && is_array($message_templates[ $context ])
1512
-                                                                  && $message_template instanceof EE_Message_Template
1513
-                        ? $message_template->get('MTP_content')
1514
-                        : '';
1515
-
1516
-                    // do we have a validator error for this field?  if we do then we'll use that value instead
1517
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1518
-                        ? $validators[ $template_field ]['value']
1519
-                        : $template_form_fields[ $field_id ]['value'];
1520
-
1521
-
1522
-                    $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1523
-                    $css_class = isset($field_setup_array['css_class'])
1524
-                        ? $field_setup_array['css_class']
1525
-                        : '';
1526
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1527
-                                                                      && in_array($template_field, $v_fields, true)
1528
-                                                                      && isset($validators[ $template_field ]['msg'])
1529
-                        ? 'validate-error ' . $css_class
1530
-                        : $css_class;
1531
-
1532
-                    // shortcode selector
1533
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1534
-                        $template_field,
1535
-                        $field_id
1536
-                    );
1537
-                }
1538
-
1539
-                // k took care of content field(s) now let's take care of others.
1540
-
1541
-                $templatefield_MTP_id = $template_field . '-MTP_ID';
1542
-                $templatefield_field_templatename_id = $template_field . '-name';
1543
-
1544
-                // foreach template field there are actually two form fields created
1545
-                $template_form_fields[ $templatefield_MTP_id ] = array(
1546
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1547
-                    'label'      => null,
1548
-                    'input'      => 'hidden',
1549
-                    'type'       => 'int',
1550
-                    'required'   => false,
1551
-                    'validation' => true,
1552
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1553
-                    'css_class'  => '',
1554
-                    'format'     => '%d',
1555
-                    'db-col'     => 'MTP_ID',
1556
-                );
1557
-
1558
-                $template_form_fields[ $templatefield_field_templatename_id ] = array(
1559
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1560
-                    'label'      => null,
1561
-                    'input'      => 'hidden',
1562
-                    'type'       => 'string',
1563
-                    'required'   => false,
1564
-                    'validation' => true,
1565
-                    'value'      => $template_field,
1566
-                    'css_class'  => '',
1567
-                    'format'     => '%s',
1568
-                    'db-col'     => 'MTP_template_field',
1569
-                );
1570
-            }
1571
-
1572
-            // add other fields
1573
-            $template_form_fields['ee-msg-current-context'] = array(
1574
-                'name'       => 'MTP_context',
1575
-                'label'      => null,
1576
-                'input'      => 'hidden',
1577
-                'type'       => 'string',
1578
-                'required'   => false,
1579
-                'validation' => true,
1580
-                'value'      => $context,
1581
-                'css_class'  => '',
1582
-                'format'     => '%s',
1583
-                'db-col'     => 'MTP_context',
1584
-            );
1585
-
1586
-            $template_form_fields['ee-msg-grp-id'] = array(
1587
-                'name'       => 'GRP_ID',
1588
-                'label'      => null,
1589
-                'input'      => 'hidden',
1590
-                'type'       => 'int',
1591
-                'required'   => false,
1592
-                'validation' => true,
1593
-                'value'      => $GRP_ID,
1594
-                'css_class'  => '',
1595
-                'format'     => '%d',
1596
-                'db-col'     => 'GRP_ID',
1597
-            );
1598
-
1599
-            $template_form_fields['ee-msg-messenger'] = array(
1600
-                'name'       => 'MTP_messenger',
1601
-                'label'      => null,
1602
-                'input'      => 'hidden',
1603
-                'type'       => 'string',
1604
-                'required'   => false,
1605
-                'validation' => true,
1606
-                'value'      => $message_template_group->messenger(),
1607
-                'css_class'  => '',
1608
-                'format'     => '%s',
1609
-                'db-col'     => 'MTP_messenger',
1610
-            );
1611
-
1612
-            $template_form_fields['ee-msg-message-type'] = array(
1613
-                'name'       => 'MTP_message_type',
1614
-                'label'      => null,
1615
-                'input'      => 'hidden',
1616
-                'type'       => 'string',
1617
-                'required'   => false,
1618
-                'validation' => true,
1619
-                'value'      => $message_template_group->message_type(),
1620
-                'css_class'  => '',
1621
-                'format'     => '%s',
1622
-                'db-col'     => 'MTP_message_type',
1623
-            );
1624
-
1625
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1626
-                'name'       => 'MTP_is_global',
1627
-                'label'      => esc_html__('Global Template', 'event_espresso'),
1628
-                'input'      => 'hidden',
1629
-                'type'       => 'int',
1630
-                'required'   => false,
1631
-                'validation' => true,
1632
-                'value'      => $message_template_group->get('MTP_is_global'),
1633
-                'css_class'  => '',
1634
-                'format'     => '%d',
1635
-                'db-col'     => 'MTP_is_global',
1636
-            );
1637
-
1638
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1639
-                'name'       => 'MTP_is_override',
1640
-                'label'      => esc_html__('Override all custom', 'event_espresso'),
1641
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1642
-                'type'       => 'int',
1643
-                'required'   => false,
1644
-                'validation' => true,
1645
-                'value'      => $message_template_group->get('MTP_is_override'),
1646
-                'css_class'  => '',
1647
-                'format'     => '%d',
1648
-                'db-col'     => 'MTP_is_override',
1649
-            );
1650
-
1651
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1652
-                'name'       => 'MTP_is_active',
1653
-                'label'      => esc_html__('Active Template', 'event_espresso'),
1654
-                'input'      => 'hidden',
1655
-                'type'       => 'int',
1656
-                'required'   => false,
1657
-                'validation' => true,
1658
-                'value'      => $message_template_group->is_active(),
1659
-                'css_class'  => '',
1660
-                'format'     => '%d',
1661
-                'db-col'     => 'MTP_is_active',
1662
-            );
1663
-
1664
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1665
-                'name'       => 'MTP_deleted',
1666
-                'label'      => null,
1667
-                'input'      => 'hidden',
1668
-                'type'       => 'int',
1669
-                'required'   => false,
1670
-                'validation' => true,
1671
-                'value'      => $message_template_group->get('MTP_deleted'),
1672
-                'css_class'  => '',
1673
-                'format'     => '%d',
1674
-                'db-col'     => 'MTP_deleted',
1675
-            );
1676
-            $sidebar_form_fields['ee-msg-author'] = array(
1677
-                'name'       => 'MTP_user_id',
1678
-                'label'      => esc_html__('Author', 'event_espresso'),
1679
-                'input'      => 'hidden',
1680
-                'type'       => 'int',
1681
-                'required'   => false,
1682
-                'validation' => false,
1683
-                'value'      => $message_template_group->user(),
1684
-                'format'     => '%d',
1685
-                'db-col'     => 'MTP_user_id',
1686
-            );
1687
-
1688
-            $sidebar_form_fields['ee-msg-route'] = array(
1689
-                'name'  => 'action',
1690
-                'input' => 'hidden',
1691
-                'type'  => 'string',
1692
-                'value' => $action,
1693
-            );
1694
-
1695
-            $sidebar_form_fields['ee-msg-id'] = array(
1696
-                'name'  => 'id',
1697
-                'input' => 'hidden',
1698
-                'type'  => 'int',
1699
-                'value' => $GRP_ID,
1700
-            );
1701
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1702
-                'name'  => $action . '_nonce',
1703
-                'input' => 'hidden',
1704
-                'type'  => 'string',
1705
-                'value' => wp_create_nonce($action . '_nonce'),
1706
-            );
1707
-
1708
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1709
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1710
-                    'name'  => 'template_switch',
1711
-                    'input' => 'hidden',
1712
-                    'type'  => 'int',
1713
-                    'value' => 1,
1714
-                );
1715
-            }
1716
-
1717
-
1718
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1719
-            $sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1720
-        } //end if ( !empty($template_field_structure) )
1721
-
1722
-        // set extra content for publish box
1723
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1724
-        $this->_set_publish_post_box_vars(
1725
-            'id',
1726
-            $GRP_ID,
1727
-            false,
1728
-            add_query_arg(
1729
-                array('action' => 'global_mtps'),
1730
-                $this->_admin_base_url
1731
-            )
1732
-        );
1733
-
1734
-        // add preview button
1735
-        $preview_url = parent::add_query_args_and_nonce(
1736
-            array(
1737
-                'message_type' => $message_template_group->message_type(),
1738
-                'messenger'    => $message_template_group->messenger(),
1739
-                'context'      => $context,
1740
-                'GRP_ID'       => $GRP_ID,
1741
-                'evt_id'       => $EVT_ID,
1742
-                'action'       => 'preview_message',
1743
-            ),
1744
-            $this->_admin_base_url
1745
-        );
1746
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1747
-                          . esc_html__('Preview', 'event_espresso')
1748
-                          . '</a>';
1749
-
1750
-
1751
-        // setup context switcher
1752
-        $context_switcher_args = array(
1753
-            'page'    => 'espresso_messages',
1754
-            'action'  => 'edit_message_template',
1755
-            'id'      => $GRP_ID,
1756
-            'evt_id'  => $EVT_ID,
1757
-            'context' => $context,
1758
-            'extra'   => $preview_button,
1759
-        );
1760
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1761
-
1762
-
1763
-        // main box
1764
-        $this->_template_args['template_fields'] = $template_fields;
1765
-        $this->_template_args['sidebar_box_id'] = 'details';
1766
-        $this->_template_args['action'] = $action;
1767
-        $this->_template_args['context'] = $context;
1768
-        $this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1769
-        $this->_template_args['learn_more_about_message_templates_link'] =
1770
-            $this->_learn_more_about_message_templates_link();
1771
-
1772
-
1773
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1774
-        $this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1775
-            $message_template_group,
1776
-            $context,
1777
-            $context_label
1778
-        );
1779
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1780
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1781
-
1782
-        $this->_template_path = $this->_template_args['GRP_ID']
1783
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1784
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1785
-
1786
-        // send along EE_Message_Template_Group object for further template use.
1787
-        $this->_template_args['MTP'] = $message_template_group;
1788
-
1789
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1790
-            $this->_template_path,
1791
-            $this->_template_args,
1792
-            true
1793
-        );
1794
-
1795
-
1796
-        // finally, let's set the admin_page title
1797
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1798
-
1799
-
1800
-        // we need to take care of setting the shortcodes property for use elsewhere.
1801
-        $this->_set_shortcodes();
1802
-
1803
-
1804
-        // final template wrapper
1805
-        $this->display_admin_page_with_sidebar();
1806
-    }
1807
-
1808
-
1809
-    public function filter_tinymce_init($mceInit, $editor_id)
1810
-    {
1811
-        return $mceInit;
1812
-    }
1813
-
1814
-
1815
-    public function add_context_switcher()
1816
-    {
1817
-        return $this->_context_switcher;
1818
-    }
1819
-
1820
-
1821
-    /**
1822
-     * Adds the activation/deactivation toggle for the message template context.
1823
-     *
1824
-     * @param EE_Message_Template_Group $message_template_group
1825
-     * @param string                    $context
1826
-     * @param string                    $context_label
1827
-     * @return string
1828
-     * @throws DomainException
1829
-     * @throws EE_Error
1830
-     * @throws InvalidIdentifierException
1831
-     */
1832
-    protected function add_active_context_element(
1833
-        EE_Message_Template_Group $message_template_group,
1834
-        $context,
1835
-        $context_label
1836
-    ) {
1837
-        $template_args = array(
1838
-            'context'                   => $context,
1839
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1840
-            'is_active'                 => $message_template_group->is_context_active($context),
1841
-            'on_off_action'             => $message_template_group->is_context_active($context)
1842
-                ? 'context-off'
1843
-                : 'context-on',
1844
-            'context_label'             => str_replace(array('(', ')'), '', $context_label),
1845
-            'message_template_group_id' => $message_template_group->ID(),
1846
-        );
1847
-        return EEH_Template::display_template(
1848
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1849
-            $template_args,
1850
-            true
1851
-        );
1852
-    }
1853
-
1854
-
1855
-    /**
1856
-     * Ajax callback for `toggle_context_template` ajax action.
1857
-     * Handles toggling the message context on or off.
1858
-     *
1859
-     * @throws EE_Error
1860
-     * @throws InvalidArgumentException
1861
-     * @throws InvalidDataTypeException
1862
-     * @throws InvalidIdentifierException
1863
-     * @throws InvalidInterfaceException
1864
-     */
1865
-    public function toggle_context_template()
1866
-    {
1867
-        $success = true;
1868
-        // check for required data
1869
-        if (! isset(
1870
-            $this->_req_data['message_template_group_id'],
1871
-            $this->_req_data['context'],
1872
-            $this->_req_data['status']
1873
-        )) {
1874
-            EE_Error::add_error(
1875
-                esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1876
-                __FILE__,
1877
-                __FUNCTION__,
1878
-                __LINE__
1879
-            );
1880
-            $success = false;
1881
-        }
1882
-
1883
-        $nonce = isset($this->_req_data['toggle_context_nonce'])
1884
-            ? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1885
-            : '';
1886
-        $nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1887
-        $this->_verify_nonce($nonce, $nonce_ref);
1888
-        $status = $this->_req_data['status'];
1889
-        if ($status !== 'off' && $status !== 'on') {
1890
-            EE_Error::add_error(
1891
-                sprintf(
1892
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1893
-                    $this->_req_data['status']
1894
-                ),
1895
-                __FILE__,
1896
-                __FUNCTION__,
1897
-                __LINE__
1898
-            );
1899
-            $success = false;
1900
-        }
1901
-        $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1902
-            $this->_req_data['message_template_group_id']
1903
-        );
1904
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1905
-            EE_Error::add_error(
1906
-                sprintf(
1907
-                    esc_html__(
1908
-                        'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1909
-                        'event_espresso'
1910
-                    ),
1911
-                    $this->_req_data['message_template_group_id'],
1912
-                    'EE_Message_Template_Group'
1913
-                ),
1914
-                __FILE__,
1915
-                __FUNCTION__,
1916
-                __LINE__
1917
-            );
1918
-            $success = false;
1919
-        }
1920
-        if ($success) {
1921
-            $success = $status === 'off'
1922
-                ? $message_template_group->deactivate_context($this->_req_data['context'])
1923
-                : $message_template_group->activate_context($this->_req_data['context']);
1924
-        }
1925
-        $this->_template_args['success'] = $success;
1926
-        $this->_return_json();
1927
-    }
1928
-
1929
-
1930
-    public function _add_form_element_before()
1931
-    {
1932
-        return '<form method="post" action="'
1933
-               . $this->_template_args["edit_message_template_form_url"]
1934
-               . '" id="ee-msg-edit-frm">';
1935
-    }
1936
-
1937
-    public function _add_form_element_after()
1938
-    {
1939
-        return '</form>';
1940
-    }
1941
-
1942
-
1943
-    /**
1944
-     * This executes switching the template pack for a message template.
1945
-     *
1946
-     * @since 4.5.0
1947
-     * @throws EE_Error
1948
-     * @throws InvalidDataTypeException
1949
-     * @throws InvalidInterfaceException
1950
-     * @throws InvalidArgumentException
1951
-     * @throws ReflectionException
1952
-     */
1953
-    public function switch_template_pack()
1954
-    {
1955
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1956
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1957
-
1958
-        // verify we have needed values.
1959
-        if (empty($GRP_ID) || empty($template_pack)) {
1960
-            $this->_template_args['error'] = true;
1961
-            EE_Error::add_error(
1962
-                esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1963
-                __FILE__,
1964
-                __FUNCTION__,
1965
-                __LINE__
1966
-            );
1967
-        } else {
1968
-            // get template, set the new template_pack and then reset to default
1969
-            /** @type EE_Message_Template_Group $message_template_group */
1970
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1971
-
1972
-            $message_template_group->set_template_pack_name($template_pack);
1973
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1974
-            $this->_req_data['mt'] = $message_template_group->message_type();
1975
-
1976
-            $query_args = $this->_reset_to_default_template();
1977
-
1978
-            if (empty($query_args['id'])) {
1979
-                EE_Error::add_error(
1980
-                    esc_html__(
1981
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1982
-                        'event_espresso'
1983
-                    ),
1984
-                    __FILE__,
1985
-                    __FUNCTION__,
1986
-                    __LINE__
1987
-                );
1988
-                $this->_template_args['error'] = true;
1989
-            } else {
1990
-                $template_label = $message_template_group->get_template_pack()->label;
1991
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1992
-                EE_Error::add_success(
1993
-                    sprintf(
1994
-                        esc_html__(
1995
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1996
-                            'event_espresso'
1997
-                        ),
1998
-                        $template_label,
1999
-                        $template_pack_labels->template_pack
2000
-                    )
2001
-                );
2002
-                // generate the redirect url for js.
2003
-                $url = self::add_query_args_and_nonce(
2004
-                    $query_args,
2005
-                    $this->_admin_base_url
2006
-                );
2007
-                $this->_template_args['data']['redirect_url'] = $url;
2008
-                $this->_template_args['success'] = true;
2009
-            }
2010
-
2011
-            $this->_return_json();
2012
-        }
2013
-    }
2014
-
2015
-
2016
-    /**
2017
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2018
-     * they want.
2019
-     *
2020
-     * @access protected
2021
-     * @return array|null
2022
-     * @throws EE_Error
2023
-     * @throws InvalidArgumentException
2024
-     * @throws InvalidDataTypeException
2025
-     * @throws InvalidInterfaceException
2026
-     */
2027
-    protected function _reset_to_default_template()
2028
-    {
2029
-
2030
-        $templates = array();
2031
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2032
-        // we need to make sure we've got the info we need.
2033
-        if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2034
-            EE_Error::add_error(
2035
-                esc_html__(
2036
-                    '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.',
2037
-                    'event_espresso'
2038
-                ),
2039
-                __FILE__,
2040
-                __FUNCTION__,
2041
-                __LINE__
2042
-            );
2043
-        }
2044
-
2045
-        // all templates will be reset to whatever the defaults are
2046
-        // for the global template matching the messenger and message type.
2047
-        $success = ! empty($GRP_ID) ? true : false;
2048
-
2049
-        if ($success) {
2050
-            // let's first determine if the incoming template is a global template,
2051
-            // if it isn't then we need to get the global template matching messenger and message type.
2052
-            // $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2053
-
2054
-
2055
-            // note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2056
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
2057
-
2058
-            if ($success) {
2059
-                // if successfully deleted, lets generate the new ones.
2060
-                // Note. We set GLOBAL to true, because resets on ANY template
2061
-                // will use the related global template defaults for regeneration.
2062
-                // This means that if a custom template is reset it resets to whatever the related global template is.
2063
-                // HOWEVER, we DO keep the template pack and template variation set
2064
-                // for the current custom template when resetting.
2065
-                $templates = $this->_generate_new_templates(
2066
-                    $this->_req_data['msgr'],
2067
-                    $this->_req_data['mt'],
2068
-                    $GRP_ID,
2069
-                    true
2070
-                );
2071
-            }
2072
-        }
2073
-
2074
-        // any error messages?
2075
-        if (! $success) {
2076
-            EE_Error::add_error(
2077
-                esc_html__(
2078
-                    'Something went wrong with deleting existing templates. Unable to reset to default',
2079
-                    'event_espresso'
2080
-                ),
2081
-                __FILE__,
2082
-                __FUNCTION__,
2083
-                __LINE__
2084
-            );
2085
-        }
2086
-
2087
-        // all good, let's add a success message!
2088
-        if ($success && ! empty($templates)) {
2089
-            // the info for the template we generated is the first element in the returned array
2090
-            // $templates = $templates[0];
2091
-            EE_Error::overwrite_success();
2092
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2093
-        }
2094
-
2095
-
2096
-        $query_args = array(
2097
-            'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2098
-            'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2099
-            'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2100
-        );
2101
-
2102
-        // if called via ajax then we return query args otherwise redirect
2103
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2104
-            return $query_args;
2105
-        } else {
2106
-            $this->_redirect_after_action(false, '', '', $query_args, true);
2107
-
2108
-            return null;
2109
-        }
2110
-    }
2111
-
2112
-
2113
-    /**
2114
-     * Retrieve and set the message preview for display.
2115
-     *
2116
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2117
-     * @return string
2118
-     * @throws ReflectionException
2119
-     * @throws EE_Error
2120
-     * @throws InvalidArgumentException
2121
-     * @throws InvalidDataTypeException
2122
-     * @throws InvalidInterfaceException
2123
-     */
2124
-    public function _preview_message($send = false)
2125
-    {
2126
-        // first make sure we've got the necessary parameters
2127
-        if (! isset(
2128
-            $this->_req_data['message_type'],
2129
-            $this->_req_data['messenger'],
2130
-            $this->_req_data['messenger'],
2131
-            $this->_req_data['GRP_ID']
2132
-        )) {
2133
-            EE_Error::add_error(
2134
-                esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2135
-                __FILE__,
2136
-                __FUNCTION__,
2137
-                __LINE__
2138
-            );
2139
-        }
2140
-
2141
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2142
-
2143
-
2144
-        // get the preview!
2145
-        $preview = EED_Messages::preview_message(
2146
-            $this->_req_data['message_type'],
2147
-            $this->_req_data['context'],
2148
-            $this->_req_data['messenger'],
2149
-            $send
2150
-        );
2151
-
2152
-        if ($send) {
2153
-            return $preview;
2154
-        }
2155
-
2156
-        // let's add a button to go back to the edit view
2157
-        $query_args = array(
2158
-            'id'      => $this->_req_data['GRP_ID'],
2159
-            'evt_id'  => $this->_req_data['evt_id'],
2160
-            'context' => $this->_req_data['context'],
2161
-            'action'  => 'edit_message_template',
2162
-        );
2163
-        $go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2164
-        $preview_button = '<a href="'
2165
-                          . $go_back_url
2166
-                          . '" class="button-secondary messages-preview-go-back-button">'
2167
-                          . esc_html__('Go Back to Edit', 'event_espresso')
2168
-                          . '</a>';
2169
-        $message_types = $this->get_installed_message_types();
2170
-        $active_messenger = $this->_message_resource_manager->get_active_messenger(
2171
-            $this->_req_data['messenger']
2172
-        );
2173
-        $active_messenger_label = $active_messenger instanceof EE_messenger
2174
-            ? ucwords($active_messenger->label['singular'])
2175
-            : esc_html__('Unknown Messenger', 'event_espresso');
2176
-        // let's provide a helpful title for context
2177
-        $preview_title = sprintf(
2178
-            esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2179
-            $active_messenger_label,
2180
-            ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2181
-        );
2182
-        if (empty($preview)) {
2183
-            $this->noEventsErrorMessage();
2184
-        }
2185
-        // setup display of preview.
2186
-        $this->_admin_page_title = $preview_title;
2187
-        $this->_template_args['admin_page_title'] = $preview_title;
2188
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2189
-        $this->_template_args['data']['force_json'] = true;
2190
-
2191
-        return '';
2192
-    }
2193
-
2194
-
2195
-    /**
2196
-     * Used to set an error if there are no events available for generating a preview/test send.
2197
-     *
2198
-     * @param bool $test_send  Whether the error should be generated for the context of a test send.
2199
-     */
2200
-    protected function noEventsErrorMessage($test_send = false)
2201
-    {
2202
-        $events_url = parent::add_query_args_and_nonce(
2203
-            array(
2204
-                'action' => 'default',
2205
-                'page'   => 'espresso_events',
2206
-            ),
2207
-            admin_url('admin.php')
2208
-        );
2209
-        $message = $test_send
2210
-            ? __(
2211
-                '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!',
2212
-                'event_espresso'
2213
-            )
2214
-            : __(
2215
-                '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!',
2216
-                'event_espresso'
2217
-            );
2218
-
2219
-        EE_Error::add_attention(
2220
-            sprintf(
2221
-                $message,
2222
-                "<a href='{$events_url}'>",
2223
-                '</a>'
2224
-            )
2225
-        );
2226
-    }
2227
-
2228
-
2229
-    /**
2230
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2231
-     * gets called automatically.
2232
-     *
2233
-     * @since 4.5.0
2234
-     *
2235
-     * @return string
2236
-     */
2237
-    protected function _display_preview_message()
2238
-    {
2239
-        $this->display_admin_page_with_no_sidebar();
2240
-    }
2241
-
2242
-
2243
-    /**
2244
-     * registers metaboxes that should show up on the "edit_message_template" page
2245
-     *
2246
-     * @access protected
2247
-     * @return void
2248
-     */
2249
-    protected function _register_edit_meta_boxes()
2250
-    {
2251
-        add_meta_box(
2252
-            'mtp_valid_shortcodes',
2253
-            esc_html__('Valid Shortcodes', 'event_espresso'),
2254
-            array($this, 'shortcode_meta_box'),
2255
-            $this->_current_screen->id,
2256
-            'side',
2257
-            'default'
2258
-        );
2259
-        add_meta_box(
2260
-            'mtp_extra_actions',
2261
-            esc_html__('Extra Actions', 'event_espresso'),
2262
-            array($this, 'extra_actions_meta_box'),
2263
-            $this->_current_screen->id,
2264
-            'side',
2265
-            'high'
2266
-        );
2267
-        add_meta_box(
2268
-            'mtp_templates',
2269
-            esc_html__('Template Styles', 'event_espresso'),
2270
-            array($this, 'template_pack_meta_box'),
2271
-            $this->_current_screen->id,
2272
-            'side',
2273
-            'high'
2274
-        );
2275
-    }
2276
-
2277
-
2278
-    /**
2279
-     * metabox content for all template pack and variation selection.
2280
-     *
2281
-     * @since 4.5.0
2282
-     * @return string
2283
-     * @throws DomainException
2284
-     * @throws EE_Error
2285
-     * @throws InvalidArgumentException
2286
-     * @throws ReflectionException
2287
-     * @throws InvalidDataTypeException
2288
-     * @throws InvalidInterfaceException
2289
-     */
2290
-    public function template_pack_meta_box()
2291
-    {
2292
-        $this->_set_message_template_group();
2293
-
2294
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
2295
-
2296
-        $tp_select_values = array();
2297
-
2298
-        foreach ($tp_collection as $tp) {
2299
-            // only include template packs that support this messenger and message type!
2300
-            $supports = $tp->get_supports();
2301
-            if (! isset($supports[ $this->_message_template_group->messenger() ])
2302
-                || ! in_array(
2303
-                    $this->_message_template_group->message_type(),
2304
-                    $supports[ $this->_message_template_group->messenger() ],
2305
-                    true
2306
-                )
2307
-            ) {
2308
-                // not supported
2309
-                continue;
2310
-            }
2311
-
2312
-            $tp_select_values[] = array(
2313
-                'text' => $tp->label,
2314
-                'id'   => $tp->dbref,
2315
-            );
2316
-        }
2317
-
2318
-        // if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2319
-        // the default template pack.  This still allows for the odd template pack to override.
2320
-        if (empty($tp_select_values)) {
2321
-            $tp_select_values[] = array(
2322
-                'text' => esc_html__('Default', 'event_espresso'),
2323
-                'id'   => 'default',
2324
-            );
2325
-        }
2326
-
2327
-        // setup variation select values for the currently selected template.
2328
-        $variations = $this->_message_template_group->get_template_pack()->get_variations(
2329
-            $this->_message_template_group->messenger(),
2330
-            $this->_message_template_group->message_type()
2331
-        );
2332
-        $variations_select_values = array();
2333
-        foreach ($variations as $variation => $label) {
2334
-            $variations_select_values[] = array(
2335
-                'text' => $label,
2336
-                'id'   => $variation,
2337
-            );
2338
-        }
2339
-
2340
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2341
-
2342
-        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2343
-            'MTP_template_pack',
2344
-            $tp_select_values,
2345
-            $this->_message_template_group->get_template_pack_name()
2346
-        );
2347
-        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
2348
-            'MTP_template_variation',
2349
-            $variations_select_values,
2350
-            $this->_message_template_group->get_template_pack_variation()
2351
-        );
2352
-        $template_args['template_pack_label'] = $template_pack_labels->template_pack;
2353
-        $template_args['template_variation_label'] = $template_pack_labels->template_variation;
2354
-        $template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2355
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2356
-
2357
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2358
-
2359
-        EEH_Template::display_template($template, $template_args);
2360
-    }
2361
-
2362
-
2363
-    /**
2364
-     * This meta box holds any extra actions related to Message Templates
2365
-     * For now, this includes Resetting templates to defaults and sending a test email.
2366
-     *
2367
-     * @access  public
2368
-     * @return void
2369
-     * @throws EE_Error
2370
-     */
2371
-    public function extra_actions_meta_box()
2372
-    {
2373
-        $template_form_fields = array();
2374
-
2375
-        $extra_args = array(
2376
-            'msgr'   => $this->_message_template_group->messenger(),
2377
-            'mt'     => $this->_message_template_group->message_type(),
2378
-            'GRP_ID' => $this->_message_template_group->GRP_ID(),
2379
-        );
2380
-        // first we need to see if there are any fields
2381
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2382
-
2383
-        if (! empty($fields)) {
2384
-            // yup there be fields
2385
-            foreach ($fields as $field => $config) {
2386
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2387
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2388
-                $default = isset($config['default']) ? $config['default'] : '';
2389
-                $default = isset($config['value']) ? $config['value'] : $default;
2390
-
2391
-                // if type is hidden and the value is empty
2392
-                // something may have gone wrong so let's correct with the defaults
2393
-                $fix = $config['input'] === 'hidden'
2394
-                       && isset($existing[ $field ])
2395
-                       && empty($existing[ $field ])
2396
-                    ? $default
2397
-                    : '';
2398
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2399
-                    ? $existing[ $field ]
2400
-                    : $fix;
2401
-
2402
-                $template_form_fields[ $field_id ] = array(
2403
-                    'name'       => 'test_settings_fld[' . $field . ']',
2404
-                    'label'      => $config['label'],
2405
-                    'input'      => $config['input'],
2406
-                    'type'       => $config['type'],
2407
-                    'required'   => $config['required'],
2408
-                    'validation' => $config['validation'],
2409
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2410
-                    'css_class'  => $config['css_class'],
2411
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2412
-                    'default'    => $default,
2413
-                    'format'     => $config['format'],
2414
-                );
2415
-            }
2416
-        }
2417
-
2418
-        $test_settings_fields = ! empty($template_form_fields)
2419
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2420
-            : '';
2421
-
2422
-        $test_settings_html = '';
2423
-        // print out $test_settings_fields
2424
-        if (! empty($test_settings_fields)) {
2425
-            echo $test_settings_fields;
2426
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2427
-            $test_settings_html .= 'name="test_button" value="';
2428
-            $test_settings_html .= esc_html__('Test Send', 'event_espresso');
2429
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2430
-        }
2431
-
2432
-        // and button
2433
-        $test_settings_html .= '<p>'
2434
-                               . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2435
-                               . '</p>';
2436
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2437
-        $test_settings_html .= $this->get_action_link_or_button(
2438
-            'reset_to_default',
2439
-            'reset',
2440
-            $extra_args,
2441
-            'button-primary reset-default-button'
2442
-        );
2443
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2444
-        echo $test_settings_html;
2445
-    }
2446
-
2447
-
2448
-    /**
2449
-     * This returns the shortcode selector skeleton for a given context and field.
2450
-     *
2451
-     * @since 4.9.rc.000
2452
-     * @param string $field           The name of the field retrieving shortcodes for.
2453
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2454
-     * @return string
2455
-     * @throws DomainException
2456
-     * @throws EE_Error
2457
-     * @throws InvalidArgumentException
2458
-     * @throws ReflectionException
2459
-     * @throws InvalidDataTypeException
2460
-     * @throws InvalidInterfaceException
2461
-     */
2462
-    protected function _get_shortcode_selector($field, $linked_input_id)
2463
-    {
2464
-        $template_args = array(
2465
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2466
-            'fieldname'       => $field,
2467
-            'linked_input_id' => $linked_input_id,
2468
-        );
2469
-
2470
-        return EEH_Template::display_template(
2471
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2472
-            $template_args,
2473
-            true
2474
-        );
2475
-    }
2476
-
2477
-
2478
-    /**
2479
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2480
-     * page)
2481
-     *
2482
-     * @access public
2483
-     * @return void
2484
-     * @throws EE_Error
2485
-     * @throws InvalidArgumentException
2486
-     * @throws ReflectionException
2487
-     * @throws InvalidDataTypeException
2488
-     * @throws InvalidInterfaceException
2489
-     */
2490
-    public function shortcode_meta_box()
2491
-    {
2492
-        $shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2493
-        // $messenger = $this->_message_template_group->messenger_obj();
2494
-        // now let's set the content depending on the status of the shortcodes array
2495
-        if (empty($shortcodes)) {
2496
-            $content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2497
-            echo $content;
2498
-        } else {
2499
-            // $alt = 0;
2500
-            ?>
22
+	/**
23
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
24
+	 */
25
+	protected $_message_resource_manager;
26
+
27
+	/**
28
+	 * @type string $_active_message_type_name
29
+	 */
30
+	protected $_active_message_type_name = '';
31
+
32
+	/**
33
+	 * @type EE_messenger $_active_messenger
34
+	 */
35
+	protected $_active_messenger;
36
+	protected $_activate_state;
37
+	protected $_activate_meta_box_type;
38
+	protected $_current_message_meta_box;
39
+	protected $_current_message_meta_box_object;
40
+	protected $_context_switcher;
41
+	protected $_shortcodes = array();
42
+	protected $_active_messengers = array();
43
+	protected $_active_message_types = array();
44
+
45
+	/**
46
+	 * @var EE_Message_Template_Group $_message_template_group
47
+	 */
48
+	protected $_message_template_group;
49
+	protected $_m_mt_settings = array();
50
+
51
+
52
+	/**
53
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
+	 * IF there is no group then it gets automatically set to the Default template pack.
55
+	 *
56
+	 * @since 4.5.0
57
+	 *
58
+	 * @var EE_Messages_Template_Pack
59
+	 */
60
+	protected $_template_pack;
61
+
62
+
63
+	/**
64
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
+	 * group is.  If there is no group then it automatically gets set to default.
66
+	 *
67
+	 * @since 4.5.0
68
+	 *
69
+	 * @var string
70
+	 */
71
+	protected $_variation;
72
+
73
+
74
+	/**
75
+	 * @param bool $routing
76
+	 * @throws EE_Error
77
+	 */
78
+	public function __construct($routing = true)
79
+	{
80
+		// make sure messages autoloader is running
81
+		EED_Messages::set_autoloaders();
82
+		parent::__construct($routing);
83
+	}
84
+
85
+
86
+	protected function _init_page_props()
87
+	{
88
+		$this->page_slug = EE_MSG_PG_SLUG;
89
+		$this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
+		$this->_admin_base_url = EE_MSG_ADMIN_URL;
91
+		$this->_admin_base_path = EE_MSG_ADMIN;
92
+
93
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
+			: array();
95
+
96
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
+		$this->_load_message_resource_manager();
98
+	}
99
+
100
+
101
+	/**
102
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
+	 *
104
+	 * @throws EE_Error
105
+	 * @throws InvalidDataTypeException
106
+	 * @throws InvalidInterfaceException
107
+	 * @throws InvalidArgumentException
108
+	 * @throws ReflectionException
109
+	 */
110
+	protected function _load_message_resource_manager()
111
+	{
112
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
+	}
114
+
115
+
116
+	/**
117
+	 * @deprecated 4.9.9.rc.014
118
+	 * @return array
119
+	 * @throws EE_Error
120
+	 * @throws InvalidArgumentException
121
+	 * @throws InvalidDataTypeException
122
+	 * @throws InvalidInterfaceException
123
+	 */
124
+	public function get_messengers_for_list_table()
125
+	{
126
+		EE_Error::doing_it_wrong(
127
+			__METHOD__,
128
+			sprintf(
129
+				esc_html__(
130
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
+					'event_espresso'
132
+				),
133
+				'Messages_Admin_Page::get_messengers_select_input()'
134
+			),
135
+			'4.9.9.rc.014'
136
+		);
137
+
138
+		$m_values = array();
139
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
+		// setup messengers for selects
141
+		$i = 1;
142
+		foreach ($active_messengers as $active_messenger) {
143
+			if ($active_messenger instanceof EE_Message) {
144
+				$m_values[ $i ]['id'] = $active_messenger->messenger();
145
+				$m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
+				$i++;
147
+			}
148
+		}
149
+
150
+		return $m_values;
151
+	}
152
+
153
+
154
+	/**
155
+	 * @deprecated 4.9.9.rc.014
156
+	 * @return array
157
+	 * @throws EE_Error
158
+	 * @throws InvalidArgumentException
159
+	 * @throws InvalidDataTypeException
160
+	 * @throws InvalidInterfaceException
161
+	 */
162
+	public function get_message_types_for_list_table()
163
+	{
164
+		EE_Error::doing_it_wrong(
165
+			__METHOD__,
166
+			sprintf(
167
+				esc_html__(
168
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
+					'event_espresso'
170
+				),
171
+				'Messages_Admin_Page::get_message_types_select_input()'
172
+			),
173
+			'4.9.9.rc.014'
174
+		);
175
+
176
+		$mt_values = array();
177
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
+		$i = 1;
179
+		foreach ($active_messages as $active_message) {
180
+			if ($active_message instanceof EE_Message) {
181
+				$mt_values[ $i ]['id'] = $active_message->message_type();
182
+				$mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
+				$i++;
184
+			}
185
+		}
186
+
187
+		return $mt_values;
188
+	}
189
+
190
+
191
+	/**
192
+	 * @deprecated 4.9.9.rc.014
193
+	 * @return array
194
+	 * @throws EE_Error
195
+	 * @throws InvalidArgumentException
196
+	 * @throws InvalidDataTypeException
197
+	 * @throws InvalidInterfaceException
198
+	 */
199
+	public function get_contexts_for_message_types_for_list_table()
200
+	{
201
+		EE_Error::doing_it_wrong(
202
+			__METHOD__,
203
+			sprintf(
204
+				esc_html__(
205
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
+					'event_espresso'
207
+				),
208
+				'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
+			),
210
+			'4.9.9.rc.014'
211
+		);
212
+
213
+		$contexts = array();
214
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
+		foreach ($active_message_contexts as $active_message) {
216
+			if ($active_message instanceof EE_Message) {
217
+				$message_type = $active_message->message_type_object();
218
+				if ($message_type instanceof EE_message_type) {
219
+					$message_type_contexts = $message_type->get_contexts();
220
+					foreach ($message_type_contexts as $context => $context_details) {
221
+						$contexts[ $context ] = $context_details['label'];
222
+					}
223
+				}
224
+			}
225
+		}
226
+
227
+		return $contexts;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Generate select input with provided messenger options array.
233
+	 *
234
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
+	 *                                 labels.
236
+	 * @return string
237
+	 * @throws EE_Error
238
+	 */
239
+	public function get_messengers_select_input($messenger_options)
240
+	{
241
+		// if empty or just one value then just return an empty string
242
+		if (empty($messenger_options)
243
+			|| ! is_array($messenger_options)
244
+			|| count($messenger_options) === 1
245
+		) {
246
+			return '';
247
+		}
248
+		// merge in default
249
+		$messenger_options = array_merge(
250
+			array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
+			$messenger_options
252
+		);
253
+		$input = new EE_Select_Input(
254
+			$messenger_options,
255
+			array(
256
+				'html_name'  => 'ee_messenger_filter_by',
257
+				'html_id'    => 'ee_messenger_filter_by',
258
+				'html_class' => 'wide',
259
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
+					: 'none_selected',
262
+			)
263
+		);
264
+
265
+		return $input->get_html_for_input();
266
+	}
267
+
268
+
269
+	/**
270
+	 * Generate select input with provided message type options array.
271
+	 *
272
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
+	 *                                    message type labels
274
+	 * @return string
275
+	 * @throws EE_Error
276
+	 */
277
+	public function get_message_types_select_input($message_type_options)
278
+	{
279
+		// if empty or count of options is 1 then just return an empty string
280
+		if (empty($message_type_options)
281
+			|| ! is_array($message_type_options)
282
+			|| count($message_type_options) === 1
283
+		) {
284
+			return '';
285
+		}
286
+		// merge in default
287
+		$message_type_options = array_merge(
288
+			array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
+			$message_type_options
290
+		);
291
+		$input = new EE_Select_Input(
292
+			$message_type_options,
293
+			array(
294
+				'html_name'  => 'ee_message_type_filter_by',
295
+				'html_id'    => 'ee_message_type_filter_by',
296
+				'html_class' => 'wide',
297
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
+					: 'none_selected',
300
+			)
301
+		);
302
+
303
+		return $input->get_html_for_input();
304
+	}
305
+
306
+
307
+	/**
308
+	 * Generate select input with provide message type contexts array.
309
+	 *
310
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
+	 *                               context label.
312
+	 * @return string
313
+	 * @throws EE_Error
314
+	 */
315
+	public function get_contexts_for_message_types_select_input($context_options)
316
+	{
317
+		// if empty or count of options is one then just return empty string
318
+		if (empty($context_options)
319
+			|| ! is_array($context_options)
320
+			|| count($context_options) === 1
321
+		) {
322
+			return '';
323
+		}
324
+		// merge in default
325
+		$context_options = array_merge(
326
+			array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
+			$context_options
328
+		);
329
+		$input = new EE_Select_Input(
330
+			$context_options,
331
+			array(
332
+				'html_name'  => 'ee_context_filter_by',
333
+				'html_id'    => 'ee_context_filter_by',
334
+				'html_class' => 'wide',
335
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
336
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
337
+					: 'none_selected',
338
+			)
339
+		);
340
+
341
+		return $input->get_html_for_input();
342
+	}
343
+
344
+
345
+	protected function _ajax_hooks()
346
+	{
347
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
+		add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
+	}
354
+
355
+
356
+	protected function _define_page_props()
357
+	{
358
+		$this->_admin_page_title = $this->page_label;
359
+		$this->_labels = array(
360
+			'buttons'    => array(
361
+				'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
+				'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
+				'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
+			),
365
+			'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
+		);
367
+	}
368
+
369
+
370
+	/**
371
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
372
+	 *
373
+	 * @access protected
374
+	 * @return void
375
+	 */
376
+	protected function _set_page_routes()
377
+	{
378
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
+			? $this->_req_data['GRP_ID']
380
+			: 0;
381
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
+			? $this->_req_data['id']
383
+			: $grp_id;
384
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
+			? $this->_req_data['MSG_ID']
386
+			: 0;
387
+
388
+		$this->_page_routes = array(
389
+			'default'                          => array(
390
+				'func'       => '_message_queue_list_table',
391
+				'capability' => 'ee_read_global_messages',
392
+			),
393
+			'global_mtps'                      => array(
394
+				'func'       => '_ee_default_messages_overview_list_table',
395
+				'capability' => 'ee_read_global_messages',
396
+			),
397
+			'custom_mtps'                      => array(
398
+				'func'       => '_custom_mtps_preview',
399
+				'capability' => 'ee_read_messages',
400
+			),
401
+			'add_new_message_template'         => array(
402
+				'func'       => '_add_message_template',
403
+				'capability' => 'ee_edit_messages',
404
+				'noheader'   => true,
405
+			),
406
+			'edit_message_template'            => array(
407
+				'func'       => '_edit_message_template',
408
+				'capability' => 'ee_edit_message',
409
+				'obj_id'     => $grp_id,
410
+			),
411
+			'preview_message'                  => array(
412
+				'func'               => '_preview_message',
413
+				'capability'         => 'ee_read_message',
414
+				'obj_id'             => $grp_id,
415
+				'noheader'           => true,
416
+				'headers_sent_route' => 'display_preview_message',
417
+			),
418
+			'display_preview_message'          => array(
419
+				'func'       => '_display_preview_message',
420
+				'capability' => 'ee_read_message',
421
+				'obj_id'     => $grp_id,
422
+			),
423
+			'insert_message_template'          => array(
424
+				'func'       => '_insert_or_update_message_template',
425
+				'capability' => 'ee_edit_messages',
426
+				'args'       => array('new_template' => true),
427
+				'noheader'   => true,
428
+			),
429
+			'update_message_template'          => array(
430
+				'func'       => '_insert_or_update_message_template',
431
+				'capability' => 'ee_edit_message',
432
+				'obj_id'     => $grp_id,
433
+				'args'       => array('new_template' => false),
434
+				'noheader'   => true,
435
+			),
436
+			'trash_message_template'           => array(
437
+				'func'       => '_trash_or_restore_message_template',
438
+				'capability' => 'ee_delete_message',
439
+				'obj_id'     => $grp_id,
440
+				'args'       => array('trash' => true, 'all' => true),
441
+				'noheader'   => true,
442
+			),
443
+			'trash_message_template_context'   => array(
444
+				'func'       => '_trash_or_restore_message_template',
445
+				'capability' => 'ee_delete_message',
446
+				'obj_id'     => $grp_id,
447
+				'args'       => array('trash' => true),
448
+				'noheader'   => true,
449
+			),
450
+			'restore_message_template'         => array(
451
+				'func'       => '_trash_or_restore_message_template',
452
+				'capability' => 'ee_delete_message',
453
+				'obj_id'     => $grp_id,
454
+				'args'       => array('trash' => false, 'all' => true),
455
+				'noheader'   => true,
456
+			),
457
+			'restore_message_template_context' => array(
458
+				'func'       => '_trash_or_restore_message_template',
459
+				'capability' => 'ee_delete_message',
460
+				'obj_id'     => $grp_id,
461
+				'args'       => array('trash' => false),
462
+				'noheader'   => true,
463
+			),
464
+			'delete_message_template'          => array(
465
+				'func'       => '_delete_message_template',
466
+				'capability' => 'ee_delete_message',
467
+				'obj_id'     => $grp_id,
468
+				'noheader'   => true,
469
+			),
470
+			'reset_to_default'                 => array(
471
+				'func'       => '_reset_to_default_template',
472
+				'capability' => 'ee_edit_message',
473
+				'obj_id'     => $grp_id,
474
+				'noheader'   => true,
475
+			),
476
+			'settings'                         => array(
477
+				'func'       => '_settings',
478
+				'capability' => 'manage_options',
479
+			),
480
+			'update_global_settings'           => array(
481
+				'func'       => '_update_global_settings',
482
+				'capability' => 'manage_options',
483
+				'noheader'   => true,
484
+			),
485
+			'generate_now'                     => array(
486
+				'func'       => '_generate_now',
487
+				'capability' => 'ee_send_message',
488
+				'noheader'   => true,
489
+			),
490
+			'generate_and_send_now'            => array(
491
+				'func'       => '_generate_and_send_now',
492
+				'capability' => 'ee_send_message',
493
+				'noheader'   => true,
494
+			),
495
+			'queue_for_resending'              => array(
496
+				'func'       => '_queue_for_resending',
497
+				'capability' => 'ee_send_message',
498
+				'noheader'   => true,
499
+			),
500
+			'send_now'                         => array(
501
+				'func'       => '_send_now',
502
+				'capability' => 'ee_send_message',
503
+				'noheader'   => true,
504
+			),
505
+			'delete_ee_message'                => array(
506
+				'func'       => '_delete_ee_messages',
507
+				'capability' => 'ee_delete_messages',
508
+				'noheader'   => true,
509
+			),
510
+			'delete_ee_messages'               => array(
511
+				'func'       => '_delete_ee_messages',
512
+				'capability' => 'ee_delete_messages',
513
+				'noheader'   => true,
514
+				'obj_id'     => $msg_id,
515
+			),
516
+		);
517
+	}
518
+
519
+
520
+	protected function _set_page_config()
521
+	{
522
+		$this->_page_config = array(
523
+			'default'                  => array(
524
+				'nav'           => array(
525
+					'label' => esc_html__('Message Activity', 'event_espresso'),
526
+					'order' => 10,
527
+				),
528
+				'list_table'    => 'EE_Message_List_Table',
529
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
+				'require_nonce' => false,
531
+			),
532
+			'global_mtps'              => array(
533
+				'nav'           => array(
534
+					'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
+					'order' => 20,
536
+				),
537
+				'list_table'    => 'Messages_Template_List_Table',
538
+				'help_tabs'     => array(
539
+					'messages_overview_help_tab'                                => array(
540
+						'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
+						'filename' => 'messages_overview',
542
+					),
543
+					'messages_overview_messages_table_column_headings_help_tab' => array(
544
+						'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
+						'filename' => 'messages_overview_table_column_headings',
546
+					),
547
+					'messages_overview_messages_filters_help_tab'               => array(
548
+						'title'    => esc_html__('Message Filters', 'event_espresso'),
549
+						'filename' => 'messages_overview_filters',
550
+					),
551
+					'messages_overview_messages_views_help_tab'                 => array(
552
+						'title'    => esc_html__('Message Views', 'event_espresso'),
553
+						'filename' => 'messages_overview_views',
554
+					),
555
+					'message_overview_message_types_help_tab'                   => array(
556
+						'title'    => esc_html__('Message Types', 'event_espresso'),
557
+						'filename' => 'messages_overview_types',
558
+					),
559
+					'messages_overview_messengers_help_tab'                     => array(
560
+						'title'    => esc_html__('Messengers', 'event_espresso'),
561
+						'filename' => 'messages_overview_messengers',
562
+					),
563
+				),
564
+				'help_tour'     => array('Messages_Overview_Help_Tour'),
565
+				'require_nonce' => false,
566
+			),
567
+			'custom_mtps'              => array(
568
+				'nav'           => array(
569
+					'label' => esc_html__('Custom Message Templates', 'event_espresso'),
570
+					'order' => 30,
571
+				),
572
+				'help_tabs'     => array(),
573
+				'help_tour'     => array(),
574
+				'require_nonce' => false,
575
+			),
576
+			'add_new_message_template' => array(
577
+				'nav'           => array(
578
+					'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
579
+					'order'      => 5,
580
+					'persistent' => false,
581
+				),
582
+				'require_nonce' => false,
583
+			),
584
+			'edit_message_template'    => array(
585
+				'labels'        => array(
586
+					'buttons'    => array(
587
+						'reset' => esc_html__('Reset Templates', 'event_espresso'),
588
+					),
589
+					'publishbox' => esc_html__('Update Actions', 'event_espresso'),
590
+				),
591
+				'nav'           => array(
592
+					'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
593
+					'order'      => 5,
594
+					'persistent' => false,
595
+					'url'        => '',
596
+				),
597
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
598
+				'has_metaboxes' => true,
599
+				'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
600
+				'help_tabs'     => array(
601
+					'edit_message_template'            => array(
602
+						'title'    => esc_html__('Message Template Editor', 'event_espresso'),
603
+						'callback' => 'edit_message_template_help_tab',
604
+					),
605
+					'message_templates_help_tab'       => array(
606
+						'title'    => esc_html__('Message Templates', 'event_espresso'),
607
+						'filename' => 'messages_templates',
608
+					),
609
+					'message_template_shortcodes'      => array(
610
+						'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
611
+						'callback' => 'message_template_shortcodes_help_tab',
612
+					),
613
+					'message_preview_help_tab'         => array(
614
+						'title'    => esc_html__('Message Preview', 'event_espresso'),
615
+						'filename' => 'messages_preview',
616
+					),
617
+					'messages_overview_other_help_tab' => array(
618
+						'title'    => esc_html__('Messages Other', 'event_espresso'),
619
+						'filename' => 'messages_overview_other',
620
+					),
621
+				),
622
+				'require_nonce' => false,
623
+			),
624
+			'display_preview_message'  => array(
625
+				'nav'           => array(
626
+					'label'      => esc_html__('Message Preview', 'event_espresso'),
627
+					'order'      => 5,
628
+					'url'        => '',
629
+					'persistent' => false,
630
+				),
631
+				'help_tabs'     => array(
632
+					'preview_message' => array(
633
+						'title'    => esc_html__('About Previews', 'event_espresso'),
634
+						'callback' => 'preview_message_help_tab',
635
+					),
636
+				),
637
+				'require_nonce' => false,
638
+			),
639
+			'settings'                 => array(
640
+				'nav'           => array(
641
+					'label' => esc_html__('Settings', 'event_espresso'),
642
+					'order' => 40,
643
+				),
644
+				'metaboxes'     => array('_messages_settings_metaboxes'),
645
+				'help_tabs'     => array(
646
+					'messages_settings_help_tab'               => array(
647
+						'title'    => esc_html__('Messages Settings', 'event_espresso'),
648
+						'filename' => 'messages_settings',
649
+					),
650
+					'messages_settings_message_types_help_tab' => array(
651
+						'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
652
+						'filename' => 'messages_settings_message_types',
653
+					),
654
+					'messages_settings_messengers_help_tab'    => array(
655
+						'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
656
+						'filename' => 'messages_settings_messengers',
657
+					),
658
+				),
659
+				'help_tour'     => array('Messages_Settings_Help_Tour'),
660
+				'require_nonce' => false,
661
+			),
662
+		);
663
+	}
664
+
665
+
666
+	protected function _add_screen_options()
667
+	{
668
+		// todo
669
+	}
670
+
671
+
672
+	protected function _add_screen_options_global_mtps()
673
+	{
674
+		/**
675
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
676
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
677
+		 */
678
+		$page_title = $this->_admin_page_title;
679
+		$this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
680
+		$this->_per_page_screen_option();
681
+		$this->_admin_page_title = $page_title;
682
+	}
683
+
684
+
685
+	protected function _add_screen_options_default()
686
+	{
687
+		$this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
688
+		$this->_per_page_screen_option();
689
+	}
690
+
691
+
692
+	// none of the below group are currently used for Messages
693
+	protected function _add_feature_pointers()
694
+	{
695
+	}
696
+
697
+	public function admin_init()
698
+	{
699
+	}
700
+
701
+	public function admin_notices()
702
+	{
703
+	}
704
+
705
+	public function admin_footer_scripts()
706
+	{
707
+	}
708
+
709
+
710
+	public function messages_help_tab()
711
+	{
712
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
713
+	}
714
+
715
+
716
+	public function messengers_help_tab()
717
+	{
718
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
719
+	}
720
+
721
+
722
+	public function message_types_help_tab()
723
+	{
724
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
725
+	}
726
+
727
+
728
+	public function messages_overview_help_tab()
729
+	{
730
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
731
+	}
732
+
733
+
734
+	public function message_templates_help_tab()
735
+	{
736
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
737
+	}
738
+
739
+
740
+	public function edit_message_template_help_tab()
741
+	{
742
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
743
+						. esc_attr__('Editor Title', 'event_espresso')
744
+						. '" />';
745
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
746
+						. esc_attr__('Context Switcher and Preview', 'event_espresso')
747
+						. '" />';
748
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
749
+						. esc_attr__('Message Template Form Fields', 'event_espresso')
750
+						. '" />';
751
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
752
+						. esc_attr__('Shortcodes Metabox', 'event_espresso')
753
+						. '" />';
754
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
755
+						. esc_attr__('Publish Metabox', 'event_espresso')
756
+						. '" />';
757
+		EEH_Template::display_template(
758
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
759
+			$args
760
+		);
761
+	}
762
+
763
+
764
+	public function message_template_shortcodes_help_tab()
765
+	{
766
+		$this->_set_shortcodes();
767
+		$args['shortcodes'] = $this->_shortcodes;
768
+		EEH_Template::display_template(
769
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
770
+			$args
771
+		);
772
+	}
773
+
774
+
775
+	public function preview_message_help_tab()
776
+	{
777
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
778
+	}
779
+
780
+
781
+	public function settings_help_tab()
782
+	{
783
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
784
+						. '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
785
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
786
+						. '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
787
+		$args['img3'] = '<div class="switch">'
788
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
789
+						. ' type="checkbox" checked="checked">'
790
+						. '<label for="ee-on-off-toggle-on"></label>'
791
+						. '</div>';
792
+		$args['img4'] = '<div class="switch">'
793
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
794
+						. ' type="checkbox">'
795
+						. '<label for="ee-on-off-toggle-on"></label>'
796
+						. '</div>';
797
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
798
+	}
799
+
800
+
801
+	public function load_scripts_styles()
802
+	{
803
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
804
+		wp_enqueue_style('espresso_ee_msg');
805
+
806
+		wp_register_script(
807
+			'ee-messages-settings',
808
+			EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
+			array('jquery-ui-droppable', 'ee-serialize-full-array'),
810
+			EVENT_ESPRESSO_VERSION,
811
+			true
812
+		);
813
+		wp_register_script(
814
+			'ee-msg-list-table-js',
815
+			EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
816
+			array('ee-dialog'),
817
+			EVENT_ESPRESSO_VERSION
818
+		);
819
+	}
820
+
821
+
822
+	public function load_scripts_styles_default()
823
+	{
824
+		wp_enqueue_script('ee-msg-list-table-js');
825
+	}
826
+
827
+
828
+	public function wp_editor_css($mce_css)
829
+	{
830
+		// if we're on the edit_message_template route
831
+		if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
832
+			$message_type_name = $this->_active_message_type_name;
833
+
834
+			// we're going to REPLACE the existing mce css
835
+			// we need to get the css file location from the active messenger
836
+			$mce_css = $this->_active_messenger->get_variation(
837
+				$this->_template_pack,
838
+				$message_type_name,
839
+				true,
840
+				'wpeditor',
841
+				$this->_variation
842
+			);
843
+		}
844
+
845
+		return $mce_css;
846
+	}
847
+
848
+
849
+	public function load_scripts_styles_edit_message_template()
850
+	{
851
+
852
+		$this->_set_shortcodes();
853
+
854
+		EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
855
+			esc_html__(
856
+				'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.',
857
+				'event_espresso'
858
+			),
859
+			$this->_message_template_group->messenger_obj()->label['singular'],
860
+			$this->_message_template_group->message_type_obj()->label['singular']
861
+		);
862
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
863
+			'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?',
864
+			'event_espresso'
865
+		);
866
+		EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
867
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
868
+			'event_espresso'
869
+		);
870
+
871
+		wp_register_script(
872
+			'ee_msgs_edit_js',
873
+			EE_MSG_ASSETS_URL . 'ee_message_editor.js',
874
+			array('jquery'),
875
+			EVENT_ESPRESSO_VERSION
876
+		);
877
+
878
+		wp_enqueue_script('ee_admin_js');
879
+		wp_enqueue_script('ee_msgs_edit_js');
880
+
881
+		// add in special css for tiny_mce
882
+		add_filter('mce_css', array($this, 'wp_editor_css'));
883
+	}
884
+
885
+
886
+	public function load_scripts_styles_display_preview_message()
887
+	{
888
+
889
+		$this->_set_message_template_group();
890
+
891
+		if (isset($this->_req_data['messenger'])) {
892
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
893
+				$this->_req_data['messenger']
894
+			);
895
+		}
896
+
897
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
898
+
899
+
900
+		wp_enqueue_style(
901
+			'espresso_preview_css',
902
+			$this->_active_messenger->get_variation(
903
+				$this->_template_pack,
904
+				$message_type_name,
905
+				true,
906
+				'preview',
907
+				$this->_variation
908
+			)
909
+		);
910
+	}
911
+
912
+
913
+	public function load_scripts_styles_settings()
914
+	{
915
+		wp_register_style(
916
+			'ee-message-settings',
917
+			EE_MSG_ASSETS_URL . 'ee_message_settings.css',
918
+			array(),
919
+			EVENT_ESPRESSO_VERSION
920
+		);
921
+		wp_enqueue_style('ee-text-links');
922
+		wp_enqueue_style('ee-message-settings');
923
+		wp_enqueue_script('ee-messages-settings');
924
+	}
925
+
926
+
927
+	/**
928
+	 * set views array for List Table
929
+	 */
930
+	public function _set_list_table_views_global_mtps()
931
+	{
932
+		$this->_views = array(
933
+			'in_use' => array(
934
+				'slug'  => 'in_use',
935
+				'label' => esc_html__('In Use', 'event_espresso'),
936
+				'count' => 0,
937
+			),
938
+		);
939
+	}
940
+
941
+
942
+	/**
943
+	 * Set views array for the Custom Template List Table
944
+	 */
945
+	public function _set_list_table_views_custom_mtps()
946
+	{
947
+		$this->_set_list_table_views_global_mtps();
948
+		$this->_views['in_use']['bulk_action'] = array(
949
+			'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
950
+		);
951
+	}
952
+
953
+
954
+	/**
955
+	 * set views array for message queue list table
956
+	 *
957
+	 * @throws InvalidDataTypeException
958
+	 * @throws InvalidInterfaceException
959
+	 * @throws InvalidArgumentException
960
+	 * @throws EE_Error
961
+	 * @throws ReflectionException
962
+	 */
963
+	public function _set_list_table_views_default()
964
+	{
965
+		EE_Registry::instance()->load_helper('Template');
966
+
967
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
968
+			'ee_send_message',
969
+			'message_list_table_bulk_actions'
970
+		)
971
+			? array(
972
+				'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
973
+				'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
974
+				'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
975
+				'send_now'              => esc_html__('Send Now', 'event_espresso'),
976
+			)
977
+			: array();
978
+
979
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
980
+			'ee_delete_messages',
981
+			'message_list_table_bulk_actions'
982
+		)
983
+			? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
984
+			: array();
985
+
986
+
987
+		$this->_views = array(
988
+			'all' => array(
989
+				'slug'        => 'all',
990
+				'label'       => esc_html__('All', 'event_espresso'),
991
+				'count'       => 0,
992
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
993
+			),
994
+		);
995
+
996
+
997
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
998
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
999
+				continue;
1000
+			}
1001
+			$status_bulk_actions = $common_bulk_actions;
1002
+			// unset bulk actions not applying to status
1003
+			if (! empty($status_bulk_actions)) {
1004
+				switch ($status) {
1005
+					case EEM_Message::status_idle:
1006
+					case EEM_Message::status_resend:
1007
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1008
+						break;
1009
+
1010
+					case EEM_Message::status_failed:
1011
+					case EEM_Message::status_debug_only:
1012
+					case EEM_Message::status_messenger_executing:
1013
+						$status_bulk_actions = array();
1014
+						break;
1015
+
1016
+					case EEM_Message::status_incomplete:
1017
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1018
+						break;
1019
+
1020
+					case EEM_Message::status_retry:
1021
+					case EEM_Message::status_sent:
1022
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1023
+						break;
1024
+				}
1025
+			}
1026
+
1027
+			// skip adding messenger executing status to views because it will be included with the Failed view.
1028
+			if ($status === EEM_Message::status_messenger_executing) {
1029
+				continue;
1030
+			}
1031
+
1032
+			$this->_views[ strtolower($status) ] = array(
1033
+				'slug'        => strtolower($status),
1034
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1035
+				'count'       => 0,
1036
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1037
+			);
1038
+		}
1039
+	}
1040
+
1041
+
1042
+	protected function _ee_default_messages_overview_list_table()
1043
+	{
1044
+		$this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1045
+		$this->display_admin_list_table_page_with_no_sidebar();
1046
+	}
1047
+
1048
+
1049
+	protected function _message_queue_list_table()
1050
+	{
1051
+		$this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1052
+		$this->_template_args['per_column'] = 6;
1053
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1054
+		$this->_template_args['before_list_table'] = '<h3>'
1055
+													 . EEM_Message::instance()->get_pretty_label_for_results()
1056
+													 . '</h3>';
1057
+		$this->display_admin_list_table_page_with_no_sidebar();
1058
+	}
1059
+
1060
+
1061
+	protected function _message_legend_items()
1062
+	{
1063
+
1064
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
1065
+		$action_items = array();
1066
+
1067
+		foreach ($action_css_classes as $action_item => $action_details) {
1068
+			if ($action_item === 'see_notifications_for') {
1069
+				continue;
1070
+			}
1071
+			$action_items[ $action_item ] = array(
1072
+				'class' => $action_details['css_class'],
1073
+				'desc'  => $action_details['label'],
1074
+			);
1075
+		}
1076
+
1077
+		/** @type array $status_items status legend setup */
1078
+		$status_items = array(
1079
+			'sent_status'                => array(
1080
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1081
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1082
+			),
1083
+			'idle_status'                => array(
1084
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1085
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1086
+			),
1087
+			'failed_status'              => array(
1088
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1089
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1090
+			),
1091
+			'messenger_executing_status' => array(
1092
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1093
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1094
+			),
1095
+			'resend_status'              => array(
1096
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1097
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1098
+			),
1099
+			'incomplete_status'          => array(
1100
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1101
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1102
+			),
1103
+			'retry_status'               => array(
1104
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1105
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1106
+			),
1107
+		);
1108
+		if (EEM_Message::debug()) {
1109
+			$status_items['debug_only_status'] = array(
1110
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1111
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1112
+			);
1113
+		}
1114
+
1115
+		return array_merge($action_items, $status_items);
1116
+	}
1117
+
1118
+
1119
+	protected function _custom_mtps_preview()
1120
+	{
1121
+		$this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1122
+		$this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1123
+											   . ' alt="' . esc_attr__(
1124
+												   'Preview Custom Message Templates screenshot',
1125
+												   'event_espresso'
1126
+											   ) . '" />';
1127
+		$this->_template_args['preview_text'] = '<strong>'
1128
+												. esc_html__(
1129
+													'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.',
1130
+													'event_espresso'
1131
+												)
1132
+												. '</strong>';
1133
+
1134
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1135
+	}
1136
+
1137
+
1138
+	/**
1139
+	 * get_message_templates
1140
+	 * This gets all the message templates for listing on the overview list.
1141
+	 *
1142
+	 * @access public
1143
+	 * @param int    $perpage the amount of templates groups to show per page
1144
+	 * @param string $type    the current _view we're getting templates for
1145
+	 * @param bool   $count   return count?
1146
+	 * @param bool   $all     disregard any paging info (get all data);
1147
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1148
+	 * @return array
1149
+	 * @throws EE_Error
1150
+	 * @throws InvalidArgumentException
1151
+	 * @throws InvalidDataTypeException
1152
+	 * @throws InvalidInterfaceException
1153
+	 */
1154
+	public function get_message_templates(
1155
+		$perpage = 10,
1156
+		$type = 'in_use',
1157
+		$count = false,
1158
+		$all = false,
1159
+		$global = true
1160
+	) {
1161
+
1162
+		$MTP = EEM_Message_Template_Group::instance();
1163
+
1164
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1165
+		$orderby = $this->_req_data['orderby'];
1166
+
1167
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1168
+			? $this->_req_data['order']
1169
+			: 'ASC';
1170
+
1171
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1172
+			? $this->_req_data['paged']
1173
+			: 1;
1174
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1175
+			? $this->_req_data['perpage']
1176
+			: $perpage;
1177
+
1178
+		$offset = ($current_page - 1) * $per_page;
1179
+		$limit = $all ? null : array($offset, $per_page);
1180
+
1181
+
1182
+		// options will match what is in the _views array property
1183
+		switch ($type) {
1184
+			case 'in_use':
1185
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1186
+				break;
1187
+			default:
1188
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1189
+		}
1190
+
1191
+		return $templates;
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * filters etc might need a list of installed message_types
1197
+	 *
1198
+	 * @return array an array of message type objects
1199
+	 */
1200
+	public function get_installed_message_types()
1201
+	{
1202
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1203
+		$installed = array();
1204
+
1205
+		foreach ($installed_message_types as $message_type) {
1206
+			$installed[ $message_type->name ] = $message_type;
1207
+		}
1208
+
1209
+		return $installed;
1210
+	}
1211
+
1212
+
1213
+	/**
1214
+	 * _add_message_template
1215
+	 *
1216
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1217
+	 *
1218
+	 * @param string $message_type
1219
+	 * @param string $messenger
1220
+	 * @param string $GRP_ID
1221
+	 *
1222
+	 * @throws EE_error
1223
+	 */
1224
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1225
+	{
1226
+		// set values override any request data
1227
+		$message_type = ! empty($message_type) ? $message_type : '';
1228
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1229
+			? $this->_req_data['message_type']
1230
+			: $message_type;
1231
+
1232
+		$messenger = ! empty($messenger) ? $messenger : '';
1233
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1234
+			? $this->_req_data['messenger']
1235
+			: $messenger;
1236
+
1237
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1238
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1239
+
1240
+		// we need messenger and message type.  They should be coming from the event editor. If not here then return error
1241
+		if (empty($message_type) || empty($messenger)) {
1242
+			throw new EE_Error(
1243
+				esc_html__(
1244
+					'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1245
+					'event_espresso'
1246
+				)
1247
+			);
1248
+		}
1249
+
1250
+		// we need the GRP_ID for the template being used as the base for the new template
1251
+		if (empty($GRP_ID)) {
1252
+			throw new EE_Error(
1253
+				esc_html__(
1254
+					'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1255
+					'event_espresso'
1256
+				)
1257
+			);
1258
+		}
1259
+
1260
+		// let's just make sure the template gets generated!
1261
+
1262
+		// we need to reassign some variables for what the insert is expecting
1263
+		$this->_req_data['MTP_messenger'] = $messenger;
1264
+		$this->_req_data['MTP_message_type'] = $message_type;
1265
+		$this->_req_data['GRP_ID'] = $GRP_ID;
1266
+		$this->_insert_or_update_message_template(true);
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * public wrapper for the _add_message_template method
1272
+	 *
1273
+	 * @param string $message_type     message type slug
1274
+	 * @param string $messenger        messenger slug
1275
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1276
+	 *                                 off of.
1277
+	 * @throws EE_error
1278
+	 */
1279
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1280
+	{
1281
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1282
+	}
1283
+
1284
+
1285
+	/**
1286
+	 * _edit_message_template
1287
+	 *
1288
+	 * @access protected
1289
+	 * @return void
1290
+	 * @throws InvalidIdentifierException
1291
+	 * @throws DomainException
1292
+	 * @throws EE_Error
1293
+	 * @throws InvalidArgumentException
1294
+	 * @throws ReflectionException
1295
+	 * @throws InvalidDataTypeException
1296
+	 * @throws InvalidInterfaceException
1297
+	 */
1298
+	protected function _edit_message_template()
1299
+	{
1300
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1301
+		$template_fields = '';
1302
+		$sidebar_fields = '';
1303
+		// we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1304
+		// valid html in the templates.
1305
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1306
+
1307
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1308
+			? absint($this->_req_data['id'])
1309
+			: false;
1310
+
1311
+		$EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
1312
+		? absint($this->_req_data['evt_id'])
1313
+		: false;
1314
+
1315
+		$this->_set_shortcodes(); // this also sets the _message_template property.
1316
+		$message_template_group = $this->_message_template_group;
1317
+		$c_label = $message_template_group->context_label();
1318
+		$c_config = $message_template_group->contexts_config();
1319
+
1320
+		reset($c_config);
1321
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1322
+			? strtolower($this->_req_data['context'])
1323
+			: key($c_config);
1324
+
1325
+
1326
+		if (empty($GRP_ID)) {
1327
+			$action = 'insert_message_template';
1328
+			$edit_message_template_form_url = add_query_arg(
1329
+				array('action' => $action, 'noheader' => true),
1330
+				EE_MSG_ADMIN_URL
1331
+			);
1332
+		} else {
1333
+			$action = 'update_message_template';
1334
+			$edit_message_template_form_url = add_query_arg(
1335
+				array('action' => $action, 'noheader' => true),
1336
+				EE_MSG_ADMIN_URL
1337
+			);
1338
+		}
1339
+
1340
+		// set active messenger for this view
1341
+		$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1342
+			$message_template_group->messenger()
1343
+		);
1344
+		$this->_active_message_type_name = $message_template_group->message_type();
1345
+
1346
+
1347
+		// Do we have any validation errors?
1348
+		$validators = $this->_get_transient();
1349
+		$v_fields = ! empty($validators) ? array_keys($validators) : array();
1350
+
1351
+
1352
+		// we need to assemble the title from Various details
1353
+		$context_label = sprintf(
1354
+			esc_html__('(%s %s)', 'event_espresso'),
1355
+			$c_config[ $context ]['label'],
1356
+			ucwords($c_label['label'])
1357
+		);
1358
+
1359
+		$title = sprintf(
1360
+			esc_html__(' %s %s Template %s', 'event_espresso'),
1361
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1362
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1363
+			$context_label
1364
+		);
1365
+
1366
+		$this->_template_args['GRP_ID'] = $GRP_ID;
1367
+		$this->_template_args['message_template'] = $message_template_group;
1368
+		$this->_template_args['is_extra_fields'] = false;
1369
+
1370
+
1371
+		// let's get EEH_MSG_Template so we can get template form fields
1372
+		$template_field_structure = EEH_MSG_Template::get_fields(
1373
+			$message_template_group->messenger(),
1374
+			$message_template_group->message_type()
1375
+		);
1376
+
1377
+		if (! $template_field_structure) {
1378
+			$template_field_structure = false;
1379
+			$template_fields = esc_html__(
1380
+				'There was an error in assembling the fields for this display (you should see an error message)',
1381
+				'event_espresso'
1382
+			);
1383
+		}
1384
+
1385
+
1386
+		$message_templates = $message_template_group->context_templates();
1387
+
1388
+
1389
+		// if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1390
+		// will get handled in the "extra" array.
1391
+		if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1392
+			foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1393
+				unset($template_field_structure[ $context ][ $reference_field ]);
1394
+			}
1395
+		}
1396
+
1397
+		// let's loop through the template_field_structure and actually assemble the input fields!
1398
+		if (! empty($template_field_structure)) {
1399
+			foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1400
+				// if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1401
+				// the extra array and reset them.
1402
+				if ($template_field === 'extra') {
1403
+					$this->_template_args['is_extra_fields'] = true;
1404
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1405
+						$message_template = $message_templates[ $context ][ $reference_field ];
1406
+						$content = $message_template instanceof EE_Message_Template
1407
+							? $message_template->get('MTP_content')
1408
+							: '';
1409
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1410
+							// let's verify if we need this extra field via the shortcodes parameter.
1411
+							$continue = false;
1412
+							if (isset($extra_array['shortcodes_required'])) {
1413
+								foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1414
+									if (! array_key_exists($shortcode, $this->_shortcodes)) {
1415
+										$continue = true;
1416
+									}
1417
+								}
1418
+								if ($continue) {
1419
+									continue;
1420
+								}
1421
+							}
1422
+
1423
+							$field_id = $reference_field
1424
+										. '-'
1425
+										. $extra_field
1426
+										. '-content';
1427
+							$template_form_fields[ $field_id ] = $extra_array;
1428
+							$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1429
+																		 . $reference_field
1430
+																		 . '][content]['
1431
+																		 . $extra_field . ']';
1432
+							$css_class = isset($extra_array['css_class'])
1433
+								? $extra_array['css_class']
1434
+								: '';
1435
+
1436
+							$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1437
+																			  && in_array($extra_field, $v_fields, true)
1438
+																			  &&
1439
+																			  (
1440
+																				  is_array($validators[ $extra_field ])
1441
+																				  && isset($validators[ $extra_field ]['msg'])
1442
+																			  )
1443
+								? 'validate-error ' . $css_class
1444
+								: $css_class;
1445
+
1446
+							$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1447
+																		  && isset($content[ $extra_field ])
1448
+								? $content[ $extra_field ]
1449
+								: '';
1450
+
1451
+							// do we have a validation error?  if we do then let's use that value instead
1452
+							$template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1453
+								? $validators[ $extra_field ]['value']
1454
+								: $template_form_fields[ $field_id ]['value'];
1455
+
1456
+
1457
+							$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1458
+
1459
+							// shortcode selector
1460
+							$field_name_to_use = $extra_field === 'main'
1461
+								? 'content'
1462
+								: $extra_field;
1463
+							$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1464
+								$field_name_to_use,
1465
+								$field_id
1466
+							);
1467
+
1468
+							if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1469
+								// we want to decode the entities
1470
+								$template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1471
+							}/**/
1472
+						}
1473
+						$templatefield_MTP_id = $reference_field . '-MTP_ID';
1474
+						$templatefield_templatename_id = $reference_field . '-name';
1475
+
1476
+						$template_form_fields[ $templatefield_MTP_id ] = array(
1477
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1478
+							'label'      => null,
1479
+							'input'      => 'hidden',
1480
+							'type'       => 'int',
1481
+							'required'   => false,
1482
+							'validation' => false,
1483
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1484
+							'css_class'  => '',
1485
+							'format'     => '%d',
1486
+							'db-col'     => 'MTP_ID',
1487
+						);
1488
+
1489
+						$template_form_fields[ $templatefield_templatename_id ] = array(
1490
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1491
+							'label'      => null,
1492
+							'input'      => 'hidden',
1493
+							'type'       => 'string',
1494
+							'required'   => false,
1495
+							'validation' => true,
1496
+							'value'      => $reference_field,
1497
+							'css_class'  => '',
1498
+							'format'     => '%s',
1499
+							'db-col'     => 'MTP_template_field',
1500
+						);
1501
+					}
1502
+					continue; // skip the next stuff, we got the necessary fields here for this dataset.
1503
+				} else {
1504
+					$field_id = $template_field . '-content';
1505
+					$template_form_fields[ $field_id ] = $field_setup_array;
1506
+					$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1507
+					$message_template = isset($message_templates[ $context ][ $template_field ])
1508
+						? $message_templates[ $context ][ $template_field ]
1509
+						: null;
1510
+					$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1511
+																  && is_array($message_templates[ $context ])
1512
+																  && $message_template instanceof EE_Message_Template
1513
+						? $message_template->get('MTP_content')
1514
+						: '';
1515
+
1516
+					// do we have a validator error for this field?  if we do then we'll use that value instead
1517
+					$template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1518
+						? $validators[ $template_field ]['value']
1519
+						: $template_form_fields[ $field_id ]['value'];
1520
+
1521
+
1522
+					$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1523
+					$css_class = isset($field_setup_array['css_class'])
1524
+						? $field_setup_array['css_class']
1525
+						: '';
1526
+					$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1527
+																	  && in_array($template_field, $v_fields, true)
1528
+																	  && isset($validators[ $template_field ]['msg'])
1529
+						? 'validate-error ' . $css_class
1530
+						: $css_class;
1531
+
1532
+					// shortcode selector
1533
+					$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1534
+						$template_field,
1535
+						$field_id
1536
+					);
1537
+				}
1538
+
1539
+				// k took care of content field(s) now let's take care of others.
1540
+
1541
+				$templatefield_MTP_id = $template_field . '-MTP_ID';
1542
+				$templatefield_field_templatename_id = $template_field . '-name';
1543
+
1544
+				// foreach template field there are actually two form fields created
1545
+				$template_form_fields[ $templatefield_MTP_id ] = array(
1546
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1547
+					'label'      => null,
1548
+					'input'      => 'hidden',
1549
+					'type'       => 'int',
1550
+					'required'   => false,
1551
+					'validation' => true,
1552
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1553
+					'css_class'  => '',
1554
+					'format'     => '%d',
1555
+					'db-col'     => 'MTP_ID',
1556
+				);
1557
+
1558
+				$template_form_fields[ $templatefield_field_templatename_id ] = array(
1559
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1560
+					'label'      => null,
1561
+					'input'      => 'hidden',
1562
+					'type'       => 'string',
1563
+					'required'   => false,
1564
+					'validation' => true,
1565
+					'value'      => $template_field,
1566
+					'css_class'  => '',
1567
+					'format'     => '%s',
1568
+					'db-col'     => 'MTP_template_field',
1569
+				);
1570
+			}
1571
+
1572
+			// add other fields
1573
+			$template_form_fields['ee-msg-current-context'] = array(
1574
+				'name'       => 'MTP_context',
1575
+				'label'      => null,
1576
+				'input'      => 'hidden',
1577
+				'type'       => 'string',
1578
+				'required'   => false,
1579
+				'validation' => true,
1580
+				'value'      => $context,
1581
+				'css_class'  => '',
1582
+				'format'     => '%s',
1583
+				'db-col'     => 'MTP_context',
1584
+			);
1585
+
1586
+			$template_form_fields['ee-msg-grp-id'] = array(
1587
+				'name'       => 'GRP_ID',
1588
+				'label'      => null,
1589
+				'input'      => 'hidden',
1590
+				'type'       => 'int',
1591
+				'required'   => false,
1592
+				'validation' => true,
1593
+				'value'      => $GRP_ID,
1594
+				'css_class'  => '',
1595
+				'format'     => '%d',
1596
+				'db-col'     => 'GRP_ID',
1597
+			);
1598
+
1599
+			$template_form_fields['ee-msg-messenger'] = array(
1600
+				'name'       => 'MTP_messenger',
1601
+				'label'      => null,
1602
+				'input'      => 'hidden',
1603
+				'type'       => 'string',
1604
+				'required'   => false,
1605
+				'validation' => true,
1606
+				'value'      => $message_template_group->messenger(),
1607
+				'css_class'  => '',
1608
+				'format'     => '%s',
1609
+				'db-col'     => 'MTP_messenger',
1610
+			);
1611
+
1612
+			$template_form_fields['ee-msg-message-type'] = array(
1613
+				'name'       => 'MTP_message_type',
1614
+				'label'      => null,
1615
+				'input'      => 'hidden',
1616
+				'type'       => 'string',
1617
+				'required'   => false,
1618
+				'validation' => true,
1619
+				'value'      => $message_template_group->message_type(),
1620
+				'css_class'  => '',
1621
+				'format'     => '%s',
1622
+				'db-col'     => 'MTP_message_type',
1623
+			);
1624
+
1625
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1626
+				'name'       => 'MTP_is_global',
1627
+				'label'      => esc_html__('Global Template', 'event_espresso'),
1628
+				'input'      => 'hidden',
1629
+				'type'       => 'int',
1630
+				'required'   => false,
1631
+				'validation' => true,
1632
+				'value'      => $message_template_group->get('MTP_is_global'),
1633
+				'css_class'  => '',
1634
+				'format'     => '%d',
1635
+				'db-col'     => 'MTP_is_global',
1636
+			);
1637
+
1638
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1639
+				'name'       => 'MTP_is_override',
1640
+				'label'      => esc_html__('Override all custom', 'event_espresso'),
1641
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1642
+				'type'       => 'int',
1643
+				'required'   => false,
1644
+				'validation' => true,
1645
+				'value'      => $message_template_group->get('MTP_is_override'),
1646
+				'css_class'  => '',
1647
+				'format'     => '%d',
1648
+				'db-col'     => 'MTP_is_override',
1649
+			);
1650
+
1651
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1652
+				'name'       => 'MTP_is_active',
1653
+				'label'      => esc_html__('Active Template', 'event_espresso'),
1654
+				'input'      => 'hidden',
1655
+				'type'       => 'int',
1656
+				'required'   => false,
1657
+				'validation' => true,
1658
+				'value'      => $message_template_group->is_active(),
1659
+				'css_class'  => '',
1660
+				'format'     => '%d',
1661
+				'db-col'     => 'MTP_is_active',
1662
+			);
1663
+
1664
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1665
+				'name'       => 'MTP_deleted',
1666
+				'label'      => null,
1667
+				'input'      => 'hidden',
1668
+				'type'       => 'int',
1669
+				'required'   => false,
1670
+				'validation' => true,
1671
+				'value'      => $message_template_group->get('MTP_deleted'),
1672
+				'css_class'  => '',
1673
+				'format'     => '%d',
1674
+				'db-col'     => 'MTP_deleted',
1675
+			);
1676
+			$sidebar_form_fields['ee-msg-author'] = array(
1677
+				'name'       => 'MTP_user_id',
1678
+				'label'      => esc_html__('Author', 'event_espresso'),
1679
+				'input'      => 'hidden',
1680
+				'type'       => 'int',
1681
+				'required'   => false,
1682
+				'validation' => false,
1683
+				'value'      => $message_template_group->user(),
1684
+				'format'     => '%d',
1685
+				'db-col'     => 'MTP_user_id',
1686
+			);
1687
+
1688
+			$sidebar_form_fields['ee-msg-route'] = array(
1689
+				'name'  => 'action',
1690
+				'input' => 'hidden',
1691
+				'type'  => 'string',
1692
+				'value' => $action,
1693
+			);
1694
+
1695
+			$sidebar_form_fields['ee-msg-id'] = array(
1696
+				'name'  => 'id',
1697
+				'input' => 'hidden',
1698
+				'type'  => 'int',
1699
+				'value' => $GRP_ID,
1700
+			);
1701
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1702
+				'name'  => $action . '_nonce',
1703
+				'input' => 'hidden',
1704
+				'type'  => 'string',
1705
+				'value' => wp_create_nonce($action . '_nonce'),
1706
+			);
1707
+
1708
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1709
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1710
+					'name'  => 'template_switch',
1711
+					'input' => 'hidden',
1712
+					'type'  => 'int',
1713
+					'value' => 1,
1714
+				);
1715
+			}
1716
+
1717
+
1718
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1719
+			$sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1720
+		} //end if ( !empty($template_field_structure) )
1721
+
1722
+		// set extra content for publish box
1723
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1724
+		$this->_set_publish_post_box_vars(
1725
+			'id',
1726
+			$GRP_ID,
1727
+			false,
1728
+			add_query_arg(
1729
+				array('action' => 'global_mtps'),
1730
+				$this->_admin_base_url
1731
+			)
1732
+		);
1733
+
1734
+		// add preview button
1735
+		$preview_url = parent::add_query_args_and_nonce(
1736
+			array(
1737
+				'message_type' => $message_template_group->message_type(),
1738
+				'messenger'    => $message_template_group->messenger(),
1739
+				'context'      => $context,
1740
+				'GRP_ID'       => $GRP_ID,
1741
+				'evt_id'       => $EVT_ID,
1742
+				'action'       => 'preview_message',
1743
+			),
1744
+			$this->_admin_base_url
1745
+		);
1746
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1747
+						  . esc_html__('Preview', 'event_espresso')
1748
+						  . '</a>';
1749
+
1750
+
1751
+		// setup context switcher
1752
+		$context_switcher_args = array(
1753
+			'page'    => 'espresso_messages',
1754
+			'action'  => 'edit_message_template',
1755
+			'id'      => $GRP_ID,
1756
+			'evt_id'  => $EVT_ID,
1757
+			'context' => $context,
1758
+			'extra'   => $preview_button,
1759
+		);
1760
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1761
+
1762
+
1763
+		// main box
1764
+		$this->_template_args['template_fields'] = $template_fields;
1765
+		$this->_template_args['sidebar_box_id'] = 'details';
1766
+		$this->_template_args['action'] = $action;
1767
+		$this->_template_args['context'] = $context;
1768
+		$this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1769
+		$this->_template_args['learn_more_about_message_templates_link'] =
1770
+			$this->_learn_more_about_message_templates_link();
1771
+
1772
+
1773
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1774
+		$this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1775
+			$message_template_group,
1776
+			$context,
1777
+			$context_label
1778
+		);
1779
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1780
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1781
+
1782
+		$this->_template_path = $this->_template_args['GRP_ID']
1783
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1784
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1785
+
1786
+		// send along EE_Message_Template_Group object for further template use.
1787
+		$this->_template_args['MTP'] = $message_template_group;
1788
+
1789
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1790
+			$this->_template_path,
1791
+			$this->_template_args,
1792
+			true
1793
+		);
1794
+
1795
+
1796
+		// finally, let's set the admin_page title
1797
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1798
+
1799
+
1800
+		// we need to take care of setting the shortcodes property for use elsewhere.
1801
+		$this->_set_shortcodes();
1802
+
1803
+
1804
+		// final template wrapper
1805
+		$this->display_admin_page_with_sidebar();
1806
+	}
1807
+
1808
+
1809
+	public function filter_tinymce_init($mceInit, $editor_id)
1810
+	{
1811
+		return $mceInit;
1812
+	}
1813
+
1814
+
1815
+	public function add_context_switcher()
1816
+	{
1817
+		return $this->_context_switcher;
1818
+	}
1819
+
1820
+
1821
+	/**
1822
+	 * Adds the activation/deactivation toggle for the message template context.
1823
+	 *
1824
+	 * @param EE_Message_Template_Group $message_template_group
1825
+	 * @param string                    $context
1826
+	 * @param string                    $context_label
1827
+	 * @return string
1828
+	 * @throws DomainException
1829
+	 * @throws EE_Error
1830
+	 * @throws InvalidIdentifierException
1831
+	 */
1832
+	protected function add_active_context_element(
1833
+		EE_Message_Template_Group $message_template_group,
1834
+		$context,
1835
+		$context_label
1836
+	) {
1837
+		$template_args = array(
1838
+			'context'                   => $context,
1839
+			'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1840
+			'is_active'                 => $message_template_group->is_context_active($context),
1841
+			'on_off_action'             => $message_template_group->is_context_active($context)
1842
+				? 'context-off'
1843
+				: 'context-on',
1844
+			'context_label'             => str_replace(array('(', ')'), '', $context_label),
1845
+			'message_template_group_id' => $message_template_group->ID(),
1846
+		);
1847
+		return EEH_Template::display_template(
1848
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1849
+			$template_args,
1850
+			true
1851
+		);
1852
+	}
1853
+
1854
+
1855
+	/**
1856
+	 * Ajax callback for `toggle_context_template` ajax action.
1857
+	 * Handles toggling the message context on or off.
1858
+	 *
1859
+	 * @throws EE_Error
1860
+	 * @throws InvalidArgumentException
1861
+	 * @throws InvalidDataTypeException
1862
+	 * @throws InvalidIdentifierException
1863
+	 * @throws InvalidInterfaceException
1864
+	 */
1865
+	public function toggle_context_template()
1866
+	{
1867
+		$success = true;
1868
+		// check for required data
1869
+		if (! isset(
1870
+			$this->_req_data['message_template_group_id'],
1871
+			$this->_req_data['context'],
1872
+			$this->_req_data['status']
1873
+		)) {
1874
+			EE_Error::add_error(
1875
+				esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1876
+				__FILE__,
1877
+				__FUNCTION__,
1878
+				__LINE__
1879
+			);
1880
+			$success = false;
1881
+		}
1882
+
1883
+		$nonce = isset($this->_req_data['toggle_context_nonce'])
1884
+			? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1885
+			: '';
1886
+		$nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1887
+		$this->_verify_nonce($nonce, $nonce_ref);
1888
+		$status = $this->_req_data['status'];
1889
+		if ($status !== 'off' && $status !== 'on') {
1890
+			EE_Error::add_error(
1891
+				sprintf(
1892
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1893
+					$this->_req_data['status']
1894
+				),
1895
+				__FILE__,
1896
+				__FUNCTION__,
1897
+				__LINE__
1898
+			);
1899
+			$success = false;
1900
+		}
1901
+		$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1902
+			$this->_req_data['message_template_group_id']
1903
+		);
1904
+		if (! $message_template_group instanceof EE_Message_Template_Group) {
1905
+			EE_Error::add_error(
1906
+				sprintf(
1907
+					esc_html__(
1908
+						'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1909
+						'event_espresso'
1910
+					),
1911
+					$this->_req_data['message_template_group_id'],
1912
+					'EE_Message_Template_Group'
1913
+				),
1914
+				__FILE__,
1915
+				__FUNCTION__,
1916
+				__LINE__
1917
+			);
1918
+			$success = false;
1919
+		}
1920
+		if ($success) {
1921
+			$success = $status === 'off'
1922
+				? $message_template_group->deactivate_context($this->_req_data['context'])
1923
+				: $message_template_group->activate_context($this->_req_data['context']);
1924
+		}
1925
+		$this->_template_args['success'] = $success;
1926
+		$this->_return_json();
1927
+	}
1928
+
1929
+
1930
+	public function _add_form_element_before()
1931
+	{
1932
+		return '<form method="post" action="'
1933
+			   . $this->_template_args["edit_message_template_form_url"]
1934
+			   . '" id="ee-msg-edit-frm">';
1935
+	}
1936
+
1937
+	public function _add_form_element_after()
1938
+	{
1939
+		return '</form>';
1940
+	}
1941
+
1942
+
1943
+	/**
1944
+	 * This executes switching the template pack for a message template.
1945
+	 *
1946
+	 * @since 4.5.0
1947
+	 * @throws EE_Error
1948
+	 * @throws InvalidDataTypeException
1949
+	 * @throws InvalidInterfaceException
1950
+	 * @throws InvalidArgumentException
1951
+	 * @throws ReflectionException
1952
+	 */
1953
+	public function switch_template_pack()
1954
+	{
1955
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1956
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1957
+
1958
+		// verify we have needed values.
1959
+		if (empty($GRP_ID) || empty($template_pack)) {
1960
+			$this->_template_args['error'] = true;
1961
+			EE_Error::add_error(
1962
+				esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1963
+				__FILE__,
1964
+				__FUNCTION__,
1965
+				__LINE__
1966
+			);
1967
+		} else {
1968
+			// get template, set the new template_pack and then reset to default
1969
+			/** @type EE_Message_Template_Group $message_template_group */
1970
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1971
+
1972
+			$message_template_group->set_template_pack_name($template_pack);
1973
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1974
+			$this->_req_data['mt'] = $message_template_group->message_type();
1975
+
1976
+			$query_args = $this->_reset_to_default_template();
1977
+
1978
+			if (empty($query_args['id'])) {
1979
+				EE_Error::add_error(
1980
+					esc_html__(
1981
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1982
+						'event_espresso'
1983
+					),
1984
+					__FILE__,
1985
+					__FUNCTION__,
1986
+					__LINE__
1987
+				);
1988
+				$this->_template_args['error'] = true;
1989
+			} else {
1990
+				$template_label = $message_template_group->get_template_pack()->label;
1991
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1992
+				EE_Error::add_success(
1993
+					sprintf(
1994
+						esc_html__(
1995
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1996
+							'event_espresso'
1997
+						),
1998
+						$template_label,
1999
+						$template_pack_labels->template_pack
2000
+					)
2001
+				);
2002
+				// generate the redirect url for js.
2003
+				$url = self::add_query_args_and_nonce(
2004
+					$query_args,
2005
+					$this->_admin_base_url
2006
+				);
2007
+				$this->_template_args['data']['redirect_url'] = $url;
2008
+				$this->_template_args['success'] = true;
2009
+			}
2010
+
2011
+			$this->_return_json();
2012
+		}
2013
+	}
2014
+
2015
+
2016
+	/**
2017
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2018
+	 * they want.
2019
+	 *
2020
+	 * @access protected
2021
+	 * @return array|null
2022
+	 * @throws EE_Error
2023
+	 * @throws InvalidArgumentException
2024
+	 * @throws InvalidDataTypeException
2025
+	 * @throws InvalidInterfaceException
2026
+	 */
2027
+	protected function _reset_to_default_template()
2028
+	{
2029
+
2030
+		$templates = array();
2031
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2032
+		// we need to make sure we've got the info we need.
2033
+		if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2034
+			EE_Error::add_error(
2035
+				esc_html__(
2036
+					'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.',
2037
+					'event_espresso'
2038
+				),
2039
+				__FILE__,
2040
+				__FUNCTION__,
2041
+				__LINE__
2042
+			);
2043
+		}
2044
+
2045
+		// all templates will be reset to whatever the defaults are
2046
+		// for the global template matching the messenger and message type.
2047
+		$success = ! empty($GRP_ID) ? true : false;
2048
+
2049
+		if ($success) {
2050
+			// let's first determine if the incoming template is a global template,
2051
+			// if it isn't then we need to get the global template matching messenger and message type.
2052
+			// $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2053
+
2054
+
2055
+			// note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2056
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
2057
+
2058
+			if ($success) {
2059
+				// if successfully deleted, lets generate the new ones.
2060
+				// Note. We set GLOBAL to true, because resets on ANY template
2061
+				// will use the related global template defaults for regeneration.
2062
+				// This means that if a custom template is reset it resets to whatever the related global template is.
2063
+				// HOWEVER, we DO keep the template pack and template variation set
2064
+				// for the current custom template when resetting.
2065
+				$templates = $this->_generate_new_templates(
2066
+					$this->_req_data['msgr'],
2067
+					$this->_req_data['mt'],
2068
+					$GRP_ID,
2069
+					true
2070
+				);
2071
+			}
2072
+		}
2073
+
2074
+		// any error messages?
2075
+		if (! $success) {
2076
+			EE_Error::add_error(
2077
+				esc_html__(
2078
+					'Something went wrong with deleting existing templates. Unable to reset to default',
2079
+					'event_espresso'
2080
+				),
2081
+				__FILE__,
2082
+				__FUNCTION__,
2083
+				__LINE__
2084
+			);
2085
+		}
2086
+
2087
+		// all good, let's add a success message!
2088
+		if ($success && ! empty($templates)) {
2089
+			// the info for the template we generated is the first element in the returned array
2090
+			// $templates = $templates[0];
2091
+			EE_Error::overwrite_success();
2092
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2093
+		}
2094
+
2095
+
2096
+		$query_args = array(
2097
+			'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2098
+			'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2099
+			'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2100
+		);
2101
+
2102
+		// if called via ajax then we return query args otherwise redirect
2103
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2104
+			return $query_args;
2105
+		} else {
2106
+			$this->_redirect_after_action(false, '', '', $query_args, true);
2107
+
2108
+			return null;
2109
+		}
2110
+	}
2111
+
2112
+
2113
+	/**
2114
+	 * Retrieve and set the message preview for display.
2115
+	 *
2116
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2117
+	 * @return string
2118
+	 * @throws ReflectionException
2119
+	 * @throws EE_Error
2120
+	 * @throws InvalidArgumentException
2121
+	 * @throws InvalidDataTypeException
2122
+	 * @throws InvalidInterfaceException
2123
+	 */
2124
+	public function _preview_message($send = false)
2125
+	{
2126
+		// first make sure we've got the necessary parameters
2127
+		if (! isset(
2128
+			$this->_req_data['message_type'],
2129
+			$this->_req_data['messenger'],
2130
+			$this->_req_data['messenger'],
2131
+			$this->_req_data['GRP_ID']
2132
+		)) {
2133
+			EE_Error::add_error(
2134
+				esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2135
+				__FILE__,
2136
+				__FUNCTION__,
2137
+				__LINE__
2138
+			);
2139
+		}
2140
+
2141
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2142
+
2143
+
2144
+		// get the preview!
2145
+		$preview = EED_Messages::preview_message(
2146
+			$this->_req_data['message_type'],
2147
+			$this->_req_data['context'],
2148
+			$this->_req_data['messenger'],
2149
+			$send
2150
+		);
2151
+
2152
+		if ($send) {
2153
+			return $preview;
2154
+		}
2155
+
2156
+		// let's add a button to go back to the edit view
2157
+		$query_args = array(
2158
+			'id'      => $this->_req_data['GRP_ID'],
2159
+			'evt_id'  => $this->_req_data['evt_id'],
2160
+			'context' => $this->_req_data['context'],
2161
+			'action'  => 'edit_message_template',
2162
+		);
2163
+		$go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2164
+		$preview_button = '<a href="'
2165
+						  . $go_back_url
2166
+						  . '" class="button-secondary messages-preview-go-back-button">'
2167
+						  . esc_html__('Go Back to Edit', 'event_espresso')
2168
+						  . '</a>';
2169
+		$message_types = $this->get_installed_message_types();
2170
+		$active_messenger = $this->_message_resource_manager->get_active_messenger(
2171
+			$this->_req_data['messenger']
2172
+		);
2173
+		$active_messenger_label = $active_messenger instanceof EE_messenger
2174
+			? ucwords($active_messenger->label['singular'])
2175
+			: esc_html__('Unknown Messenger', 'event_espresso');
2176
+		// let's provide a helpful title for context
2177
+		$preview_title = sprintf(
2178
+			esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2179
+			$active_messenger_label,
2180
+			ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2181
+		);
2182
+		if (empty($preview)) {
2183
+			$this->noEventsErrorMessage();
2184
+		}
2185
+		// setup display of preview.
2186
+		$this->_admin_page_title = $preview_title;
2187
+		$this->_template_args['admin_page_title'] = $preview_title;
2188
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2189
+		$this->_template_args['data']['force_json'] = true;
2190
+
2191
+		return '';
2192
+	}
2193
+
2194
+
2195
+	/**
2196
+	 * Used to set an error if there are no events available for generating a preview/test send.
2197
+	 *
2198
+	 * @param bool $test_send  Whether the error should be generated for the context of a test send.
2199
+	 */
2200
+	protected function noEventsErrorMessage($test_send = false)
2201
+	{
2202
+		$events_url = parent::add_query_args_and_nonce(
2203
+			array(
2204
+				'action' => 'default',
2205
+				'page'   => 'espresso_events',
2206
+			),
2207
+			admin_url('admin.php')
2208
+		);
2209
+		$message = $test_send
2210
+			? __(
2211
+				'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!',
2212
+				'event_espresso'
2213
+			)
2214
+			: __(
2215
+				'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!',
2216
+				'event_espresso'
2217
+			);
2218
+
2219
+		EE_Error::add_attention(
2220
+			sprintf(
2221
+				$message,
2222
+				"<a href='{$events_url}'>",
2223
+				'</a>'
2224
+			)
2225
+		);
2226
+	}
2227
+
2228
+
2229
+	/**
2230
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2231
+	 * gets called automatically.
2232
+	 *
2233
+	 * @since 4.5.0
2234
+	 *
2235
+	 * @return string
2236
+	 */
2237
+	protected function _display_preview_message()
2238
+	{
2239
+		$this->display_admin_page_with_no_sidebar();
2240
+	}
2241
+
2242
+
2243
+	/**
2244
+	 * registers metaboxes that should show up on the "edit_message_template" page
2245
+	 *
2246
+	 * @access protected
2247
+	 * @return void
2248
+	 */
2249
+	protected function _register_edit_meta_boxes()
2250
+	{
2251
+		add_meta_box(
2252
+			'mtp_valid_shortcodes',
2253
+			esc_html__('Valid Shortcodes', 'event_espresso'),
2254
+			array($this, 'shortcode_meta_box'),
2255
+			$this->_current_screen->id,
2256
+			'side',
2257
+			'default'
2258
+		);
2259
+		add_meta_box(
2260
+			'mtp_extra_actions',
2261
+			esc_html__('Extra Actions', 'event_espresso'),
2262
+			array($this, 'extra_actions_meta_box'),
2263
+			$this->_current_screen->id,
2264
+			'side',
2265
+			'high'
2266
+		);
2267
+		add_meta_box(
2268
+			'mtp_templates',
2269
+			esc_html__('Template Styles', 'event_espresso'),
2270
+			array($this, 'template_pack_meta_box'),
2271
+			$this->_current_screen->id,
2272
+			'side',
2273
+			'high'
2274
+		);
2275
+	}
2276
+
2277
+
2278
+	/**
2279
+	 * metabox content for all template pack and variation selection.
2280
+	 *
2281
+	 * @since 4.5.0
2282
+	 * @return string
2283
+	 * @throws DomainException
2284
+	 * @throws EE_Error
2285
+	 * @throws InvalidArgumentException
2286
+	 * @throws ReflectionException
2287
+	 * @throws InvalidDataTypeException
2288
+	 * @throws InvalidInterfaceException
2289
+	 */
2290
+	public function template_pack_meta_box()
2291
+	{
2292
+		$this->_set_message_template_group();
2293
+
2294
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
2295
+
2296
+		$tp_select_values = array();
2297
+
2298
+		foreach ($tp_collection as $tp) {
2299
+			// only include template packs that support this messenger and message type!
2300
+			$supports = $tp->get_supports();
2301
+			if (! isset($supports[ $this->_message_template_group->messenger() ])
2302
+				|| ! in_array(
2303
+					$this->_message_template_group->message_type(),
2304
+					$supports[ $this->_message_template_group->messenger() ],
2305
+					true
2306
+				)
2307
+			) {
2308
+				// not supported
2309
+				continue;
2310
+			}
2311
+
2312
+			$tp_select_values[] = array(
2313
+				'text' => $tp->label,
2314
+				'id'   => $tp->dbref,
2315
+			);
2316
+		}
2317
+
2318
+		// if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2319
+		// the default template pack.  This still allows for the odd template pack to override.
2320
+		if (empty($tp_select_values)) {
2321
+			$tp_select_values[] = array(
2322
+				'text' => esc_html__('Default', 'event_espresso'),
2323
+				'id'   => 'default',
2324
+			);
2325
+		}
2326
+
2327
+		// setup variation select values for the currently selected template.
2328
+		$variations = $this->_message_template_group->get_template_pack()->get_variations(
2329
+			$this->_message_template_group->messenger(),
2330
+			$this->_message_template_group->message_type()
2331
+		);
2332
+		$variations_select_values = array();
2333
+		foreach ($variations as $variation => $label) {
2334
+			$variations_select_values[] = array(
2335
+				'text' => $label,
2336
+				'id'   => $variation,
2337
+			);
2338
+		}
2339
+
2340
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2341
+
2342
+		$template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2343
+			'MTP_template_pack',
2344
+			$tp_select_values,
2345
+			$this->_message_template_group->get_template_pack_name()
2346
+		);
2347
+		$template_args['variations_selector'] = EEH_Form_Fields::select_input(
2348
+			'MTP_template_variation',
2349
+			$variations_select_values,
2350
+			$this->_message_template_group->get_template_pack_variation()
2351
+		);
2352
+		$template_args['template_pack_label'] = $template_pack_labels->template_pack;
2353
+		$template_args['template_variation_label'] = $template_pack_labels->template_variation;
2354
+		$template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2355
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2356
+
2357
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2358
+
2359
+		EEH_Template::display_template($template, $template_args);
2360
+	}
2361
+
2362
+
2363
+	/**
2364
+	 * This meta box holds any extra actions related to Message Templates
2365
+	 * For now, this includes Resetting templates to defaults and sending a test email.
2366
+	 *
2367
+	 * @access  public
2368
+	 * @return void
2369
+	 * @throws EE_Error
2370
+	 */
2371
+	public function extra_actions_meta_box()
2372
+	{
2373
+		$template_form_fields = array();
2374
+
2375
+		$extra_args = array(
2376
+			'msgr'   => $this->_message_template_group->messenger(),
2377
+			'mt'     => $this->_message_template_group->message_type(),
2378
+			'GRP_ID' => $this->_message_template_group->GRP_ID(),
2379
+		);
2380
+		// first we need to see if there are any fields
2381
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2382
+
2383
+		if (! empty($fields)) {
2384
+			// yup there be fields
2385
+			foreach ($fields as $field => $config) {
2386
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2387
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2388
+				$default = isset($config['default']) ? $config['default'] : '';
2389
+				$default = isset($config['value']) ? $config['value'] : $default;
2390
+
2391
+				// if type is hidden and the value is empty
2392
+				// something may have gone wrong so let's correct with the defaults
2393
+				$fix = $config['input'] === 'hidden'
2394
+					   && isset($existing[ $field ])
2395
+					   && empty($existing[ $field ])
2396
+					? $default
2397
+					: '';
2398
+				$existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2399
+					? $existing[ $field ]
2400
+					: $fix;
2401
+
2402
+				$template_form_fields[ $field_id ] = array(
2403
+					'name'       => 'test_settings_fld[' . $field . ']',
2404
+					'label'      => $config['label'],
2405
+					'input'      => $config['input'],
2406
+					'type'       => $config['type'],
2407
+					'required'   => $config['required'],
2408
+					'validation' => $config['validation'],
2409
+					'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2410
+					'css_class'  => $config['css_class'],
2411
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2412
+					'default'    => $default,
2413
+					'format'     => $config['format'],
2414
+				);
2415
+			}
2416
+		}
2417
+
2418
+		$test_settings_fields = ! empty($template_form_fields)
2419
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2420
+			: '';
2421
+
2422
+		$test_settings_html = '';
2423
+		// print out $test_settings_fields
2424
+		if (! empty($test_settings_fields)) {
2425
+			echo $test_settings_fields;
2426
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2427
+			$test_settings_html .= 'name="test_button" value="';
2428
+			$test_settings_html .= esc_html__('Test Send', 'event_espresso');
2429
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2430
+		}
2431
+
2432
+		// and button
2433
+		$test_settings_html .= '<p>'
2434
+							   . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2435
+							   . '</p>';
2436
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2437
+		$test_settings_html .= $this->get_action_link_or_button(
2438
+			'reset_to_default',
2439
+			'reset',
2440
+			$extra_args,
2441
+			'button-primary reset-default-button'
2442
+		);
2443
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2444
+		echo $test_settings_html;
2445
+	}
2446
+
2447
+
2448
+	/**
2449
+	 * This returns the shortcode selector skeleton for a given context and field.
2450
+	 *
2451
+	 * @since 4.9.rc.000
2452
+	 * @param string $field           The name of the field retrieving shortcodes for.
2453
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2454
+	 * @return string
2455
+	 * @throws DomainException
2456
+	 * @throws EE_Error
2457
+	 * @throws InvalidArgumentException
2458
+	 * @throws ReflectionException
2459
+	 * @throws InvalidDataTypeException
2460
+	 * @throws InvalidInterfaceException
2461
+	 */
2462
+	protected function _get_shortcode_selector($field, $linked_input_id)
2463
+	{
2464
+		$template_args = array(
2465
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2466
+			'fieldname'       => $field,
2467
+			'linked_input_id' => $linked_input_id,
2468
+		);
2469
+
2470
+		return EEH_Template::display_template(
2471
+			EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2472
+			$template_args,
2473
+			true
2474
+		);
2475
+	}
2476
+
2477
+
2478
+	/**
2479
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2480
+	 * page)
2481
+	 *
2482
+	 * @access public
2483
+	 * @return void
2484
+	 * @throws EE_Error
2485
+	 * @throws InvalidArgumentException
2486
+	 * @throws ReflectionException
2487
+	 * @throws InvalidDataTypeException
2488
+	 * @throws InvalidInterfaceException
2489
+	 */
2490
+	public function shortcode_meta_box()
2491
+	{
2492
+		$shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2493
+		// $messenger = $this->_message_template_group->messenger_obj();
2494
+		// now let's set the content depending on the status of the shortcodes array
2495
+		if (empty($shortcodes)) {
2496
+			$content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2497
+			echo $content;
2498
+		} else {
2499
+			// $alt = 0;
2500
+			?>
2501 2501
             <div style="float:right; margin-top:10px"><?php
2502
-                            echo $this->_get_help_tab_link('message_template_shortcodes');
2503
-                            ?></div>
2502
+							echo $this->_get_help_tab_link('message_template_shortcodes');
2503
+							?></div>
2504 2504
             <p class="small-text"><?php
2505
-                                  printf(
2506
-                                      esc_html__(
2507
-                                          'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2508
-                                          'event_espresso'
2509
-                                      ),
2510
-                                      '<span class="dashicons dashicons-menu"></span>'
2511
-                                  );
2512
-                                ?>
2505
+								  printf(
2506
+									  esc_html__(
2507
+										  'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2508
+										  'event_espresso'
2509
+									  ),
2510
+									  '<span class="dashicons dashicons-menu"></span>'
2511
+								  );
2512
+								?>
2513 2513
             </p>
2514 2514
             <?php
2515
-        }
2516
-    }
2517
-
2518
-
2519
-    /**
2520
-     * used to set the $_shortcodes property for when its needed elsewhere.
2521
-     *
2522
-     * @access protected
2523
-     * @return void
2524
-     * @throws EE_Error
2525
-     * @throws InvalidArgumentException
2526
-     * @throws ReflectionException
2527
-     * @throws InvalidDataTypeException
2528
-     * @throws InvalidInterfaceException
2529
-     */
2530
-    protected function _set_shortcodes()
2531
-    {
2532
-
2533
-        // no need to run this if the property is already set
2534
-        if (! empty($this->_shortcodes)) {
2535
-            return;
2536
-        }
2537
-
2538
-        $this->_shortcodes = $this->_get_shortcodes();
2539
-    }
2540
-
2541
-
2542
-    /**
2543
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2544
-     * property)
2545
-     *
2546
-     * @access  protected
2547
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2548
-     *                         for. Defaults to all (for the given context)
2549
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2550
-     * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2551
-     *                         true just an array of shortcode/label pairs.
2552
-     * @throws EE_Error
2553
-     * @throws InvalidArgumentException
2554
-     * @throws ReflectionException
2555
-     * @throws InvalidDataTypeException
2556
-     * @throws InvalidInterfaceException
2557
-     */
2558
-    protected function _get_shortcodes($fields = array(), $merged = true)
2559
-    {
2560
-        $this->_set_message_template_group();
2561
-
2562
-        // we need the messenger and message template to retrieve the valid shortcodes array.
2563
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2564
-            ? absint($this->_req_data['id'])
2565
-            : false;
2566
-        $context = isset($this->_req_data['context'])
2567
-            ? $this->_req_data['context']
2568
-            : key($this->_message_template_group->contexts_config());
2569
-
2570
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2571
-    }
2572
-
2573
-
2574
-    /**
2575
-     * This sets the _message_template property (containing the called message_template object)
2576
-     *
2577
-     * @access protected
2578
-     * @return void
2579
-     * @throws EE_Error
2580
-     * @throws InvalidArgumentException
2581
-     * @throws ReflectionException
2582
-     * @throws InvalidDataTypeException
2583
-     * @throws InvalidInterfaceException
2584
-     */
2585
-    protected function _set_message_template_group()
2586
-    {
2587
-
2588
-        if (! empty($this->_message_template_group)) {
2589
-            return;
2590
-        } //get out if this is already set.
2591
-
2592
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2593
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2594
-
2595
-        // let's get the message templates
2596
-        $MTP = EEM_Message_Template_Group::instance();
2597
-
2598
-        if (empty($GRP_ID)) {
2599
-            $this->_message_template_group = $MTP->create_default_object();
2600
-        } else {
2601
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2602
-        }
2603
-
2604
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2605
-        $this->_variation = $this->_message_template_group->get_template_pack_variation();
2606
-    }
2607
-
2608
-
2609
-    /**
2610
-     * sets up a context switcher for edit forms
2611
-     *
2612
-     * @access  protected
2613
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2614
-     * @param array                      $args                  various things the context switcher needs.
2615
-     * @throws EE_Error
2616
-     */
2617
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2618
-    {
2619
-        $context_details = $template_group_object->contexts_config();
2620
-        $context_label = $template_group_object->context_label();
2621
-        ob_start();
2622
-        ?>
2515
+		}
2516
+	}
2517
+
2518
+
2519
+	/**
2520
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2521
+	 *
2522
+	 * @access protected
2523
+	 * @return void
2524
+	 * @throws EE_Error
2525
+	 * @throws InvalidArgumentException
2526
+	 * @throws ReflectionException
2527
+	 * @throws InvalidDataTypeException
2528
+	 * @throws InvalidInterfaceException
2529
+	 */
2530
+	protected function _set_shortcodes()
2531
+	{
2532
+
2533
+		// no need to run this if the property is already set
2534
+		if (! empty($this->_shortcodes)) {
2535
+			return;
2536
+		}
2537
+
2538
+		$this->_shortcodes = $this->_get_shortcodes();
2539
+	}
2540
+
2541
+
2542
+	/**
2543
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2544
+	 * property)
2545
+	 *
2546
+	 * @access  protected
2547
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2548
+	 *                         for. Defaults to all (for the given context)
2549
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2550
+	 * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2551
+	 *                         true just an array of shortcode/label pairs.
2552
+	 * @throws EE_Error
2553
+	 * @throws InvalidArgumentException
2554
+	 * @throws ReflectionException
2555
+	 * @throws InvalidDataTypeException
2556
+	 * @throws InvalidInterfaceException
2557
+	 */
2558
+	protected function _get_shortcodes($fields = array(), $merged = true)
2559
+	{
2560
+		$this->_set_message_template_group();
2561
+
2562
+		// we need the messenger and message template to retrieve the valid shortcodes array.
2563
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2564
+			? absint($this->_req_data['id'])
2565
+			: false;
2566
+		$context = isset($this->_req_data['context'])
2567
+			? $this->_req_data['context']
2568
+			: key($this->_message_template_group->contexts_config());
2569
+
2570
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2571
+	}
2572
+
2573
+
2574
+	/**
2575
+	 * This sets the _message_template property (containing the called message_template object)
2576
+	 *
2577
+	 * @access protected
2578
+	 * @return void
2579
+	 * @throws EE_Error
2580
+	 * @throws InvalidArgumentException
2581
+	 * @throws ReflectionException
2582
+	 * @throws InvalidDataTypeException
2583
+	 * @throws InvalidInterfaceException
2584
+	 */
2585
+	protected function _set_message_template_group()
2586
+	{
2587
+
2588
+		if (! empty($this->_message_template_group)) {
2589
+			return;
2590
+		} //get out if this is already set.
2591
+
2592
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2593
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2594
+
2595
+		// let's get the message templates
2596
+		$MTP = EEM_Message_Template_Group::instance();
2597
+
2598
+		if (empty($GRP_ID)) {
2599
+			$this->_message_template_group = $MTP->create_default_object();
2600
+		} else {
2601
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2602
+		}
2603
+
2604
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2605
+		$this->_variation = $this->_message_template_group->get_template_pack_variation();
2606
+	}
2607
+
2608
+
2609
+	/**
2610
+	 * sets up a context switcher for edit forms
2611
+	 *
2612
+	 * @access  protected
2613
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2614
+	 * @param array                      $args                  various things the context switcher needs.
2615
+	 * @throws EE_Error
2616
+	 */
2617
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2618
+	{
2619
+		$context_details = $template_group_object->contexts_config();
2620
+		$context_label = $template_group_object->context_label();
2621
+		ob_start();
2622
+		?>
2623 2623
         <div class="ee-msg-switcher-container">
2624 2624
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2625 2625
                 <?php
2626
-                foreach ($args as $name => $value) {
2627
-                    if ($name === 'context' || empty($value) || $name === 'extra') {
2628
-                        continue;
2629
-                    }
2630
-                    ?>
2626
+				foreach ($args as $name => $value) {
2627
+					if ($name === 'context' || empty($value) || $name === 'extra') {
2628
+						continue;
2629
+					}
2630
+					?>
2631 2631
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2632 2632
                     <?php
2633
-                }
2634
-                // setup nonce_url
2635
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2636
-                ?>
2633
+				}
2634
+				// setup nonce_url
2635
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2636
+				?>
2637 2637
                 <select name="context">
2638 2638
                     <?php
2639
-                    $context_templates = $template_group_object->context_templates();
2640
-                    if (is_array($context_templates)) :
2641
-                        foreach ($context_templates as $context => $template_fields) :
2642
-                            $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2643
-                            ?>
2639
+					$context_templates = $template_group_object->context_templates();
2640
+					if (is_array($context_templates)) :
2641
+						foreach ($context_templates as $context => $template_fields) :
2642
+							$checked = ($context === $args['context']) ? 'selected="selected"' : '';
2643
+							?>
2644 2644
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2645 2645
                                 <?php echo $context_details[ $context ]['label']; ?>
2646 2646
                             </option>
2647 2647
                         <?php endforeach;
2648
-                    endif; ?>
2648
+					endif; ?>
2649 2649
                 </select>
2650 2650
                 <?php $button_text = sprintf(__('Switch %s', 'event_espresso'), ucwords($context_label['label'])); ?>
2651 2651
                 <input id="submit-msg-context-switcher-sbmt" class="button-secondary" type="submit"
@@ -2654,1925 +2654,1925 @@  discard block
 block discarded – undo
2654 2654
             <?php echo $args['extra']; ?>
2655 2655
         </div> <!-- end .ee-msg-switcher-container -->
2656 2656
         <?php
2657
-        $output = ob_get_contents();
2658
-        ob_clean();
2659
-        $this->_context_switcher = $output;
2660
-    }
2661
-
2662
-
2663
-    /**
2664
-     * utility for sanitizing new values coming in.
2665
-     * Note: this is only used when updating a context.
2666
-     *
2667
-     * @access protected
2668
-     *
2669
-     * @param int $index This helps us know which template field to select from the request array.
2670
-     *
2671
-     * @return array
2672
-     */
2673
-    protected function _set_message_template_column_values($index)
2674
-    {
2675
-        if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2676
-            foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2677
-                $this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2678
-            }
2679
-        }
2680
-
2681
-
2682
-        $set_column_values = array(
2683
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2684
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2685
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2686
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2687
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2688
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2689
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2690
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2691
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2692
-                ? absint($this->_req_data['MTP_is_global'])
2693
-                : 0,
2694
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2695
-                ? absint($this->_req_data['MTP_is_override'])
2696
-                : 0,
2697
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2698
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2699
-        );
2700
-
2701
-
2702
-        return $set_column_values;
2703
-    }
2704
-
2705
-
2706
-    protected function _insert_or_update_message_template($new = false)
2707
-    {
2708
-
2709
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2710
-        $success = 0;
2711
-        $override = false;
2712
-
2713
-        // setup notices description
2714
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2715
-
2716
-        // need the message type and messenger objects to be able to use the labels for the notices
2717
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2718
-        $messenger_label = $messenger_object instanceof EE_messenger
2719
-            ? ucwords($messenger_object->label['singular'])
2720
-            : '';
2721
-
2722
-        $message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2723
-            ? $this->_req_data['MTP_message_type']
2724
-            : '';
2725
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2726
-
2727
-        $message_type_label = $message_type_object instanceof EE_message_type
2728
-            ? ucwords($message_type_object->label['singular'])
2729
-            : '';
2730
-
2731
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2732
-            ? $this->_req_data['MTP_context']
2733
-            : '';
2734
-        $context = ucwords(str_replace('_', ' ', $context_slug));
2735
-
2736
-        $item_desc = $messenger_label && $message_type_label
2737
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2738
-            : '';
2739
-        $item_desc .= 'Message Template';
2740
-        $query_args = array();
2741
-        $edit_array = array();
2742
-        $action_desc = '';
2743
-
2744
-        // if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2745
-        // user to edit.
2746
-        if ($new) {
2747
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2748
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2749
-                if (empty($edit_array)) {
2750
-                    $success = 0;
2751
-                } else {
2752
-                    $success = 1;
2753
-                    $edit_array = $edit_array[0];
2754
-                    $query_args = array(
2755
-                        'id'      => $edit_array['GRP_ID'],
2756
-                        'context' => $edit_array['MTP_context'],
2757
-                        'action'  => 'edit_message_template',
2758
-                    );
2759
-                }
2760
-            }
2761
-            $action_desc = 'created';
2762
-        } else {
2763
-            $MTPG = EEM_Message_Template_Group::instance();
2764
-            $MTP = EEM_Message_Template::instance();
2765
-
2766
-
2767
-            // run update for each template field in displayed context
2768
-            if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2769
-                EE_Error::add_error(
2770
-                    esc_html__(
2771
-                        'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2772
-                        'event_espresso'
2773
-                    ),
2774
-                    __FILE__,
2775
-                    __FUNCTION__,
2776
-                    __LINE__
2777
-                );
2778
-                $success = 0;
2779
-            } else {
2780
-                // first validate all fields!
2781
-                // this filter allows client code to add its own validation to the template fields as well.
2782
-                // returning an empty array means everything passed validation.
2783
-                // errors in validation should be represented in an array with the following shape:
2784
-                // array(
2785
-                //   'fieldname' => array(
2786
-                //          'msg' => 'error message'
2787
-                //          'value' => 'value for field producing error'
2788
-                // )
2789
-                $custom_validation = (array) apply_filters(
2790
-                    'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2791
-                    array(),
2792
-                    $this->_req_data['MTP_template_fields'],
2793
-                    $context_slug,
2794
-                    $messenger_slug,
2795
-                    $message_type_slug
2796
-                );
2797
-
2798
-                $system_validation = $MTPG->validate(
2799
-                    $this->_req_data['MTP_template_fields'],
2800
-                    $context_slug,
2801
-                    $messenger_slug,
2802
-                    $message_type_slug
2803
-                );
2804
-
2805
-                $system_validation = ! is_array($system_validation) && $system_validation ? array()
2806
-                    : $system_validation;
2807
-                $validates = array_merge($custom_validation, $system_validation);
2808
-
2809
-                // if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2810
-                // appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2811
-                //  WE need to make sure there is no actual error messages in validates.
2812
-                if (is_array($validates) && ! empty($validates)) {
2813
-                    // add the transient so when the form loads we know which fields to highlight
2814
-                    $this->_add_transient('edit_message_template', $validates);
2815
-
2816
-                    $success = 0;
2817
-
2818
-                    // setup notices
2819
-                    foreach ($validates as $field => $error) {
2820
-                        if (isset($error['msg'])) {
2821
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2822
-                        }
2823
-                    }
2824
-                } else {
2825
-                    $set_column_values = array();
2826
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2827
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2828
-
2829
-                        $where_cols_n_values = array(
2830
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2831
-                        );
2832
-                        // if they aren't allowed to use all JS, restrict them to just posty-y tags
2833
-                        if (! current_user_can('unfiltered_html')) {
2834
-                            if (is_array($set_column_values['MTP_content'])) {
2835
-                                foreach ($set_column_values['MTP_content'] as $key => $value) {
2836
-                                    // remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2837
-                                    // only removes slashes from double-quotes, so attributes using single quotes always
2838
-                                    // appear invalid.) But currently the models expect slashed data, so after wp_kses
2839
-                                    // runs we need to re-slash the data. Sheesh. See
2840
-                                    // https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2841
-                                    $set_column_values['MTP_content'][ $key ] = addslashes(
2842
-                                        wp_kses(
2843
-                                            stripslashes($value),
2844
-                                            wp_kses_allowed_html('post')
2845
-                                        )
2846
-                                    );
2847
-                                }
2848
-                            } else {
2849
-                                $set_column_values['MTP_content'] = wp_kses(
2850
-                                    $set_column_values['MTP_content'],
2851
-                                    wp_kses_allowed_html('post')
2852
-                                );
2853
-                            }
2854
-                        }
2855
-                        $message_template_fields = array(
2856
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2857
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2858
-                            'MTP_context'        => $set_column_values['MTP_context'],
2859
-                            'MTP_content'        => $set_column_values['MTP_content'],
2860
-                        );
2861
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2862
-                            if ($updated === false) {
2863
-                                EE_Error::add_error(
2864
-                                    sprintf(
2865
-                                        esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2866
-                                        $template_field
2867
-                                    ),
2868
-                                    __FILE__,
2869
-                                    __FUNCTION__,
2870
-                                    __LINE__
2871
-                                );
2872
-                            } else {
2873
-                                $success = 1;
2874
-                            }
2875
-                        } else {
2876
-                            // only do this logic if we don't have a MTP_ID for this field
2877
-                            if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2878
-                                // this has already been through the template field validator and sanitized, so it will be
2879
-                                // safe to insert this field.  Why insert?  This typically happens when we introduce a new
2880
-                                // message template field in a messenger/message type and existing users don't have the
2881
-                                // default setup for it.
2882
-                                // @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2883
-                                $updated = $MTP->insert($message_template_fields);
2884
-                                if (! $updated || is_wp_error($updated)) {
2885
-                                    EE_Error::add_error(
2886
-                                        sprintf(
2887
-                                            esc_html__('%s field could not be updated.', 'event_espresso'),
2888
-                                            $template_field
2889
-                                        ),
2890
-                                        __FILE__,
2891
-                                        __FUNCTION__,
2892
-                                        __LINE__
2893
-                                    );
2894
-                                    $success = 0;
2895
-                                } else {
2896
-                                    $success = 1;
2897
-                                }
2898
-                            }
2899
-                        }
2900
-                        $action_desc = 'updated';
2901
-                    }
2902
-
2903
-                    // we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2904
-                    $mtpg_fields = array(
2905
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2906
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2907
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2908
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2909
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2910
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2911
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2912
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2913
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2914
-                            : '',
2915
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2916
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2917
-                            : '',
2918
-                    );
2919
-
2920
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2921
-                    $updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2922
-
2923
-                    if ($updated === false) {
2924
-                        EE_Error::add_error(
2925
-                            sprintf(
2926
-                                esc_html__(
2927
-                                    'The Message Template Group (%d) was NOT updated for some reason',
2928
-                                    'event_espresso'
2929
-                                ),
2930
-                                $set_column_values['GRP_ID']
2931
-                            ),
2932
-                            __FILE__,
2933
-                            __FUNCTION__,
2934
-                            __LINE__
2935
-                        );
2936
-                    } else {
2937
-                        // k now we need to ensure the template_pack and template_variation fields are set.
2938
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2939
-                            ? $this->_req_data['MTP_template_pack']
2940
-                            : 'default';
2941
-
2942
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2943
-                            ? $this->_req_data['MTP_template_variation']
2944
-                            : 'default';
2945
-
2946
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2947
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2948
-                            $mtpg_obj->set_template_pack_name($template_pack);
2949
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2950
-                        }
2951
-                        $success = 1;
2952
-                    }
2953
-                }
2954
-            }
2955
-        }
2956
-
2957
-        // we return things differently if doing ajax
2958
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2959
-            $this->_template_args['success'] = $success;
2960
-            $this->_template_args['error'] = ! $success ? true : false;
2961
-            $this->_template_args['content'] = '';
2962
-            $this->_template_args['data'] = array(
2963
-                'grpID'        => $edit_array['GRP_ID'],
2964
-                'templateName' => $edit_array['template_name'],
2965
-            );
2966
-            if ($success) {
2967
-                EE_Error::overwrite_success();
2968
-                EE_Error::add_success(
2969
-                    esc_html__(
2970
-                        '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.',
2971
-                        'event_espresso'
2972
-                    )
2973
-                );
2974
-            }
2975
-
2976
-            $this->_return_json();
2977
-        }
2978
-
2979
-
2980
-        // was a test send triggered?
2981
-        if (isset($this->_req_data['test_button'])) {
2982
-            EE_Error::overwrite_success();
2983
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2984
-            $override = true;
2985
-        }
2986
-
2987
-        if (empty($query_args)) {
2988
-            $query_args = array(
2989
-                'id'      => $this->_req_data['GRP_ID'],
2990
-                'context' => $context_slug,
2991
-                'action'  => 'edit_message_template',
2992
-            );
2993
-        }
2994
-
2995
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2996
-    }
2997
-
2998
-
2999
-    /**
3000
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
3001
-     *
3002
-     * @param  string $context      what context being tested
3003
-     * @param  string $messenger    messenger being tested
3004
-     * @param  string $message_type message type being tested
3005
-     * @throws EE_Error
3006
-     * @throws InvalidArgumentException
3007
-     * @throws InvalidDataTypeException
3008
-     * @throws InvalidInterfaceException
3009
-     */
3010
-    protected function _do_test_send($context, $messenger, $message_type)
3011
-    {
3012
-        // set things up for preview
3013
-        $this->_req_data['messenger'] = $messenger;
3014
-        $this->_req_data['message_type'] = $message_type;
3015
-        $this->_req_data['context'] = $context;
3016
-        $this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
3017
-        $active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
3018
-
3019
-        // let's save any existing fields that might be required by the messenger
3020
-        if (isset($this->_req_data['test_settings_fld'])
3021
-            && $active_messenger instanceof EE_messenger
3022
-            && apply_filters(
3023
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3024
-                true,
3025
-                $this->_req_data['test_settings_fld'],
3026
-                $active_messenger
3027
-            )
3028
-        ) {
3029
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
3030
-        }
3031
-
3032
-        /**
3033
-         * Use filter to add additional controls on whether message can send or not
3034
-         */
3035
-        if (apply_filters(
3036
-            'FHEE__Messages_Admin_Page__do_test_send__can_send',
3037
-            true,
3038
-            $context,
3039
-            $this->_req_data,
3040
-            $messenger,
3041
-            $message_type
3042
-        )) {
3043
-            if (EEM_Event::instance()->count() > 0) {
3044
-                $success = $this->_preview_message(true);
3045
-                if ($success) {
3046
-                    EE_Error::add_success(__('Test message sent', 'event_espresso'));
3047
-                } else {
3048
-                    EE_Error::add_error(
3049
-                        esc_html__('The test message was not sent', 'event_espresso'),
3050
-                        __FILE__,
3051
-                        __FUNCTION__,
3052
-                        __LINE__
3053
-                    );
3054
-                }
3055
-            } else {
3056
-                $this->noEventsErrorMessage(true);
3057
-            }
3058
-        }
3059
-    }
3060
-
3061
-
3062
-    /**
3063
-     * _generate_new_templates
3064
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3065
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3066
-     * for the event.
3067
-     *
3068
-     *
3069
-     * @param  string $messenger     the messenger we are generating templates for
3070
-     * @param array   $message_types array of message types that the templates are generated for.
3071
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3072
-     *                               indicate the message_template_group being used as the base.
3073
-     *
3074
-     * @param bool    $global
3075
-     *
3076
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
3077
-     *                               encountering problems.
3078
-     * @throws EE_Error
3079
-     */
3080
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3081
-    {
3082
-
3083
-        // if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3084
-        // just don't generate any templates.
3085
-        if (empty($message_types)) {
3086
-            return true;
3087
-        }
3088
-
3089
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3090
-    }
3091
-
3092
-
3093
-    /**
3094
-     * [_trash_or_restore_message_template]
3095
-     *
3096
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3097
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3098
-     *                        an individual context (FALSE).
3099
-     * @return void
3100
-     * @throws EE_Error
3101
-     * @throws InvalidArgumentException
3102
-     * @throws InvalidDataTypeException
3103
-     * @throws InvalidInterfaceException
3104
-     */
3105
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
3106
-    {
3107
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3108
-        $MTP = EEM_Message_Template_Group::instance();
3109
-
3110
-        $success = 1;
3111
-
3112
-        // incoming GRP_IDs
3113
-        if ($all) {
3114
-            // Checkboxes
3115
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3116
-                // if array has more than one element then success message should be plural.
3117
-                // todo: what about nonce?
3118
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3119
-
3120
-                // cycle through checkboxes
3121
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3122
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3123
-                    if (! $trashed_or_restored) {
3124
-                        $success = 0;
3125
-                    }
3126
-                }
3127
-            } else {
3128
-                // grab single GRP_ID and handle
3129
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3130
-                if (! empty($GRP_ID)) {
3131
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3132
-                    if (! $trashed_or_restored) {
3133
-                        $success = 0;
3134
-                    }
3135
-                } else {
3136
-                    $success = 0;
3137
-                }
3138
-            }
3139
-        }
3140
-
3141
-        $action_desc = $trash
3142
-            ? esc_html__('moved to the trash', 'event_espresso')
3143
-            : esc_html__('restored', 'event_espresso');
3144
-
3145
-        $action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3146
-
3147
-        $item_desc = $all ? _n(
3148
-            'Message Template Group',
3149
-            'Message Template Groups',
3150
-            $success,
3151
-            'event_espresso'
3152
-        ) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3153
-
3154
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3155
-            'template',
3156
-            'templates',
3157
-            $success,
3158
-            'event_espresso'
3159
-        ) : $item_desc;
3160
-
3161
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
3162
-    }
3163
-
3164
-
3165
-    /**
3166
-     * [_delete_message_template]
3167
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3168
-     *
3169
-     * @return void
3170
-     * @throws EE_Error
3171
-     * @throws InvalidArgumentException
3172
-     * @throws InvalidDataTypeException
3173
-     * @throws InvalidInterfaceException
3174
-     */
3175
-    protected function _delete_message_template()
3176
-    {
3177
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3178
-
3179
-        // checkboxes
3180
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3181
-            // if array has more than one element then success message should be plural
3182
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3183
-
3184
-            // cycle through bulk action checkboxes
3185
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3186
-                $success = $this->_delete_mtp_permanently($GRP_ID);
3187
-            }
3188
-        } else {
3189
-            // grab single grp_id and delete
3190
-            $GRP_ID = absint($this->_req_data['id']);
3191
-            $success = $this->_delete_mtp_permanently($GRP_ID);
3192
-        }
3193
-
3194
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3195
-    }
3196
-
3197
-
3198
-    /**
3199
-     * helper for permanently deleting a mtP group and all related message_templates
3200
-     *
3201
-     * @param  int  $GRP_ID        The group being deleted
3202
-     * @param  bool $include_group whether to delete the Message Template Group as well.
3203
-     * @return bool boolean to indicate the success of the deletes or not.
3204
-     * @throws EE_Error
3205
-     * @throws InvalidArgumentException
3206
-     * @throws InvalidDataTypeException
3207
-     * @throws InvalidInterfaceException
3208
-     */
3209
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3210
-    {
3211
-        $success = 1;
3212
-        $MTPG = EEM_Message_Template_Group::instance();
3213
-        // first let's GET this group
3214
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
3215
-        // then delete permanently all the related Message Templates
3216
-        $deleted = $MTG->delete_related_permanently('Message_Template');
3217
-
3218
-        if ($deleted === 0) {
3219
-            $success = 0;
3220
-        }
3221
-
3222
-        // now delete permanently this particular group
3223
-
3224
-        if ($include_group && ! $MTG->delete_permanently()) {
3225
-            $success = 0;
3226
-        }
3227
-
3228
-        return $success;
3229
-    }
3230
-
3231
-
3232
-    /**
3233
-     *    _learn_more_about_message_templates_link
3234
-     *
3235
-     * @access protected
3236
-     * @return string
3237
-     */
3238
-    protected function _learn_more_about_message_templates_link()
3239
-    {
3240
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3241
-               . esc_html__('learn more about how message templates works', 'event_espresso')
3242
-               . '</a>';
3243
-    }
3244
-
3245
-
3246
-    /**
3247
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3248
-     * ajax and other routes.
3249
-     *
3250
-     * @return void
3251
-     * @throws DomainException
3252
-     */
3253
-    protected function _settings()
3254
-    {
3255
-
3256
-
3257
-        $this->_set_m_mt_settings();
3258
-
3259
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3260
-            ? $this->_req_data['selected_messenger']
3261
-            : 'email';
3262
-
3263
-        // let's setup the messenger tabs
3264
-        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3265
-            $this->_m_mt_settings['messenger_tabs'],
3266
-            'messenger_links',
3267
-            '|',
3268
-            $selected_messenger
3269
-        );
3270
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3271
-        $this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3272
-
3273
-        $this->display_admin_page_with_sidebar();
3274
-    }
3275
-
3276
-
3277
-    /**
3278
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3279
-     *
3280
-     * @access protected
3281
-     * @return void
3282
-     * @throws DomainException
3283
-     */
3284
-    protected function _set_m_mt_settings()
3285
-    {
3286
-        // first if this is already set then lets get out no need to regenerate data.
3287
-        if (! empty($this->_m_mt_settings)) {
3288
-            return;
3289
-        }
3290
-
3291
-        // get all installed messengers and message_types
3292
-        /** @type EE_messenger[] $messengers */
3293
-        $messengers = $this->_message_resource_manager->installed_messengers();
3294
-        /** @type EE_message_type[] $message_types */
3295
-        $message_types = $this->_message_resource_manager->installed_message_types();
3296
-
3297
-
3298
-        // assemble the array for the _tab_text_links helper
3299
-
3300
-        foreach ($messengers as $messenger) {
3301
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3302
-                'label' => ucwords($messenger->label['singular']),
3303
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3304
-                    ? 'messenger-active'
3305
-                    : '',
3306
-                'href'  => $messenger->name,
3307
-                'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3308
-                'slug'  => $messenger->name,
3309
-                'obj'   => $messenger,
3310
-            );
3311
-
3312
-
3313
-            $message_types_for_messenger = $messenger->get_valid_message_types();
3314
-
3315
-            foreach ($message_types as $message_type) {
3316
-                // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3317
-                // it shouldn't show in either the inactive OR active metabox.
3318
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3319
-                    continue;
3320
-                }
3321
-
3322
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3323
-                    $messenger->name,
3324
-                    $message_type->name
3325
-                )
3326
-                    ? 'active'
3327
-                    : 'inactive';
3328
-
3329
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3330
-                    'label'    => ucwords($message_type->label['singular']),
3331
-                    'class'    => 'message-type-' . $a_or_i,
3332
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3333
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3334
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3335
-                    'title'    => $a_or_i === 'active'
3336
-                        ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3337
-                        : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3338
-                    'content'  => $a_or_i === 'active'
3339
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
3340
-                        : $this->_message_type_settings_content($message_type, $messenger),
3341
-                    'slug'     => $message_type->name,
3342
-                    'active'   => $a_or_i === 'active',
3343
-                    'obj'      => $message_type,
3344
-                );
3345
-            }
3346
-        }
3347
-    }
3348
-
3349
-
3350
-    /**
3351
-     * This just prepares the content for the message type settings
3352
-     *
3353
-     * @param  EE_message_type $message_type The message type object
3354
-     * @param  EE_messenger    $messenger    The messenger object
3355
-     * @param  boolean         $active       Whether the message type is active or not
3356
-     * @return string html output for the content
3357
-     * @throws DomainException
3358
-     */
3359
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
3360
-    {
3361
-        // get message type fields
3362
-        $fields = $message_type->get_admin_settings_fields();
3363
-        $settings_template_args['template_form_fields'] = '';
3364
-
3365
-        if (! empty($fields) && $active) {
3366
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3367
-            foreach ($fields as $fldname => $fldprops) {
3368
-                $field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3369
-                $template_form_field[ $field_id ] = array(
3370
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3371
-                    'label'      => $fldprops['label'],
3372
-                    'input'      => $fldprops['field_type'],
3373
-                    'type'       => $fldprops['value_type'],
3374
-                    'required'   => $fldprops['required'],
3375
-                    'validation' => $fldprops['validation'],
3376
-                    'value'      => isset($existing_settings[ $fldname ])
3377
-                        ? $existing_settings[ $fldname ]
3378
-                        : $fldprops['default'],
3379
-                    'options'    => isset($fldprops['options'])
3380
-                        ? $fldprops['options']
3381
-                        : array(),
3382
-                    'default'    => isset($existing_settings[ $fldname ])
3383
-                        ? $existing_settings[ $fldname ]
3384
-                        : $fldprops['default'],
3385
-                    'css_class'  => 'no-drag',
3386
-                    'format'     => $fldprops['format'],
3387
-                );
3388
-            }
3389
-
3390
-
3391
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3392
-                ? $this->_generate_admin_form_fields(
3393
-                    $template_form_field,
3394
-                    'string',
3395
-                    'ee_mt_activate_form'
3396
-                )
3397
-                : '';
3398
-        }
3399
-
3400
-        $settings_template_args['description'] = $message_type->description;
3401
-        // we also need some hidden fields
3402
-        $settings_template_args['hidden_fields'] = array(
3403
-            'message_type_settings[messenger]'    => array(
3404
-                'type'  => 'hidden',
3405
-                'value' => $messenger->name,
3406
-            ),
3407
-            'message_type_settings[message_type]' => array(
3408
-                'type'  => 'hidden',
3409
-                'value' => $message_type->name,
3410
-            ),
3411
-            'type'                                => array(
3412
-                'type'  => 'hidden',
3413
-                'value' => 'message_type',
3414
-            ),
3415
-        );
3416
-
3417
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3418
-            $settings_template_args['hidden_fields'],
3419
-            'array'
3420
-        );
3421
-        $settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3422
-            ? ' hidden'
3423
-            : '';
3424
-
3425
-
3426
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3427
-        $content = EEH_Template::display_template($template, $settings_template_args, true);
3428
-
3429
-        return $content;
3430
-    }
3431
-
3432
-
3433
-    /**
3434
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
3435
-     *
3436
-     * @access protected
3437
-     * @return void
3438
-     * @throws DomainException
3439
-     */
3440
-    protected function _messages_settings_metaboxes()
3441
-    {
3442
-        $this->_set_m_mt_settings();
3443
-        $m_boxes = $mt_boxes = array();
3444
-        $m_template_args = $mt_template_args = array();
3445
-
3446
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3447
-            ? $this->_req_data['selected_messenger']
3448
-            : 'email';
3449
-
3450
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
3451
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3452
-                $hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3453
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3454
-                // messenger meta boxes
3455
-                $active = $selected_messenger === $messenger;
3456
-                $active_mt_tabs = isset(
3457
-                    $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3458
-                )
3459
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3460
-                    : '';
3461
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3462
-                    esc_html__('%s Settings', 'event_espresso'),
3463
-                    $tab_array['label']
3464
-                );
3465
-                $m_template_args[ $messenger . '_a_box' ] = array(
3466
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3467
-                    'inactive_message_types' => isset(
3468
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3469
-                    )
3470
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3471
-                        : '',
3472
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3473
-                    'hidden'                 => $active ? '' : ' hidden',
3474
-                    'hide_on_message'        => $hide_on_message,
3475
-                    'messenger'              => $messenger,
3476
-                    'active'                 => $active,
3477
-                );
3478
-                // message type meta boxes
3479
-                // (which is really just the inactive container for each messenger
3480
-                // showing inactive message types for that messenger)
3481
-                $mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3482
-                $mt_template_args[ $messenger . '_i_box' ] = array(
3483
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3484
-                    'inactive_message_types' => isset(
3485
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3486
-                    )
3487
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3488
-                        : '',
3489
-                    'hidden'                 => $active ? '' : ' hidden',
3490
-                    'hide_on_message'        => $hide_on_message,
3491
-                    'hide_off_message'       => $hide_off_message,
3492
-                    'messenger'              => $messenger,
3493
-                    'active'                 => $active,
3494
-                );
3495
-            }
3496
-        }
3497
-
3498
-
3499
-        // register messenger metaboxes
3500
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3501
-        foreach ($m_boxes as $box => $label) {
3502
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3503
-            $msgr = str_replace('_a_box', '', $box);
3504
-            add_meta_box(
3505
-                'espresso_' . $msgr . '_settings',
3506
-                $label,
3507
-                function ($post, $metabox) {
3508
-                    echo EEH_Template::display_template(
3509
-                        $metabox["args"]["template_path"],
3510
-                        $metabox["args"]["template_args"],
3511
-                        true
3512
-                    );
3513
-                },
3514
-                $this->_current_screen->id,
3515
-                'normal',
3516
-                'high',
3517
-                $callback_args
3518
-            );
3519
-        }
3520
-
3521
-        // register message type metaboxes
3522
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3523
-        foreach ($mt_boxes as $box => $label) {
3524
-            $callback_args = array(
3525
-                'template_path' => $mt_template_path,
3526
-                'template_args' => $mt_template_args[ $box ],
3527
-            );
3528
-            $mt = str_replace('_i_box', '', $box);
3529
-            add_meta_box(
3530
-                'espresso_' . $mt . '_inactive_mts',
3531
-                $label,
3532
-                function ($post, $metabox) {
3533
-                    echo EEH_Template::display_template(
3534
-                        $metabox["args"]["template_path"],
3535
-                        $metabox["args"]["template_args"],
3536
-                        true
3537
-                    );
3538
-                },
3539
-                $this->_current_screen->id,
3540
-                'side',
3541
-                'high',
3542
-                $callback_args
3543
-            );
3544
-        }
3545
-
3546
-        // register metabox for global messages settings but only when on the main site.  On single site installs this
3547
-        // will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3548
-        if (is_main_site()) {
3549
-            add_meta_box(
3550
-                'espresso_global_message_settings',
3551
-                esc_html__('Global Message Settings', 'event_espresso'),
3552
-                array($this, 'global_messages_settings_metabox_content'),
3553
-                $this->_current_screen->id,
3554
-                'normal',
3555
-                'low',
3556
-                array()
3557
-            );
3558
-        }
3559
-    }
3560
-
3561
-
3562
-    /**
3563
-     *  This generates the content for the global messages settings metabox.
3564
-     *
3565
-     * @return string
3566
-     * @throws EE_Error
3567
-     * @throws InvalidArgumentException
3568
-     * @throws ReflectionException
3569
-     * @throws InvalidDataTypeException
3570
-     * @throws InvalidInterfaceException
3571
-     */
3572
-    public function global_messages_settings_metabox_content()
3573
-    {
3574
-        $form = $this->_generate_global_settings_form();
3575
-        echo $form->form_open(
3576
-            $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3577
-            'POST'
3578
-        )
3579
-             . $form->get_html()
3580
-             . $form->form_close();
3581
-    }
3582
-
3583
-
3584
-    /**
3585
-     * This generates and returns the form object for the global messages settings.
3586
-     *
3587
-     * @return EE_Form_Section_Proper
3588
-     * @throws EE_Error
3589
-     * @throws InvalidArgumentException
3590
-     * @throws ReflectionException
3591
-     * @throws InvalidDataTypeException
3592
-     * @throws InvalidInterfaceException
3593
-     */
3594
-    protected function _generate_global_settings_form()
3595
-    {
3596
-        EE_Registry::instance()->load_helper('HTML');
3597
-        /** @var EE_Network_Core_Config $network_config */
3598
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3599
-
3600
-        return new EE_Form_Section_Proper(
3601
-            array(
3602
-                'name'            => 'global_messages_settings',
3603
-                'html_id'         => 'global_messages_settings',
3604
-                'html_class'      => 'form-table',
3605
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3606
-                'subsections'     => apply_filters(
3607
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3608
-                    array(
3609
-                        'do_messages_on_same_request' => new EE_Select_Input(
3610
-                            array(
3611
-                                true  => esc_html__("On the same request", "event_espresso"),
3612
-                                false => esc_html__("On a separate request", "event_espresso"),
3613
-                            ),
3614
-                            array(
3615
-                                'default'         => $network_config->do_messages_on_same_request,
3616
-                                'html_label_text' => esc_html__(
3617
-                                    'Generate and send all messages:',
3618
-                                    'event_espresso'
3619
-                                ),
3620
-                                'html_help_text'  => esc_html__(
3621
-                                    '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.',
3622
-                                    'event_espresso'
3623
-                                ),
3624
-                            )
3625
-                        ),
3626
-                        'delete_threshold'            => new EE_Select_Input(
3627
-                            array(
3628
-                                0  => esc_html__('Forever', 'event_espresso'),
3629
-                                3  => esc_html__('3 Months', 'event_espresso'),
3630
-                                6  => esc_html__('6 Months', 'event_espresso'),
3631
-                                9  => esc_html__('9 Months', 'event_espresso'),
3632
-                                12 => esc_html__('12 Months', 'event_espresso'),
3633
-                                24 => esc_html__('24 Months', 'event_espresso'),
3634
-                                36 => esc_html__('36 Months', 'event_espresso'),
3635
-                            ),
3636
-                            array(
3637
-                                'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3638
-                                'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3639
-                                'html_help_text'  => esc_html__(
3640
-                                    'You can control how long a record of processed messages is kept via this option.',
3641
-                                    'event_espresso'
3642
-                                ),
3643
-                            )
3644
-                        ),
3645
-                        'update_settings'             => new EE_Submit_Input(
3646
-                            array(
3647
-                                'default'         => esc_html__('Update', 'event_espresso'),
3648
-                                'html_label_text' => '&nbsp',
3649
-                            )
3650
-                        ),
3651
-                    )
3652
-                ),
3653
-            )
3654
-        );
3655
-    }
3656
-
3657
-
3658
-    /**
3659
-     * This handles updating the global settings set on the admin page.
3660
-     *
3661
-     * @throws EE_Error
3662
-     * @throws InvalidDataTypeException
3663
-     * @throws InvalidInterfaceException
3664
-     * @throws InvalidArgumentException
3665
-     * @throws ReflectionException
3666
-     */
3667
-    protected function _update_global_settings()
3668
-    {
3669
-        /** @var EE_Network_Core_Config $network_config */
3670
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3671
-        $messages_config = EE_Registry::instance()->CFG->messages;
3672
-        $form = $this->_generate_global_settings_form();
3673
-        if ($form->was_submitted()) {
3674
-            $form->receive_form_submission();
3675
-            if ($form->is_valid()) {
3676
-                $valid_data = $form->valid_data();
3677
-                foreach ($valid_data as $property => $value) {
3678
-                    $setter = 'set_' . $property;
3679
-                    if (method_exists($network_config, $setter)) {
3680
-                        $network_config->{$setter}($value);
3681
-                    } elseif (property_exists($network_config, $property)
3682
-                        && $network_config->{$property} !== $value
3683
-                    ) {
3684
-                        $network_config->{$property} = $value;
3685
-                    } elseif (property_exists($messages_config, $property)
3686
-                        && $messages_config->{$property} !== $value
3687
-                    ) {
3688
-                        $messages_config->{$property} = $value;
3689
-                    }
3690
-                }
3691
-                // only update if the form submission was valid!
3692
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3693
-                EE_Registry::instance()->CFG->update_espresso_config();
3694
-                EE_Error::overwrite_success();
3695
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3696
-            }
3697
-        }
3698
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3699
-    }
3700
-
3701
-
3702
-    /**
3703
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3704
-     *
3705
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3706
-     * @return string html formatted tabs
3707
-     * @throws DomainException
3708
-     */
3709
-    protected function _get_mt_tabs($tab_array)
3710
-    {
3711
-        $tab_array = (array) $tab_array;
3712
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3713
-        $tabs = '';
3714
-
3715
-        foreach ($tab_array as $tab) {
3716
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3717
-        }
3718
-
3719
-        return $tabs;
3720
-    }
3721
-
3722
-
3723
-    /**
3724
-     * This prepares the content of the messenger meta box admin settings
3725
-     *
3726
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3727
-     * @return string html formatted content
3728
-     * @throws DomainException
3729
-     */
3730
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3731
-    {
3732
-
3733
-        $fields = $messenger->get_admin_settings_fields();
3734
-        $settings_template_args['template_form_fields'] = '';
3735
-
3736
-        // is $messenger active?
3737
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3738
-
3739
-
3740
-        if (! empty($fields)) {
3741
-            $existing_settings = $messenger->get_existing_admin_settings();
3742
-
3743
-            foreach ($fields as $fldname => $fldprops) {
3744
-                $field_id = $messenger->name . '-' . $fldname;
3745
-                $template_form_field[ $field_id ] = array(
3746
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3747
-                    'label'      => $fldprops['label'],
3748
-                    'input'      => $fldprops['field_type'],
3749
-                    'type'       => $fldprops['value_type'],
3750
-                    'required'   => $fldprops['required'],
3751
-                    'validation' => $fldprops['validation'],
3752
-                    'value'      => isset($existing_settings[ $field_id ])
3753
-                        ? $existing_settings[ $field_id ]
3754
-                        : $fldprops['default'],
3755
-                    'css_class'  => '',
3756
-                    'format'     => $fldprops['format'],
3757
-                );
3758
-            }
3759
-
3760
-
3761
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3762
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3763
-                : '';
3764
-        }
3765
-
3766
-        // we also need some hidden fields
3767
-        $settings_template_args['hidden_fields'] = array(
3768
-            'messenger_settings[messenger]' => array(
3769
-                'type'  => 'hidden',
3770
-                'value' => $messenger->name,
3771
-            ),
3772
-            'type'                          => array(
3773
-                'type'  => 'hidden',
3774
-                'value' => 'messenger',
3775
-            ),
3776
-        );
3777
-
3778
-        // make sure any active message types that are existing are included in the hidden fields
3779
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3780
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3781
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3782
-                    'type'  => 'hidden',
3783
-                    'value' => $mt,
3784
-                );
3785
-            }
3786
-        }
3787
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3788
-            $settings_template_args['hidden_fields'],
3789
-            'array'
3790
-        );
3791
-        $active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3792
-
3793
-        $settings_template_args['messenger'] = $messenger->name;
3794
-        $settings_template_args['description'] = $messenger->description;
3795
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3796
-
3797
-
3798
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3799
-            $messenger->name
3800
-        )
3801
-            ? $settings_template_args['show_hide_edit_form']
3802
-            : ' hidden';
3803
-
3804
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3805
-            ? ' hidden'
3806
-            : $settings_template_args['show_hide_edit_form'];
3807
-
3808
-
3809
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3810
-        $settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3811
-        $settings_template_args['on_off_status'] = $active ? true : false;
3812
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3813
-        $content = EEH_Template::display_template(
3814
-            $template,
3815
-            $settings_template_args,
3816
-            true
3817
-        );
3818
-
3819
-        return $content;
3820
-    }
3821
-
3822
-
3823
-    /**
3824
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3825
-     *
3826
-     * @throws DomainException
3827
-     * @throws EE_Error
3828
-     * @throws InvalidDataTypeException
3829
-     * @throws InvalidInterfaceException
3830
-     * @throws InvalidArgumentException
3831
-     * @throws ReflectionException
3832
-     */
3833
-    public function activate_messenger_toggle()
3834
-    {
3835
-        $success = true;
3836
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3837
-        // let's check that we have required data
3838
-        if (! isset($this->_req_data['messenger'])) {
3839
-            EE_Error::add_error(
3840
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3841
-                __FILE__,
3842
-                __FUNCTION__,
3843
-                __LINE__
3844
-            );
3845
-            $success = false;
3846
-        }
3847
-
3848
-        // do a nonce check here since we're not arriving via a normal route
3849
-        $nonce = isset($this->_req_data['activate_nonce'])
3850
-            ? sanitize_text_field($this->_req_data['activate_nonce'])
3851
-            : '';
3852
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3853
-
3854
-        $this->_verify_nonce($nonce, $nonce_ref);
3855
-
3856
-
3857
-        if (! isset($this->_req_data['status'])) {
3858
-            EE_Error::add_error(
3859
-                esc_html__(
3860
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3861
-                    'event_espresso'
3862
-                ),
3863
-                __FILE__,
3864
-                __FUNCTION__,
3865
-                __LINE__
3866
-            );
3867
-            $success = false;
3868
-        }
3869
-
3870
-        // do check to verify we have a valid status.
3871
-        $status = $this->_req_data['status'];
3872
-
3873
-        if ($status !== 'off' && $status !== 'on') {
3874
-            EE_Error::add_error(
3875
-                sprintf(
3876
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3877
-                    $this->_req_data['status']
3878
-                ),
3879
-                __FILE__,
3880
-                __FUNCTION__,
3881
-                __LINE__
3882
-            );
3883
-            $success = false;
3884
-        }
3885
-
3886
-        if ($success) {
3887
-            // made it here?  Stop dawdling then!!
3888
-            $success = $status === 'off'
3889
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3890
-                : $this->_activate_messenger($this->_req_data['messenger']);
3891
-        }
3892
-
3893
-        $this->_template_args['success'] = $success;
3894
-
3895
-        // no special instructions so let's just do the json return (which should automatically do all the special stuff).
3896
-        $this->_return_json();
3897
-    }
3898
-
3899
-
3900
-    /**
3901
-     * used by ajax from the messages settings page to activate|deactivate a message type
3902
-     *
3903
-     * @throws DomainException
3904
-     * @throws EE_Error
3905
-     * @throws ReflectionException
3906
-     * @throws InvalidDataTypeException
3907
-     * @throws InvalidInterfaceException
3908
-     * @throws InvalidArgumentException
3909
-     */
3910
-    public function activate_mt_toggle()
3911
-    {
3912
-        $success = true;
3913
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3914
-
3915
-        // let's make sure we have the necessary data
3916
-        if (! isset($this->_req_data['message_type'])) {
3917
-            EE_Error::add_error(
3918
-                esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3919
-                __FILE__,
3920
-                __FUNCTION__,
3921
-                __LINE__
3922
-            );
3923
-            $success = false;
3924
-        }
3925
-
3926
-        if (! isset($this->_req_data['messenger'])) {
3927
-            EE_Error::add_error(
3928
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3929
-                __FILE__,
3930
-                __FUNCTION__,
3931
-                __LINE__
3932
-            );
3933
-            $success = false;
3934
-        }
3935
-
3936
-        if (! isset($this->_req_data['status'])) {
3937
-            EE_Error::add_error(
3938
-                esc_html__(
3939
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3940
-                    'event_espresso'
3941
-                ),
3942
-                __FILE__,
3943
-                __FUNCTION__,
3944
-                __LINE__
3945
-            );
3946
-            $success = false;
3947
-        }
3948
-
3949
-
3950
-        // do check to verify we have a valid status.
3951
-        $status = $this->_req_data['status'];
3952
-
3953
-        if ($status !== 'activate' && $status !== 'deactivate') {
3954
-            EE_Error::add_error(
3955
-                sprintf(
3956
-                    esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3957
-                    $this->_req_data['status']
3958
-                ),
3959
-                __FILE__,
3960
-                __FUNCTION__,
3961
-                __LINE__
3962
-            );
3963
-            $success = false;
3964
-        }
3965
-
3966
-
3967
-        // do a nonce check here since we're not arriving via a normal route
3968
-        $nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3969
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3970
-
3971
-        $this->_verify_nonce($nonce, $nonce_ref);
3972
-
3973
-        if ($success) {
3974
-            // made it here? um, what are you waiting for then?
3975
-            $success = $status === 'deactivate'
3976
-                ? $this->_deactivate_message_type_for_messenger(
3977
-                    $this->_req_data['messenger'],
3978
-                    $this->_req_data['message_type']
3979
-                )
3980
-                : $this->_activate_message_type_for_messenger(
3981
-                    $this->_req_data['messenger'],
3982
-                    $this->_req_data['message_type']
3983
-                );
3984
-        }
3985
-
3986
-        $this->_template_args['success'] = $success;
3987
-        $this->_return_json();
3988
-    }
3989
-
3990
-
3991
-    /**
3992
-     * Takes care of processing activating a messenger and preparing the appropriate response.
3993
-     *
3994
-     * @param string $messenger_name The name of the messenger being activated
3995
-     * @return bool
3996
-     * @throws DomainException
3997
-     * @throws EE_Error
3998
-     * @throws InvalidArgumentException
3999
-     * @throws ReflectionException
4000
-     * @throws InvalidDataTypeException
4001
-     * @throws InvalidInterfaceException
4002
-     */
4003
-    protected function _activate_messenger($messenger_name)
4004
-    {
4005
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4006
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4007
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger
4008
-            ? $active_messenger->get_default_message_types()
4009
-            : array();
4010
-
4011
-        // ensure is active
4012
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
4013
-
4014
-        // set response_data for reload
4015
-        foreach ($message_types_to_activate as $message_type_name) {
4016
-            /** @var EE_message_type $message_type */
4017
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4018
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4019
-                $messenger_name,
4020
-                $message_type_name
4021
-            )
4022
-                && $message_type instanceof EE_message_type
4023
-            ) {
4024
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
4025
-                if ($message_type->get_admin_settings_fields()) {
4026
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
4027
-                }
4028
-            }
4029
-        }
4030
-
4031
-        // add success message for activating messenger
4032
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4033
-    }
4034
-
4035
-
4036
-    /**
4037
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
4038
-     *
4039
-     * @param string $messenger_name The name of the messenger being activated
4040
-     * @return bool
4041
-     * @throws DomainException
4042
-     * @throws EE_Error
4043
-     * @throws InvalidArgumentException
4044
-     * @throws ReflectionException
4045
-     * @throws InvalidDataTypeException
4046
-     * @throws InvalidInterfaceException
4047
-     */
4048
-    protected function _deactivate_messenger($messenger_name)
4049
-    {
4050
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4051
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4052
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
4053
-
4054
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4055
-    }
4056
-
4057
-
4058
-    /**
4059
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4060
-     *
4061
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
4062
-     * @param string $message_type_name The name of the message type being activated for the messenger
4063
-     * @return bool
4064
-     * @throws DomainException
4065
-     * @throws EE_Error
4066
-     * @throws InvalidArgumentException
4067
-     * @throws ReflectionException
4068
-     * @throws InvalidDataTypeException
4069
-     * @throws InvalidInterfaceException
4070
-     */
4071
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4072
-    {
4073
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4074
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4075
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4076
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4077
-
4078
-        // ensure is active
4079
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
4080
-
4081
-        // set response for load
4082
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4083
-            $messenger_name,
4084
-            $message_type_name
4085
-        )
4086
-        ) {
4087
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
4088
-            if ($message_type_to_activate->get_admin_settings_fields()) {
4089
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
4090
-            }
4091
-        }
4092
-
4093
-        return $this->_setup_response_message_for_activating_messenger_with_message_types(
4094
-            $active_messenger,
4095
-            $message_type_to_activate
4096
-        );
4097
-    }
4098
-
4099
-
4100
-    /**
4101
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4102
-     *
4103
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4104
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
4105
-     * @return bool
4106
-     * @throws DomainException
4107
-     * @throws EE_Error
4108
-     * @throws InvalidArgumentException
4109
-     * @throws ReflectionException
4110
-     * @throws InvalidDataTypeException
4111
-     * @throws InvalidInterfaceException
4112
-     */
4113
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4114
-    {
4115
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4116
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4117
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4118
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4119
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4120
-
4121
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4122
-            $active_messenger,
4123
-            $message_type_to_deactivate
4124
-        );
4125
-    }
4126
-
4127
-
4128
-    /**
4129
-     * This just initializes the defaults for activating messenger and message type responses.
4130
-     */
4131
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
4132
-    {
4133
-        $this->_template_args['data']['active_mts'] = array();
4134
-        $this->_template_args['data']['mt_reload'] = array();
4135
-    }
4136
-
4137
-
4138
-    /**
4139
-     * Setup appropriate response for activating a messenger and/or message types
4140
-     *
4141
-     * @param EE_messenger         $messenger
4142
-     * @param EE_message_type|null $message_type
4143
-     * @return bool
4144
-     * @throws DomainException
4145
-     * @throws EE_Error
4146
-     * @throws InvalidArgumentException
4147
-     * @throws ReflectionException
4148
-     * @throws InvalidDataTypeException
4149
-     * @throws InvalidInterfaceException
4150
-     */
4151
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
4152
-        $messenger,
4153
-        EE_Message_Type $message_type = null
4154
-    ) {
4155
-        // if $messenger isn't a valid messenger object then get out.
4156
-        if (! $messenger instanceof EE_Messenger) {
4157
-            EE_Error::add_error(
4158
-                esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4159
-                __FILE__,
4160
-                __FUNCTION__,
4161
-                __LINE__
4162
-            );
4163
-
4164
-            return false;
4165
-        }
4166
-        // activated
4167
-        if ($this->_template_args['data']['active_mts']) {
4168
-            EE_Error::overwrite_success();
4169
-            // activated a message type with the messenger
4170
-            if ($message_type instanceof EE_message_type) {
4171
-                EE_Error::add_success(
4172
-                    sprintf(
4173
-                        esc_html__(
4174
-                            '%s message type has been successfully activated with the %s messenger',
4175
-                            'event_espresso'
4176
-                        ),
4177
-                        ucwords($message_type->label['singular']),
4178
-                        ucwords($messenger->label['singular'])
4179
-                    )
4180
-                );
4181
-
4182
-                // if message type was invoice then let's make sure we activate the invoice payment method.
4183
-                if ($message_type->name === 'invoice') {
4184
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
4185
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4186
-                    if ($pm instanceof EE_Payment_Method) {
4187
-                        EE_Error::add_attention(
4188
-                            esc_html__(
4189
-                                '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.',
4190
-                                'event_espresso'
4191
-                            )
4192
-                        );
4193
-                    }
4194
-                }
4195
-                // just toggles the entire messenger
4196
-            } else {
4197
-                EE_Error::add_success(
4198
-                    sprintf(
4199
-                        esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4200
-                        ucwords($messenger->label['singular'])
4201
-                    )
4202
-                );
4203
-            }
4204
-
4205
-            return true;
4206
-
4207
-            // possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4208
-            // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4209
-            // in which case we just give a success message for the messenger being successfully activated.
4210
-        } else {
4211
-            if (! $messenger->get_default_message_types()) {
4212
-                // messenger doesn't have any default message types so still a success.
4213
-                EE_Error::add_success(
4214
-                    sprintf(
4215
-                        esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4216
-                        ucwords($messenger->label['singular'])
4217
-                    )
4218
-                );
4219
-
4220
-                return true;
4221
-            } else {
4222
-                EE_Error::add_error(
4223
-                    $message_type instanceof EE_message_type
4224
-                        ? sprintf(
4225
-                            esc_html__(
4226
-                                '%s message type was not successfully activated with the %s messenger',
4227
-                                'event_espresso'
4228
-                            ),
4229
-                            ucwords($message_type->label['singular']),
4230
-                            ucwords($messenger->label['singular'])
4231
-                        )
4232
-                        : sprintf(
4233
-                            esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4234
-                            ucwords($messenger->label['singular'])
4235
-                        ),
4236
-                    __FILE__,
4237
-                    __FUNCTION__,
4238
-                    __LINE__
4239
-                );
4240
-
4241
-                return false;
4242
-            }
4243
-        }
4244
-    }
4245
-
4246
-
4247
-    /**
4248
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
4249
-     *
4250
-     * @param EE_messenger         $messenger
4251
-     * @param EE_message_type|null $message_type
4252
-     * @return bool
4253
-     * @throws DomainException
4254
-     * @throws EE_Error
4255
-     * @throws InvalidArgumentException
4256
-     * @throws ReflectionException
4257
-     * @throws InvalidDataTypeException
4258
-     * @throws InvalidInterfaceException
4259
-     */
4260
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4261
-        $messenger,
4262
-        EE_message_type $message_type = null
4263
-    ) {
4264
-        EE_Error::overwrite_success();
4265
-
4266
-        // if $messenger isn't a valid messenger object then get out.
4267
-        if (! $messenger instanceof EE_Messenger) {
4268
-            EE_Error::add_error(
4269
-                esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4270
-                __FILE__,
4271
-                __FUNCTION__,
4272
-                __LINE__
4273
-            );
4274
-
4275
-            return false;
4276
-        }
4277
-
4278
-        if ($message_type instanceof EE_message_type) {
4279
-            $message_type_name = $message_type->name;
4280
-            EE_Error::add_success(
4281
-                sprintf(
4282
-                    esc_html__(
4283
-                        '%s message type has been successfully deactivated for the %s messenger.',
4284
-                        'event_espresso'
4285
-                    ),
4286
-                    ucwords($message_type->label['singular']),
4287
-                    ucwords($messenger->label['singular'])
4288
-                )
4289
-            );
4290
-        } else {
4291
-            $message_type_name = '';
4292
-            EE_Error::add_success(
4293
-                sprintf(
4294
-                    esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4295
-                    ucwords($messenger->label['singular'])
4296
-                )
4297
-            );
4298
-        }
4299
-
4300
-        // if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4301
-        if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4302
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
4303
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4304
-            if ($count_updated > 0) {
4305
-                $msg = $message_type_name === 'invoice'
4306
-                    ? esc_html__(
4307
-                        '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.',
4308
-                        'event_espresso'
4309
-                    )
4310
-                    : esc_html__(
4311
-                        '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.',
4312
-                        'event_espresso'
4313
-                    );
4314
-                EE_Error::add_attention($msg);
4315
-            }
4316
-        }
4317
-
4318
-        return true;
4319
-    }
4320
-
4321
-
4322
-    /**
4323
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4324
-     *
4325
-     * @throws DomainException
4326
-     */
4327
-    public function update_mt_form()
4328
-    {
4329
-        if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4330
-            EE_Error::add_error(
4331
-                esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4332
-                __FILE__,
4333
-                __FUNCTION__,
4334
-                __LINE__
4335
-            );
4336
-            $this->_return_json();
4337
-        }
4338
-
4339
-        $message_types = $this->get_installed_message_types();
4340
-
4341
-        $message_type = $message_types[ $this->_req_data['message_type'] ];
4342
-        $messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4343
-
4344
-        $content = $this->_message_type_settings_content(
4345
-            $message_type,
4346
-            $messenger,
4347
-            true
4348
-        );
4349
-        $this->_template_args['success'] = true;
4350
-        $this->_template_args['content'] = $content;
4351
-        $this->_return_json();
4352
-    }
4353
-
4354
-
4355
-    /**
4356
-     * this handles saving the settings for a messenger or message type
4357
-     *
4358
-     */
4359
-    public function save_settings()
4360
-    {
4361
-        if (! isset($this->_req_data['type'])) {
4362
-            EE_Error::add_error(
4363
-                esc_html__(
4364
-                    'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4365
-                    'event_espresso'
4366
-                ),
4367
-                __FILE__,
4368
-                __FUNCTION__,
4369
-                __LINE__
4370
-            );
4371
-            $this->_template_args['error'] = true;
4372
-            $this->_return_json();
4373
-        }
4374
-
4375
-
4376
-        if ($this->_req_data['type'] === 'messenger') {
4377
-            // this should be an array.
4378
-            $settings = $this->_req_data['messenger_settings'];
4379
-            $messenger = $settings['messenger'];
4380
-            // let's setup the settings data
4381
-            foreach ($settings as $key => $value) {
4382
-                switch ($key) {
4383
-                    case 'messenger':
4384
-                        unset($settings['messenger']);
4385
-                        break;
4386
-                    case 'message_types':
4387
-                        unset($settings['message_types']);
4388
-                        break;
4389
-                    default:
4390
-                        $settings[ $key ] = $value;
4391
-                        break;
4392
-                }
4393
-            }
4394
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4395
-        } elseif ($this->_req_data['type'] === 'message_type') {
4396
-            $settings = $this->_req_data['message_type_settings'];
4397
-            $messenger = $settings['messenger'];
4398
-            $message_type = $settings['message_type'];
4399
-
4400
-            foreach ($settings as $key => $value) {
4401
-                switch ($key) {
4402
-                    case 'messenger':
4403
-                        unset($settings['messenger']);
4404
-                        break;
4405
-                    case 'message_type':
4406
-                        unset($settings['message_type']);
4407
-                        break;
4408
-                    default:
4409
-                        $settings[ $key ] = $value;
4410
-                        break;
4411
-                }
4412
-            }
4413
-
4414
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4415
-        }
4416
-
4417
-        // okay we should have the data all setup.  Now we just update!
4418
-        $success = $this->_message_resource_manager->update_active_messengers_option();
4419
-
4420
-        if ($success) {
4421
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
4422
-        } else {
4423
-            EE_Error::add_error(
4424
-                esc_html__(
4425
-                    'Settings did not get updated',
4426
-                    'event_espresso'
4427
-                ),
4428
-                __FILE__,
4429
-                __FUNCTION__,
4430
-                __LINE__
4431
-            );
4432
-        }
4433
-
4434
-        $this->_template_args['success'] = $success;
4435
-        $this->_return_json();
4436
-    }
4437
-
4438
-
4439
-
4440
-
4441
-    /**  EE MESSAGE PROCESSING ACTIONS **/
4442
-
4443
-
4444
-    /**
4445
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4446
-     * However, this does not send immediately, it just queues for sending.
4447
-     *
4448
-     * @since 4.9.0
4449
-     * @throws EE_Error
4450
-     * @throws InvalidDataTypeException
4451
-     * @throws InvalidInterfaceException
4452
-     * @throws InvalidArgumentException
4453
-     * @throws ReflectionException
4454
-     */
4455
-    protected function _generate_now()
4456
-    {
4457
-        EED_Messages::generate_now($this->_get_msg_ids_from_request());
4458
-        $this->_redirect_after_action(false, '', '', array(), true);
4459
-    }
4460
-
4461
-
4462
-    /**
4463
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4464
-     * are EEM_Message::status_resend or EEM_Message::status_idle
4465
-     *
4466
-     * @since 4.9.0
4467
-     * @throws EE_Error
4468
-     * @throws InvalidDataTypeException
4469
-     * @throws InvalidInterfaceException
4470
-     * @throws InvalidArgumentException
4471
-     * @throws ReflectionException
4472
-     */
4473
-    protected function _generate_and_send_now()
4474
-    {
4475
-        EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4476
-        $this->_redirect_after_action(false, '', '', array(), true);
4477
-    }
4478
-
4479
-
4480
-    /**
4481
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4482
-     *
4483
-     * @since 4.9.0
4484
-     * @throws EE_Error
4485
-     * @throws InvalidDataTypeException
4486
-     * @throws InvalidInterfaceException
4487
-     * @throws InvalidArgumentException
4488
-     * @throws ReflectionException
4489
-     */
4490
-    protected function _queue_for_resending()
4491
-    {
4492
-        EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4493
-        $this->_redirect_after_action(false, '', '', array(), true);
4494
-    }
4495
-
4496
-
4497
-    /**
4498
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4499
-     *
4500
-     * @since 4.9.0
4501
-     * @throws EE_Error
4502
-     * @throws InvalidDataTypeException
4503
-     * @throws InvalidInterfaceException
4504
-     * @throws InvalidArgumentException
4505
-     * @throws ReflectionException
4506
-     */
4507
-    protected function _send_now()
4508
-    {
4509
-        EED_Messages::send_now($this->_get_msg_ids_from_request());
4510
-        $this->_redirect_after_action(false, '', '', array(), true);
4511
-    }
4512
-
4513
-
4514
-    /**
4515
-     * Deletes EE_messages for IDs in the request.
4516
-     *
4517
-     * @since 4.9.0
4518
-     * @throws EE_Error
4519
-     * @throws InvalidDataTypeException
4520
-     * @throws InvalidInterfaceException
4521
-     * @throws InvalidArgumentException
4522
-     */
4523
-    protected function _delete_ee_messages()
4524
-    {
4525
-        $msg_ids = $this->_get_msg_ids_from_request();
4526
-        $deleted_count = 0;
4527
-        foreach ($msg_ids as $msg_id) {
4528
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4529
-                $deleted_count++;
4530
-            }
4531
-        }
4532
-        if ($deleted_count) {
4533
-            EE_Error::add_success(
4534
-                esc_html(
4535
-                    _n(
4536
-                        'Message successfully deleted',
4537
-                        'Messages successfully deleted',
4538
-                        $deleted_count,
4539
-                        'event_espresso'
4540
-                    )
4541
-                )
4542
-            );
4543
-            $this->_redirect_after_action(
4544
-                false,
4545
-                '',
4546
-                '',
4547
-                array(),
4548
-                true
4549
-            );
4550
-        } else {
4551
-            EE_Error::add_error(
4552
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4553
-                __FILE__,
4554
-                __FUNCTION__,
4555
-                __LINE__
4556
-            );
4557
-            $this->_redirect_after_action(false, '', '', array(), true);
4558
-        }
4559
-    }
4560
-
4561
-
4562
-    /**
4563
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4564
-     *
4565
-     * @since 4.9.0
4566
-     * @return array
4567
-     */
4568
-    protected function _get_msg_ids_from_request()
4569
-    {
4570
-        if (! isset($this->_req_data['MSG_ID'])) {
4571
-            return array();
4572
-        }
4573
-
4574
-        return is_array($this->_req_data['MSG_ID'])
4575
-            ? array_keys($this->_req_data['MSG_ID'])
4576
-            : array($this->_req_data['MSG_ID']);
4577
-    }
2657
+		$output = ob_get_contents();
2658
+		ob_clean();
2659
+		$this->_context_switcher = $output;
2660
+	}
2661
+
2662
+
2663
+	/**
2664
+	 * utility for sanitizing new values coming in.
2665
+	 * Note: this is only used when updating a context.
2666
+	 *
2667
+	 * @access protected
2668
+	 *
2669
+	 * @param int $index This helps us know which template field to select from the request array.
2670
+	 *
2671
+	 * @return array
2672
+	 */
2673
+	protected function _set_message_template_column_values($index)
2674
+	{
2675
+		if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2676
+			foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2677
+				$this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2678
+			}
2679
+		}
2680
+
2681
+
2682
+		$set_column_values = array(
2683
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2684
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2685
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2686
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2687
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2688
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2689
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2690
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2691
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2692
+				? absint($this->_req_data['MTP_is_global'])
2693
+				: 0,
2694
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2695
+				? absint($this->_req_data['MTP_is_override'])
2696
+				: 0,
2697
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2698
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2699
+		);
2700
+
2701
+
2702
+		return $set_column_values;
2703
+	}
2704
+
2705
+
2706
+	protected function _insert_or_update_message_template($new = false)
2707
+	{
2708
+
2709
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2710
+		$success = 0;
2711
+		$override = false;
2712
+
2713
+		// setup notices description
2714
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2715
+
2716
+		// need the message type and messenger objects to be able to use the labels for the notices
2717
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2718
+		$messenger_label = $messenger_object instanceof EE_messenger
2719
+			? ucwords($messenger_object->label['singular'])
2720
+			: '';
2721
+
2722
+		$message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2723
+			? $this->_req_data['MTP_message_type']
2724
+			: '';
2725
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2726
+
2727
+		$message_type_label = $message_type_object instanceof EE_message_type
2728
+			? ucwords($message_type_object->label['singular'])
2729
+			: '';
2730
+
2731
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2732
+			? $this->_req_data['MTP_context']
2733
+			: '';
2734
+		$context = ucwords(str_replace('_', ' ', $context_slug));
2735
+
2736
+		$item_desc = $messenger_label && $message_type_label
2737
+			? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2738
+			: '';
2739
+		$item_desc .= 'Message Template';
2740
+		$query_args = array();
2741
+		$edit_array = array();
2742
+		$action_desc = '';
2743
+
2744
+		// if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2745
+		// user to edit.
2746
+		if ($new) {
2747
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2748
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2749
+				if (empty($edit_array)) {
2750
+					$success = 0;
2751
+				} else {
2752
+					$success = 1;
2753
+					$edit_array = $edit_array[0];
2754
+					$query_args = array(
2755
+						'id'      => $edit_array['GRP_ID'],
2756
+						'context' => $edit_array['MTP_context'],
2757
+						'action'  => 'edit_message_template',
2758
+					);
2759
+				}
2760
+			}
2761
+			$action_desc = 'created';
2762
+		} else {
2763
+			$MTPG = EEM_Message_Template_Group::instance();
2764
+			$MTP = EEM_Message_Template::instance();
2765
+
2766
+
2767
+			// run update for each template field in displayed context
2768
+			if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2769
+				EE_Error::add_error(
2770
+					esc_html__(
2771
+						'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2772
+						'event_espresso'
2773
+					),
2774
+					__FILE__,
2775
+					__FUNCTION__,
2776
+					__LINE__
2777
+				);
2778
+				$success = 0;
2779
+			} else {
2780
+				// first validate all fields!
2781
+				// this filter allows client code to add its own validation to the template fields as well.
2782
+				// returning an empty array means everything passed validation.
2783
+				// errors in validation should be represented in an array with the following shape:
2784
+				// array(
2785
+				//   'fieldname' => array(
2786
+				//          'msg' => 'error message'
2787
+				//          'value' => 'value for field producing error'
2788
+				// )
2789
+				$custom_validation = (array) apply_filters(
2790
+					'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2791
+					array(),
2792
+					$this->_req_data['MTP_template_fields'],
2793
+					$context_slug,
2794
+					$messenger_slug,
2795
+					$message_type_slug
2796
+				);
2797
+
2798
+				$system_validation = $MTPG->validate(
2799
+					$this->_req_data['MTP_template_fields'],
2800
+					$context_slug,
2801
+					$messenger_slug,
2802
+					$message_type_slug
2803
+				);
2804
+
2805
+				$system_validation = ! is_array($system_validation) && $system_validation ? array()
2806
+					: $system_validation;
2807
+				$validates = array_merge($custom_validation, $system_validation);
2808
+
2809
+				// if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2810
+				// appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2811
+				//  WE need to make sure there is no actual error messages in validates.
2812
+				if (is_array($validates) && ! empty($validates)) {
2813
+					// add the transient so when the form loads we know which fields to highlight
2814
+					$this->_add_transient('edit_message_template', $validates);
2815
+
2816
+					$success = 0;
2817
+
2818
+					// setup notices
2819
+					foreach ($validates as $field => $error) {
2820
+						if (isset($error['msg'])) {
2821
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2822
+						}
2823
+					}
2824
+				} else {
2825
+					$set_column_values = array();
2826
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2827
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2828
+
2829
+						$where_cols_n_values = array(
2830
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2831
+						);
2832
+						// if they aren't allowed to use all JS, restrict them to just posty-y tags
2833
+						if (! current_user_can('unfiltered_html')) {
2834
+							if (is_array($set_column_values['MTP_content'])) {
2835
+								foreach ($set_column_values['MTP_content'] as $key => $value) {
2836
+									// remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2837
+									// only removes slashes from double-quotes, so attributes using single quotes always
2838
+									// appear invalid.) But currently the models expect slashed data, so after wp_kses
2839
+									// runs we need to re-slash the data. Sheesh. See
2840
+									// https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2841
+									$set_column_values['MTP_content'][ $key ] = addslashes(
2842
+										wp_kses(
2843
+											stripslashes($value),
2844
+											wp_kses_allowed_html('post')
2845
+										)
2846
+									);
2847
+								}
2848
+							} else {
2849
+								$set_column_values['MTP_content'] = wp_kses(
2850
+									$set_column_values['MTP_content'],
2851
+									wp_kses_allowed_html('post')
2852
+								);
2853
+							}
2854
+						}
2855
+						$message_template_fields = array(
2856
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2857
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2858
+							'MTP_context'        => $set_column_values['MTP_context'],
2859
+							'MTP_content'        => $set_column_values['MTP_content'],
2860
+						);
2861
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2862
+							if ($updated === false) {
2863
+								EE_Error::add_error(
2864
+									sprintf(
2865
+										esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2866
+										$template_field
2867
+									),
2868
+									__FILE__,
2869
+									__FUNCTION__,
2870
+									__LINE__
2871
+								);
2872
+							} else {
2873
+								$success = 1;
2874
+							}
2875
+						} else {
2876
+							// only do this logic if we don't have a MTP_ID for this field
2877
+							if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2878
+								// this has already been through the template field validator and sanitized, so it will be
2879
+								// safe to insert this field.  Why insert?  This typically happens when we introduce a new
2880
+								// message template field in a messenger/message type and existing users don't have the
2881
+								// default setup for it.
2882
+								// @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2883
+								$updated = $MTP->insert($message_template_fields);
2884
+								if (! $updated || is_wp_error($updated)) {
2885
+									EE_Error::add_error(
2886
+										sprintf(
2887
+											esc_html__('%s field could not be updated.', 'event_espresso'),
2888
+											$template_field
2889
+										),
2890
+										__FILE__,
2891
+										__FUNCTION__,
2892
+										__LINE__
2893
+									);
2894
+									$success = 0;
2895
+								} else {
2896
+									$success = 1;
2897
+								}
2898
+							}
2899
+						}
2900
+						$action_desc = 'updated';
2901
+					}
2902
+
2903
+					// we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2904
+					$mtpg_fields = array(
2905
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2906
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2907
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2908
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2909
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2910
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2911
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2912
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2913
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2914
+							: '',
2915
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2916
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2917
+							: '',
2918
+					);
2919
+
2920
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2921
+					$updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2922
+
2923
+					if ($updated === false) {
2924
+						EE_Error::add_error(
2925
+							sprintf(
2926
+								esc_html__(
2927
+									'The Message Template Group (%d) was NOT updated for some reason',
2928
+									'event_espresso'
2929
+								),
2930
+								$set_column_values['GRP_ID']
2931
+							),
2932
+							__FILE__,
2933
+							__FUNCTION__,
2934
+							__LINE__
2935
+						);
2936
+					} else {
2937
+						// k now we need to ensure the template_pack and template_variation fields are set.
2938
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2939
+							? $this->_req_data['MTP_template_pack']
2940
+							: 'default';
2941
+
2942
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2943
+							? $this->_req_data['MTP_template_variation']
2944
+							: 'default';
2945
+
2946
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2947
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2948
+							$mtpg_obj->set_template_pack_name($template_pack);
2949
+							$mtpg_obj->set_template_pack_variation($template_variation);
2950
+						}
2951
+						$success = 1;
2952
+					}
2953
+				}
2954
+			}
2955
+		}
2956
+
2957
+		// we return things differently if doing ajax
2958
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2959
+			$this->_template_args['success'] = $success;
2960
+			$this->_template_args['error'] = ! $success ? true : false;
2961
+			$this->_template_args['content'] = '';
2962
+			$this->_template_args['data'] = array(
2963
+				'grpID'        => $edit_array['GRP_ID'],
2964
+				'templateName' => $edit_array['template_name'],
2965
+			);
2966
+			if ($success) {
2967
+				EE_Error::overwrite_success();
2968
+				EE_Error::add_success(
2969
+					esc_html__(
2970
+						'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.',
2971
+						'event_espresso'
2972
+					)
2973
+				);
2974
+			}
2975
+
2976
+			$this->_return_json();
2977
+		}
2978
+
2979
+
2980
+		// was a test send triggered?
2981
+		if (isset($this->_req_data['test_button'])) {
2982
+			EE_Error::overwrite_success();
2983
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2984
+			$override = true;
2985
+		}
2986
+
2987
+		if (empty($query_args)) {
2988
+			$query_args = array(
2989
+				'id'      => $this->_req_data['GRP_ID'],
2990
+				'context' => $context_slug,
2991
+				'action'  => 'edit_message_template',
2992
+			);
2993
+		}
2994
+
2995
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2996
+	}
2997
+
2998
+
2999
+	/**
3000
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
3001
+	 *
3002
+	 * @param  string $context      what context being tested
3003
+	 * @param  string $messenger    messenger being tested
3004
+	 * @param  string $message_type message type being tested
3005
+	 * @throws EE_Error
3006
+	 * @throws InvalidArgumentException
3007
+	 * @throws InvalidDataTypeException
3008
+	 * @throws InvalidInterfaceException
3009
+	 */
3010
+	protected function _do_test_send($context, $messenger, $message_type)
3011
+	{
3012
+		// set things up for preview
3013
+		$this->_req_data['messenger'] = $messenger;
3014
+		$this->_req_data['message_type'] = $message_type;
3015
+		$this->_req_data['context'] = $context;
3016
+		$this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
3017
+		$active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
3018
+
3019
+		// let's save any existing fields that might be required by the messenger
3020
+		if (isset($this->_req_data['test_settings_fld'])
3021
+			&& $active_messenger instanceof EE_messenger
3022
+			&& apply_filters(
3023
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3024
+				true,
3025
+				$this->_req_data['test_settings_fld'],
3026
+				$active_messenger
3027
+			)
3028
+		) {
3029
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
3030
+		}
3031
+
3032
+		/**
3033
+		 * Use filter to add additional controls on whether message can send or not
3034
+		 */
3035
+		if (apply_filters(
3036
+			'FHEE__Messages_Admin_Page__do_test_send__can_send',
3037
+			true,
3038
+			$context,
3039
+			$this->_req_data,
3040
+			$messenger,
3041
+			$message_type
3042
+		)) {
3043
+			if (EEM_Event::instance()->count() > 0) {
3044
+				$success = $this->_preview_message(true);
3045
+				if ($success) {
3046
+					EE_Error::add_success(__('Test message sent', 'event_espresso'));
3047
+				} else {
3048
+					EE_Error::add_error(
3049
+						esc_html__('The test message was not sent', 'event_espresso'),
3050
+						__FILE__,
3051
+						__FUNCTION__,
3052
+						__LINE__
3053
+					);
3054
+				}
3055
+			} else {
3056
+				$this->noEventsErrorMessage(true);
3057
+			}
3058
+		}
3059
+	}
3060
+
3061
+
3062
+	/**
3063
+	 * _generate_new_templates
3064
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3065
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3066
+	 * for the event.
3067
+	 *
3068
+	 *
3069
+	 * @param  string $messenger     the messenger we are generating templates for
3070
+	 * @param array   $message_types array of message types that the templates are generated for.
3071
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3072
+	 *                               indicate the message_template_group being used as the base.
3073
+	 *
3074
+	 * @param bool    $global
3075
+	 *
3076
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
3077
+	 *                               encountering problems.
3078
+	 * @throws EE_Error
3079
+	 */
3080
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3081
+	{
3082
+
3083
+		// if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3084
+		// just don't generate any templates.
3085
+		if (empty($message_types)) {
3086
+			return true;
3087
+		}
3088
+
3089
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3090
+	}
3091
+
3092
+
3093
+	/**
3094
+	 * [_trash_or_restore_message_template]
3095
+	 *
3096
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3097
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3098
+	 *                        an individual context (FALSE).
3099
+	 * @return void
3100
+	 * @throws EE_Error
3101
+	 * @throws InvalidArgumentException
3102
+	 * @throws InvalidDataTypeException
3103
+	 * @throws InvalidInterfaceException
3104
+	 */
3105
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
3106
+	{
3107
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3108
+		$MTP = EEM_Message_Template_Group::instance();
3109
+
3110
+		$success = 1;
3111
+
3112
+		// incoming GRP_IDs
3113
+		if ($all) {
3114
+			// Checkboxes
3115
+			if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3116
+				// if array has more than one element then success message should be plural.
3117
+				// todo: what about nonce?
3118
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3119
+
3120
+				// cycle through checkboxes
3121
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3122
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3123
+					if (! $trashed_or_restored) {
3124
+						$success = 0;
3125
+					}
3126
+				}
3127
+			} else {
3128
+				// grab single GRP_ID and handle
3129
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3130
+				if (! empty($GRP_ID)) {
3131
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3132
+					if (! $trashed_or_restored) {
3133
+						$success = 0;
3134
+					}
3135
+				} else {
3136
+					$success = 0;
3137
+				}
3138
+			}
3139
+		}
3140
+
3141
+		$action_desc = $trash
3142
+			? esc_html__('moved to the trash', 'event_espresso')
3143
+			: esc_html__('restored', 'event_espresso');
3144
+
3145
+		$action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3146
+
3147
+		$item_desc = $all ? _n(
3148
+			'Message Template Group',
3149
+			'Message Template Groups',
3150
+			$success,
3151
+			'event_espresso'
3152
+		) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3153
+
3154
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3155
+			'template',
3156
+			'templates',
3157
+			$success,
3158
+			'event_espresso'
3159
+		) : $item_desc;
3160
+
3161
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
3162
+	}
3163
+
3164
+
3165
+	/**
3166
+	 * [_delete_message_template]
3167
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3168
+	 *
3169
+	 * @return void
3170
+	 * @throws EE_Error
3171
+	 * @throws InvalidArgumentException
3172
+	 * @throws InvalidDataTypeException
3173
+	 * @throws InvalidInterfaceException
3174
+	 */
3175
+	protected function _delete_message_template()
3176
+	{
3177
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3178
+
3179
+		// checkboxes
3180
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3181
+			// if array has more than one element then success message should be plural
3182
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3183
+
3184
+			// cycle through bulk action checkboxes
3185
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3186
+				$success = $this->_delete_mtp_permanently($GRP_ID);
3187
+			}
3188
+		} else {
3189
+			// grab single grp_id and delete
3190
+			$GRP_ID = absint($this->_req_data['id']);
3191
+			$success = $this->_delete_mtp_permanently($GRP_ID);
3192
+		}
3193
+
3194
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3195
+	}
3196
+
3197
+
3198
+	/**
3199
+	 * helper for permanently deleting a mtP group and all related message_templates
3200
+	 *
3201
+	 * @param  int  $GRP_ID        The group being deleted
3202
+	 * @param  bool $include_group whether to delete the Message Template Group as well.
3203
+	 * @return bool boolean to indicate the success of the deletes or not.
3204
+	 * @throws EE_Error
3205
+	 * @throws InvalidArgumentException
3206
+	 * @throws InvalidDataTypeException
3207
+	 * @throws InvalidInterfaceException
3208
+	 */
3209
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3210
+	{
3211
+		$success = 1;
3212
+		$MTPG = EEM_Message_Template_Group::instance();
3213
+		// first let's GET this group
3214
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
3215
+		// then delete permanently all the related Message Templates
3216
+		$deleted = $MTG->delete_related_permanently('Message_Template');
3217
+
3218
+		if ($deleted === 0) {
3219
+			$success = 0;
3220
+		}
3221
+
3222
+		// now delete permanently this particular group
3223
+
3224
+		if ($include_group && ! $MTG->delete_permanently()) {
3225
+			$success = 0;
3226
+		}
3227
+
3228
+		return $success;
3229
+	}
3230
+
3231
+
3232
+	/**
3233
+	 *    _learn_more_about_message_templates_link
3234
+	 *
3235
+	 * @access protected
3236
+	 * @return string
3237
+	 */
3238
+	protected function _learn_more_about_message_templates_link()
3239
+	{
3240
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3241
+			   . esc_html__('learn more about how message templates works', 'event_espresso')
3242
+			   . '</a>';
3243
+	}
3244
+
3245
+
3246
+	/**
3247
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3248
+	 * ajax and other routes.
3249
+	 *
3250
+	 * @return void
3251
+	 * @throws DomainException
3252
+	 */
3253
+	protected function _settings()
3254
+	{
3255
+
3256
+
3257
+		$this->_set_m_mt_settings();
3258
+
3259
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3260
+			? $this->_req_data['selected_messenger']
3261
+			: 'email';
3262
+
3263
+		// let's setup the messenger tabs
3264
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3265
+			$this->_m_mt_settings['messenger_tabs'],
3266
+			'messenger_links',
3267
+			'|',
3268
+			$selected_messenger
3269
+		);
3270
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3271
+		$this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3272
+
3273
+		$this->display_admin_page_with_sidebar();
3274
+	}
3275
+
3276
+
3277
+	/**
3278
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3279
+	 *
3280
+	 * @access protected
3281
+	 * @return void
3282
+	 * @throws DomainException
3283
+	 */
3284
+	protected function _set_m_mt_settings()
3285
+	{
3286
+		// first if this is already set then lets get out no need to regenerate data.
3287
+		if (! empty($this->_m_mt_settings)) {
3288
+			return;
3289
+		}
3290
+
3291
+		// get all installed messengers and message_types
3292
+		/** @type EE_messenger[] $messengers */
3293
+		$messengers = $this->_message_resource_manager->installed_messengers();
3294
+		/** @type EE_message_type[] $message_types */
3295
+		$message_types = $this->_message_resource_manager->installed_message_types();
3296
+
3297
+
3298
+		// assemble the array for the _tab_text_links helper
3299
+
3300
+		foreach ($messengers as $messenger) {
3301
+			$this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3302
+				'label' => ucwords($messenger->label['singular']),
3303
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3304
+					? 'messenger-active'
3305
+					: '',
3306
+				'href'  => $messenger->name,
3307
+				'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3308
+				'slug'  => $messenger->name,
3309
+				'obj'   => $messenger,
3310
+			);
3311
+
3312
+
3313
+			$message_types_for_messenger = $messenger->get_valid_message_types();
3314
+
3315
+			foreach ($message_types as $message_type) {
3316
+				// first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3317
+				// it shouldn't show in either the inactive OR active metabox.
3318
+				if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3319
+					continue;
3320
+				}
3321
+
3322
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3323
+					$messenger->name,
3324
+					$message_type->name
3325
+				)
3326
+					? 'active'
3327
+					: 'inactive';
3328
+
3329
+				$this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3330
+					'label'    => ucwords($message_type->label['singular']),
3331
+					'class'    => 'message-type-' . $a_or_i,
3332
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3333
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3334
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3335
+					'title'    => $a_or_i === 'active'
3336
+						? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3337
+						: esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3338
+					'content'  => $a_or_i === 'active'
3339
+						? $this->_message_type_settings_content($message_type, $messenger, true)
3340
+						: $this->_message_type_settings_content($message_type, $messenger),
3341
+					'slug'     => $message_type->name,
3342
+					'active'   => $a_or_i === 'active',
3343
+					'obj'      => $message_type,
3344
+				);
3345
+			}
3346
+		}
3347
+	}
3348
+
3349
+
3350
+	/**
3351
+	 * This just prepares the content for the message type settings
3352
+	 *
3353
+	 * @param  EE_message_type $message_type The message type object
3354
+	 * @param  EE_messenger    $messenger    The messenger object
3355
+	 * @param  boolean         $active       Whether the message type is active or not
3356
+	 * @return string html output for the content
3357
+	 * @throws DomainException
3358
+	 */
3359
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
3360
+	{
3361
+		// get message type fields
3362
+		$fields = $message_type->get_admin_settings_fields();
3363
+		$settings_template_args['template_form_fields'] = '';
3364
+
3365
+		if (! empty($fields) && $active) {
3366
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3367
+			foreach ($fields as $fldname => $fldprops) {
3368
+				$field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3369
+				$template_form_field[ $field_id ] = array(
3370
+					'name'       => 'message_type_settings[' . $fldname . ']',
3371
+					'label'      => $fldprops['label'],
3372
+					'input'      => $fldprops['field_type'],
3373
+					'type'       => $fldprops['value_type'],
3374
+					'required'   => $fldprops['required'],
3375
+					'validation' => $fldprops['validation'],
3376
+					'value'      => isset($existing_settings[ $fldname ])
3377
+						? $existing_settings[ $fldname ]
3378
+						: $fldprops['default'],
3379
+					'options'    => isset($fldprops['options'])
3380
+						? $fldprops['options']
3381
+						: array(),
3382
+					'default'    => isset($existing_settings[ $fldname ])
3383
+						? $existing_settings[ $fldname ]
3384
+						: $fldprops['default'],
3385
+					'css_class'  => 'no-drag',
3386
+					'format'     => $fldprops['format'],
3387
+				);
3388
+			}
3389
+
3390
+
3391
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3392
+				? $this->_generate_admin_form_fields(
3393
+					$template_form_field,
3394
+					'string',
3395
+					'ee_mt_activate_form'
3396
+				)
3397
+				: '';
3398
+		}
3399
+
3400
+		$settings_template_args['description'] = $message_type->description;
3401
+		// we also need some hidden fields
3402
+		$settings_template_args['hidden_fields'] = array(
3403
+			'message_type_settings[messenger]'    => array(
3404
+				'type'  => 'hidden',
3405
+				'value' => $messenger->name,
3406
+			),
3407
+			'message_type_settings[message_type]' => array(
3408
+				'type'  => 'hidden',
3409
+				'value' => $message_type->name,
3410
+			),
3411
+			'type'                                => array(
3412
+				'type'  => 'hidden',
3413
+				'value' => 'message_type',
3414
+			),
3415
+		);
3416
+
3417
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3418
+			$settings_template_args['hidden_fields'],
3419
+			'array'
3420
+		);
3421
+		$settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3422
+			? ' hidden'
3423
+			: '';
3424
+
3425
+
3426
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3427
+		$content = EEH_Template::display_template($template, $settings_template_args, true);
3428
+
3429
+		return $content;
3430
+	}
3431
+
3432
+
3433
+	/**
3434
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
3435
+	 *
3436
+	 * @access protected
3437
+	 * @return void
3438
+	 * @throws DomainException
3439
+	 */
3440
+	protected function _messages_settings_metaboxes()
3441
+	{
3442
+		$this->_set_m_mt_settings();
3443
+		$m_boxes = $mt_boxes = array();
3444
+		$m_template_args = $mt_template_args = array();
3445
+
3446
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3447
+			? $this->_req_data['selected_messenger']
3448
+			: 'email';
3449
+
3450
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
3451
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3452
+				$hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3453
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3454
+				// messenger meta boxes
3455
+				$active = $selected_messenger === $messenger;
3456
+				$active_mt_tabs = isset(
3457
+					$this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3458
+				)
3459
+					? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3460
+					: '';
3461
+				$m_boxes[ $messenger . '_a_box' ] = sprintf(
3462
+					esc_html__('%s Settings', 'event_espresso'),
3463
+					$tab_array['label']
3464
+				);
3465
+				$m_template_args[ $messenger . '_a_box' ] = array(
3466
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3467
+					'inactive_message_types' => isset(
3468
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3469
+					)
3470
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3471
+						: '',
3472
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3473
+					'hidden'                 => $active ? '' : ' hidden',
3474
+					'hide_on_message'        => $hide_on_message,
3475
+					'messenger'              => $messenger,
3476
+					'active'                 => $active,
3477
+				);
3478
+				// message type meta boxes
3479
+				// (which is really just the inactive container for each messenger
3480
+				// showing inactive message types for that messenger)
3481
+				$mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3482
+				$mt_template_args[ $messenger . '_i_box' ] = array(
3483
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3484
+					'inactive_message_types' => isset(
3485
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3486
+					)
3487
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3488
+						: '',
3489
+					'hidden'                 => $active ? '' : ' hidden',
3490
+					'hide_on_message'        => $hide_on_message,
3491
+					'hide_off_message'       => $hide_off_message,
3492
+					'messenger'              => $messenger,
3493
+					'active'                 => $active,
3494
+				);
3495
+			}
3496
+		}
3497
+
3498
+
3499
+		// register messenger metaboxes
3500
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3501
+		foreach ($m_boxes as $box => $label) {
3502
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3503
+			$msgr = str_replace('_a_box', '', $box);
3504
+			add_meta_box(
3505
+				'espresso_' . $msgr . '_settings',
3506
+				$label,
3507
+				function ($post, $metabox) {
3508
+					echo EEH_Template::display_template(
3509
+						$metabox["args"]["template_path"],
3510
+						$metabox["args"]["template_args"],
3511
+						true
3512
+					);
3513
+				},
3514
+				$this->_current_screen->id,
3515
+				'normal',
3516
+				'high',
3517
+				$callback_args
3518
+			);
3519
+		}
3520
+
3521
+		// register message type metaboxes
3522
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3523
+		foreach ($mt_boxes as $box => $label) {
3524
+			$callback_args = array(
3525
+				'template_path' => $mt_template_path,
3526
+				'template_args' => $mt_template_args[ $box ],
3527
+			);
3528
+			$mt = str_replace('_i_box', '', $box);
3529
+			add_meta_box(
3530
+				'espresso_' . $mt . '_inactive_mts',
3531
+				$label,
3532
+				function ($post, $metabox) {
3533
+					echo EEH_Template::display_template(
3534
+						$metabox["args"]["template_path"],
3535
+						$metabox["args"]["template_args"],
3536
+						true
3537
+					);
3538
+				},
3539
+				$this->_current_screen->id,
3540
+				'side',
3541
+				'high',
3542
+				$callback_args
3543
+			);
3544
+		}
3545
+
3546
+		// register metabox for global messages settings but only when on the main site.  On single site installs this
3547
+		// will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3548
+		if (is_main_site()) {
3549
+			add_meta_box(
3550
+				'espresso_global_message_settings',
3551
+				esc_html__('Global Message Settings', 'event_espresso'),
3552
+				array($this, 'global_messages_settings_metabox_content'),
3553
+				$this->_current_screen->id,
3554
+				'normal',
3555
+				'low',
3556
+				array()
3557
+			);
3558
+		}
3559
+	}
3560
+
3561
+
3562
+	/**
3563
+	 *  This generates the content for the global messages settings metabox.
3564
+	 *
3565
+	 * @return string
3566
+	 * @throws EE_Error
3567
+	 * @throws InvalidArgumentException
3568
+	 * @throws ReflectionException
3569
+	 * @throws InvalidDataTypeException
3570
+	 * @throws InvalidInterfaceException
3571
+	 */
3572
+	public function global_messages_settings_metabox_content()
3573
+	{
3574
+		$form = $this->_generate_global_settings_form();
3575
+		echo $form->form_open(
3576
+			$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3577
+			'POST'
3578
+		)
3579
+			 . $form->get_html()
3580
+			 . $form->form_close();
3581
+	}
3582
+
3583
+
3584
+	/**
3585
+	 * This generates and returns the form object for the global messages settings.
3586
+	 *
3587
+	 * @return EE_Form_Section_Proper
3588
+	 * @throws EE_Error
3589
+	 * @throws InvalidArgumentException
3590
+	 * @throws ReflectionException
3591
+	 * @throws InvalidDataTypeException
3592
+	 * @throws InvalidInterfaceException
3593
+	 */
3594
+	protected function _generate_global_settings_form()
3595
+	{
3596
+		EE_Registry::instance()->load_helper('HTML');
3597
+		/** @var EE_Network_Core_Config $network_config */
3598
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3599
+
3600
+		return new EE_Form_Section_Proper(
3601
+			array(
3602
+				'name'            => 'global_messages_settings',
3603
+				'html_id'         => 'global_messages_settings',
3604
+				'html_class'      => 'form-table',
3605
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3606
+				'subsections'     => apply_filters(
3607
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3608
+					array(
3609
+						'do_messages_on_same_request' => new EE_Select_Input(
3610
+							array(
3611
+								true  => esc_html__("On the same request", "event_espresso"),
3612
+								false => esc_html__("On a separate request", "event_espresso"),
3613
+							),
3614
+							array(
3615
+								'default'         => $network_config->do_messages_on_same_request,
3616
+								'html_label_text' => esc_html__(
3617
+									'Generate and send all messages:',
3618
+									'event_espresso'
3619
+								),
3620
+								'html_help_text'  => esc_html__(
3621
+									'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.',
3622
+									'event_espresso'
3623
+								),
3624
+							)
3625
+						),
3626
+						'delete_threshold'            => new EE_Select_Input(
3627
+							array(
3628
+								0  => esc_html__('Forever', 'event_espresso'),
3629
+								3  => esc_html__('3 Months', 'event_espresso'),
3630
+								6  => esc_html__('6 Months', 'event_espresso'),
3631
+								9  => esc_html__('9 Months', 'event_espresso'),
3632
+								12 => esc_html__('12 Months', 'event_espresso'),
3633
+								24 => esc_html__('24 Months', 'event_espresso'),
3634
+								36 => esc_html__('36 Months', 'event_espresso'),
3635
+							),
3636
+							array(
3637
+								'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3638
+								'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3639
+								'html_help_text'  => esc_html__(
3640
+									'You can control how long a record of processed messages is kept via this option.',
3641
+									'event_espresso'
3642
+								),
3643
+							)
3644
+						),
3645
+						'update_settings'             => new EE_Submit_Input(
3646
+							array(
3647
+								'default'         => esc_html__('Update', 'event_espresso'),
3648
+								'html_label_text' => '&nbsp',
3649
+							)
3650
+						),
3651
+					)
3652
+				),
3653
+			)
3654
+		);
3655
+	}
3656
+
3657
+
3658
+	/**
3659
+	 * This handles updating the global settings set on the admin page.
3660
+	 *
3661
+	 * @throws EE_Error
3662
+	 * @throws InvalidDataTypeException
3663
+	 * @throws InvalidInterfaceException
3664
+	 * @throws InvalidArgumentException
3665
+	 * @throws ReflectionException
3666
+	 */
3667
+	protected function _update_global_settings()
3668
+	{
3669
+		/** @var EE_Network_Core_Config $network_config */
3670
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3671
+		$messages_config = EE_Registry::instance()->CFG->messages;
3672
+		$form = $this->_generate_global_settings_form();
3673
+		if ($form->was_submitted()) {
3674
+			$form->receive_form_submission();
3675
+			if ($form->is_valid()) {
3676
+				$valid_data = $form->valid_data();
3677
+				foreach ($valid_data as $property => $value) {
3678
+					$setter = 'set_' . $property;
3679
+					if (method_exists($network_config, $setter)) {
3680
+						$network_config->{$setter}($value);
3681
+					} elseif (property_exists($network_config, $property)
3682
+						&& $network_config->{$property} !== $value
3683
+					) {
3684
+						$network_config->{$property} = $value;
3685
+					} elseif (property_exists($messages_config, $property)
3686
+						&& $messages_config->{$property} !== $value
3687
+					) {
3688
+						$messages_config->{$property} = $value;
3689
+					}
3690
+				}
3691
+				// only update if the form submission was valid!
3692
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3693
+				EE_Registry::instance()->CFG->update_espresso_config();
3694
+				EE_Error::overwrite_success();
3695
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3696
+			}
3697
+		}
3698
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3699
+	}
3700
+
3701
+
3702
+	/**
3703
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3704
+	 *
3705
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3706
+	 * @return string html formatted tabs
3707
+	 * @throws DomainException
3708
+	 */
3709
+	protected function _get_mt_tabs($tab_array)
3710
+	{
3711
+		$tab_array = (array) $tab_array;
3712
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3713
+		$tabs = '';
3714
+
3715
+		foreach ($tab_array as $tab) {
3716
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3717
+		}
3718
+
3719
+		return $tabs;
3720
+	}
3721
+
3722
+
3723
+	/**
3724
+	 * This prepares the content of the messenger meta box admin settings
3725
+	 *
3726
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3727
+	 * @return string html formatted content
3728
+	 * @throws DomainException
3729
+	 */
3730
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3731
+	{
3732
+
3733
+		$fields = $messenger->get_admin_settings_fields();
3734
+		$settings_template_args['template_form_fields'] = '';
3735
+
3736
+		// is $messenger active?
3737
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3738
+
3739
+
3740
+		if (! empty($fields)) {
3741
+			$existing_settings = $messenger->get_existing_admin_settings();
3742
+
3743
+			foreach ($fields as $fldname => $fldprops) {
3744
+				$field_id = $messenger->name . '-' . $fldname;
3745
+				$template_form_field[ $field_id ] = array(
3746
+					'name'       => 'messenger_settings[' . $field_id . ']',
3747
+					'label'      => $fldprops['label'],
3748
+					'input'      => $fldprops['field_type'],
3749
+					'type'       => $fldprops['value_type'],
3750
+					'required'   => $fldprops['required'],
3751
+					'validation' => $fldprops['validation'],
3752
+					'value'      => isset($existing_settings[ $field_id ])
3753
+						? $existing_settings[ $field_id ]
3754
+						: $fldprops['default'],
3755
+					'css_class'  => '',
3756
+					'format'     => $fldprops['format'],
3757
+				);
3758
+			}
3759
+
3760
+
3761
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3762
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3763
+				: '';
3764
+		}
3765
+
3766
+		// we also need some hidden fields
3767
+		$settings_template_args['hidden_fields'] = array(
3768
+			'messenger_settings[messenger]' => array(
3769
+				'type'  => 'hidden',
3770
+				'value' => $messenger->name,
3771
+			),
3772
+			'type'                          => array(
3773
+				'type'  => 'hidden',
3774
+				'value' => 'messenger',
3775
+			),
3776
+		);
3777
+
3778
+		// make sure any active message types that are existing are included in the hidden fields
3779
+		if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3780
+			foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3781
+				$settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3782
+					'type'  => 'hidden',
3783
+					'value' => $mt,
3784
+				);
3785
+			}
3786
+		}
3787
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3788
+			$settings_template_args['hidden_fields'],
3789
+			'array'
3790
+		);
3791
+		$active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3792
+
3793
+		$settings_template_args['messenger'] = $messenger->name;
3794
+		$settings_template_args['description'] = $messenger->description;
3795
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3796
+
3797
+
3798
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3799
+			$messenger->name
3800
+		)
3801
+			? $settings_template_args['show_hide_edit_form']
3802
+			: ' hidden';
3803
+
3804
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3805
+			? ' hidden'
3806
+			: $settings_template_args['show_hide_edit_form'];
3807
+
3808
+
3809
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3810
+		$settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3811
+		$settings_template_args['on_off_status'] = $active ? true : false;
3812
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3813
+		$content = EEH_Template::display_template(
3814
+			$template,
3815
+			$settings_template_args,
3816
+			true
3817
+		);
3818
+
3819
+		return $content;
3820
+	}
3821
+
3822
+
3823
+	/**
3824
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3825
+	 *
3826
+	 * @throws DomainException
3827
+	 * @throws EE_Error
3828
+	 * @throws InvalidDataTypeException
3829
+	 * @throws InvalidInterfaceException
3830
+	 * @throws InvalidArgumentException
3831
+	 * @throws ReflectionException
3832
+	 */
3833
+	public function activate_messenger_toggle()
3834
+	{
3835
+		$success = true;
3836
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3837
+		// let's check that we have required data
3838
+		if (! isset($this->_req_data['messenger'])) {
3839
+			EE_Error::add_error(
3840
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3841
+				__FILE__,
3842
+				__FUNCTION__,
3843
+				__LINE__
3844
+			);
3845
+			$success = false;
3846
+		}
3847
+
3848
+		// do a nonce check here since we're not arriving via a normal route
3849
+		$nonce = isset($this->_req_data['activate_nonce'])
3850
+			? sanitize_text_field($this->_req_data['activate_nonce'])
3851
+			: '';
3852
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3853
+
3854
+		$this->_verify_nonce($nonce, $nonce_ref);
3855
+
3856
+
3857
+		if (! isset($this->_req_data['status'])) {
3858
+			EE_Error::add_error(
3859
+				esc_html__(
3860
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3861
+					'event_espresso'
3862
+				),
3863
+				__FILE__,
3864
+				__FUNCTION__,
3865
+				__LINE__
3866
+			);
3867
+			$success = false;
3868
+		}
3869
+
3870
+		// do check to verify we have a valid status.
3871
+		$status = $this->_req_data['status'];
3872
+
3873
+		if ($status !== 'off' && $status !== 'on') {
3874
+			EE_Error::add_error(
3875
+				sprintf(
3876
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3877
+					$this->_req_data['status']
3878
+				),
3879
+				__FILE__,
3880
+				__FUNCTION__,
3881
+				__LINE__
3882
+			);
3883
+			$success = false;
3884
+		}
3885
+
3886
+		if ($success) {
3887
+			// made it here?  Stop dawdling then!!
3888
+			$success = $status === 'off'
3889
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3890
+				: $this->_activate_messenger($this->_req_data['messenger']);
3891
+		}
3892
+
3893
+		$this->_template_args['success'] = $success;
3894
+
3895
+		// no special instructions so let's just do the json return (which should automatically do all the special stuff).
3896
+		$this->_return_json();
3897
+	}
3898
+
3899
+
3900
+	/**
3901
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3902
+	 *
3903
+	 * @throws DomainException
3904
+	 * @throws EE_Error
3905
+	 * @throws ReflectionException
3906
+	 * @throws InvalidDataTypeException
3907
+	 * @throws InvalidInterfaceException
3908
+	 * @throws InvalidArgumentException
3909
+	 */
3910
+	public function activate_mt_toggle()
3911
+	{
3912
+		$success = true;
3913
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3914
+
3915
+		// let's make sure we have the necessary data
3916
+		if (! isset($this->_req_data['message_type'])) {
3917
+			EE_Error::add_error(
3918
+				esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3919
+				__FILE__,
3920
+				__FUNCTION__,
3921
+				__LINE__
3922
+			);
3923
+			$success = false;
3924
+		}
3925
+
3926
+		if (! isset($this->_req_data['messenger'])) {
3927
+			EE_Error::add_error(
3928
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3929
+				__FILE__,
3930
+				__FUNCTION__,
3931
+				__LINE__
3932
+			);
3933
+			$success = false;
3934
+		}
3935
+
3936
+		if (! isset($this->_req_data['status'])) {
3937
+			EE_Error::add_error(
3938
+				esc_html__(
3939
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3940
+					'event_espresso'
3941
+				),
3942
+				__FILE__,
3943
+				__FUNCTION__,
3944
+				__LINE__
3945
+			);
3946
+			$success = false;
3947
+		}
3948
+
3949
+
3950
+		// do check to verify we have a valid status.
3951
+		$status = $this->_req_data['status'];
3952
+
3953
+		if ($status !== 'activate' && $status !== 'deactivate') {
3954
+			EE_Error::add_error(
3955
+				sprintf(
3956
+					esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3957
+					$this->_req_data['status']
3958
+				),
3959
+				__FILE__,
3960
+				__FUNCTION__,
3961
+				__LINE__
3962
+			);
3963
+			$success = false;
3964
+		}
3965
+
3966
+
3967
+		// do a nonce check here since we're not arriving via a normal route
3968
+		$nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3969
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3970
+
3971
+		$this->_verify_nonce($nonce, $nonce_ref);
3972
+
3973
+		if ($success) {
3974
+			// made it here? um, what are you waiting for then?
3975
+			$success = $status === 'deactivate'
3976
+				? $this->_deactivate_message_type_for_messenger(
3977
+					$this->_req_data['messenger'],
3978
+					$this->_req_data['message_type']
3979
+				)
3980
+				: $this->_activate_message_type_for_messenger(
3981
+					$this->_req_data['messenger'],
3982
+					$this->_req_data['message_type']
3983
+				);
3984
+		}
3985
+
3986
+		$this->_template_args['success'] = $success;
3987
+		$this->_return_json();
3988
+	}
3989
+
3990
+
3991
+	/**
3992
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
3993
+	 *
3994
+	 * @param string $messenger_name The name of the messenger being activated
3995
+	 * @return bool
3996
+	 * @throws DomainException
3997
+	 * @throws EE_Error
3998
+	 * @throws InvalidArgumentException
3999
+	 * @throws ReflectionException
4000
+	 * @throws InvalidDataTypeException
4001
+	 * @throws InvalidInterfaceException
4002
+	 */
4003
+	protected function _activate_messenger($messenger_name)
4004
+	{
4005
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4006
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4007
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger
4008
+			? $active_messenger->get_default_message_types()
4009
+			: array();
4010
+
4011
+		// ensure is active
4012
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
4013
+
4014
+		// set response_data for reload
4015
+		foreach ($message_types_to_activate as $message_type_name) {
4016
+			/** @var EE_message_type $message_type */
4017
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4018
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4019
+				$messenger_name,
4020
+				$message_type_name
4021
+			)
4022
+				&& $message_type instanceof EE_message_type
4023
+			) {
4024
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
4025
+				if ($message_type->get_admin_settings_fields()) {
4026
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
4027
+				}
4028
+			}
4029
+		}
4030
+
4031
+		// add success message for activating messenger
4032
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4033
+	}
4034
+
4035
+
4036
+	/**
4037
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
4038
+	 *
4039
+	 * @param string $messenger_name The name of the messenger being activated
4040
+	 * @return bool
4041
+	 * @throws DomainException
4042
+	 * @throws EE_Error
4043
+	 * @throws InvalidArgumentException
4044
+	 * @throws ReflectionException
4045
+	 * @throws InvalidDataTypeException
4046
+	 * @throws InvalidInterfaceException
4047
+	 */
4048
+	protected function _deactivate_messenger($messenger_name)
4049
+	{
4050
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4051
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4052
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
4053
+
4054
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4055
+	}
4056
+
4057
+
4058
+	/**
4059
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4060
+	 *
4061
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
4062
+	 * @param string $message_type_name The name of the message type being activated for the messenger
4063
+	 * @return bool
4064
+	 * @throws DomainException
4065
+	 * @throws EE_Error
4066
+	 * @throws InvalidArgumentException
4067
+	 * @throws ReflectionException
4068
+	 * @throws InvalidDataTypeException
4069
+	 * @throws InvalidInterfaceException
4070
+	 */
4071
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4072
+	{
4073
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4074
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4075
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4076
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4077
+
4078
+		// ensure is active
4079
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
4080
+
4081
+		// set response for load
4082
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4083
+			$messenger_name,
4084
+			$message_type_name
4085
+		)
4086
+		) {
4087
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
4088
+			if ($message_type_to_activate->get_admin_settings_fields()) {
4089
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
4090
+			}
4091
+		}
4092
+
4093
+		return $this->_setup_response_message_for_activating_messenger_with_message_types(
4094
+			$active_messenger,
4095
+			$message_type_to_activate
4096
+		);
4097
+	}
4098
+
4099
+
4100
+	/**
4101
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4102
+	 *
4103
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4104
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
4105
+	 * @return bool
4106
+	 * @throws DomainException
4107
+	 * @throws EE_Error
4108
+	 * @throws InvalidArgumentException
4109
+	 * @throws ReflectionException
4110
+	 * @throws InvalidDataTypeException
4111
+	 * @throws InvalidInterfaceException
4112
+	 */
4113
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4114
+	{
4115
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4116
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4117
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4118
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4119
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4120
+
4121
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4122
+			$active_messenger,
4123
+			$message_type_to_deactivate
4124
+		);
4125
+	}
4126
+
4127
+
4128
+	/**
4129
+	 * This just initializes the defaults for activating messenger and message type responses.
4130
+	 */
4131
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
4132
+	{
4133
+		$this->_template_args['data']['active_mts'] = array();
4134
+		$this->_template_args['data']['mt_reload'] = array();
4135
+	}
4136
+
4137
+
4138
+	/**
4139
+	 * Setup appropriate response for activating a messenger and/or message types
4140
+	 *
4141
+	 * @param EE_messenger         $messenger
4142
+	 * @param EE_message_type|null $message_type
4143
+	 * @return bool
4144
+	 * @throws DomainException
4145
+	 * @throws EE_Error
4146
+	 * @throws InvalidArgumentException
4147
+	 * @throws ReflectionException
4148
+	 * @throws InvalidDataTypeException
4149
+	 * @throws InvalidInterfaceException
4150
+	 */
4151
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
4152
+		$messenger,
4153
+		EE_Message_Type $message_type = null
4154
+	) {
4155
+		// if $messenger isn't a valid messenger object then get out.
4156
+		if (! $messenger instanceof EE_Messenger) {
4157
+			EE_Error::add_error(
4158
+				esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4159
+				__FILE__,
4160
+				__FUNCTION__,
4161
+				__LINE__
4162
+			);
4163
+
4164
+			return false;
4165
+		}
4166
+		// activated
4167
+		if ($this->_template_args['data']['active_mts']) {
4168
+			EE_Error::overwrite_success();
4169
+			// activated a message type with the messenger
4170
+			if ($message_type instanceof EE_message_type) {
4171
+				EE_Error::add_success(
4172
+					sprintf(
4173
+						esc_html__(
4174
+							'%s message type has been successfully activated with the %s messenger',
4175
+							'event_espresso'
4176
+						),
4177
+						ucwords($message_type->label['singular']),
4178
+						ucwords($messenger->label['singular'])
4179
+					)
4180
+				);
4181
+
4182
+				// if message type was invoice then let's make sure we activate the invoice payment method.
4183
+				if ($message_type->name === 'invoice') {
4184
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
4185
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4186
+					if ($pm instanceof EE_Payment_Method) {
4187
+						EE_Error::add_attention(
4188
+							esc_html__(
4189
+								'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.',
4190
+								'event_espresso'
4191
+							)
4192
+						);
4193
+					}
4194
+				}
4195
+				// just toggles the entire messenger
4196
+			} else {
4197
+				EE_Error::add_success(
4198
+					sprintf(
4199
+						esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4200
+						ucwords($messenger->label['singular'])
4201
+					)
4202
+				);
4203
+			}
4204
+
4205
+			return true;
4206
+
4207
+			// possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4208
+			// message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4209
+			// in which case we just give a success message for the messenger being successfully activated.
4210
+		} else {
4211
+			if (! $messenger->get_default_message_types()) {
4212
+				// messenger doesn't have any default message types so still a success.
4213
+				EE_Error::add_success(
4214
+					sprintf(
4215
+						esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4216
+						ucwords($messenger->label['singular'])
4217
+					)
4218
+				);
4219
+
4220
+				return true;
4221
+			} else {
4222
+				EE_Error::add_error(
4223
+					$message_type instanceof EE_message_type
4224
+						? sprintf(
4225
+							esc_html__(
4226
+								'%s message type was not successfully activated with the %s messenger',
4227
+								'event_espresso'
4228
+							),
4229
+							ucwords($message_type->label['singular']),
4230
+							ucwords($messenger->label['singular'])
4231
+						)
4232
+						: sprintf(
4233
+							esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4234
+							ucwords($messenger->label['singular'])
4235
+						),
4236
+					__FILE__,
4237
+					__FUNCTION__,
4238
+					__LINE__
4239
+				);
4240
+
4241
+				return false;
4242
+			}
4243
+		}
4244
+	}
4245
+
4246
+
4247
+	/**
4248
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
4249
+	 *
4250
+	 * @param EE_messenger         $messenger
4251
+	 * @param EE_message_type|null $message_type
4252
+	 * @return bool
4253
+	 * @throws DomainException
4254
+	 * @throws EE_Error
4255
+	 * @throws InvalidArgumentException
4256
+	 * @throws ReflectionException
4257
+	 * @throws InvalidDataTypeException
4258
+	 * @throws InvalidInterfaceException
4259
+	 */
4260
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4261
+		$messenger,
4262
+		EE_message_type $message_type = null
4263
+	) {
4264
+		EE_Error::overwrite_success();
4265
+
4266
+		// if $messenger isn't a valid messenger object then get out.
4267
+		if (! $messenger instanceof EE_Messenger) {
4268
+			EE_Error::add_error(
4269
+				esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4270
+				__FILE__,
4271
+				__FUNCTION__,
4272
+				__LINE__
4273
+			);
4274
+
4275
+			return false;
4276
+		}
4277
+
4278
+		if ($message_type instanceof EE_message_type) {
4279
+			$message_type_name = $message_type->name;
4280
+			EE_Error::add_success(
4281
+				sprintf(
4282
+					esc_html__(
4283
+						'%s message type has been successfully deactivated for the %s messenger.',
4284
+						'event_espresso'
4285
+					),
4286
+					ucwords($message_type->label['singular']),
4287
+					ucwords($messenger->label['singular'])
4288
+				)
4289
+			);
4290
+		} else {
4291
+			$message_type_name = '';
4292
+			EE_Error::add_success(
4293
+				sprintf(
4294
+					esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4295
+					ucwords($messenger->label['singular'])
4296
+				)
4297
+			);
4298
+		}
4299
+
4300
+		// if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4301
+		if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4302
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
4303
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4304
+			if ($count_updated > 0) {
4305
+				$msg = $message_type_name === 'invoice'
4306
+					? esc_html__(
4307
+						'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.',
4308
+						'event_espresso'
4309
+					)
4310
+					: esc_html__(
4311
+						'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.',
4312
+						'event_espresso'
4313
+					);
4314
+				EE_Error::add_attention($msg);
4315
+			}
4316
+		}
4317
+
4318
+		return true;
4319
+	}
4320
+
4321
+
4322
+	/**
4323
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4324
+	 *
4325
+	 * @throws DomainException
4326
+	 */
4327
+	public function update_mt_form()
4328
+	{
4329
+		if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4330
+			EE_Error::add_error(
4331
+				esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4332
+				__FILE__,
4333
+				__FUNCTION__,
4334
+				__LINE__
4335
+			);
4336
+			$this->_return_json();
4337
+		}
4338
+
4339
+		$message_types = $this->get_installed_message_types();
4340
+
4341
+		$message_type = $message_types[ $this->_req_data['message_type'] ];
4342
+		$messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4343
+
4344
+		$content = $this->_message_type_settings_content(
4345
+			$message_type,
4346
+			$messenger,
4347
+			true
4348
+		);
4349
+		$this->_template_args['success'] = true;
4350
+		$this->_template_args['content'] = $content;
4351
+		$this->_return_json();
4352
+	}
4353
+
4354
+
4355
+	/**
4356
+	 * this handles saving the settings for a messenger or message type
4357
+	 *
4358
+	 */
4359
+	public function save_settings()
4360
+	{
4361
+		if (! isset($this->_req_data['type'])) {
4362
+			EE_Error::add_error(
4363
+				esc_html__(
4364
+					'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4365
+					'event_espresso'
4366
+				),
4367
+				__FILE__,
4368
+				__FUNCTION__,
4369
+				__LINE__
4370
+			);
4371
+			$this->_template_args['error'] = true;
4372
+			$this->_return_json();
4373
+		}
4374
+
4375
+
4376
+		if ($this->_req_data['type'] === 'messenger') {
4377
+			// this should be an array.
4378
+			$settings = $this->_req_data['messenger_settings'];
4379
+			$messenger = $settings['messenger'];
4380
+			// let's setup the settings data
4381
+			foreach ($settings as $key => $value) {
4382
+				switch ($key) {
4383
+					case 'messenger':
4384
+						unset($settings['messenger']);
4385
+						break;
4386
+					case 'message_types':
4387
+						unset($settings['message_types']);
4388
+						break;
4389
+					default:
4390
+						$settings[ $key ] = $value;
4391
+						break;
4392
+				}
4393
+			}
4394
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4395
+		} elseif ($this->_req_data['type'] === 'message_type') {
4396
+			$settings = $this->_req_data['message_type_settings'];
4397
+			$messenger = $settings['messenger'];
4398
+			$message_type = $settings['message_type'];
4399
+
4400
+			foreach ($settings as $key => $value) {
4401
+				switch ($key) {
4402
+					case 'messenger':
4403
+						unset($settings['messenger']);
4404
+						break;
4405
+					case 'message_type':
4406
+						unset($settings['message_type']);
4407
+						break;
4408
+					default:
4409
+						$settings[ $key ] = $value;
4410
+						break;
4411
+				}
4412
+			}
4413
+
4414
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4415
+		}
4416
+
4417
+		// okay we should have the data all setup.  Now we just update!
4418
+		$success = $this->_message_resource_manager->update_active_messengers_option();
4419
+
4420
+		if ($success) {
4421
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
4422
+		} else {
4423
+			EE_Error::add_error(
4424
+				esc_html__(
4425
+					'Settings did not get updated',
4426
+					'event_espresso'
4427
+				),
4428
+				__FILE__,
4429
+				__FUNCTION__,
4430
+				__LINE__
4431
+			);
4432
+		}
4433
+
4434
+		$this->_template_args['success'] = $success;
4435
+		$this->_return_json();
4436
+	}
4437
+
4438
+
4439
+
4440
+
4441
+	/**  EE MESSAGE PROCESSING ACTIONS **/
4442
+
4443
+
4444
+	/**
4445
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4446
+	 * However, this does not send immediately, it just queues for sending.
4447
+	 *
4448
+	 * @since 4.9.0
4449
+	 * @throws EE_Error
4450
+	 * @throws InvalidDataTypeException
4451
+	 * @throws InvalidInterfaceException
4452
+	 * @throws InvalidArgumentException
4453
+	 * @throws ReflectionException
4454
+	 */
4455
+	protected function _generate_now()
4456
+	{
4457
+		EED_Messages::generate_now($this->_get_msg_ids_from_request());
4458
+		$this->_redirect_after_action(false, '', '', array(), true);
4459
+	}
4460
+
4461
+
4462
+	/**
4463
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4464
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
4465
+	 *
4466
+	 * @since 4.9.0
4467
+	 * @throws EE_Error
4468
+	 * @throws InvalidDataTypeException
4469
+	 * @throws InvalidInterfaceException
4470
+	 * @throws InvalidArgumentException
4471
+	 * @throws ReflectionException
4472
+	 */
4473
+	protected function _generate_and_send_now()
4474
+	{
4475
+		EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4476
+		$this->_redirect_after_action(false, '', '', array(), true);
4477
+	}
4478
+
4479
+
4480
+	/**
4481
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4482
+	 *
4483
+	 * @since 4.9.0
4484
+	 * @throws EE_Error
4485
+	 * @throws InvalidDataTypeException
4486
+	 * @throws InvalidInterfaceException
4487
+	 * @throws InvalidArgumentException
4488
+	 * @throws ReflectionException
4489
+	 */
4490
+	protected function _queue_for_resending()
4491
+	{
4492
+		EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4493
+		$this->_redirect_after_action(false, '', '', array(), true);
4494
+	}
4495
+
4496
+
4497
+	/**
4498
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4499
+	 *
4500
+	 * @since 4.9.0
4501
+	 * @throws EE_Error
4502
+	 * @throws InvalidDataTypeException
4503
+	 * @throws InvalidInterfaceException
4504
+	 * @throws InvalidArgumentException
4505
+	 * @throws ReflectionException
4506
+	 */
4507
+	protected function _send_now()
4508
+	{
4509
+		EED_Messages::send_now($this->_get_msg_ids_from_request());
4510
+		$this->_redirect_after_action(false, '', '', array(), true);
4511
+	}
4512
+
4513
+
4514
+	/**
4515
+	 * Deletes EE_messages for IDs in the request.
4516
+	 *
4517
+	 * @since 4.9.0
4518
+	 * @throws EE_Error
4519
+	 * @throws InvalidDataTypeException
4520
+	 * @throws InvalidInterfaceException
4521
+	 * @throws InvalidArgumentException
4522
+	 */
4523
+	protected function _delete_ee_messages()
4524
+	{
4525
+		$msg_ids = $this->_get_msg_ids_from_request();
4526
+		$deleted_count = 0;
4527
+		foreach ($msg_ids as $msg_id) {
4528
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4529
+				$deleted_count++;
4530
+			}
4531
+		}
4532
+		if ($deleted_count) {
4533
+			EE_Error::add_success(
4534
+				esc_html(
4535
+					_n(
4536
+						'Message successfully deleted',
4537
+						'Messages successfully deleted',
4538
+						$deleted_count,
4539
+						'event_espresso'
4540
+					)
4541
+				)
4542
+			);
4543
+			$this->_redirect_after_action(
4544
+				false,
4545
+				'',
4546
+				'',
4547
+				array(),
4548
+				true
4549
+			);
4550
+		} else {
4551
+			EE_Error::add_error(
4552
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4553
+				__FILE__,
4554
+				__FUNCTION__,
4555
+				__LINE__
4556
+			);
4557
+			$this->_redirect_after_action(false, '', '', array(), true);
4558
+		}
4559
+	}
4560
+
4561
+
4562
+	/**
4563
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4564
+	 *
4565
+	 * @since 4.9.0
4566
+	 * @return array
4567
+	 */
4568
+	protected function _get_msg_ids_from_request()
4569
+	{
4570
+		if (! isset($this->_req_data['MSG_ID'])) {
4571
+			return array();
4572
+		}
4573
+
4574
+		return is_array($this->_req_data['MSG_ID'])
4575
+			? array_keys($this->_req_data['MSG_ID'])
4576
+			: array($this->_req_data['MSG_ID']);
4577
+	}
4578 4578
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -38,103 +38,103 @@
 block discarded – undo
38 38
  * @since           4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.4.0');
65
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.4.0');
65
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
-        /**
98
-         * espresso_version
99
-         * Returns the plugin version
100
-         *
101
-         * @return string
102
-         */
103
-        function espresso_version()
104
-        {
105
-            return apply_filters('FHEE__espresso__espresso_version', '4.10.4.rc.022');
106
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
+		/**
98
+		 * espresso_version
99
+		 * Returns the plugin version
100
+		 *
101
+		 * @return string
102
+		 */
103
+		function espresso_version()
104
+		{
105
+			return apply_filters('FHEE__espresso__espresso_version', '4.10.4.rc.022');
106
+		}
107 107
 
108
-        /**
109
-         * espresso_plugin_activation
110
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
-         */
112
-        function espresso_plugin_activation()
113
-        {
114
-            update_option('ee_espresso_activation', true);
115
-        }
108
+		/**
109
+		 * espresso_plugin_activation
110
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
+		 */
112
+		function espresso_plugin_activation()
113
+		{
114
+			update_option('ee_espresso_activation', true);
115
+		}
116 116
 
117
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
117
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118 118
 
119
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
120
-        bootstrap_espresso();
121
-    }
119
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
120
+		bootstrap_espresso();
121
+	}
122 122
 }
123 123
 if (! function_exists('espresso_deactivate_plugin')) {
124
-    /**
125
-     *    deactivate_plugin
126
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
-     *
128
-     * @access public
129
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
-     * @return    void
131
-     */
132
-    function espresso_deactivate_plugin($plugin_basename = '')
133
-    {
134
-        if (! function_exists('deactivate_plugins')) {
135
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
-        }
137
-        unset($_GET['activate'], $_REQUEST['activate']);
138
-        deactivate_plugins($plugin_basename);
139
-    }
124
+	/**
125
+	 *    deactivate_plugin
126
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
+	 *
128
+	 * @access public
129
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
+	 * @return    void
131
+	 */
132
+	function espresso_deactivate_plugin($plugin_basename = '')
133
+	{
134
+		if (! function_exists('deactivate_plugins')) {
135
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
+		}
137
+		unset($_GET['activate'], $_REQUEST['activate']);
138
+		deactivate_plugins($plugin_basename);
139
+	}
140 140
 }
Please login to merge, or discard this patch.
core/libraries/messages/EE_messenger.lib.php 2 patches
Indentation   +722 added lines, -722 removed lines patch added patch discarded remove patch
@@ -18,182 +18,182 @@  discard block
 block discarded – undo
18 18
 
19 19
 
20 20
 
21
-    /**
22
-     * This property holds the default message types associated with this messenger when it is activated. The values of the array must match a valid message type.
23
-     * This property gets set by the _set_default_message_types() method.
24
-     *
25
-     * @var array
26
-     */
27
-    protected $_default_message_types = array();
21
+	/**
22
+	 * This property holds the default message types associated with this messenger when it is activated. The values of the array must match a valid message type.
23
+	 * This property gets set by the _set_default_message_types() method.
24
+	 *
25
+	 * @var array
26
+	 */
27
+	protected $_default_message_types = array();
28 28
 
29 29
 
30 30
 
31 31
 
32
-    /**
33
-     * This property holds the message types that are valid for use with this messenger.
34
-     * It gets set by the _set_valid_message_types() method.
35
-     *
36
-     * @var array
37
-     */
38
-    protected $_valid_message_types = array();
32
+	/**
33
+	 * This property holds the message types that are valid for use with this messenger.
34
+	 * It gets set by the _set_valid_message_types() method.
35
+	 *
36
+	 * @var array
37
+	 */
38
+	protected $_valid_message_types = array();
39 39
 
40 40
 
41 41
 
42
-    /**
43
-     * Holds the configuration for the EE_Messages_Validator class to know how to validated the different fields. Note that the Validator will match each field here with the allowed shortcodes set in the "valid_shortcodes" array for the matched message type context.  So message types don't need to set a $_validator_config property.
44
-     *
45
-     * Remember, ALL fields must be declared in this array.  However, an empty value for the field means that the field will accept all valid shortcodes set for the given context in the message type (by default).
46
-     *
47
-     * Array should be in this format:
48
-     *
49
-     * array(
50
-     *  'field_name(i.e.to)' => array(
51
-     *      'shortcodes' => array('email'), //an array of shortcode groups (correspond to EE_Shortcodes library class) that are allowed in the field. Typically you can just include $this->_valid_shortcodes['field_name'] as the value here (because they will match).
52
-     *      'specific_shortcodes' => array( array('[EVENT_AUTHOR_EMAIL]' => __('Admin Email', 'event_espresso')), //if this index is present you can further restrict the field to ONLY specific shortcodes if an entire group isn't sufficient. Specific shortcodes need to be listed as an array with the index the shortcode and the value = the label.
53
-     *      'type' => 'email' //this is the field type and should match one of the validator types (see EE_Messages_Validator::validator() for all the possible types).  If not required you can just leave empty.,
54
-     *      'required' => array'[SHORTCODE]') //this is used to indicate the shortcodes that MUST be in the assembled array of shortcodes by the validator in order for this field to be included in validation.  Otherwise the validator will always assign shortcodes for this field (regardless of whether the field settings for the given messenger/message_type/context use the field or not.).. please note, this does NOT mean that the shortcodes listed here MUST be in the given field.
55
-     *  )
56
-     * )
57
-     *
58
-     * @var array
59
-     */
60
-    protected $_validator_config = array();
42
+	/**
43
+	 * Holds the configuration for the EE_Messages_Validator class to know how to validated the different fields. Note that the Validator will match each field here with the allowed shortcodes set in the "valid_shortcodes" array for the matched message type context.  So message types don't need to set a $_validator_config property.
44
+	 *
45
+	 * Remember, ALL fields must be declared in this array.  However, an empty value for the field means that the field will accept all valid shortcodes set for the given context in the message type (by default).
46
+	 *
47
+	 * Array should be in this format:
48
+	 *
49
+	 * array(
50
+	 *  'field_name(i.e.to)' => array(
51
+	 *      'shortcodes' => array('email'), //an array of shortcode groups (correspond to EE_Shortcodes library class) that are allowed in the field. Typically you can just include $this->_valid_shortcodes['field_name'] as the value here (because they will match).
52
+	 *      'specific_shortcodes' => array( array('[EVENT_AUTHOR_EMAIL]' => __('Admin Email', 'event_espresso')), //if this index is present you can further restrict the field to ONLY specific shortcodes if an entire group isn't sufficient. Specific shortcodes need to be listed as an array with the index the shortcode and the value = the label.
53
+	 *      'type' => 'email' //this is the field type and should match one of the validator types (see EE_Messages_Validator::validator() for all the possible types).  If not required you can just leave empty.,
54
+	 *      'required' => array'[SHORTCODE]') //this is used to indicate the shortcodes that MUST be in the assembled array of shortcodes by the validator in order for this field to be included in validation.  Otherwise the validator will always assign shortcodes for this field (regardless of whether the field settings for the given messenger/message_type/context use the field or not.).. please note, this does NOT mean that the shortcodes listed here MUST be in the given field.
55
+	 *  )
56
+	 * )
57
+	 *
58
+	 * @var array
59
+	 */
60
+	protected $_validator_config = array();
61 61
 
62 62
 
63 63
 
64
-    /**
65
-     * This will hold the EEM_message_templates model for interacting with the database and retrieving active templates for the messenger
66
-     * @var object
67
-     */
68
-    protected $_EEM_data;
64
+	/**
65
+	 * This will hold the EEM_message_templates model for interacting with the database and retrieving active templates for the messenger
66
+	 * @var object
67
+	 */
68
+	protected $_EEM_data;
69 69
 
70 70
 
71 71
 
72
-    /**
73
-     * this property just holds an array of the various template refs.
74
-     * @var array
75
-     */
76
-    protected $_template_fields = array();
72
+	/**
73
+	 * this property just holds an array of the various template refs.
74
+	 * @var array
75
+	 */
76
+	protected $_template_fields = array();
77 77
 
78 78
 
79 79
 
80 80
 
81
-    /**
82
-     * This holds an array of the arguments used in parsing a template for the sender.
83
-     * @var array
84
-     */
85
-    protected $_template_args = array();
81
+	/**
82
+	 * This holds an array of the arguments used in parsing a template for the sender.
83
+	 * @var array
84
+	 */
85
+	protected $_template_args = array();
86 86
 
87 87
 
88 88
 
89 89
 
90 90
 
91 91
 
92
-    /**
93
-     * This property will hold the configuration for any test settings fields that are required for the "test" button that is used to trigger an actual test of this messenger
94
-     *
95
-     * @protected
96
-     * @var array
97
-     */
98
-    protected $_test_settings_fields = array();
92
+	/**
93
+	 * This property will hold the configuration for any test settings fields that are required for the "test" button that is used to trigger an actual test of this messenger
94
+	 *
95
+	 * @protected
96
+	 * @var array
97
+	 */
98
+	protected $_test_settings_fields = array();
99 99
 
100 100
 
101 101
 
102 102
 
103 103
 
104 104
 
105
-    /**
106
-     * This will hold the EE_Messages_Template_Pack object when set on the messenger.  This is set via the validate and setup method which grabs the template pack from the incoming messages object.
107
-     *
108
-     * @since 4.5.0
109
-     *
110
-     * @var EE_Messages_Template_Pack
111
-     */
112
-    protected $_tmp_pack;
105
+	/**
106
+	 * This will hold the EE_Messages_Template_Pack object when set on the messenger.  This is set via the validate and setup method which grabs the template pack from the incoming messages object.
107
+	 *
108
+	 * @since 4.5.0
109
+	 *
110
+	 * @var EE_Messages_Template_Pack
111
+	 */
112
+	protected $_tmp_pack;
113 113
 
114 114
 
115 115
 
116 116
 
117
-    /**
118
-     * This will hold the variation to use when performing a send.  It is set via the validate and setup method which grabs the variation from the incoming messages object on the send method.
119
-     *
120
-     * @since 4.5.0
121
-     *
122
-     * @var string
123
-     */
124
-    protected $_variation;
117
+	/**
118
+	 * This will hold the variation to use when performing a send.  It is set via the validate and setup method which grabs the variation from the incoming messages object on the send method.
119
+	 *
120
+	 * @since 4.5.0
121
+	 *
122
+	 * @var string
123
+	 */
124
+	protected $_variation;
125 125
 
126 126
 
127 127
 
128 128
 
129 129
 
130
-    /**
131
-     * This property is a stdClass that holds labels for all the various supporting properties for this messenger.  These labels are set via the _set_supports_labels() method in children classes. Initially this will include the label for:
132
-     *
133
-     *  - template pack
134
-     *  - template variation
135
-     *
136
-     * @since 4.5.0
137
-     *
138
-     * @var stdClass
139
-     */
140
-    protected $_supports_labels;
130
+	/**
131
+	 * This property is a stdClass that holds labels for all the various supporting properties for this messenger.  These labels are set via the _set_supports_labels() method in children classes. Initially this will include the label for:
132
+	 *
133
+	 *  - template pack
134
+	 *  - template variation
135
+	 *
136
+	 * @since 4.5.0
137
+	 *
138
+	 * @var stdClass
139
+	 */
140
+	protected $_supports_labels;
141 141
 
142 142
 
143 143
 
144 144
 
145 145
 
146
-    /**
147
-     * This property is set when the send_message() method is called and holds the Message Type used to generate templates with this messenger for the messages.
148
-     *
149
-     * @var EE_message_type
150
-     */
151
-    protected $_incoming_message_type;
146
+	/**
147
+	 * This property is set when the send_message() method is called and holds the Message Type used to generate templates with this messenger for the messages.
148
+	 *
149
+	 * @var EE_message_type
150
+	 */
151
+	protected $_incoming_message_type;
152 152
 
153 153
 
154 154
 
155
-    /**
156
-     * This flag sets whether a messenger is activated by default  on installation (or reactivation) of EE core or not.
157
-     *
158
-     * @var bool
159
-     */
160
-    public $activate_on_install = false;
155
+	/**
156
+	 * This flag sets whether a messenger is activated by default  on installation (or reactivation) of EE core or not.
157
+	 *
158
+	 * @var bool
159
+	 */
160
+	public $activate_on_install = false;
161 161
 
162 162
 
163 163
 
164 164
 
165 165
 
166
-    public function __construct()
167
-    {
168
-        $this->_EEM_data = EEM_Message_Template_Group::instance();
169
-        $this->_messages_item_type = 'messenger';
166
+	public function __construct()
167
+	{
168
+		$this->_EEM_data = EEM_Message_Template_Group::instance();
169
+		$this->_messages_item_type = 'messenger';
170 170
 
171
-        parent::__construct();
171
+		parent::__construct();
172 172
 
173
-        $this->_set_test_settings_fields();
174
-        $this->_set_template_fields();
175
-        $this->_set_default_message_types();
176
-        $this->_set_valid_message_types();
177
-        $this->_set_validator_config();
173
+		$this->_set_test_settings_fields();
174
+		$this->_set_template_fields();
175
+		$this->_set_default_message_types();
176
+		$this->_set_valid_message_types();
177
+		$this->_set_validator_config();
178 178
 
179 179
 
180
-        $this->_supports_labels = new stdClass();
181
-        $this->_set_supports_labels();
182
-    }
180
+		$this->_supports_labels = new stdClass();
181
+		$this->_set_supports_labels();
182
+	}
183 183
 
184 184
 
185 185
 
186 186
 
187 187
 
188
-    /**
189
-     * _set_template_fields
190
-     * This sets up the fields that a messenger requires for the message to go out.
191
-     *
192
-     * @abstract
193
-     * @access  protected
194
-     * @return void
195
-     */
196
-    abstract protected function _set_template_fields();
188
+	/**
189
+	 * _set_template_fields
190
+	 * This sets up the fields that a messenger requires for the message to go out.
191
+	 *
192
+	 * @abstract
193
+	 * @access  protected
194
+	 * @return void
195
+	 */
196
+	abstract protected function _set_template_fields();
197 197
 
198 198
 
199 199
 
@@ -203,14 +203,14 @@  discard block
 block discarded – undo
203 203
 
204 204
 
205 205
 
206
-    /**
207
-     * This method sets the _default_message_type property (see definition in docs attached to property)
208
-     *
209
-     * @abstract
210
-     * @access protected
211
-     * @return void
212
-     */
213
-    abstract protected function _set_default_message_types();
206
+	/**
207
+	 * This method sets the _default_message_type property (see definition in docs attached to property)
208
+	 *
209
+	 * @abstract
210
+	 * @access protected
211
+	 * @return void
212
+	 */
213
+	abstract protected function _set_default_message_types();
214 214
 
215 215
 
216 216
 
@@ -218,15 +218,15 @@  discard block
 block discarded – undo
218 218
 
219 219
 
220 220
 
221
-    /**
222
-     * Sets the _valid_message_types property (see definition in cods attached to property)
223
-     *
224
-     * @since 4.5.0
225
-     *
226
-     * @abstract
227
-     * @return void
228
-     */
229
-    abstract protected function _set_valid_message_types();
221
+	/**
222
+	 * Sets the _valid_message_types property (see definition in cods attached to property)
223
+	 *
224
+	 * @since 4.5.0
225
+	 *
226
+	 * @abstract
227
+	 * @return void
228
+	 */
229
+	abstract protected function _set_valid_message_types();
230 230
 
231 231
 
232 232
 
@@ -234,171 +234,171 @@  discard block
 block discarded – undo
234 234
 
235 235
 
236 236
 
237
-    /**
238
-     * Child classes must declare the $_validator_config property using this method.
239
-     * See comments for $_validator_config for details on what it is used for.
240
-     *
241
-     * NOTE:  messengers should set an array of valid shortcodes for ALL scenarios.  The corresponding validator class (validators/{messenger}) can be used to restrict only certain shortcodes per template so users cannot add certain shortcodes.
242
-     *
243
-     * @access protected
244
-     * @return void
245
-     */
246
-    abstract protected function _set_validator_config();
237
+	/**
238
+	 * Child classes must declare the $_validator_config property using this method.
239
+	 * See comments for $_validator_config for details on what it is used for.
240
+	 *
241
+	 * NOTE:  messengers should set an array of valid shortcodes for ALL scenarios.  The corresponding validator class (validators/{messenger}) can be used to restrict only certain shortcodes per template so users cannot add certain shortcodes.
242
+	 *
243
+	 * @access protected
244
+	 * @return void
245
+	 */
246
+	abstract protected function _set_validator_config();
247 247
 
248 248
 
249 249
 
250 250
 
251 251
 
252 252
 
253
-    /**
254
-     * We just deliver the messages don't kill us!!  This method will need to be modified by child classes for whatever action is taken to actually send a message.
255
-     *
256
-     * @return bool|WP_Error
257
-     * @throw \Exception
258
-     */
259
-    abstract protected function _send_message();
253
+	/**
254
+	 * We just deliver the messages don't kill us!!  This method will need to be modified by child classes for whatever action is taken to actually send a message.
255
+	 *
256
+	 * @return bool|WP_Error
257
+	 * @throw \Exception
258
+	 */
259
+	abstract protected function _send_message();
260 260
 
261 261
 
262 262
 
263 263
 
264
-    /**
265
-     * We give you pretty previews of the messages!
266
-     * @return string html body for message content.
267
-     */
268
-    abstract protected function _preview();
264
+	/**
265
+	 * We give you pretty previews of the messages!
266
+	 * @return string html body for message content.
267
+	 */
268
+	abstract protected function _preview();
269 269
 
270 270
 
271 271
 
272 272
 
273
-    /**
274
-     * Used by messengers (or preview) for enqueueing any scripts or styles need in message generation.
275
-     *
276
-     * @since 4.5.0
277
-     *
278
-     * @return void
279
-     */
280
-    public function enqueue_scripts_styles()
281
-    {
282
-        do_action('AHEE__EE_messenger__enqueue_scripts_styles');
283
-    }
273
+	/**
274
+	 * Used by messengers (or preview) for enqueueing any scripts or styles need in message generation.
275
+	 *
276
+	 * @since 4.5.0
277
+	 *
278
+	 * @return void
279
+	 */
280
+	public function enqueue_scripts_styles()
281
+	{
282
+		do_action('AHEE__EE_messenger__enqueue_scripts_styles');
283
+	}
284 284
 
285 285
 
286 286
 
287 287
 
288 288
 
289
-    /**
290
-     * This is used to indicate whether a messenger must be sent immediately or not.
291
-     * eg. The HTML messenger will override this to return true because it should be displayed in user's browser right
292
-     * away.  The PDF messenger is similar.
293
-     *
294
-     * This flag thus overrides any priorities that may be set on the message type used to generate the message.
295
-     *
296
-     * Default for this is false.  So children classes must override this if they want a message to be executed immediately.
297
-     *
298
-     * @since  4.9.0
299
-     * @return bool
300
-     */
301
-    public function send_now()
302
-    {
303
-        return false;
304
-    }
289
+	/**
290
+	 * This is used to indicate whether a messenger must be sent immediately or not.
291
+	 * eg. The HTML messenger will override this to return true because it should be displayed in user's browser right
292
+	 * away.  The PDF messenger is similar.
293
+	 *
294
+	 * This flag thus overrides any priorities that may be set on the message type used to generate the message.
295
+	 *
296
+	 * Default for this is false.  So children classes must override this if they want a message to be executed immediately.
297
+	 *
298
+	 * @since  4.9.0
299
+	 * @return bool
300
+	 */
301
+	public function send_now()
302
+	{
303
+		return false;
304
+	}
305 305
 
306 306
 
307 307
 
308 308
 
309 309
 
310
-    /**
311
-     * This is a way for a messenger to indicate whether it allows an empty to field or not.
312
-     * Note: If the generated message is a for a preview, this value is ignored.
313
-     * @since 4.9.0
314
-     * @return bool
315
-     */
316
-    public function allow_empty_to_field()
317
-    {
318
-        return false;
319
-    }
310
+	/**
311
+	 * This is a way for a messenger to indicate whether it allows an empty to field or not.
312
+	 * Note: If the generated message is a for a preview, this value is ignored.
313
+	 * @since 4.9.0
314
+	 * @return bool
315
+	 */
316
+	public function allow_empty_to_field()
317
+	{
318
+		return false;
319
+	}
320 320
 
321 321
 
322 322
 
323 323
 
324 324
 
325
-    /**
326
-     * Sets the defaults for the _supports_labels property.  Can be overridden by child classes.
327
-     * @see property definition for info on how its formatted.
328
-     *
329
-     * @since 4.5.0;
330
-     * @return void
331
-     */
332
-    protected function _set_supports_labels()
333
-    {
334
-        $this->_set_supports_labels_defaults();
335
-    }
325
+	/**
326
+	 * Sets the defaults for the _supports_labels property.  Can be overridden by child classes.
327
+	 * @see property definition for info on how its formatted.
328
+	 *
329
+	 * @since 4.5.0;
330
+	 * @return void
331
+	 */
332
+	protected function _set_supports_labels()
333
+	{
334
+		$this->_set_supports_labels_defaults();
335
+	}
336 336
 
337 337
 
338 338
 
339 339
 
340 340
 
341
-    /**
342
-     * Sets the defaults for the _supports_labels property.
343
-     *
344
-     * @since 4.5.0
345
-     *
346
-     * @return void
347
-     */
348
-    private function _set_supports_labels_defaults()
349
-    {
350
-        $this->_supports_labels->template_pack = __('Template Structure', 'event_espresso');
351
-        $this->_supports_labels->template_variation = __('Template Style', 'event_espresso');
352
-        $this->_supports_labels->template_pack_description = __('Template Structure options are bundled structural changes for templates.', 'event_espresso');
341
+	/**
342
+	 * Sets the defaults for the _supports_labels property.
343
+	 *
344
+	 * @since 4.5.0
345
+	 *
346
+	 * @return void
347
+	 */
348
+	private function _set_supports_labels_defaults()
349
+	{
350
+		$this->_supports_labels->template_pack = __('Template Structure', 'event_espresso');
351
+		$this->_supports_labels->template_variation = __('Template Style', 'event_espresso');
352
+		$this->_supports_labels->template_pack_description = __('Template Structure options are bundled structural changes for templates.', 'event_espresso');
353 353
 
354
-        $this->_supports_labels->template_variation_description = __('These are different styles to choose from for the selected template structure.  Usually these affect things like font style, color, borders etc.  In some cases the styles will also make minor layout changes.', 'event_espresso');
354
+		$this->_supports_labels->template_variation_description = __('These are different styles to choose from for the selected template structure.  Usually these affect things like font style, color, borders etc.  In some cases the styles will also make minor layout changes.', 'event_espresso');
355 355
 
356
-        $this->_supports_labels = apply_filters('FHEE__EE_messenger___set_supports_labels_defaults___supports_labels', $this->_supports_labels, $this);
357
-    }
356
+		$this->_supports_labels = apply_filters('FHEE__EE_messenger___set_supports_labels_defaults___supports_labels', $this->_supports_labels, $this);
357
+	}
358 358
 
359 359
 
360 360
 
361 361
 
362 362
 
363
-    /**
364
-     * This returns the _supports_labels property.
365
-     *
366
-     * @since 4.5.0
367
-     *
368
-     * @return stdClass
369
-     */
370
-    public function get_supports_labels()
371
-    {
372
-        if (empty($this->_supports_labels->template_pack) || empty($this->_supports_labels->template_variation)) {
373
-            $this->_set_supports_labels_defaults();
374
-        }
375
-        return apply_filters('FHEE__EE_messenger__get_supports_labels', $this->_supports_labels, $this);
376
-    }
363
+	/**
364
+	 * This returns the _supports_labels property.
365
+	 *
366
+	 * @since 4.5.0
367
+	 *
368
+	 * @return stdClass
369
+	 */
370
+	public function get_supports_labels()
371
+	{
372
+		if (empty($this->_supports_labels->template_pack) || empty($this->_supports_labels->template_variation)) {
373
+			$this->_set_supports_labels_defaults();
374
+		}
375
+		return apply_filters('FHEE__EE_messenger__get_supports_labels', $this->_supports_labels, $this);
376
+	}
377 377
 
378 378
 
379 379
 
380 380
 
381
-    /**
382
-     * Used to retrieve a variation (typically the path/url to a css file)
383
-     *
384
-     * @since 4.5.0
385
-     *
386
-     * @param EE_Messages_Template_Pack $pack   The template pack used for retrieving the variation.
387
-     * @param string                    $message_type_name The name property of the message type that we need the variation for.
388
-     * @param bool                      $url   Whether to return url (true) or path (false). Default is false.
389
-     * @param string                    $type What variation type to return. Default is 'main'.
390
-     * @param string               $variation What variation for the template pack
391
-     * @param bool             $skip_filters This allows messengers to add a filter for another messengers get_variation but call skip filters on the callback so there is no recursion on apply_filters.
392
-     *
393
-     * @return string                    path or url for the requested variation.
394
-     */
395
-    public function get_variation(EE_Messages_Template_Pack $pack, $message_type_name, $url = false, $type = 'main', $variation = 'default', $skip_filters = false)
396
-    {
397
-        $this->_tmp_pack = $pack;
398
-        $variation_path = apply_filters('EE_messenger__get_variation__variation', false, $pack, $this->name, $message_type_name, $url, $type, $variation, $skip_filters);
399
-        $variation_path = empty($variation_path) ? $this->_tmp_pack->get_variation($this->name, $message_type_name, $type, $variation, $url, '.css', $skip_filters) : $variation_path;
400
-        return $variation_path;
401
-    }
381
+	/**
382
+	 * Used to retrieve a variation (typically the path/url to a css file)
383
+	 *
384
+	 * @since 4.5.0
385
+	 *
386
+	 * @param EE_Messages_Template_Pack $pack   The template pack used for retrieving the variation.
387
+	 * @param string                    $message_type_name The name property of the message type that we need the variation for.
388
+	 * @param bool                      $url   Whether to return url (true) or path (false). Default is false.
389
+	 * @param string                    $type What variation type to return. Default is 'main'.
390
+	 * @param string               $variation What variation for the template pack
391
+	 * @param bool             $skip_filters This allows messengers to add a filter for another messengers get_variation but call skip filters on the callback so there is no recursion on apply_filters.
392
+	 *
393
+	 * @return string                    path or url for the requested variation.
394
+	 */
395
+	public function get_variation(EE_Messages_Template_Pack $pack, $message_type_name, $url = false, $type = 'main', $variation = 'default', $skip_filters = false)
396
+	{
397
+		$this->_tmp_pack = $pack;
398
+		$variation_path = apply_filters('EE_messenger__get_variation__variation', false, $pack, $this->name, $message_type_name, $url, $type, $variation, $skip_filters);
399
+		$variation_path = empty($variation_path) ? $this->_tmp_pack->get_variation($this->name, $message_type_name, $type, $variation, $url, '.css', $skip_filters) : $variation_path;
400
+		return $variation_path;
401
+	}
402 402
 
403 403
 
404 404
 
@@ -406,479 +406,479 @@  discard block
 block discarded – undo
406 406
 
407 407
 
408 408
 
409
-    /**
410
-     * This just returns the default message types associated with this messenger when it is first activated.
411
-     *
412
-     * @access public
413
-     * @return array
414
-     */
415
-    public function get_default_message_types()
416
-    {
417
-        $class = get_class($this);
409
+	/**
410
+	 * This just returns the default message types associated with this messenger when it is first activated.
411
+	 *
412
+	 * @access public
413
+	 * @return array
414
+	 */
415
+	public function get_default_message_types()
416
+	{
417
+		$class = get_class($this);
418 418
 
419
-        // messenger specific filter
420
-        $default_types = apply_filters('FHEE__' . $class . '__get_default_message_types__default_types', $this->_default_message_types, $this);
419
+		// messenger specific filter
420
+		$default_types = apply_filters('FHEE__' . $class . '__get_default_message_types__default_types', $this->_default_message_types, $this);
421 421
 
422
-        // all messengers filter
423
-        $default_types = apply_filters('FHEE__EE_messenger__get_default_message_types__default_types', $default_types, $this);
424
-        return $default_types;
425
-    }
422
+		// all messengers filter
423
+		$default_types = apply_filters('FHEE__EE_messenger__get_default_message_types__default_types', $default_types, $this);
424
+		return $default_types;
425
+	}
426 426
 
427 427
 
428 428
 
429 429
 
430
-    /**
431
-     * Returns the valid message types associated with this messenger.
432
-     *
433
-     * @since 4.5.0
434
-     *
435
-     * @return array
436
-     */
437
-    public function get_valid_message_types()
438
-    {
439
-        $class = get_class($this);
440
-
441
-        // messenger specific filter
442
-        // messenger specific filter
443
-        $valid_types = apply_filters('FHEE__' . $class . '__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
444
-
445
-        // all messengers filter
446
-        $valid_types = apply_filters('FHEE__EE_messenger__get_valid_message_types__valid_types', $valid_types, $this);
447
-        return $valid_types;
448
-    }
449
-
450
-
451
-
452
-
453
-
454
-    /**
455
-     * this is just used by the custom validators (EE_Messages_Validator classes) to modify the _validator_config for certain message_type/messenger combos where a context may only use certain shortcodes etc.
456
-     *
457
-     * @access public
458
-     * @param array $new_config Whatever is put in here will reset the _validator_config property
459
-     */
460
-    public function set_validator_config($new_config)
461
-    {
462
-        $this->_validator_config = $new_config;
463
-    }
464
-
465
-
466
-
467
-
468
-    /**
469
-     * This returns the _validator_config property
470
-     *
471
-     * @access public
472
-     * @return array
473
-     */
474
-    public function get_validator_config()
475
-    {
476
-        $class = get_class($this);
477
-
478
-        $config = apply_filters('FHEE__' . $class . '__get_validator_config', $this->_validator_config, $this);
479
-        $config = apply_filters('FHEE__EE_messenger__get_validator_config', $config, $this);
480
-        return $config;
481
-    }
482
-
483
-
484
-
485
-
486
-    /**
487
-     * this public method accepts a page slug (for an EE_admin page) and will return the response from the child class callback function if that page is registered via the `_admin_registered_page` property set by the child class.
488
-     *
489
-     * @param string $page the slug of the EE admin page
490
-     * @param array $message_types an array of active message type objects
491
-     * @param string $action the page action (to allow for more specific handling - i.e. edit vs. add pages)
492
-     * @param array $extra  This is just an extra argument that can be used to pass additional data for setting up page content.
493
-     * @access public
494
-     * @return string content for page
495
-     */
496
-    public function get_messenger_admin_page_content($page, $action = null, $extra = array(), $message_types = array())
497
-    {
498
-        return $this->_get_admin_page_content($page, $action, $extra, $message_types);
499
-    }
500
-
501
-
502
-
503
-    /**
504
-     * @param $message_types
505
-     * @param array $extra
506
-     * @return mixed|string
507
-     */
508
-    protected function _get_admin_content_events_edit($message_types, $extra)
509
-    {
510
-        // defaults
511
-        $template_args = array();
512
-        $selector_rows = '';
513
-
514
-        // we don't need message types here so we're just going to ignore. we do, however, expect the event id here. The event id is needed to provide a link to setup a custom template for this event.
515
-        $event_id = isset($extra['event']) ? $extra['event'] : null;
516
-
517
-        $template_wrapper_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
518
-        $template_row_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_row.template.php';
519
-
520
-        // array of template objects for global and custom (non-trashed) (but remember just for this messenger!)
521
-        $global_templates = EEM_Message_Template_Group::instance()->get_all(
522
-            array( array( 'MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true ) )
523
-        );
524
-        $templates_for_event = EEM_Message_Template_Group::instance()->get_all_custom_templates_by_event(
525
-            $event_id,
526
-            array(
527
-                'MTP_messenger' => $this->name,
528
-                'MTP_is_active' => true
529
-            )
530
-        );
531
-        $templates_for_event = !empty($templates_for_event) ? $templates_for_event : array();
532
-
533
-        // so we need to setup the rows for the selectors and we use the global mtpgs (cause those will the active message template groups)
534
-        foreach ($global_templates as $mtpgID => $mtpg) {
535
-            if ($mtpg instanceof EE_Message_Template_Group) {
536
-                // verify this message type is supposed to show on this page
537
-                $mtp_obj = $mtpg->message_type_obj();
538
-                if (! $mtp_obj instanceof EE_message_type) {
539
-                    continue;
540
-                }
541
-                $mtp_obj->admin_registered_pages = (array) $mtp_obj->admin_registered_pages;
542
-                if (! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
543
-                    continue;
544
-                }
545
-                $select_values = array();
546
-                $select_values[ $mtpgID ] = __('Global', 'event_espresso');
547
-                $default_value = array_key_exists($mtpgID, $templates_for_event) && ! $mtpg->get('MTP_is_override') ? $mtpgID : null;
548
-                // if the override has been set for the global template, then that means even if there are custom templates already created we ignore them because of the set override.
549
-                if (! $mtpg->get('MTP_is_override')) {
550
-                    // any custom templates for this message type?
551
-                    $custom_templates = EEM_Message_Template_Group::instance()->get_custom_message_template_by_m_and_mt($this->name, $mtpg->message_type());
552
-                    foreach ($custom_templates as $cmtpgID => $cmtpg) {
553
-                        $select_values[ $cmtpgID ] = $cmtpg->name();
554
-                        $default_value = array_key_exists($cmtpgID, $templates_for_event) ? $cmtpgID : $default_value;
555
-                    }
556
-                }
557
-                // if there is no $default_value then we set it as the global
558
-                $default_value = empty($default_value) ? $mtpgID : $default_value;
559
-                $edit_url = EEH_URL::add_query_args_and_nonce(array( 'page' => 'espresso_messages', 'action' => 'edit_message_template', 'id' => $default_value, 'evt_id' => $event_id ), admin_url('admin.php'));
560
-                $create_url = EEH_URL::add_query_args_and_nonce(array( 'page' => 'espresso_messages', 'action' => 'add_new_message_template', 'GRP_ID' => $default_value ), admin_url('admin.php'));
561
-                $st_args['mt_name'] = ucwords($mtp_obj->label['singular']);
562
-                $st_args['mt_slug'] = $mtpg->message_type();
563
-                $st_args['messenger_slug'] = $this->name;
564
-                $st_args['selector'] = EEH_Form_Fields::select_input('event_message_templates_relation[' . $mtpgID . ']', $select_values, $default_value, 'data-messenger="' . $this->name . '" data-messagetype="' . $mtpg->message_type() . '"', 'message-template-selector');
565
-                // note that  message template group that has override_all_custom set will remove the ability to set a custom message template based off of the global (and that also in turn overrides any other custom templates).
566
-                $st_args['create_button'] = $mtpg->get('MTP_is_override') ? '' : '<a data-messenger="' . $this->name . '" data-messagetype="' . $mtpg->message_type() . '" data-grpid="' . $default_value . '" target="_blank" href="' . $create_url . '" class="button button-small create-mtpg-button">' . __('Create New Custom', 'event_espresso') . '</a>';
567
-                $st_args['create_button'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_messages', 'espresso_messages_add_new_message_template') ? $st_args['create_button'] : '';
568
-                $st_args['edit_button'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_message', 'espresso_messages_edit_message_template', $mtpgID) ? '<a data-messagetype="' . $mtpg->message_type() . '" data-grpid="' . $default_value . '" target="_blank" href="' . $edit_url . '" class="button button-small edit-mtpg-button">' . __('Edit', 'event_espresso') . '</a>' : '';
569
-                $selector_rows .= EEH_Template::display_template($template_row_path, $st_args, true);
570
-            }
571
-        }
572
-
573
-        // if no selectors present then get out.
574
-        if (empty($selector_rows)) {
575
-            return '';
576
-        }
577
-
578
-        $template_args['selector_rows'] = $selector_rows;
579
-        return EEH_Template::display_template($template_wrapper_path, $template_args, true);
580
-    }
581
-
582
-
583
-
584
-
585
-
586
-
587
-    /**
588
-     * get_template_fields
589
-     *
590
-     * @access public
591
-     * @return array $this->_template_fields
592
-     */
593
-    public function get_template_fields()
594
-    {
595
-        $template_fields = apply_filters('FHEE__' . get_class($this) . '__get_template_fields', $this->_template_fields, $this);
596
-        $template_fields = apply_filters('FHEE__EE_messenger__get_template_fields', $template_fields, $this);
597
-        return $template_fields;
598
-    }
599
-
600
-
601
-
602
-
603
-    /** SETUP METHODS **/
604
-    /**
605
-     * The following method doesn't NEED to be used by child classes but might be modified by the specific messenger
606
-     * @param string $item
607
-     * @param mixed $value
608
-     */
609
-    protected function _set_template_value($item, $value)
610
-    {
611
-        if (array_key_exists($item, $this->_template_fields)) {
612
-            $prop = '_' . $item;
613
-            $this->{$prop}= $value;
614
-        }
615
-    }
616
-
617
-    /**
618
-     * Sets up the message for sending.
619
-     *
620
-     * @param  EE_message $message the message object that contains details about the message.
621
-     * @param EE_message_type $message_type The message type object used in combination with this messenger to generate the provided message.
622
-     *
623
-     * @return bool Very important that all messengers return bool for successful send or not.  Error messages can be
624
-     *              added to EE_Error.
625
-     *              true = message sent successfully
626
-     *              false = message not sent but can be retried (i.e. the failure might be just due to communication issues at the time of send).
627
-     *              Throwing a SendMessageException means the message failed sending and cannot be retried.
628
-     *
629
-     * @throws SendMessageException
630
-     */
631
-    final public function send_message($message, EE_message_type $message_type)
632
-    {
633
-        try {
634
-            $this->_validate_and_setup($message);
635
-            $this->_incoming_message_type = $message_type;
636
-            $response = $this->_send_message();
637
-            if ($response instanceof WP_Error) {
638
-                EE_Error::add_error($response->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
639
-                $response = false;
640
-            }
641
-        } catch (\Exception $e) {
642
-            // convert to an instance of SendMessageException
643
-            throw new SendMessageException($e->getMessage());
644
-        }
645
-        return $response;
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     * Sets up and returns message preview
652
-     * @param  EE_Message $message incoming message object
653
-     * @param EE_message_type $message_type This is whatever message type was used in combination with this messenger to generate the message.
654
-     * @param  bool   $send    true we will actually use the _send method (for test sends). FALSE we just return preview
655
-     * @return string          return the message html content
656
-     */
657
-    public function get_preview(EE_Message $message, EE_message_type $message_type, $send = false)
658
-    {
659
-        $this->_validate_and_setup($message);
660
-
661
-        $this->_incoming_message_type = $message_type;
662
-
663
-        if ($send) {
664
-            // are we overriding any existing template fields?
665
-            $settings = apply_filters(
666
-                'FHEE__EE_messenger__get_preview__messenger_test_settings',
667
-                $this->get_existing_test_settings(),
668
-                $this,
669
-                $send,
670
-                $message,
671
-                $message_type
672
-            );
673
-            if (! empty($settings)) {
674
-                foreach ($settings as $field => $value) {
675
-                    $this->_set_template_value($field, $value);
676
-                }
677
-            }
678
-        }
679
-
680
-        // enqueue preview js so that any links/buttons on the page are disabled.
681
-        if (! $send) {
682
-            // the below may seem like duplication.  However, typically if a messenger enqueues scripts/styles,
683
-            // it deregisters all existing wp scripts and styles first.  So the second hook ensures our previewer still gets setup.
684
-            add_action('admin_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
685
-            add_action('wp_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
686
-            add_action('AHEE__EE_messenger__enqueue_scripts_styles', array( $this, 'add_preview_script' ), 10);
687
-        }
688
-
689
-        return $send ? $this->_send_message() : $this->_preview();
690
-    }
691
-
692
-
693
-
694
-
695
-    /**
696
-     * Callback for enqueue_scripts so that we setup the preview script for all previews.
697
-     *
698
-     * @since 4.5.0
699
-     *
700
-     * @return void
701
-     */
702
-    public function add_preview_script()
703
-    {
704
-        // error message
705
-        EE_Registry::$i18n_js_strings['links_disabled'] = __('All the links on this page have been disabled because this is a generated preview message for the purpose of ensuring layout, style, and content setup.  To test generated links, you must trigger an actual message notification.', 'event_espresso');
706
-        wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL . 'messages/messenger/assets/js/ee-messages-preview.js', array( 'jquery' ), EVENT_ESPRESSO_VERSION, true);
707
-        wp_localize_script('ee-messages-preview-js', 'eei18n', EE_Registry::$i18n_js_strings);
708
-        wp_enqueue_script('ee-messages-preview-js');
709
-    }
710
-
711
-
712
-
713
-
714
-    /**
715
-     * simply validates the incoming message object and then sets up the properties for the messenger
716
-     * @param  EE_Message $message
717
-     * @throws EE_Error
718
-     */
719
-    protected function _validate_and_setup(EE_Message $message)
720
-    {
721
-        $template_pack = $message->get_template_pack();
722
-        $variation = $message->get_template_pack_variation();
723
-
724
-        // verify we have the required template pack value on the $message object.
725
-        if (! $template_pack instanceof EE_Messages_Template_Pack) {
726
-            throw new EE_Error(__('Incoming $message object must have an EE_Messages_Template_Pack object available.', 'event_espresso'));
727
-        }
728
-
729
-        $this->_tmp_pack = $template_pack;
730
-
731
-        $this->_variation = $variation ? $variation : 'default';
732
-
733
-        $template_fields = $this->get_template_fields();
734
-
735
-        foreach ($template_fields as $template => $value) {
736
-            if ($template !== 'extra') {
737
-                $column_value = $message->get_field_or_extra_meta('MSG_' . $template);
738
-                $message_template_value = $column_value ? $column_value : null;
739
-                $this->_set_template_value($template, $message_template_value);
740
-            }
741
-        }
742
-    }
743
-
744
-
745
-
746
-    /**
747
-     * Utility method for child classes to get the contents of a template file and return
748
-     *
749
-     * We're assuming the child messenger class has already setup template args!
750
-     * @param  bool $preview if true we use the preview wrapper otherwise we use main wrapper.
751
-     * @return string
752
-     * @throws \EE_Error
753
-     */
754
-    protected function _get_main_template($preview = false)
755
-    {
756
-        $type = $preview ? 'preview' : 'main';
757
-
758
-        $wrapper_template = $this->_tmp_pack->get_wrapper($this->name, $type);
759
-
760
-        // check file exists and is readable
761
-        if (!is_readable($wrapper_template)) {
762
-            throw new EE_Error(sprintf(__('Unable to access the template file for the %s messenger main content wrapper.  The location being attempted is %s.', 'event_espresso'), ucwords($this->label['singular']), $wrapper_template));
763
-        }
764
-
765
-        // add message type to template args
766
-        $this->_template_args['message_type'] = $this->_incoming_message_type;
767
-
768
-        return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
769
-    }
770
-
771
-
772
-
773
-    /**
774
-     * set the _test_settings_fields property
775
-     *
776
-     * @access protected
777
-     * @return void
778
-     */
779
-    protected function _set_test_settings_fields()
780
-    {
781
-        $this->_test_settings_fields = array();
782
-    }
783
-
784
-
785
-
786
-    /**
787
-     * return the _test_settings_fields property
788
-     * @return array
789
-     */
790
-    public function get_test_settings_fields()
791
-    {
792
-        return $this->_test_settings_fields;
793
-    }
794
-
795
-
796
-
797
-
798
-    /**
799
-     * This just returns any existing test settings that might be saved in the database
800
-     *
801
-     * @access public
802
-     * @return array
803
-     */
804
-    public function get_existing_test_settings()
805
-    {
806
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
807
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
808
-        $settings = $Message_Resource_Manager->get_active_messengers_option();
809
-        return isset($settings[ $this->name ]['test_settings']) ? $settings[ $this->name ]['test_settings'] : array();
810
-    }
811
-
812
-
813
-
814
-    /**
815
-     * All this does is set the existing test settings (in the db) for the messenger
816
-     *
817
-     * @access public
818
-     * @param $settings
819
-     * @return bool success/fail
820
-     */
821
-    public function set_existing_test_settings($settings)
822
-    {
823
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
824
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
825
-        $existing = $Message_Resource_Manager->get_active_messengers_option();
826
-        $existing[ $this->name ]['test_settings'] = $settings;
827
-        return $Message_Resource_Manager->update_active_messengers_option($existing);
828
-    }
829
-
830
-
831
-
832
-    /**
833
-     * This just returns the field label for a given field setup in the _template_fields property.
834
-     *
835
-     * @since   4.3.0
836
-     *
837
-     * @param string $field The field to retrieve the label for
838
-     * @return string             The label
839
-     */
840
-    public function get_field_label($field)
841
-    {
842
-        // first let's see if the field requests is in the top level array.
843
-        if (isset($this->_template_fields[ $field ]) && !empty($this->_template_fields[ $field ]['label'])) {
844
-            return $this->_template[ $field ]['label'];
845
-        }
846
-
847
-        // nope so let's look in the extra array to see if it's there HOWEVER if the field exists as a top level index in the extra array then we know the label is in the 'main' index.
848
-        if (isset($this->_template_fields['extra']) && !empty($this->_template_fields['extra'][ $field ]) && !empty($this->_template_fields['extra'][ $field ]['main']['label'])) {
849
-            return $this->_template_fields['extra'][ $field ]['main']['label'];
850
-        }
851
-
852
-        // now it's possible this field may just be existing in any of the extra array items.
853
-        if (!empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
854
-            foreach ($this->_template_fields['extra'] as $main_field => $subfields) {
855
-                if (!is_array($subfields)) {
856
-                    continue;
857
-                }
858
-                if (isset($subfields[ $field ]) && !empty($subfields[ $field ]['label'])) {
859
-                    return $subfields[ $field ]['label'];
860
-                }
861
-            }
862
-        }
863
-
864
-        // if we made it here then there's no label set so let's just return the $field.
865
-        return $field;
866
-    }
867
-
868
-
869
-
870
-
871
-    /**
872
-     * This is a method called from EE_messages when this messenger is a generating messenger and the sending messenger is a different messenger.  Child messengers can set hooks for the sending messenger to callback on if necessary (i.e. swap out css files or something else).
873
-     *
874
-     * @since 4.5.0
875
-     *
876
-     * @param string $sending_messenger_name the name of the sending messenger so we only set the hooks needed.
877
-     *
878
-     * @return void
879
-     */
880
-    public function do_secondary_messenger_hooks($sending_messenger_name)
881
-    {
882
-        return;
883
-    }
430
+	/**
431
+	 * Returns the valid message types associated with this messenger.
432
+	 *
433
+	 * @since 4.5.0
434
+	 *
435
+	 * @return array
436
+	 */
437
+	public function get_valid_message_types()
438
+	{
439
+		$class = get_class($this);
440
+
441
+		// messenger specific filter
442
+		// messenger specific filter
443
+		$valid_types = apply_filters('FHEE__' . $class . '__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
444
+
445
+		// all messengers filter
446
+		$valid_types = apply_filters('FHEE__EE_messenger__get_valid_message_types__valid_types', $valid_types, $this);
447
+		return $valid_types;
448
+	}
449
+
450
+
451
+
452
+
453
+
454
+	/**
455
+	 * this is just used by the custom validators (EE_Messages_Validator classes) to modify the _validator_config for certain message_type/messenger combos where a context may only use certain shortcodes etc.
456
+	 *
457
+	 * @access public
458
+	 * @param array $new_config Whatever is put in here will reset the _validator_config property
459
+	 */
460
+	public function set_validator_config($new_config)
461
+	{
462
+		$this->_validator_config = $new_config;
463
+	}
464
+
465
+
466
+
467
+
468
+	/**
469
+	 * This returns the _validator_config property
470
+	 *
471
+	 * @access public
472
+	 * @return array
473
+	 */
474
+	public function get_validator_config()
475
+	{
476
+		$class = get_class($this);
477
+
478
+		$config = apply_filters('FHEE__' . $class . '__get_validator_config', $this->_validator_config, $this);
479
+		$config = apply_filters('FHEE__EE_messenger__get_validator_config', $config, $this);
480
+		return $config;
481
+	}
482
+
483
+
484
+
485
+
486
+	/**
487
+	 * this public method accepts a page slug (for an EE_admin page) and will return the response from the child class callback function if that page is registered via the `_admin_registered_page` property set by the child class.
488
+	 *
489
+	 * @param string $page the slug of the EE admin page
490
+	 * @param array $message_types an array of active message type objects
491
+	 * @param string $action the page action (to allow for more specific handling - i.e. edit vs. add pages)
492
+	 * @param array $extra  This is just an extra argument that can be used to pass additional data for setting up page content.
493
+	 * @access public
494
+	 * @return string content for page
495
+	 */
496
+	public function get_messenger_admin_page_content($page, $action = null, $extra = array(), $message_types = array())
497
+	{
498
+		return $this->_get_admin_page_content($page, $action, $extra, $message_types);
499
+	}
500
+
501
+
502
+
503
+	/**
504
+	 * @param $message_types
505
+	 * @param array $extra
506
+	 * @return mixed|string
507
+	 */
508
+	protected function _get_admin_content_events_edit($message_types, $extra)
509
+	{
510
+		// defaults
511
+		$template_args = array();
512
+		$selector_rows = '';
513
+
514
+		// we don't need message types here so we're just going to ignore. we do, however, expect the event id here. The event id is needed to provide a link to setup a custom template for this event.
515
+		$event_id = isset($extra['event']) ? $extra['event'] : null;
516
+
517
+		$template_wrapper_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
518
+		$template_row_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_row.template.php';
519
+
520
+		// array of template objects for global and custom (non-trashed) (but remember just for this messenger!)
521
+		$global_templates = EEM_Message_Template_Group::instance()->get_all(
522
+			array( array( 'MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true ) )
523
+		);
524
+		$templates_for_event = EEM_Message_Template_Group::instance()->get_all_custom_templates_by_event(
525
+			$event_id,
526
+			array(
527
+				'MTP_messenger' => $this->name,
528
+				'MTP_is_active' => true
529
+			)
530
+		);
531
+		$templates_for_event = !empty($templates_for_event) ? $templates_for_event : array();
532
+
533
+		// so we need to setup the rows for the selectors and we use the global mtpgs (cause those will the active message template groups)
534
+		foreach ($global_templates as $mtpgID => $mtpg) {
535
+			if ($mtpg instanceof EE_Message_Template_Group) {
536
+				// verify this message type is supposed to show on this page
537
+				$mtp_obj = $mtpg->message_type_obj();
538
+				if (! $mtp_obj instanceof EE_message_type) {
539
+					continue;
540
+				}
541
+				$mtp_obj->admin_registered_pages = (array) $mtp_obj->admin_registered_pages;
542
+				if (! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
543
+					continue;
544
+				}
545
+				$select_values = array();
546
+				$select_values[ $mtpgID ] = __('Global', 'event_espresso');
547
+				$default_value = array_key_exists($mtpgID, $templates_for_event) && ! $mtpg->get('MTP_is_override') ? $mtpgID : null;
548
+				// if the override has been set for the global template, then that means even if there are custom templates already created we ignore them because of the set override.
549
+				if (! $mtpg->get('MTP_is_override')) {
550
+					// any custom templates for this message type?
551
+					$custom_templates = EEM_Message_Template_Group::instance()->get_custom_message_template_by_m_and_mt($this->name, $mtpg->message_type());
552
+					foreach ($custom_templates as $cmtpgID => $cmtpg) {
553
+						$select_values[ $cmtpgID ] = $cmtpg->name();
554
+						$default_value = array_key_exists($cmtpgID, $templates_for_event) ? $cmtpgID : $default_value;
555
+					}
556
+				}
557
+				// if there is no $default_value then we set it as the global
558
+				$default_value = empty($default_value) ? $mtpgID : $default_value;
559
+				$edit_url = EEH_URL::add_query_args_and_nonce(array( 'page' => 'espresso_messages', 'action' => 'edit_message_template', 'id' => $default_value, 'evt_id' => $event_id ), admin_url('admin.php'));
560
+				$create_url = EEH_URL::add_query_args_and_nonce(array( 'page' => 'espresso_messages', 'action' => 'add_new_message_template', 'GRP_ID' => $default_value ), admin_url('admin.php'));
561
+				$st_args['mt_name'] = ucwords($mtp_obj->label['singular']);
562
+				$st_args['mt_slug'] = $mtpg->message_type();
563
+				$st_args['messenger_slug'] = $this->name;
564
+				$st_args['selector'] = EEH_Form_Fields::select_input('event_message_templates_relation[' . $mtpgID . ']', $select_values, $default_value, 'data-messenger="' . $this->name . '" data-messagetype="' . $mtpg->message_type() . '"', 'message-template-selector');
565
+				// note that  message template group that has override_all_custom set will remove the ability to set a custom message template based off of the global (and that also in turn overrides any other custom templates).
566
+				$st_args['create_button'] = $mtpg->get('MTP_is_override') ? '' : '<a data-messenger="' . $this->name . '" data-messagetype="' . $mtpg->message_type() . '" data-grpid="' . $default_value . '" target="_blank" href="' . $create_url . '" class="button button-small create-mtpg-button">' . __('Create New Custom', 'event_espresso') . '</a>';
567
+				$st_args['create_button'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_messages', 'espresso_messages_add_new_message_template') ? $st_args['create_button'] : '';
568
+				$st_args['edit_button'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_message', 'espresso_messages_edit_message_template', $mtpgID) ? '<a data-messagetype="' . $mtpg->message_type() . '" data-grpid="' . $default_value . '" target="_blank" href="' . $edit_url . '" class="button button-small edit-mtpg-button">' . __('Edit', 'event_espresso') . '</a>' : '';
569
+				$selector_rows .= EEH_Template::display_template($template_row_path, $st_args, true);
570
+			}
571
+		}
572
+
573
+		// if no selectors present then get out.
574
+		if (empty($selector_rows)) {
575
+			return '';
576
+		}
577
+
578
+		$template_args['selector_rows'] = $selector_rows;
579
+		return EEH_Template::display_template($template_wrapper_path, $template_args, true);
580
+	}
581
+
582
+
583
+
584
+
585
+
586
+
587
+	/**
588
+	 * get_template_fields
589
+	 *
590
+	 * @access public
591
+	 * @return array $this->_template_fields
592
+	 */
593
+	public function get_template_fields()
594
+	{
595
+		$template_fields = apply_filters('FHEE__' . get_class($this) . '__get_template_fields', $this->_template_fields, $this);
596
+		$template_fields = apply_filters('FHEE__EE_messenger__get_template_fields', $template_fields, $this);
597
+		return $template_fields;
598
+	}
599
+
600
+
601
+
602
+
603
+	/** SETUP METHODS **/
604
+	/**
605
+	 * The following method doesn't NEED to be used by child classes but might be modified by the specific messenger
606
+	 * @param string $item
607
+	 * @param mixed $value
608
+	 */
609
+	protected function _set_template_value($item, $value)
610
+	{
611
+		if (array_key_exists($item, $this->_template_fields)) {
612
+			$prop = '_' . $item;
613
+			$this->{$prop}= $value;
614
+		}
615
+	}
616
+
617
+	/**
618
+	 * Sets up the message for sending.
619
+	 *
620
+	 * @param  EE_message $message the message object that contains details about the message.
621
+	 * @param EE_message_type $message_type The message type object used in combination with this messenger to generate the provided message.
622
+	 *
623
+	 * @return bool Very important that all messengers return bool for successful send or not.  Error messages can be
624
+	 *              added to EE_Error.
625
+	 *              true = message sent successfully
626
+	 *              false = message not sent but can be retried (i.e. the failure might be just due to communication issues at the time of send).
627
+	 *              Throwing a SendMessageException means the message failed sending and cannot be retried.
628
+	 *
629
+	 * @throws SendMessageException
630
+	 */
631
+	final public function send_message($message, EE_message_type $message_type)
632
+	{
633
+		try {
634
+			$this->_validate_and_setup($message);
635
+			$this->_incoming_message_type = $message_type;
636
+			$response = $this->_send_message();
637
+			if ($response instanceof WP_Error) {
638
+				EE_Error::add_error($response->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
639
+				$response = false;
640
+			}
641
+		} catch (\Exception $e) {
642
+			// convert to an instance of SendMessageException
643
+			throw new SendMessageException($e->getMessage());
644
+		}
645
+		return $response;
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 * Sets up and returns message preview
652
+	 * @param  EE_Message $message incoming message object
653
+	 * @param EE_message_type $message_type This is whatever message type was used in combination with this messenger to generate the message.
654
+	 * @param  bool   $send    true we will actually use the _send method (for test sends). FALSE we just return preview
655
+	 * @return string          return the message html content
656
+	 */
657
+	public function get_preview(EE_Message $message, EE_message_type $message_type, $send = false)
658
+	{
659
+		$this->_validate_and_setup($message);
660
+
661
+		$this->_incoming_message_type = $message_type;
662
+
663
+		if ($send) {
664
+			// are we overriding any existing template fields?
665
+			$settings = apply_filters(
666
+				'FHEE__EE_messenger__get_preview__messenger_test_settings',
667
+				$this->get_existing_test_settings(),
668
+				$this,
669
+				$send,
670
+				$message,
671
+				$message_type
672
+			);
673
+			if (! empty($settings)) {
674
+				foreach ($settings as $field => $value) {
675
+					$this->_set_template_value($field, $value);
676
+				}
677
+			}
678
+		}
679
+
680
+		// enqueue preview js so that any links/buttons on the page are disabled.
681
+		if (! $send) {
682
+			// the below may seem like duplication.  However, typically if a messenger enqueues scripts/styles,
683
+			// it deregisters all existing wp scripts and styles first.  So the second hook ensures our previewer still gets setup.
684
+			add_action('admin_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
685
+			add_action('wp_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
686
+			add_action('AHEE__EE_messenger__enqueue_scripts_styles', array( $this, 'add_preview_script' ), 10);
687
+		}
688
+
689
+		return $send ? $this->_send_message() : $this->_preview();
690
+	}
691
+
692
+
693
+
694
+
695
+	/**
696
+	 * Callback for enqueue_scripts so that we setup the preview script for all previews.
697
+	 *
698
+	 * @since 4.5.0
699
+	 *
700
+	 * @return void
701
+	 */
702
+	public function add_preview_script()
703
+	{
704
+		// error message
705
+		EE_Registry::$i18n_js_strings['links_disabled'] = __('All the links on this page have been disabled because this is a generated preview message for the purpose of ensuring layout, style, and content setup.  To test generated links, you must trigger an actual message notification.', 'event_espresso');
706
+		wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL . 'messages/messenger/assets/js/ee-messages-preview.js', array( 'jquery' ), EVENT_ESPRESSO_VERSION, true);
707
+		wp_localize_script('ee-messages-preview-js', 'eei18n', EE_Registry::$i18n_js_strings);
708
+		wp_enqueue_script('ee-messages-preview-js');
709
+	}
710
+
711
+
712
+
713
+
714
+	/**
715
+	 * simply validates the incoming message object and then sets up the properties for the messenger
716
+	 * @param  EE_Message $message
717
+	 * @throws EE_Error
718
+	 */
719
+	protected function _validate_and_setup(EE_Message $message)
720
+	{
721
+		$template_pack = $message->get_template_pack();
722
+		$variation = $message->get_template_pack_variation();
723
+
724
+		// verify we have the required template pack value on the $message object.
725
+		if (! $template_pack instanceof EE_Messages_Template_Pack) {
726
+			throw new EE_Error(__('Incoming $message object must have an EE_Messages_Template_Pack object available.', 'event_espresso'));
727
+		}
728
+
729
+		$this->_tmp_pack = $template_pack;
730
+
731
+		$this->_variation = $variation ? $variation : 'default';
732
+
733
+		$template_fields = $this->get_template_fields();
734
+
735
+		foreach ($template_fields as $template => $value) {
736
+			if ($template !== 'extra') {
737
+				$column_value = $message->get_field_or_extra_meta('MSG_' . $template);
738
+				$message_template_value = $column_value ? $column_value : null;
739
+				$this->_set_template_value($template, $message_template_value);
740
+			}
741
+		}
742
+	}
743
+
744
+
745
+
746
+	/**
747
+	 * Utility method for child classes to get the contents of a template file and return
748
+	 *
749
+	 * We're assuming the child messenger class has already setup template args!
750
+	 * @param  bool $preview if true we use the preview wrapper otherwise we use main wrapper.
751
+	 * @return string
752
+	 * @throws \EE_Error
753
+	 */
754
+	protected function _get_main_template($preview = false)
755
+	{
756
+		$type = $preview ? 'preview' : 'main';
757
+
758
+		$wrapper_template = $this->_tmp_pack->get_wrapper($this->name, $type);
759
+
760
+		// check file exists and is readable
761
+		if (!is_readable($wrapper_template)) {
762
+			throw new EE_Error(sprintf(__('Unable to access the template file for the %s messenger main content wrapper.  The location being attempted is %s.', 'event_espresso'), ucwords($this->label['singular']), $wrapper_template));
763
+		}
764
+
765
+		// add message type to template args
766
+		$this->_template_args['message_type'] = $this->_incoming_message_type;
767
+
768
+		return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
769
+	}
770
+
771
+
772
+
773
+	/**
774
+	 * set the _test_settings_fields property
775
+	 *
776
+	 * @access protected
777
+	 * @return void
778
+	 */
779
+	protected function _set_test_settings_fields()
780
+	{
781
+		$this->_test_settings_fields = array();
782
+	}
783
+
784
+
785
+
786
+	/**
787
+	 * return the _test_settings_fields property
788
+	 * @return array
789
+	 */
790
+	public function get_test_settings_fields()
791
+	{
792
+		return $this->_test_settings_fields;
793
+	}
794
+
795
+
796
+
797
+
798
+	/**
799
+	 * This just returns any existing test settings that might be saved in the database
800
+	 *
801
+	 * @access public
802
+	 * @return array
803
+	 */
804
+	public function get_existing_test_settings()
805
+	{
806
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
807
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
808
+		$settings = $Message_Resource_Manager->get_active_messengers_option();
809
+		return isset($settings[ $this->name ]['test_settings']) ? $settings[ $this->name ]['test_settings'] : array();
810
+	}
811
+
812
+
813
+
814
+	/**
815
+	 * All this does is set the existing test settings (in the db) for the messenger
816
+	 *
817
+	 * @access public
818
+	 * @param $settings
819
+	 * @return bool success/fail
820
+	 */
821
+	public function set_existing_test_settings($settings)
822
+	{
823
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
824
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
825
+		$existing = $Message_Resource_Manager->get_active_messengers_option();
826
+		$existing[ $this->name ]['test_settings'] = $settings;
827
+		return $Message_Resource_Manager->update_active_messengers_option($existing);
828
+	}
829
+
830
+
831
+
832
+	/**
833
+	 * This just returns the field label for a given field setup in the _template_fields property.
834
+	 *
835
+	 * @since   4.3.0
836
+	 *
837
+	 * @param string $field The field to retrieve the label for
838
+	 * @return string             The label
839
+	 */
840
+	public function get_field_label($field)
841
+	{
842
+		// first let's see if the field requests is in the top level array.
843
+		if (isset($this->_template_fields[ $field ]) && !empty($this->_template_fields[ $field ]['label'])) {
844
+			return $this->_template[ $field ]['label'];
845
+		}
846
+
847
+		// nope so let's look in the extra array to see if it's there HOWEVER if the field exists as a top level index in the extra array then we know the label is in the 'main' index.
848
+		if (isset($this->_template_fields['extra']) && !empty($this->_template_fields['extra'][ $field ]) && !empty($this->_template_fields['extra'][ $field ]['main']['label'])) {
849
+			return $this->_template_fields['extra'][ $field ]['main']['label'];
850
+		}
851
+
852
+		// now it's possible this field may just be existing in any of the extra array items.
853
+		if (!empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
854
+			foreach ($this->_template_fields['extra'] as $main_field => $subfields) {
855
+				if (!is_array($subfields)) {
856
+					continue;
857
+				}
858
+				if (isset($subfields[ $field ]) && !empty($subfields[ $field ]['label'])) {
859
+					return $subfields[ $field ]['label'];
860
+				}
861
+			}
862
+		}
863
+
864
+		// if we made it here then there's no label set so let's just return the $field.
865
+		return $field;
866
+	}
867
+
868
+
869
+
870
+
871
+	/**
872
+	 * This is a method called from EE_messages when this messenger is a generating messenger and the sending messenger is a different messenger.  Child messengers can set hooks for the sending messenger to callback on if necessary (i.e. swap out css files or something else).
873
+	 *
874
+	 * @since 4.5.0
875
+	 *
876
+	 * @param string $sending_messenger_name the name of the sending messenger so we only set the hooks needed.
877
+	 *
878
+	 * @return void
879
+	 */
880
+	public function do_secondary_messenger_hooks($sending_messenger_name)
881
+	{
882
+		return;
883
+	}
884 884
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
         $class = get_class($this);
418 418
 
419 419
         // messenger specific filter
420
-        $default_types = apply_filters('FHEE__' . $class . '__get_default_message_types__default_types', $this->_default_message_types, $this);
420
+        $default_types = apply_filters('FHEE__'.$class.'__get_default_message_types__default_types', $this->_default_message_types, $this);
421 421
 
422 422
         // all messengers filter
423 423
         $default_types = apply_filters('FHEE__EE_messenger__get_default_message_types__default_types', $default_types, $this);
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
 
441 441
         // messenger specific filter
442 442
         // messenger specific filter
443
-        $valid_types = apply_filters('FHEE__' . $class . '__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
443
+        $valid_types = apply_filters('FHEE__'.$class.'__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
444 444
 
445 445
         // all messengers filter
446 446
         $valid_types = apply_filters('FHEE__EE_messenger__get_valid_message_types__valid_types', $valid_types, $this);
@@ -475,7 +475,7 @@  discard block
 block discarded – undo
475 475
     {
476 476
         $class = get_class($this);
477 477
 
478
-        $config = apply_filters('FHEE__' . $class . '__get_validator_config', $this->_validator_config, $this);
478
+        $config = apply_filters('FHEE__'.$class.'__get_validator_config', $this->_validator_config, $this);
479 479
         $config = apply_filters('FHEE__EE_messenger__get_validator_config', $config, $this);
480 480
         return $config;
481 481
     }
@@ -514,12 +514,12 @@  discard block
 block discarded – undo
514 514
         // we don't need message types here so we're just going to ignore. we do, however, expect the event id here. The event id is needed to provide a link to setup a custom template for this event.
515 515
         $event_id = isset($extra['event']) ? $extra['event'] : null;
516 516
 
517
-        $template_wrapper_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
518
-        $template_row_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_row.template.php';
517
+        $template_wrapper_path = EE_LIBRARIES.'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
518
+        $template_row_path = EE_LIBRARIES.'messages/messenger/admin_templates/event_switcher_row.template.php';
519 519
 
520 520
         // array of template objects for global and custom (non-trashed) (but remember just for this messenger!)
521 521
         $global_templates = EEM_Message_Template_Group::instance()->get_all(
522
-            array( array( 'MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true ) )
522
+            array(array('MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true))
523 523
         );
524 524
         $templates_for_event = EEM_Message_Template_Group::instance()->get_all_custom_templates_by_event(
525 525
             $event_id,
@@ -528,44 +528,44 @@  discard block
 block discarded – undo
528 528
                 'MTP_is_active' => true
529 529
             )
530 530
         );
531
-        $templates_for_event = !empty($templates_for_event) ? $templates_for_event : array();
531
+        $templates_for_event = ! empty($templates_for_event) ? $templates_for_event : array();
532 532
 
533 533
         // so we need to setup the rows for the selectors and we use the global mtpgs (cause those will the active message template groups)
534 534
         foreach ($global_templates as $mtpgID => $mtpg) {
535 535
             if ($mtpg instanceof EE_Message_Template_Group) {
536 536
                 // verify this message type is supposed to show on this page
537 537
                 $mtp_obj = $mtpg->message_type_obj();
538
-                if (! $mtp_obj instanceof EE_message_type) {
538
+                if ( ! $mtp_obj instanceof EE_message_type) {
539 539
                     continue;
540 540
                 }
541 541
                 $mtp_obj->admin_registered_pages = (array) $mtp_obj->admin_registered_pages;
542
-                if (! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
542
+                if ( ! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
543 543
                     continue;
544 544
                 }
545 545
                 $select_values = array();
546
-                $select_values[ $mtpgID ] = __('Global', 'event_espresso');
546
+                $select_values[$mtpgID] = __('Global', 'event_espresso');
547 547
                 $default_value = array_key_exists($mtpgID, $templates_for_event) && ! $mtpg->get('MTP_is_override') ? $mtpgID : null;
548 548
                 // if the override has been set for the global template, then that means even if there are custom templates already created we ignore them because of the set override.
549
-                if (! $mtpg->get('MTP_is_override')) {
549
+                if ( ! $mtpg->get('MTP_is_override')) {
550 550
                     // any custom templates for this message type?
551 551
                     $custom_templates = EEM_Message_Template_Group::instance()->get_custom_message_template_by_m_and_mt($this->name, $mtpg->message_type());
552 552
                     foreach ($custom_templates as $cmtpgID => $cmtpg) {
553
-                        $select_values[ $cmtpgID ] = $cmtpg->name();
553
+                        $select_values[$cmtpgID] = $cmtpg->name();
554 554
                         $default_value = array_key_exists($cmtpgID, $templates_for_event) ? $cmtpgID : $default_value;
555 555
                     }
556 556
                 }
557 557
                 // if there is no $default_value then we set it as the global
558 558
                 $default_value = empty($default_value) ? $mtpgID : $default_value;
559
-                $edit_url = EEH_URL::add_query_args_and_nonce(array( 'page' => 'espresso_messages', 'action' => 'edit_message_template', 'id' => $default_value, 'evt_id' => $event_id ), admin_url('admin.php'));
560
-                $create_url = EEH_URL::add_query_args_and_nonce(array( 'page' => 'espresso_messages', 'action' => 'add_new_message_template', 'GRP_ID' => $default_value ), admin_url('admin.php'));
559
+                $edit_url = EEH_URL::add_query_args_and_nonce(array('page' => 'espresso_messages', 'action' => 'edit_message_template', 'id' => $default_value, 'evt_id' => $event_id), admin_url('admin.php'));
560
+                $create_url = EEH_URL::add_query_args_and_nonce(array('page' => 'espresso_messages', 'action' => 'add_new_message_template', 'GRP_ID' => $default_value), admin_url('admin.php'));
561 561
                 $st_args['mt_name'] = ucwords($mtp_obj->label['singular']);
562 562
                 $st_args['mt_slug'] = $mtpg->message_type();
563 563
                 $st_args['messenger_slug'] = $this->name;
564
-                $st_args['selector'] = EEH_Form_Fields::select_input('event_message_templates_relation[' . $mtpgID . ']', $select_values, $default_value, 'data-messenger="' . $this->name . '" data-messagetype="' . $mtpg->message_type() . '"', 'message-template-selector');
564
+                $st_args['selector'] = EEH_Form_Fields::select_input('event_message_templates_relation['.$mtpgID.']', $select_values, $default_value, 'data-messenger="'.$this->name.'" data-messagetype="'.$mtpg->message_type().'"', 'message-template-selector');
565 565
                 // note that  message template group that has override_all_custom set will remove the ability to set a custom message template based off of the global (and that also in turn overrides any other custom templates).
566
-                $st_args['create_button'] = $mtpg->get('MTP_is_override') ? '' : '<a data-messenger="' . $this->name . '" data-messagetype="' . $mtpg->message_type() . '" data-grpid="' . $default_value . '" target="_blank" href="' . $create_url . '" class="button button-small create-mtpg-button">' . __('Create New Custom', 'event_espresso') . '</a>';
566
+                $st_args['create_button'] = $mtpg->get('MTP_is_override') ? '' : '<a data-messenger="'.$this->name.'" data-messagetype="'.$mtpg->message_type().'" data-grpid="'.$default_value.'" target="_blank" href="'.$create_url.'" class="button button-small create-mtpg-button">'.__('Create New Custom', 'event_espresso').'</a>';
567 567
                 $st_args['create_button'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_messages', 'espresso_messages_add_new_message_template') ? $st_args['create_button'] : '';
568
-                $st_args['edit_button'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_message', 'espresso_messages_edit_message_template', $mtpgID) ? '<a data-messagetype="' . $mtpg->message_type() . '" data-grpid="' . $default_value . '" target="_blank" href="' . $edit_url . '" class="button button-small edit-mtpg-button">' . __('Edit', 'event_espresso') . '</a>' : '';
568
+                $st_args['edit_button'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_message', 'espresso_messages_edit_message_template', $mtpgID) ? '<a data-messagetype="'.$mtpg->message_type().'" data-grpid="'.$default_value.'" target="_blank" href="'.$edit_url.'" class="button button-small edit-mtpg-button">'.__('Edit', 'event_espresso').'</a>' : '';
569 569
                 $selector_rows .= EEH_Template::display_template($template_row_path, $st_args, true);
570 570
             }
571 571
         }
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
      */
593 593
     public function get_template_fields()
594 594
     {
595
-        $template_fields = apply_filters('FHEE__' . get_class($this) . '__get_template_fields', $this->_template_fields, $this);
595
+        $template_fields = apply_filters('FHEE__'.get_class($this).'__get_template_fields', $this->_template_fields, $this);
596 596
         $template_fields = apply_filters('FHEE__EE_messenger__get_template_fields', $template_fields, $this);
597 597
         return $template_fields;
598 598
     }
@@ -609,8 +609,8 @@  discard block
 block discarded – undo
609 609
     protected function _set_template_value($item, $value)
610 610
     {
611 611
         if (array_key_exists($item, $this->_template_fields)) {
612
-            $prop = '_' . $item;
613
-            $this->{$prop}= $value;
612
+            $prop = '_'.$item;
613
+            $this->{$prop} = $value;
614 614
         }
615 615
     }
616 616
 
@@ -670,7 +670,7 @@  discard block
 block discarded – undo
670 670
                 $message,
671 671
                 $message_type
672 672
             );
673
-            if (! empty($settings)) {
673
+            if ( ! empty($settings)) {
674 674
                 foreach ($settings as $field => $value) {
675 675
                     $this->_set_template_value($field, $value);
676 676
                 }
@@ -678,12 +678,12 @@  discard block
 block discarded – undo
678 678
         }
679 679
 
680 680
         // enqueue preview js so that any links/buttons on the page are disabled.
681
-        if (! $send) {
681
+        if ( ! $send) {
682 682
             // the below may seem like duplication.  However, typically if a messenger enqueues scripts/styles,
683 683
             // it deregisters all existing wp scripts and styles first.  So the second hook ensures our previewer still gets setup.
684
-            add_action('admin_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
685
-            add_action('wp_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
686
-            add_action('AHEE__EE_messenger__enqueue_scripts_styles', array( $this, 'add_preview_script' ), 10);
684
+            add_action('admin_enqueue_scripts', array($this, 'add_preview_script'), 10);
685
+            add_action('wp_enqueue_scripts', array($this, 'add_preview_script'), 10);
686
+            add_action('AHEE__EE_messenger__enqueue_scripts_styles', array($this, 'add_preview_script'), 10);
687 687
         }
688 688
 
689 689
         return $send ? $this->_send_message() : $this->_preview();
@@ -703,7 +703,7 @@  discard block
 block discarded – undo
703 703
     {
704 704
         // error message
705 705
         EE_Registry::$i18n_js_strings['links_disabled'] = __('All the links on this page have been disabled because this is a generated preview message for the purpose of ensuring layout, style, and content setup.  To test generated links, you must trigger an actual message notification.', 'event_espresso');
706
-        wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL . 'messages/messenger/assets/js/ee-messages-preview.js', array( 'jquery' ), EVENT_ESPRESSO_VERSION, true);
706
+        wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL.'messages/messenger/assets/js/ee-messages-preview.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
707 707
         wp_localize_script('ee-messages-preview-js', 'eei18n', EE_Registry::$i18n_js_strings);
708 708
         wp_enqueue_script('ee-messages-preview-js');
709 709
     }
@@ -722,7 +722,7 @@  discard block
 block discarded – undo
722 722
         $variation = $message->get_template_pack_variation();
723 723
 
724 724
         // verify we have the required template pack value on the $message object.
725
-        if (! $template_pack instanceof EE_Messages_Template_Pack) {
725
+        if ( ! $template_pack instanceof EE_Messages_Template_Pack) {
726 726
             throw new EE_Error(__('Incoming $message object must have an EE_Messages_Template_Pack object available.', 'event_espresso'));
727 727
         }
728 728
 
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 
735 735
         foreach ($template_fields as $template => $value) {
736 736
             if ($template !== 'extra') {
737
-                $column_value = $message->get_field_or_extra_meta('MSG_' . $template);
737
+                $column_value = $message->get_field_or_extra_meta('MSG_'.$template);
738 738
                 $message_template_value = $column_value ? $column_value : null;
739 739
                 $this->_set_template_value($template, $message_template_value);
740 740
             }
@@ -758,7 +758,7 @@  discard block
 block discarded – undo
758 758
         $wrapper_template = $this->_tmp_pack->get_wrapper($this->name, $type);
759 759
 
760 760
         // check file exists and is readable
761
-        if (!is_readable($wrapper_template)) {
761
+        if ( ! is_readable($wrapper_template)) {
762 762
             throw new EE_Error(sprintf(__('Unable to access the template file for the %s messenger main content wrapper.  The location being attempted is %s.', 'event_espresso'), ucwords($this->label['singular']), $wrapper_template));
763 763
         }
764 764
 
@@ -806,7 +806,7 @@  discard block
 block discarded – undo
806 806
         /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
807 807
         $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
808 808
         $settings = $Message_Resource_Manager->get_active_messengers_option();
809
-        return isset($settings[ $this->name ]['test_settings']) ? $settings[ $this->name ]['test_settings'] : array();
809
+        return isset($settings[$this->name]['test_settings']) ? $settings[$this->name]['test_settings'] : array();
810 810
     }
811 811
 
812 812
 
@@ -823,7 +823,7 @@  discard block
 block discarded – undo
823 823
         /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
824 824
         $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
825 825
         $existing = $Message_Resource_Manager->get_active_messengers_option();
826
-        $existing[ $this->name ]['test_settings'] = $settings;
826
+        $existing[$this->name]['test_settings'] = $settings;
827 827
         return $Message_Resource_Manager->update_active_messengers_option($existing);
828 828
     }
829 829
 
@@ -840,23 +840,23 @@  discard block
 block discarded – undo
840 840
     public function get_field_label($field)
841 841
     {
842 842
         // first let's see if the field requests is in the top level array.
843
-        if (isset($this->_template_fields[ $field ]) && !empty($this->_template_fields[ $field ]['label'])) {
844
-            return $this->_template[ $field ]['label'];
843
+        if (isset($this->_template_fields[$field]) && ! empty($this->_template_fields[$field]['label'])) {
844
+            return $this->_template[$field]['label'];
845 845
         }
846 846
 
847 847
         // nope so let's look in the extra array to see if it's there HOWEVER if the field exists as a top level index in the extra array then we know the label is in the 'main' index.
848
-        if (isset($this->_template_fields['extra']) && !empty($this->_template_fields['extra'][ $field ]) && !empty($this->_template_fields['extra'][ $field ]['main']['label'])) {
849
-            return $this->_template_fields['extra'][ $field ]['main']['label'];
848
+        if (isset($this->_template_fields['extra']) && ! empty($this->_template_fields['extra'][$field]) && ! empty($this->_template_fields['extra'][$field]['main']['label'])) {
849
+            return $this->_template_fields['extra'][$field]['main']['label'];
850 850
         }
851 851
 
852 852
         // now it's possible this field may just be existing in any of the extra array items.
853
-        if (!empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
853
+        if ( ! empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
854 854
             foreach ($this->_template_fields['extra'] as $main_field => $subfields) {
855
-                if (!is_array($subfields)) {
855
+                if ( ! is_array($subfields)) {
856 856
                     continue;
857 857
                 }
858
-                if (isset($subfields[ $field ]) && !empty($subfields[ $field ]['label'])) {
859
-                    return $subfields[ $field ]['label'];
858
+                if (isset($subfields[$field]) && ! empty($subfields[$field]['label'])) {
859
+                    return $subfields[$field]['label'];
860 860
                 }
861 861
             }
862 862
         }
Please login to merge, or discard this patch.