Completed
Branch fix/remove-help-tours-payments (daccff)
by
unknown
08:54 queued 07:01
created
admin_pages/messages/Messages_Admin_Page.core.php 1 patch
Indentation   +4640 added lines, -4640 removed lines patch added patch discarded remove patch
@@ -16,2683 +16,2683 @@  discard block
 block discarded – undo
16 16
  */
17 17
 class Messages_Admin_Page extends EE_Admin_Page
18 18
 {
19
-    /**
20
-     * @var EEM_Message
21
-     */
22
-    private $MSG_MODEL;
23
-
24
-    /**
25
-     * @var EEM_Message_Template
26
-     */
27
-    private $MTP_MODEL;
28
-
29
-    /**
30
-     * @var EEM_Message_Template_Group
31
-     */
32
-    private $MTG_MODEL;
33
-
34
-    /**
35
-     * @var EE_Message_Resource_Manager $_message_resource_manager
36
-     */
37
-    protected $_message_resource_manager;
38
-
39
-    /**
40
-     * @var string
41
-     */
42
-    protected $_active_message_type_name = '';
43
-
44
-    /**
45
-     * @var string
46
-     */
47
-    protected $_active_messenger_name = '';
48
-
49
-    /**
50
-     * @var EE_messenger $_active_messenger
51
-     */
52
-    protected $_active_messenger;
53
-
54
-    protected $_activate_meta_box_type;
55
-
56
-    protected $_current_message_meta_box;
57
-
58
-    protected $_current_message_meta_box_object;
59
-
60
-    protected $_context_switcher;
61
-
62
-    protected $_shortcodes           = [];
63
-
64
-    protected $_active_messengers    = [];
65
-
66
-    protected $_active_message_types = [];
67
-
68
-    /**
69
-     * @var EE_Message_Template_Group $_message_template_group
70
-     */
71
-    protected $_message_template_group;
72
-
73
-    protected $_m_mt_settings = [];
74
-
75
-
76
-    /**
77
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
78
-     * IF there is no group then it gets automatically set to the Default template pack.
79
-     *
80
-     * @since 4.5.0
81
-     *
82
-     * @var EE_Messages_Template_Pack
83
-     */
84
-    protected $_template_pack;
85
-
86
-
87
-    /**
88
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
89
-     * group is.  If there is no group then it automatically gets set to default.
90
-     *
91
-     * @since 4.5.0
92
-     *
93
-     * @var string
94
-     */
95
-    protected $_variation;
96
-
97
-
98
-    /**
99
-     * @param bool $routing
100
-     * @throws EE_Error
101
-     * @throws ReflectionException
102
-     */
103
-    public function __construct($routing = true)
104
-    {
105
-        // make sure messages autoloader is running
106
-        EED_Messages::set_autoloaders();
107
-        parent::__construct($routing);
108
-    }
109
-
110
-
111
-    /**
112
-     * @return EEM_Message
113
-     * @throws EE_Error
114
-     */
115
-    public function getMsgModel()
116
-    {
117
-        if (! $this->MSG_MODEL instanceof EEM_Message) {
118
-            $this->MSG_MODEL = EEM_Message::instance();
119
-        }
120
-        return $this->MSG_MODEL;
121
-    }
122
-
123
-
124
-    /**
125
-     * @return EEM_Message_Template
126
-     * @throws EE_Error
127
-     */
128
-    public function getMtpModel()
129
-    {
130
-        if (! $this->MTP_MODEL instanceof EEM_Message_Template) {
131
-            $this->MTP_MODEL = EEM_Message_Template::instance();
132
-        }
133
-        return $this->MTP_MODEL;
134
-    }
135
-
136
-
137
-    /**
138
-     * @return EEM_Message_Template_Group
139
-     * @throws EE_Error
140
-     */
141
-    public function getMtgModel()
142
-    {
143
-        if (! $this->MTG_MODEL instanceof EEM_Message_Template_Group) {
144
-            $this->MTG_MODEL = EEM_Message_Template_Group::instance();
145
-        }
146
-        return $this->MTG_MODEL;
147
-    }
148
-
149
-
150
-    /**
151
-     * @throws EE_Error
152
-     * @throws ReflectionException
153
-     */
154
-    protected function _init_page_props()
155
-    {
156
-        $this->page_slug        = EE_MSG_PG_SLUG;
157
-        $this->page_label       = esc_html__('Messages Settings', 'event_espresso');
158
-        $this->_admin_base_url  = EE_MSG_ADMIN_URL;
159
-        $this->_admin_base_path = EE_MSG_ADMIN;
160
-
161
-        $messenger    = $this->request->getRequestParam('messenger', '');
162
-        $message_type = $this->request->getRequestParam('message_type', '');
163
-        $this->_active_messenger_name    = $this->request->getRequestParam('MTP_messenger', $messenger);
164
-        $this->_active_message_type_name = $this->request->getRequestParam('MTP_message_type', $message_type);
165
-
166
-        $this->_load_message_resource_manager();
167
-    }
168
-
169
-
170
-    /**
171
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
172
-     *
173
-     * @throws EE_Error
174
-     * @throws InvalidDataTypeException
175
-     * @throws InvalidInterfaceException
176
-     * @throws InvalidArgumentException
177
-     * @throws ReflectionException
178
-     */
179
-    protected function _load_message_resource_manager()
180
-    {
181
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
182
-    }
183
-
184
-
185
-    /**
186
-     * @return array
187
-     * @throws EE_Error
188
-     * @throws InvalidArgumentException
189
-     * @throws InvalidDataTypeException
190
-     * @throws InvalidInterfaceException
191
-     * @deprecated 4.9.9.rc.014
192
-     */
193
-    public function get_messengers_for_list_table()
194
-    {
195
-        EE_Error::doing_it_wrong(
196
-            __METHOD__,
197
-            sprintf(
198
-                esc_html__(
199
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
200
-                    'event_espresso'
201
-                ),
202
-                'Messages_Admin_Page::get_messengers_select_input()'
203
-            ),
204
-            '4.9.9.rc.014'
205
-        );
206
-
207
-        $m_values          = [];
208
-        $active_messengers = $this->getMsgModel()->get_all(['group_by' => 'MSG_messenger']);
209
-        // setup messengers for selects
210
-        $i = 1;
211
-        foreach ($active_messengers as $active_messenger) {
212
-            if ($active_messenger instanceof EE_Message) {
213
-                $m_values[ $i ]['id']   = $active_messenger->messenger();
214
-                $m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
215
-                $i++;
216
-            }
217
-        }
218
-
219
-        return $m_values;
220
-    }
221
-
222
-
223
-    /**
224
-     * @return array
225
-     * @throws EE_Error
226
-     * @throws InvalidArgumentException
227
-     * @throws InvalidDataTypeException
228
-     * @throws InvalidInterfaceException
229
-     * @deprecated 4.9.9.rc.014
230
-     */
231
-    public function get_message_types_for_list_table()
232
-    {
233
-        EE_Error::doing_it_wrong(
234
-            __METHOD__,
235
-            sprintf(
236
-                esc_html__(
237
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
238
-                    'event_espresso'
239
-                ),
240
-                'Messages_Admin_Page::get_message_types_select_input()'
241
-            ),
242
-            '4.9.9.rc.014'
243
-        );
244
-
245
-        $mt_values       = [];
246
-        $active_messages = $this->getMsgModel()->get_all(['group_by' => 'MSG_message_type']);
247
-        $i               = 1;
248
-        foreach ($active_messages as $active_message) {
249
-            if ($active_message instanceof EE_Message) {
250
-                $mt_values[ $i ]['id']   = $active_message->message_type();
251
-                $mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
252
-                $i++;
253
-            }
254
-        }
255
-
256
-        return $mt_values;
257
-    }
258
-
259
-
260
-    /**
261
-     * @return array
262
-     * @throws EE_Error
263
-     * @throws InvalidArgumentException
264
-     * @throws InvalidDataTypeException
265
-     * @throws InvalidInterfaceException
266
-     * @deprecated 4.9.9.rc.014
267
-     */
268
-    public function get_contexts_for_message_types_for_list_table()
269
-    {
270
-        EE_Error::doing_it_wrong(
271
-            __METHOD__,
272
-            sprintf(
273
-                esc_html__(
274
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
275
-                    'event_espresso'
276
-                ),
277
-                'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
278
-            ),
279
-            '4.9.9.rc.014'
280
-        );
281
-
282
-        $contexts                = [];
283
-        $active_message_contexts = $this->getMsgModel()->get_all(['group_by' => 'MSG_context']);
284
-        foreach ($active_message_contexts as $active_message) {
285
-            if ($active_message instanceof EE_Message) {
286
-                $message_type = $active_message->message_type_object();
287
-                if ($message_type instanceof EE_message_type) {
288
-                    $message_type_contexts = $message_type->get_contexts();
289
-                    foreach ($message_type_contexts as $context => $context_details) {
290
-                        $contexts[ $context ] = $context_details['label'];
291
-                    }
292
-                }
293
-            }
294
-        }
295
-
296
-        return $contexts;
297
-    }
298
-
299
-
300
-    /**
301
-     * Generate select input with provided messenger options array.
302
-     *
303
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
304
-     *                                 labels.
305
-     * @return string
306
-     * @throws EE_Error
307
-     */
308
-    public function get_messengers_select_input($messenger_options)
309
-    {
310
-        // if empty or just one value then just return an empty string
311
-        if (
312
-            empty($messenger_options)
313
-            || ! is_array($messenger_options)
314
-            || count($messenger_options) === 1
315
-        ) {
316
-            return '';
317
-        }
318
-        // merge in default
319
-        $messenger_options = array_merge(
320
-            ['none_selected' => esc_html__('Show All Messengers', 'event_espresso')],
321
-            $messenger_options
322
-        );
323
-        $input             = new EE_Select_Input(
324
-            $messenger_options,
325
-            [
326
-                'html_name'  => 'ee_messenger_filter_by',
327
-                'html_id'    => 'ee_messenger_filter_by',
328
-                'html_class' => 'wide',
329
-                'default'    => $this->request->getRequestParam('ee_messenger_filter_by', 'none_selected', 'title'),
330
-            ]
331
-        );
332
-
333
-        return $input->get_html_for_input();
334
-    }
335
-
336
-
337
-    /**
338
-     * Generate select input with provided message type options array.
339
-     *
340
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
341
-     *                                    message type labels
342
-     * @return string
343
-     * @throws EE_Error
344
-     */
345
-    public function get_message_types_select_input($message_type_options)
346
-    {
347
-        // if empty or count of options is 1 then just return an empty string
348
-        if (
349
-            empty($message_type_options)
350
-            || ! is_array($message_type_options)
351
-            || count($message_type_options) === 1
352
-        ) {
353
-            return '';
354
-        }
355
-        // merge in default
356
-        $message_type_options = array_merge(
357
-            ['none_selected' => esc_html__('Show All Message Types', 'event_espresso')],
358
-            $message_type_options
359
-        );
360
-        $input                = new EE_Select_Input(
361
-            $message_type_options,
362
-            [
363
-                'html_name'  => 'ee_message_type_filter_by',
364
-                'html_id'    => 'ee_message_type_filter_by',
365
-                'html_class' => 'wide',
366
-                'default'    => $this->request->getRequestParam('ee_message_type_filter_by', 'none_selected', 'title'),
367
-            ]
368
-        );
369
-
370
-        return $input->get_html_for_input();
371
-    }
372
-
373
-
374
-    /**
375
-     * Generate select input with provide message type contexts array.
376
-     *
377
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
378
-     *                               context label.
379
-     * @return string
380
-     * @throws EE_Error
381
-     */
382
-    public function get_contexts_for_message_types_select_input($context_options)
383
-    {
384
-        // if empty or count of options is one then just return empty string
385
-        if (
386
-            empty($context_options)
387
-            || ! is_array($context_options)
388
-            || count($context_options) === 1
389
-        ) {
390
-            return '';
391
-        }
392
-        // merge in default
393
-        $context_options = array_merge(
394
-            ['none_selected' => esc_html__('Show all Contexts', 'event_espresso')],
395
-            $context_options
396
-        );
397
-        $input           = new EE_Select_Input(
398
-            $context_options,
399
-            [
400
-                'html_name'  => 'ee_context_filter_by',
401
-                'html_id'    => 'ee_context_filter_by',
402
-                'html_class' => 'wide',
403
-                'default'    => $this->request->getRequestParam('ee_context_filter_by', 'none_selected', 'title'),
404
-            ]
405
-        );
406
-
407
-        return $input->get_html_for_input();
408
-    }
409
-
410
-
411
-    protected function _ajax_hooks()
412
-    {
413
-        add_action('wp_ajax_activate_messenger', [$this, 'activate_messenger_toggle']);
414
-        add_action('wp_ajax_activate_mt', [$this, 'activate_mt_toggle']);
415
-        add_action('wp_ajax_ee_msgs_save_settings', [$this, 'save_settings']);
416
-        add_action('wp_ajax_ee_msgs_update_mt_form', [$this, 'update_mt_form']);
417
-        add_action('wp_ajax_switch_template_pack', [$this, 'switch_template_pack']);
418
-        add_action('wp_ajax_toggle_context_template', [$this, 'toggle_context_template']);
419
-    }
420
-
421
-
422
-    protected function _define_page_props()
423
-    {
424
-        $this->_admin_page_title = $this->page_label;
425
-        $this->_labels           = [
426
-            'buttons'    => [
427
-                'add'    => esc_html__('Add New Message Template', 'event_espresso'),
428
-                'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
429
-                'delete' => esc_html__('Delete Message Template', 'event_espresso'),
430
-            ],
431
-            'publishbox' => esc_html__('Update Actions', 'event_espresso'),
432
-        ];
433
-    }
434
-
435
-
436
-    /**
437
-     *        an array for storing key => value pairs of request actions and their corresponding methods
438
-     *
439
-     * @access protected
440
-     * @return void
441
-     */
442
-    protected function _set_page_routes()
443
-    {
444
-        $GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
445
-        $GRP_ID = $this->request->getRequestParam('id', $GRP_ID, 'int');
446
-        $MSG_ID = $this->request->getRequestParam('MSG_ID', 0, 'int');
447
-
448
-        $this->_page_routes = [
449
-            'default'                          => [
450
-                'func'       => '_message_queue_list_table',
451
-                'capability' => 'ee_read_global_messages',
452
-            ],
453
-            'global_mtps'                      => [
454
-                'func'       => '_ee_default_messages_overview_list_table',
455
-                'capability' => 'ee_read_global_messages',
456
-            ],
457
-            'custom_mtps'                      => [
458
-                'func'       => '_custom_mtps_preview',
459
-                'capability' => 'ee_read_messages',
460
-            ],
461
-            'add_new_message_template'         => [
462
-                'func'       => 'add_message_template',
463
-                'capability' => 'ee_edit_messages',
464
-                'noheader'   => true,
465
-            ],
466
-            'edit_message_template'            => [
467
-                'func'       => '_edit_message_template',
468
-                'capability' => 'ee_edit_message',
469
-                'obj_id'     => $GRP_ID,
470
-            ],
471
-            'preview_message'                  => [
472
-                'func'               => '_preview_message',
473
-                'capability'         => 'ee_read_message',
474
-                'obj_id'             => $GRP_ID,
475
-                'noheader'           => true,
476
-                'headers_sent_route' => 'display_preview_message',
477
-            ],
478
-            'display_preview_message'          => [
479
-                'func'       => '_display_preview_message',
480
-                'capability' => 'ee_read_message',
481
-                'obj_id'     => $GRP_ID,
482
-            ],
483
-            'insert_message_template'          => [
484
-                'func'       => '_insert_or_update_message_template',
485
-                'capability' => 'ee_edit_messages',
486
-                'args'       => ['new' => true],
487
-                'noheader'   => true,
488
-            ],
489
-            'update_message_template'          => [
490
-                'func'       => '_insert_or_update_message_template',
491
-                'capability' => 'ee_edit_message',
492
-                'obj_id'     => $GRP_ID,
493
-                'args'       => ['new' => false],
494
-                'noheader'   => true,
495
-            ],
496
-            'trash_message_template'           => [
497
-                'func'       => '_trash_or_restore_message_template',
498
-                'capability' => 'ee_delete_message',
499
-                'obj_id'     => $GRP_ID,
500
-                'args'       => ['trash' => true, 'all' => true],
501
-                'noheader'   => true,
502
-            ],
503
-            'trash_message_template_context'   => [
504
-                'func'       => '_trash_or_restore_message_template',
505
-                'capability' => 'ee_delete_message',
506
-                'obj_id'     => $GRP_ID,
507
-                'args'       => ['trash' => true],
508
-                'noheader'   => true,
509
-            ],
510
-            'restore_message_template'         => [
511
-                'func'       => '_trash_or_restore_message_template',
512
-                'capability' => 'ee_delete_message',
513
-                'obj_id'     => $GRP_ID,
514
-                'args'       => ['trash' => false, 'all' => true],
515
-                'noheader'   => true,
516
-            ],
517
-            'restore_message_template_context' => [
518
-                'func'       => '_trash_or_restore_message_template',
519
-                'capability' => 'ee_delete_message',
520
-                'obj_id'     => $GRP_ID,
521
-                'args'       => ['trash' => false],
522
-                'noheader'   => true,
523
-            ],
524
-            'delete_message_template'          => [
525
-                'func'       => '_delete_message_template',
526
-                'capability' => 'ee_delete_message',
527
-                'obj_id'     => $GRP_ID,
528
-                'noheader'   => true,
529
-            ],
530
-            'reset_to_default'                 => [
531
-                'func'       => '_reset_to_default_template',
532
-                'capability' => 'ee_edit_message',
533
-                'obj_id'     => $GRP_ID,
534
-                'noheader'   => true,
535
-            ],
536
-            'settings'                         => [
537
-                'func'       => '_settings',
538
-                'capability' => 'manage_options',
539
-            ],
540
-            'update_global_settings'           => [
541
-                'func'       => '_update_global_settings',
542
-                'capability' => 'manage_options',
543
-                'noheader'   => true,
544
-            ],
545
-            'generate_now'                     => [
546
-                'func'       => '_generate_now',
547
-                'capability' => 'ee_send_message',
548
-                'noheader'   => true,
549
-            ],
550
-            'generate_and_send_now'            => [
551
-                'func'       => '_generate_and_send_now',
552
-                'capability' => 'ee_send_message',
553
-                'noheader'   => true,
554
-            ],
555
-            'queue_for_resending'              => [
556
-                'func'       => '_queue_for_resending',
557
-                'capability' => 'ee_send_message',
558
-                'noheader'   => true,
559
-            ],
560
-            'send_now'                         => [
561
-                'func'       => '_send_now',
562
-                'capability' => 'ee_send_message',
563
-                'noheader'   => true,
564
-            ],
565
-            'delete_ee_message'                => [
566
-                'func'       => '_delete_ee_messages',
567
-                'capability' => 'ee_delete_messages',
568
-                'noheader'   => true,
569
-            ],
570
-            'delete_ee_messages'               => [
571
-                'func'       => '_delete_ee_messages',
572
-                'capability' => 'ee_delete_messages',
573
-                'noheader'   => true,
574
-                'obj_id'     => $MSG_ID,
575
-            ],
576
-        ];
577
-    }
578
-
579
-
580
-    protected function _set_page_config()
581
-    {
582
-        $this->_page_config = [
583
-            'default'                  => [
584
-                'nav'           => [
585
-                    'label' => esc_html__('Message Activity', 'event_espresso'),
586
-                    'order' => 10,
587
-                ],
588
-                'list_table'    => 'EE_Message_List_Table',
589
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
590
-                'require_nonce' => false,
591
-            ],
592
-            'global_mtps'              => [
593
-                'nav'           => [
594
-                    'label' => esc_html__('Default Message Templates', 'event_espresso'),
595
-                    'order' => 20,
596
-                ],
597
-                'list_table'    => 'Messages_Template_List_Table',
598
-                'help_tabs'     => [
599
-                    'messages_overview_help_tab'                                => [
600
-                        'title'    => esc_html__('Messages Overview', 'event_espresso'),
601
-                        'filename' => 'messages_overview',
602
-                    ],
603
-                    'messages_overview_messages_table_column_headings_help_tab' => [
604
-                        'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
605
-                        'filename' => 'messages_overview_table_column_headings',
606
-                    ],
607
-                    'messages_overview_messages_filters_help_tab'               => [
608
-                        'title'    => esc_html__('Message Filters', 'event_espresso'),
609
-                        'filename' => 'messages_overview_filters',
610
-                    ],
611
-                    'messages_overview_messages_views_help_tab'                 => [
612
-                        'title'    => esc_html__('Message Views', 'event_espresso'),
613
-                        'filename' => 'messages_overview_views',
614
-                    ],
615
-                    'message_overview_message_types_help_tab'                   => [
616
-                        'title'    => esc_html__('Message Types', 'event_espresso'),
617
-                        'filename' => 'messages_overview_types',
618
-                    ],
619
-                    'messages_overview_messengers_help_tab'                     => [
620
-                        'title'    => esc_html__('Messengers', 'event_espresso'),
621
-                        'filename' => 'messages_overview_messengers',
622
-                    ],
623
-                ],
624
-                'require_nonce' => false,
625
-            ],
626
-            'custom_mtps'              => [
627
-                'nav'           => [
628
-                    'label' => esc_html__('Custom Message Templates', 'event_espresso'),
629
-                    'order' => 30,
630
-                ],
631
-                'help_tabs'     => [],
632
-                'require_nonce' => false,
633
-            ],
634
-            'add_new_message_template' => [
635
-                'nav'           => [
636
-                    'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
637
-                    'order'      => 5,
638
-                    'persistent' => false,
639
-                ],
640
-                'require_nonce' => false,
641
-            ],
642
-            'edit_message_template'    => [
643
-                'labels'        => [
644
-                    'buttons'    => [
645
-                        'reset' => esc_html__('Reset Templates', 'event_espresso'),
646
-                    ],
647
-                    'publishbox' => esc_html__('Update Actions', 'event_espresso'),
648
-                ],
649
-                'nav'           => [
650
-                    'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
651
-                    'order'      => 5,
652
-                    'persistent' => false,
653
-                    'url'        => '',
654
-                ],
655
-                'metaboxes'     => ['_publish_post_box', '_register_edit_meta_boxes'],
656
-                'has_metaboxes' => true,
657
-                'help_tabs'     => [
658
-                    'edit_message_template'            => [
659
-                        'title'    => esc_html__('Message Template Editor', 'event_espresso'),
660
-                        'callback' => 'edit_message_template_help_tab',
661
-                    ],
662
-                    'message_templates_help_tab'       => [
663
-                        'title'    => esc_html__('Message Templates', 'event_espresso'),
664
-                        'filename' => 'messages_templates',
665
-                    ],
666
-                    'message_template_shortcodes'      => [
667
-                        'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
668
-                        'callback' => 'message_template_shortcodes_help_tab',
669
-                    ],
670
-                    'message_preview_help_tab'         => [
671
-                        'title'    => esc_html__('Message Preview', 'event_espresso'),
672
-                        'filename' => 'messages_preview',
673
-                    ],
674
-                    'messages_overview_other_help_tab' => [
675
-                        'title'    => esc_html__('Messages Other', 'event_espresso'),
676
-                        'filename' => 'messages_overview_other',
677
-                    ],
678
-                ],
679
-                'require_nonce' => false,
680
-            ],
681
-            'display_preview_message'  => [
682
-                'nav'           => [
683
-                    'label'      => esc_html__('Message Preview', 'event_espresso'),
684
-                    'order'      => 5,
685
-                    'url'        => '',
686
-                    'persistent' => false,
687
-                ],
688
-                'help_tabs'     => [
689
-                    'preview_message' => [
690
-                        'title'    => esc_html__('About Previews', 'event_espresso'),
691
-                        'callback' => 'preview_message_help_tab',
692
-                    ],
693
-                ],
694
-                'require_nonce' => false,
695
-            ],
696
-            'settings'                 => [
697
-                'nav'           => [
698
-                    'label' => esc_html__('Settings', 'event_espresso'),
699
-                    'order' => 40,
700
-                ],
701
-                'metaboxes'     => ['_messages_settings_metaboxes'],
702
-                'help_tabs'     => [
703
-                    'messages_settings_help_tab'               => [
704
-                        'title'    => esc_html__('Messages Settings', 'event_espresso'),
705
-                        'filename' => 'messages_settings',
706
-                    ],
707
-                    'messages_settings_message_types_help_tab' => [
708
-                        'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
709
-                        'filename' => 'messages_settings_message_types',
710
-                    ],
711
-                    'messages_settings_messengers_help_tab'    => [
712
-                        'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
713
-                        'filename' => 'messages_settings_messengers',
714
-                    ],
715
-                ],
716
-                'require_nonce' => false,
717
-            ],
718
-        ];
719
-    }
720
-
721
-
722
-    protected function _add_screen_options()
723
-    {
724
-        // todo
725
-    }
726
-
727
-
728
-    protected function _add_screen_options_global_mtps()
729
-    {
730
-        /**
731
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
732
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
733
-         */
734
-        $page_title              = $this->_admin_page_title;
735
-        $this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
736
-        $this->_per_page_screen_option();
737
-        $this->_admin_page_title = $page_title;
738
-    }
739
-
740
-
741
-    protected function _add_screen_options_default()
742
-    {
743
-        $this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
744
-        $this->_per_page_screen_option();
745
-    }
746
-
747
-
748
-    // none of the below group are currently used for Messages
749
-    protected function _add_feature_pointers()
750
-    {
751
-    }
752
-
753
-
754
-    public function admin_init()
755
-    {
756
-    }
757
-
758
-
759
-    public function admin_notices()
760
-    {
761
-    }
762
-
763
-
764
-    public function admin_footer_scripts()
765
-    {
766
-    }
767
-
768
-
769
-    public function messages_help_tab()
770
-    {
771
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
772
-    }
773
-
774
-
775
-    public function messengers_help_tab()
776
-    {
777
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
778
-    }
779
-
780
-
781
-    public function message_types_help_tab()
782
-    {
783
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
784
-    }
785
-
786
-
787
-    public function messages_overview_help_tab()
788
-    {
789
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
790
-    }
791
-
792
-
793
-    public function message_templates_help_tab()
794
-    {
795
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
796
-    }
797
-
798
-
799
-    public function edit_message_template_help_tab()
800
-    {
801
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
802
-                        . esc_attr__('Editor Title', 'event_espresso')
803
-                        . '" />';
804
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
805
-                        . esc_attr__('Context Switcher and Preview', 'event_espresso')
806
-                        . '" />';
807
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
808
-                        . esc_attr__('Message Template Form Fields', 'event_espresso')
809
-                        . '" />';
810
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
811
-                        . esc_attr__('Shortcodes Metabox', 'event_espresso')
812
-                        . '" />';
813
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
814
-                        . esc_attr__('Publish Metabox', 'event_espresso')
815
-                        . '" />';
816
-        EEH_Template::display_template(
817
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
818
-            $args
819
-        );
820
-    }
821
-
822
-
823
-    /**
824
-     * @throws ReflectionException
825
-     * @throws EE_Error
826
-     */
827
-    public function message_template_shortcodes_help_tab()
828
-    {
829
-        $this->_set_shortcodes();
830
-        $args['shortcodes'] = $this->_shortcodes;
831
-        EEH_Template::display_template(
832
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
833
-            $args
834
-        );
835
-    }
836
-
837
-
838
-    public function preview_message_help_tab()
839
-    {
840
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
841
-    }
842
-
843
-
844
-    public function settings_help_tab()
845
-    {
846
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
847
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
848
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
849
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
850
-        $args['img3'] = '<div class="switch">'
851
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
852
-                        . ' type="checkbox" checked="checked">'
853
-                        . '<label for="ee-on-off-toggle-on"></label>'
854
-                        . '</div>';
855
-        $args['img4'] = '<div class="switch">'
856
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
857
-                        . ' type="checkbox">'
858
-                        . '<label for="ee-on-off-toggle-on"></label>'
859
-                        . '</div>';
860
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
861
-    }
862
-
863
-
864
-    public function load_scripts_styles()
865
-    {
866
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
867
-        wp_enqueue_style('espresso_ee_msg');
868
-
869
-        wp_register_script(
870
-            'ee-messages-settings',
871
-            EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
872
-            ['jquery-ui-droppable', 'ee-serialize-full-array'],
873
-            EVENT_ESPRESSO_VERSION,
874
-            true
875
-        );
876
-        wp_register_script(
877
-            'ee-msg-list-table-js',
878
-            EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
879
-            ['ee-dialog'],
880
-            EVENT_ESPRESSO_VERSION
881
-        );
882
-    }
883
-
884
-
885
-    public function load_scripts_styles_default()
886
-    {
887
-        wp_enqueue_script('ee-msg-list-table-js');
888
-    }
889
-
890
-
891
-    public function wp_editor_css($mce_css)
892
-    {
893
-        // if we're on the edit_message_template route
894
-        if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
895
-            $message_type_name = $this->_active_message_type_name;
896
-
897
-            // we're going to REPLACE the existing mce css
898
-            // we need to get the css file location from the active messenger
899
-            $mce_css = $this->_active_messenger->get_variation(
900
-                $this->_template_pack,
901
-                $message_type_name,
902
-                true,
903
-                'wpeditor',
904
-                $this->_variation
905
-            );
906
-        }
907
-
908
-        return $mce_css;
909
-    }
910
-
911
-
912
-    /**
913
-     * @throws EE_Error
914
-     * @throws ReflectionException
915
-     */
916
-    public function load_scripts_styles_edit_message_template()
917
-    {
918
-
919
-        $this->_set_shortcodes();
920
-
921
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
922
-            esc_html__(
923
-                'Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
924
-                'event_espresso'
925
-            ),
926
-            $this->_message_template_group->messenger_obj()->label['singular'],
927
-            $this->_message_template_group->message_type_obj()->label['singular']
928
-        );
929
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
930
-            'Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
931
-            'event_espresso'
932
-        );
933
-        EE_Registry::$i18n_js_strings['server_error']                 = esc_html__(
934
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
935
-            'event_espresso'
936
-        );
937
-
938
-        wp_register_script(
939
-            'ee_msgs_edit_js',
940
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
941
-            ['jquery'],
942
-            EVENT_ESPRESSO_VERSION
943
-        );
944
-
945
-        wp_enqueue_script('ee_admin_js');
946
-        wp_enqueue_script('ee_msgs_edit_js');
947
-
948
-        // add in special css for tiny_mce
949
-        add_filter('mce_css', [$this, 'wp_editor_css']);
950
-    }
951
-
952
-
953
-    /**
954
-     * @throws EE_Error
955
-     * @throws ReflectionException
956
-     */
957
-    public function load_scripts_styles_display_preview_message()
958
-    {
959
-        $this->_set_message_template_group();
960
-        if ($this->_active_messenger_name) {
961
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
962
-                $this->_active_messenger_name
963
-            );
964
-        }
965
-
966
-        wp_enqueue_style(
967
-            'espresso_preview_css',
968
-            $this->_active_messenger->get_variation(
969
-                $this->_template_pack,
970
-                $this->_active_message_type_name,
971
-                true,
972
-                'preview',
973
-                $this->_variation
974
-            )
975
-        );
976
-    }
977
-
978
-
979
-    public function load_scripts_styles_settings()
980
-    {
981
-        wp_register_style(
982
-            'ee-message-settings',
983
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
984
-            [],
985
-            EVENT_ESPRESSO_VERSION
986
-        );
987
-        wp_enqueue_style('ee-text-links');
988
-        wp_enqueue_style('ee-message-settings');
989
-        wp_enqueue_script('ee-messages-settings');
990
-    }
991
-
992
-
993
-    /**
994
-     * set views array for List Table
995
-     */
996
-    public function _set_list_table_views_global_mtps()
997
-    {
998
-        $this->_views = [
999
-            'in_use' => [
1000
-                'slug'  => 'in_use',
1001
-                'label' => esc_html__('In Use', 'event_espresso'),
1002
-                'count' => 0,
1003
-            ],
1004
-        ];
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Set views array for the Custom Template List Table
1010
-     */
1011
-    public function _set_list_table_views_custom_mtps()
1012
-    {
1013
-        $this->_set_list_table_views_global_mtps();
1014
-        $this->_views['in_use']['bulk_action'] = [
1015
-            'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
1016
-        ];
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     * set views array for message queue list table
1022
-     *
1023
-     * @throws InvalidDataTypeException
1024
-     * @throws InvalidInterfaceException
1025
-     * @throws InvalidArgumentException
1026
-     * @throws EE_Error
1027
-     * @throws ReflectionException
1028
-     */
1029
-    public function _set_list_table_views_default()
1030
-    {
1031
-        EE_Registry::instance()->load_helper('Template');
1032
-
1033
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
1034
-            'ee_send_message',
1035
-            'message_list_table_bulk_actions'
1036
-        )
1037
-            ? [
1038
-                'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
1039
-                'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
1040
-                'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
1041
-                'send_now'              => esc_html__('Send Now', 'event_espresso'),
1042
-            ]
1043
-            : [];
1044
-
1045
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
1046
-            'ee_delete_messages',
1047
-            'message_list_table_bulk_actions'
1048
-        )
1049
-            ? ['delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso')]
1050
-            : [];
1051
-
1052
-
1053
-        $this->_views = [
1054
-            'all' => [
1055
-                'slug'        => 'all',
1056
-                'label'       => esc_html__('All', 'event_espresso'),
1057
-                'count'       => 0,
1058
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
1059
-            ],
1060
-        ];
1061
-
1062
-
1063
-        foreach ($this->getMsgModel()->all_statuses() as $status) {
1064
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
1065
-                continue;
1066
-            }
1067
-            $status_bulk_actions = $common_bulk_actions;
1068
-            // unset bulk actions not applying to status
1069
-            if (! empty($status_bulk_actions)) {
1070
-                switch ($status) {
1071
-                    case EEM_Message::status_idle:
1072
-                    case EEM_Message::status_resend:
1073
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1074
-                        break;
1075
-
1076
-                    case EEM_Message::status_failed:
1077
-                    case EEM_Message::status_debug_only:
1078
-                    case EEM_Message::status_messenger_executing:
1079
-                        $status_bulk_actions = [];
1080
-                        break;
1081
-
1082
-                    case EEM_Message::status_incomplete:
1083
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1084
-                        break;
1085
-
1086
-                    case EEM_Message::status_retry:
1087
-                    case EEM_Message::status_sent:
1088
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1089
-                        break;
1090
-                }
1091
-            }
1092
-
1093
-            // skip adding messenger executing status to views because it will be included with the Failed view.
1094
-            if ($status === EEM_Message::status_messenger_executing) {
1095
-                continue;
1096
-            }
1097
-
1098
-            $this->_views[ strtolower($status) ] = [
1099
-                'slug'        => strtolower($status),
1100
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1101
-                'count'       => 0,
1102
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1103
-            ];
1104
-        }
1105
-    }
1106
-
1107
-
1108
-    /**
1109
-     * @throws EE_Error
1110
-     */
1111
-    protected function _ee_default_messages_overview_list_table()
1112
-    {
1113
-        $this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1114
-        $this->display_admin_list_table_page_with_no_sidebar();
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * @throws EE_Error
1120
-     * @throws ReflectionException
1121
-     */
1122
-    protected function _message_queue_list_table()
1123
-    {
1124
-        $this->_search_btn_label                   = esc_html__('Message Activity', 'event_espresso');
1125
-        $this->_template_args['per_column']        = 6;
1126
-        $this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
1127
-        $this->_template_args['before_list_table'] = '<h3>'
1128
-                                                     . $this->getMsgModel()->get_pretty_label_for_results()
1129
-                                                     . '</h3>';
1130
-        $this->display_admin_list_table_page_with_no_sidebar();
1131
-    }
1132
-
1133
-
1134
-    /**
1135
-     * @throws EE_Error
1136
-     */
1137
-    protected function _message_legend_items()
1138
-    {
1139
-
1140
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
1141
-        $action_items       = [];
1142
-
1143
-        foreach ($action_css_classes as $action_item => $action_details) {
1144
-            if ($action_item === 'see_notifications_for') {
1145
-                continue;
1146
-            }
1147
-            $action_items[ $action_item ] = [
1148
-                'class' => $action_details['css_class'],
1149
-                'desc'  => $action_details['label'],
1150
-            ];
1151
-        }
1152
-
1153
-        /** @var array $status_items status legend setup */
1154
-        $status_items = [
1155
-            'sent_status'                => [
1156
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1157
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1158
-            ],
1159
-            'idle_status'                => [
1160
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1161
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1162
-            ],
1163
-            'failed_status'              => [
1164
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1165
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1166
-            ],
1167
-            'messenger_executing_status' => [
1168
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1169
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1170
-            ],
1171
-            'resend_status'              => [
1172
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1173
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1174
-            ],
1175
-            'incomplete_status'          => [
1176
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1177
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1178
-            ],
1179
-            'retry_status'               => [
1180
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1181
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1182
-            ],
1183
-        ];
1184
-        if (EEM_Message::debug()) {
1185
-            $status_items['debug_only_status'] = [
1186
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1187
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1188
-            ];
1189
-        }
1190
-
1191
-        return array_merge($action_items, $status_items);
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * @throws EE_Error
1197
-     */
1198
-    protected function _custom_mtps_preview()
1199
-    {
1200
-        $this->_admin_page_title              = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1201
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1202
-                                                . ' alt="' . esc_attr__(
1203
-                                                    'Preview Custom Message Templates screenshot',
1204
-                                                    'event_espresso'
1205
-                                                ) . '" />';
1206
-        $this->_template_args['preview_text'] = '<strong>'
1207
-                                                . esc_html__(
1208
-                                                    'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1209
-                                                    'event_espresso'
1210
-                                                )
1211
-                                                . '</strong>';
1212
-
1213
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1214
-    }
1215
-
1216
-
1217
-    /**
1218
-     * get_message_templates
1219
-     * This gets all the message templates for listing on the overview list.
1220
-     *
1221
-     * @access public
1222
-     * @param int    $per_page the amount of templates groups to show per page
1223
-     * @param string $type     the current _view we're getting templates for
1224
-     * @param bool   $count    return count?
1225
-     * @param bool   $all      disregard any paging info (get all data);
1226
-     * @param bool   $global   whether to return just global (true) or custom templates (false)
1227
-     * @return array
1228
-     * @throws EE_Error
1229
-     * @throws InvalidArgumentException
1230
-     * @throws InvalidDataTypeException
1231
-     * @throws InvalidInterfaceException
1232
-     */
1233
-    public function get_message_templates(
1234
-        $per_page = 10,
1235
-        $type = 'in_use',
1236
-        $count = false,
1237
-        $all = false,
1238
-        $global = true
1239
-    ) {
1240
-        $orderby = $this->request->getRequestParam('orderby', 'GRP_ID');
1241
-        $this->request->setRequestParam('orderby', $orderby);
1242
-
1243
-        $order        = $this->request->getRequestParam('order', 'ASC');
1244
-        $current_page = $this->request->getRequestParam('paged', 1, 'int');
1245
-        $per_page     = $this->request->getRequestParam('perpage', $per_page, 'int');
1246
-
1247
-        $offset = ($current_page - 1) * $per_page;
1248
-        $limit  = $all ? null : [$offset, $per_page];
1249
-
1250
-        // options will match what is in the _views array property
1251
-        return $type === 'in_use'
1252
-            ? $this->getMtgModel()->get_all_active_message_templates(
1253
-                $orderby,
1254
-                $order,
1255
-                $limit,
1256
-                $count,
1257
-                $global,
1258
-                true
1259
-            )
1260
-            : $this->getMtgModel()->get_all_trashed_grouped_message_templates(
1261
-                $orderby,
1262
-                $order,
1263
-                $limit,
1264
-                $count,
1265
-                $global
1266
-            );
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * filters etc might need a list of installed message_types
1272
-     *
1273
-     * @return array an array of message type objects
1274
-     */
1275
-    public function get_installed_message_types()
1276
-    {
1277
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1278
-        $installed               = [];
1279
-
1280
-        foreach ($installed_message_types as $message_type) {
1281
-            $installed[ $message_type->name ] = $message_type;
1282
-        }
1283
-
1284
-        return $installed;
1285
-    }
1286
-
1287
-
1288
-    /**
1289
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1290
-     *
1291
-     * @param string $message_type
1292
-     * @param string $messenger
1293
-     * @param string $GRP_ID
1294
-     *
1295
-     * @throws EE_error
1296
-     * @throws ReflectionException
1297
-     */
1298
-    public function add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1299
-    {
1300
-        // set values override any request data
1301
-        $message_type = ! empty($message_type) ? $message_type : $this->_active_message_type_name;
1302
-        $messenger    = ! empty($messenger) ? $messenger : $this->_active_messenger_name;
1303
-        $GRP_ID       = ! empty($GRP_ID) ? $GRP_ID : $this->request->getRequestParam('GRP_ID', 0, 'int');
1304
-
1305
-        // we need messenger and message type.  They should be coming from the event editor. If not here then return error
1306
-        if (empty($message_type) || empty($messenger)) {
1307
-            throw new EE_Error(
1308
-                esc_html__(
1309
-                    'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1310
-                    'event_espresso'
1311
-                )
1312
-            );
1313
-        }
1314
-
1315
-        // we need the GRP_ID for the template being used as the base for the new template
1316
-        if (empty($GRP_ID)) {
1317
-            throw new EE_Error(
1318
-                esc_html__(
1319
-                    'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1320
-                    'event_espresso'
1321
-                )
1322
-            );
1323
-        }
1324
-
1325
-        // let's just make sure the template gets generated!
1326
-
1327
-        // we need to reassign some variables for what the insert is expecting
1328
-        $this->request->setRequestParam('MTP_messenger', $messenger);
1329
-        $this->request->setRequestParam('MTP_message_type', $message_type);
1330
-        $this->request->setRequestParam('GRP_ID', $GRP_ID);
1331
-
1332
-        $this->_insert_or_update_message_template(true);
1333
-    }
1334
-
1335
-
1336
-    /**
1337
-     * @param string $message_type     message type slug
1338
-     * @param string $messenger        messenger slug
1339
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1340
-     *                                 off of.
1341
-     * @throws EE_error
1342
-     * @throws ReflectionException
1343
-     * @deprecated $VID:$
1344
-     */
1345
-    protected function _add_message_template($message_type, $messenger, $GRP_ID)
1346
-    {
1347
-        $this->add_message_template($message_type, $messenger, $GRP_ID);
1348
-    }
1349
-
1350
-
1351
-    /**
1352
-     * _edit_message_template
1353
-     *
1354
-     * @access protected
1355
-     * @return void
1356
-     * @throws InvalidIdentifierException
1357
-     * @throws DomainException
1358
-     * @throws EE_Error
1359
-     * @throws InvalidArgumentException
1360
-     * @throws ReflectionException
1361
-     * @throws InvalidDataTypeException
1362
-     * @throws InvalidInterfaceException
1363
-     */
1364
-    protected function _edit_message_template()
1365
-    {
1366
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1367
-        $template_fields = '';
1368
-        $sidebar_fields  = '';
1369
-        // we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1370
-        // valid html in the templates.
1371
-        add_filter('tiny_mce_before_init', [$this, 'filter_tinymce_init'], 10, 2);
1372
-
1373
-        $GRP_ID = $this->request->getRequestParam('id', 0, 'int');
1374
-        $EVT_ID = $this->request->getRequestParam('evt_id', 0, 'int');
1375
-
1376
-        $this->_set_shortcodes(); // this also sets the _message_template property.
1377
-        $message_template_group = $this->_message_template_group;
1378
-        $c_label                = $message_template_group->context_label();
1379
-        $c_config               = $message_template_group->contexts_config();
1380
-
1381
-        reset($c_config);
1382
-        $context = $this->request->getRequestParam('context', key($c_config));
1383
-        $context = strtolower($context);
1384
-
1385
-        $action = empty($GRP_ID) ? 'insert_message_template' : 'update_message_template';
1386
-
1387
-        $edit_message_template_form_url = add_query_arg(
1388
-            ['action' => $action, 'noheader' => true],
1389
-            EE_MSG_ADMIN_URL
1390
-        );
1391
-
1392
-        // set active messenger for this view
1393
-        $this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1394
-            $message_template_group->messenger()
1395
-        );
1396
-        $this->_active_message_type_name = $message_template_group->message_type();
1397
-
1398
-
1399
-        // Do we have any validation errors?
1400
-        $validators = $this->_get_transient();
1401
-        $v_fields   = ! empty($validators) ? array_keys($validators) : [];
1402
-
1403
-
1404
-        // we need to assemble the title from Various details
1405
-        $context_label = sprintf(
1406
-            esc_html__('(%s %s)', 'event_espresso'),
1407
-            $c_config[ $context ]['label'],
1408
-            ucwords($c_label['label'])
1409
-        );
1410
-
1411
-        $title = sprintf(
1412
-            esc_html__(' %s %s Template %s', 'event_espresso'),
1413
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1414
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1415
-            $context_label
1416
-        );
1417
-
1418
-        $this->_template_args['GRP_ID']           = $GRP_ID;
1419
-        $this->_template_args['message_template'] = $message_template_group;
1420
-        $this->_template_args['is_extra_fields']  = false;
1421
-
1422
-
1423
-        // let's get EEH_MSG_Template so we can get template form fields
1424
-        $template_field_structure = EEH_MSG_Template::get_fields(
1425
-            $message_template_group->messenger(),
1426
-            $message_template_group->message_type()
1427
-        );
1428
-
1429
-        if (! $template_field_structure) {
1430
-            $template_field_structure = false;
1431
-            $template_fields          = esc_html__(
1432
-                'There was an error in assembling the fields for this display (you should see an error message)',
1433
-                'event_espresso'
1434
-            );
1435
-        }
1436
-
1437
-
1438
-        $message_templates = $message_template_group->context_templates();
1439
-
1440
-
1441
-        // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1442
-        // will get handled in the "extra" array.
1443
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1444
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1445
-                unset($template_field_structure[ $context ][ $reference_field ]);
1446
-            }
1447
-        }
1448
-
1449
-        // let's loop through the template_field_structure and actually assemble the input fields!
1450
-        if (! empty($template_field_structure)) {
1451
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1452
-                // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1453
-                // the extra array and reset them.
1454
-                if ($template_field === 'extra') {
1455
-                    $this->_template_args['is_extra_fields'] = true;
1456
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1457
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1458
-                        $content          = $message_template instanceof EE_Message_Template
1459
-                            ? $message_template->get('MTP_content')
1460
-                            : '';
1461
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1462
-                            // let's verify if we need this extra field via the shortcodes parameter.
1463
-                            $continue = false;
1464
-                            if (isset($extra_array['shortcodes_required'])) {
1465
-                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1466
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1467
-                                        $continue = true;
1468
-                                    }
1469
-                                }
1470
-                                if ($continue) {
1471
-                                    continue;
1472
-                                }
1473
-                            }
1474
-
1475
-                            $field_id = $reference_field . '-' . $extra_field . '-content';
1476
-
1477
-                            $template_form_fields[ $field_id ]         = $extra_array;
1478
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1479
-                                                                         . $reference_field
1480
-                                                                         . '][content]['
1481
-                                                                         . $extra_field . ']';
1482
-                            $css_class                                 = isset($extra_array['css_class'])
1483
-                                ? $extra_array['css_class']
1484
-                                : '';
1485
-
1486
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1487
-                                                                              && in_array($extra_field, $v_fields, true)
1488
-                                                                              && (
1489
-                                                                                  is_array($validators[ $extra_field ])
1490
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1491
-                                                                              )
1492
-                                ? 'validate-error ' . $css_class
1493
-                                : $css_class;
1494
-
1495
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1496
-                                                                          && isset($content[ $extra_field ])
1497
-                                ? $content[ $extra_field ]
1498
-                                : '';
1499
-
1500
-                            // do we have a validation error?  if we do then let's use that value instead
1501
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1502
-                                ? $validators[ $extra_field ]['value']
1503
-                                : $template_form_fields[ $field_id ]['value'];
1504
-
1505
-
1506
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1507
-
1508
-                            // shortcode selector
1509
-                            $field_name_to_use                                   = $extra_field === 'main'
1510
-                                ? 'content'
1511
-                                : $extra_field;
1512
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1513
-                                $field_name_to_use,
1514
-                                $field_id
1515
-                            );
1516
-                        }
1517
-                        $template_field_MTP_id           = $reference_field . '-MTP_ID';
1518
-                        $template_field_template_name_id = $reference_field . '-name';
1519
-
1520
-                        $template_form_fields[ $template_field_MTP_id ] = [
1521
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1522
-                            'label'      => null,
1523
-                            'input'      => 'hidden',
1524
-                            'type'       => 'int',
1525
-                            'required'   => false,
1526
-                            'validation' => false,
1527
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1528
-                            'css_class'  => '',
1529
-                            'format'     => '%d',
1530
-                            'db-col'     => 'MTP_ID',
1531
-                        ];
1532
-
1533
-                        $template_form_fields[ $template_field_template_name_id ] = [
1534
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1535
-                            'label'      => null,
1536
-                            'input'      => 'hidden',
1537
-                            'type'       => 'string',
1538
-                            'required'   => false,
1539
-                            'validation' => true,
1540
-                            'value'      => $reference_field,
1541
-                            'css_class'  => '',
1542
-                            'format'     => '%s',
1543
-                            'db-col'     => 'MTP_template_field',
1544
-                        ];
1545
-                    }
1546
-                    continue; // skip the next stuff, we got the necessary fields here for this dataset.
1547
-                } else {
1548
-                    $field_id                                   = $template_field . '-content';
1549
-                    $template_form_fields[ $field_id ]          = $field_setup_array;
1550
-                    $template_form_fields[ $field_id ]['name']  =
1551
-                        'MTP_template_fields[' . $template_field . '][content]';
1552
-                    $message_template                           =
1553
-                        isset($message_templates[ $context ][ $template_field ])
1554
-                            ? $message_templates[ $context ][ $template_field ]
1555
-                            : null;
1556
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1557
-                                                                  && is_array($message_templates[ $context ])
1558
-                                                                  && $message_template instanceof EE_Message_Template
1559
-                        ? $message_template->get('MTP_content')
1560
-                        : '';
1561
-
1562
-                    // do we have a validator error for this field?  if we do then we'll use that value instead
1563
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1564
-                        ? $validators[ $template_field ]['value']
1565
-                        : $template_form_fields[ $field_id ]['value'];
1566
-
1567
-
1568
-                    $template_form_fields[ $field_id ]['db-col']    = 'MTP_content';
1569
-                    $css_class                                      = isset($field_setup_array['css_class'])
1570
-                        ? $field_setup_array['css_class']
1571
-                        : '';
1572
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1573
-                                                                      && in_array($template_field, $v_fields, true)
1574
-                                                                      && isset($validators[ $template_field ]['msg'])
1575
-                        ? 'validate-error ' . $css_class
1576
-                        : $css_class;
1577
-
1578
-                    // shortcode selector
1579
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1580
-                        $template_field,
1581
-                        $field_id
1582
-                    );
1583
-                }
1584
-
1585
-                // k took care of content field(s) now let's take care of others.
1586
-
1587
-                $template_field_MTP_id                 = $template_field . '-MTP_ID';
1588
-                $template_field_field_template_name_id = $template_field . '-name';
1589
-
1590
-                // foreach template field there are actually two form fields created
1591
-                $template_form_fields[ $template_field_MTP_id ] = [
1592
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1593
-                    'label'      => null,
1594
-                    'input'      => 'hidden',
1595
-                    'type'       => 'int',
1596
-                    'required'   => false,
1597
-                    'validation' => true,
1598
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1599
-                    'css_class'  => '',
1600
-                    'format'     => '%d',
1601
-                    'db-col'     => 'MTP_ID',
1602
-                ];
1603
-
1604
-                $template_form_fields[ $template_field_field_template_name_id ] = [
1605
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1606
-                    'label'      => null,
1607
-                    'input'      => 'hidden',
1608
-                    'type'       => 'string',
1609
-                    'required'   => false,
1610
-                    'validation' => true,
1611
-                    'value'      => $template_field,
1612
-                    'css_class'  => '',
1613
-                    'format'     => '%s',
1614
-                    'db-col'     => 'MTP_template_field',
1615
-                ];
1616
-            }
1617
-
1618
-            // add other fields
1619
-            $template_form_fields['ee-msg-current-context'] = [
1620
-                'name'       => 'MTP_context',
1621
-                'label'      => null,
1622
-                'input'      => 'hidden',
1623
-                'type'       => 'string',
1624
-                'required'   => false,
1625
-                'validation' => true,
1626
-                'value'      => $context,
1627
-                'css_class'  => '',
1628
-                'format'     => '%s',
1629
-                'db-col'     => 'MTP_context',
1630
-            ];
1631
-
1632
-            $template_form_fields['ee-msg-grp-id'] = [
1633
-                'name'       => 'GRP_ID',
1634
-                'label'      => null,
1635
-                'input'      => 'hidden',
1636
-                'type'       => 'int',
1637
-                'required'   => false,
1638
-                'validation' => true,
1639
-                'value'      => $GRP_ID,
1640
-                'css_class'  => '',
1641
-                'format'     => '%d',
1642
-                'db-col'     => 'GRP_ID',
1643
-            ];
1644
-
1645
-            $template_form_fields['ee-msg-messenger'] = [
1646
-                'name'       => 'MTP_messenger',
1647
-                'label'      => null,
1648
-                'input'      => 'hidden',
1649
-                'type'       => 'string',
1650
-                'required'   => false,
1651
-                'validation' => true,
1652
-                'value'      => $message_template_group->messenger(),
1653
-                'css_class'  => '',
1654
-                'format'     => '%s',
1655
-                'db-col'     => 'MTP_messenger',
1656
-            ];
1657
-
1658
-            $template_form_fields['ee-msg-message-type'] = [
1659
-                'name'       => 'MTP_message_type',
1660
-                'label'      => null,
1661
-                'input'      => 'hidden',
1662
-                'type'       => 'string',
1663
-                'required'   => false,
1664
-                'validation' => true,
1665
-                'value'      => $message_template_group->message_type(),
1666
-                'css_class'  => '',
1667
-                'format'     => '%s',
1668
-                'db-col'     => 'MTP_message_type',
1669
-            ];
1670
-
1671
-            $sidebar_form_fields['ee-msg-is-global'] = [
1672
-                'name'       => 'MTP_is_global',
1673
-                'label'      => esc_html__('Global Template', 'event_espresso'),
1674
-                'input'      => 'hidden',
1675
-                'type'       => 'int',
1676
-                'required'   => false,
1677
-                'validation' => true,
1678
-                'value'      => $message_template_group->get('MTP_is_global'),
1679
-                'css_class'  => '',
1680
-                'format'     => '%d',
1681
-                'db-col'     => 'MTP_is_global',
1682
-            ];
1683
-
1684
-            $sidebar_form_fields['ee-msg-is-override'] = [
1685
-                'name'       => 'MTP_is_override',
1686
-                'label'      => esc_html__('Override all custom', 'event_espresso'),
1687
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1688
-                'type'       => 'int',
1689
-                'required'   => false,
1690
-                'validation' => true,
1691
-                'value'      => $message_template_group->get('MTP_is_override'),
1692
-                'css_class'  => '',
1693
-                'format'     => '%d',
1694
-                'db-col'     => 'MTP_is_override',
1695
-            ];
1696
-
1697
-            $sidebar_form_fields['ee-msg-is-active'] = [
1698
-                'name'       => 'MTP_is_active',
1699
-                'label'      => esc_html__('Active Template', 'event_espresso'),
1700
-                'input'      => 'hidden',
1701
-                'type'       => 'int',
1702
-                'required'   => false,
1703
-                'validation' => true,
1704
-                'value'      => $message_template_group->is_active(),
1705
-                'css_class'  => '',
1706
-                'format'     => '%d',
1707
-                'db-col'     => 'MTP_is_active',
1708
-            ];
1709
-
1710
-            $sidebar_form_fields['ee-msg-deleted'] = [
1711
-                'name'       => 'MTP_deleted',
1712
-                'label'      => null,
1713
-                'input'      => 'hidden',
1714
-                'type'       => 'int',
1715
-                'required'   => false,
1716
-                'validation' => true,
1717
-                'value'      => $message_template_group->get('MTP_deleted'),
1718
-                'css_class'  => '',
1719
-                'format'     => '%d',
1720
-                'db-col'     => 'MTP_deleted',
1721
-            ];
1722
-            $sidebar_form_fields['ee-msg-author']  = [
1723
-                'name'       => 'MTP_user_id',
1724
-                'label'      => esc_html__('Author', 'event_espresso'),
1725
-                'input'      => 'hidden',
1726
-                'type'       => 'int',
1727
-                'required'   => false,
1728
-                'validation' => false,
1729
-                'value'      => $message_template_group->user(),
1730
-                'format'     => '%d',
1731
-                'db-col'     => 'MTP_user_id',
1732
-            ];
1733
-
1734
-            $sidebar_form_fields['ee-msg-route'] = [
1735
-                'name'  => 'action',
1736
-                'input' => 'hidden',
1737
-                'type'  => 'string',
1738
-                'value' => $action,
1739
-            ];
1740
-
1741
-            $sidebar_form_fields['ee-msg-id']        = [
1742
-                'name'  => 'id',
1743
-                'input' => 'hidden',
1744
-                'type'  => 'int',
1745
-                'value' => $GRP_ID,
1746
-            ];
1747
-            $sidebar_form_fields['ee-msg-evt-nonce'] = [
1748
-                'name'  => $action . '_nonce',
1749
-                'input' => 'hidden',
1750
-                'type'  => 'string',
1751
-                'value' => wp_create_nonce($action . '_nonce'),
1752
-            ];
1753
-
1754
-            $template_switch = $this->request->getRequestParam('template_switch');
1755
-            if ($template_switch) {
1756
-                $sidebar_form_fields['ee-msg-template-switch'] = [
1757
-                    'name'  => 'template_switch',
1758
-                    'input' => 'hidden',
1759
-                    'type'  => 'int',
1760
-                    'value' => 1,
1761
-                ];
1762
-            }
1763
-
1764
-
1765
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1766
-            $sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1767
-        } //end if ( !empty($template_field_structure) )
1768
-
1769
-        // set extra content for publish box
1770
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1771
-        $this->_set_publish_post_box_vars(
1772
-            'id',
1773
-            $GRP_ID,
1774
-            false,
1775
-            add_query_arg(
1776
-                ['action' => 'global_mtps'],
1777
-                $this->_admin_base_url
1778
-            )
1779
-        );
1780
-
1781
-        // add preview button
1782
-        $preview_url    = parent::add_query_args_and_nonce(
1783
-            [
1784
-                'message_type' => $message_template_group->message_type(),
1785
-                'messenger'    => $message_template_group->messenger(),
1786
-                'context'      => $context,
1787
-                'GRP_ID'       => $GRP_ID,
1788
-                'evt_id'       => $EVT_ID ?: false,
1789
-                'action'       => 'preview_message',
1790
-            ],
1791
-            $this->_admin_base_url
1792
-        );
1793
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1794
-                          . esc_html__('Preview', 'event_espresso')
1795
-                          . '</a>';
1796
-
1797
-
1798
-        // setup context switcher
1799
-        $this->_set_context_switcher(
1800
-            $message_template_group,
1801
-            [
1802
-                'page'    => 'espresso_messages',
1803
-                'action'  => 'edit_message_template',
1804
-                'id'      => $GRP_ID,
1805
-                'evt_id'  => $EVT_ID,
1806
-                'context' => $context,
1807
-                'extra'   => $preview_button,
1808
-            ]
1809
-        );
1810
-
1811
-
1812
-        // main box
1813
-        $this->_template_args['template_fields']                         = $template_fields;
1814
-        $this->_template_args['sidebar_box_id']                          = 'details';
1815
-        $this->_template_args['action']                                  = $action;
1816
-        $this->_template_args['context']                                 = $context;
1817
-        $this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1818
-        $this->_template_args['learn_more_about_message_templates_link'] =
1819
-            $this->_learn_more_about_message_templates_link();
1820
-
1821
-
1822
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1823
-        $this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1824
-            $message_template_group,
1825
-            $context,
1826
-            $context_label
1827
-        );
1828
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1829
-        $this->_template_args['after_admin_page_content']  = $this->_add_form_element_after();
1830
-
1831
-        $this->_template_path = $this->_template_args['GRP_ID']
1832
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1833
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1834
-
1835
-        // send along EE_Message_Template_Group object for further template use.
1836
-        $this->_template_args['MTP'] = $message_template_group;
1837
-
1838
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1839
-            $this->_template_path,
1840
-            $this->_template_args,
1841
-            true
1842
-        );
1843
-
1844
-
1845
-        // finally, let's set the admin_page title
1846
-        $this->_admin_page_title = sprintf(esc_html__('Editing %s', 'event_espresso'), $title);
1847
-
1848
-
1849
-        // we need to take care of setting the shortcodes property for use elsewhere.
1850
-        $this->_set_shortcodes();
1851
-
1852
-
1853
-        // final template wrapper
1854
-        $this->display_admin_page_with_sidebar();
1855
-    }
1856
-
1857
-
1858
-    public function filter_tinymce_init($mceInit, $editor_id)
1859
-    {
1860
-        return $mceInit;
1861
-    }
1862
-
1863
-
1864
-    public function add_context_switcher()
1865
-    {
1866
-        return $this->_context_switcher;
1867
-    }
1868
-
1869
-
1870
-    /**
1871
-     * Adds the activation/deactivation toggle for the message template context.
1872
-     *
1873
-     * @param EE_Message_Template_Group $message_template_group
1874
-     * @param string                    $context
1875
-     * @param string                    $context_label
1876
-     * @return string
1877
-     * @throws DomainException
1878
-     * @throws EE_Error
1879
-     * @throws InvalidIdentifierException
1880
-     * @throws ReflectionException
1881
-     */
1882
-    protected function add_active_context_element(
1883
-        EE_Message_Template_Group $message_template_group,
1884
-        $context,
1885
-        $context_label
1886
-    ) {
1887
-        $template_args = [
1888
-            'context'                   => $context,
1889
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1890
-            'is_active'                 => $message_template_group->is_context_active($context),
1891
-            'on_off_action'             => $message_template_group->is_context_active($context)
1892
-                ? 'context-off'
1893
-                : 'context-on',
1894
-            'context_label'             => str_replace(['(', ')'], '', $context_label),
1895
-            'message_template_group_id' => $message_template_group->ID(),
1896
-        ];
1897
-        return EEH_Template::display_template(
1898
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1899
-            $template_args,
1900
-            true
1901
-        );
1902
-    }
1903
-
1904
-
1905
-    /**
1906
-     * Ajax callback for `toggle_context_template` ajax action.
1907
-     * Handles toggling the message context on or off.
1908
-     *
1909
-     * @throws EE_Error
1910
-     * @throws InvalidArgumentException
1911
-     * @throws InvalidDataTypeException
1912
-     * @throws InvalidIdentifierException
1913
-     * @throws InvalidInterfaceException
1914
-     */
1915
-    public function toggle_context_template()
1916
-    {
1917
-        $success = true;
1918
-        // check for required data
1919
-        if (
1920
-            ! (
1921
-                $this->request->requestParamIsSet('message_template_group_id')
1922
-                && $this->request->requestParamIsSet('context')
1923
-                && $this->request->requestParamIsSet('status')
1924
-            )
1925
-        ) {
1926
-            EE_Error::add_error(
1927
-                esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1928
-                __FILE__,
1929
-                __FUNCTION__,
1930
-                __LINE__
1931
-            );
1932
-            $success = false;
1933
-        }
1934
-
1935
-        $nonce   = $this->request->getRequestParam('toggle_context_nonce', '');
1936
-        $context = $this->request->getRequestParam('context', '');
1937
-        $status  = $this->request->getRequestParam('status', '');
1938
-
1939
-        $this->_verify_nonce($nonce, "activate_{$context}_toggle_nonce");
1940
-
1941
-        if ($status !== 'off' && $status !== 'on') {
1942
-            EE_Error::add_error(
1943
-                sprintf(
1944
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1945
-                    $status
1946
-                ),
1947
-                __FILE__,
1948
-                __FUNCTION__,
1949
-                __LINE__
1950
-            );
1951
-            $success = false;
1952
-        }
1953
-        $message_template_group_id = $this->request->getRequestParam('message_template_group_id', 0, 'int');
1954
-        $message_template_group    = $this->getMtgModel()->get_one_by_ID($message_template_group_id);
1955
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1956
-            EE_Error::add_error(
1957
-                sprintf(
1958
-                    esc_html__(
1959
-                        'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1960
-                        'event_espresso'
1961
-                    ),
1962
-                    $message_template_group_id,
1963
-                    'EE_Message_Template_Group'
1964
-                ),
1965
-                __FILE__,
1966
-                __FUNCTION__,
1967
-                __LINE__
1968
-            );
1969
-            $success = false;
1970
-        }
1971
-        if ($success) {
1972
-            $success = $status === 'off'
1973
-                ? $message_template_group->deactivate_context($context)
1974
-                : $message_template_group->activate_context($context);
1975
-        }
1976
-        $this->_template_args['success'] = $success;
1977
-        $this->_return_json();
1978
-    }
1979
-
1980
-
1981
-    public function _add_form_element_before()
1982
-    {
1983
-        return '<form method="post" action="'
1984
-               . $this->_template_args['edit_message_template_form_url']
1985
-               . '" id="ee-msg-edit-frm">';
1986
-    }
1987
-
1988
-
1989
-    public function _add_form_element_after()
1990
-    {
1991
-        return '</form>';
1992
-    }
1993
-
1994
-
1995
-    /**
1996
-     * This executes switching the template pack for a message template.
1997
-     *
1998
-     * @throws EE_Error
1999
-     * @throws InvalidDataTypeException
2000
-     * @throws InvalidInterfaceException
2001
-     * @throws InvalidArgumentException
2002
-     * @throws ReflectionException
2003
-     * @since 4.5.0
2004
-     */
2005
-    public function switch_template_pack()
2006
-    {
2007
-
2008
-        $GRP_ID        = $this->request->getRequestParam('GRP_ID', 0, 'int');
2009
-        $template_pack = $this->request->getRequestParam('template_pack', '');
2010
-
2011
-        // verify we have needed values.
2012
-        if (empty($GRP_ID) || empty($template_pack)) {
2013
-            $this->_template_args['error'] = true;
2014
-            EE_Error::add_error(
2015
-                esc_html__('The required date for switching templates is not available.', 'event_espresso'),
2016
-                __FILE__,
2017
-                __FUNCTION__,
2018
-                __LINE__
2019
-            );
2020
-        } else {
2021
-            // get template, set the new template_pack and then reset to default
2022
-            /** @var EE_Message_Template_Group $message_template_group */
2023
-            $message_template_group = $this->getMtgModel()->get_one_by_ID($GRP_ID);
2024
-
2025
-            $message_template_group->set_template_pack_name($template_pack);
2026
-            $this->request->setRequestParam('msgr', $message_template_group->messenger());
2027
-            $this->request->setRequestParam('mt', $message_template_group->message_type());
2028
-
2029
-            $query_args = $this->_reset_to_default_template();
2030
-
2031
-            if (empty($query_args['id'])) {
2032
-                EE_Error::add_error(
2033
-                    esc_html__(
2034
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
2035
-                        'event_espresso'
2036
-                    ),
2037
-                    __FILE__,
2038
-                    __FUNCTION__,
2039
-                    __LINE__
2040
-                );
2041
-                $this->_template_args['error'] = true;
2042
-            } else {
2043
-                $template_label       = $message_template_group->get_template_pack()->label;
2044
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
2045
-                EE_Error::add_success(
2046
-                    sprintf(
2047
-                        esc_html__(
2048
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
2049
-                            'event_espresso'
2050
-                        ),
2051
-                        $template_label,
2052
-                        $template_pack_labels->template_pack
2053
-                    )
2054
-                );
2055
-                // generate the redirect url for js.
2056
-                $url = self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2057
-
2058
-                $this->_template_args['data']['redirect_url'] = $url;
2059
-                $this->_template_args['success']              = true;
2060
-            }
2061
-
2062
-            $this->_return_json();
2063
-        }
2064
-    }
2065
-
2066
-
2067
-    /**
2068
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2069
-     * they want.
2070
-     *
2071
-     * @access protected
2072
-     * @return array|void
2073
-     * @throws EE_Error
2074
-     * @throws InvalidArgumentException
2075
-     * @throws InvalidDataTypeException
2076
-     * @throws InvalidInterfaceException
2077
-     * @throws ReflectionException
2078
-     */
2079
-    protected function _reset_to_default_template()
2080
-    {
2081
-        $templates    = [];
2082
-        $GRP_ID       = $this->request->getRequestParam('GRP_ID', 0, 'int');
2083
-        $messenger    = $this->request->getRequestParam('msgr');
2084
-        $message_type = $this->request->getRequestParam('mt');
2085
-        // we need to make sure we've got the info we need.
2086
-        if (! ($GRP_ID && $messenger && $message_type)) {
2087
-            EE_Error::add_error(
2088
-                esc_html__(
2089
-                    'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
2090
-                    'event_espresso'
2091
-                ),
2092
-                __FILE__,
2093
-                __FUNCTION__,
2094
-                __LINE__
2095
-            );
2096
-        }
2097
-
2098
-        // all templates will be reset to whatever the defaults are
2099
-        // for the global template matching the messenger and message type.
2100
-        $success = ! empty($GRP_ID);
2101
-
2102
-        if ($success) {
2103
-            // let's first determine if the incoming template is a global template,
2104
-            // if it isn't then we need to get the global template matching messenger and message type.
2105
-            // $MTPG = $this->getMtgModel()->get_one_by_ID( $GRP_ID );
2106
-
2107
-
2108
-            // note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2109
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
2110
-
2111
-            if ($success) {
2112
-                // if successfully deleted, lets generate the new ones.
2113
-                // Note. We set GLOBAL to true, because resets on ANY template
2114
-                // will use the related global template defaults for regeneration.
2115
-                // This means that if a custom template is reset it resets to whatever the related global template is.
2116
-                // HOWEVER, we DO keep the template pack and template variation set
2117
-                // for the current custom template when resetting.
2118
-                $templates = $this->_generate_new_templates($messenger, $message_type, $GRP_ID, true);
2119
-            }
2120
-        }
2121
-
2122
-        // any error messages?
2123
-        if (! $success) {
2124
-            EE_Error::add_error(
2125
-                esc_html__(
2126
-                    'Something went wrong with deleting existing templates. Unable to reset to default',
2127
-                    'event_espresso'
2128
-                ),
2129
-                __FILE__,
2130
-                __FUNCTION__,
2131
-                __LINE__
2132
-            );
2133
-        }
2134
-
2135
-        // all good, let's add a success message!
2136
-        if ($success && ! empty($templates)) {
2137
-            // the info for the template we generated is the first element in the returned array
2138
-            EE_Error::overwrite_success();
2139
-            EE_Error::add_success(esc_html__('Templates have been reset to defaults.', 'event_espresso'));
2140
-        }
2141
-
2142
-
2143
-        $query_args = [
2144
-            'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
2145
-            'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
2146
-            'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2147
-        ];
2148
-
2149
-        // if called via ajax then we return query args otherwise redirect
2150
-        if ($this->request->isAjax()) {
2151
-            return $query_args;
2152
-        }
2153
-        $this->_redirect_after_action(false, '', '', $query_args, true);
2154
-    }
2155
-
2156
-
2157
-    /**
2158
-     * Retrieve and set the message preview for display.
2159
-     *
2160
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2161
-     * @return string
2162
-     * @throws ReflectionException
2163
-     * @throws EE_Error
2164
-     * @throws InvalidArgumentException
2165
-     * @throws InvalidDataTypeException
2166
-     * @throws InvalidInterfaceException
2167
-     */
2168
-    public function _preview_message($send = false)
2169
-    {
2170
-        // first make sure we've got the necessary parameters
2171
-        $GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
2172
-        if (! ($GRP_ID && $this->_active_messenger_name && $this->_active_message_type_name)) {
2173
-            EE_Error::add_error(
2174
-                esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2175
-                __FILE__,
2176
-                __FUNCTION__,
2177
-                __LINE__
2178
-            );
2179
-        }
2180
-
2181
-        $context = $this->request->getRequestParam('context');
2182
-        // get the preview!
2183
-        $preview = EED_Messages::preview_message(
2184
-            $this->_active_message_type_name,
2185
-            $context,
2186
-            $this->_active_messenger_name,
2187
-            $send
2188
-        );
2189
-
2190
-        if ($send) {
2191
-            return $preview;
2192
-        }
2193
-
2194
-        // if we have an evt_id set on the request, use it.
2195
-        $EVT_ID = $this->request->getRequestParam('evt_id', 0, 'int');
2196
-
2197
-        // let's add a button to go back to the edit view
2198
-        $query_args             = [
2199
-            'id'      => $GRP_ID,
2200
-            'evt_id'  => $EVT_ID,
2201
-            'context' => $context,
2202
-            'action'  => 'edit_message_template',
2203
-        ];
2204
-        $go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2205
-        $preview_button         = '<a href="'
2206
-                                  . $go_back_url
2207
-                                  . '" class="button-secondary messages-preview-go-back-button">'
2208
-                                  . esc_html__('Go Back to Edit', 'event_espresso')
2209
-                                  . '</a>';
2210
-        $message_types          = $this->get_installed_message_types();
2211
-        $active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_active_messenger_name);
2212
-        $active_messenger_label = $active_messenger instanceof EE_messenger
2213
-            ? ucwords($active_messenger->label['singular'])
2214
-            : esc_html__('Unknown Messenger', 'event_espresso');
2215
-        // let's provide a helpful title for context
2216
-        $preview_title = sprintf(
2217
-            esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2218
-            $active_messenger_label,
2219
-            ucwords($message_types[ $this->_active_message_type_name ]->label['singular'])
2220
-        );
2221
-        if (empty($preview)) {
2222
-            $this->noEventsErrorMessage();
2223
-        }
2224
-        // setup display of preview.
2225
-        $this->_admin_page_title                    = $preview_title;
2226
-        $this->_template_args['admin_page_title']   = $preview_title;
2227
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2228
-        $this->_template_args['data']['force_json'] = true;
2229
-
2230
-        return '';
2231
-    }
2232
-
2233
-
2234
-    /**
2235
-     * Used to set an error if there are no events available for generating a preview/test send.
2236
-     *
2237
-     * @param bool $test_send Whether the error should be generated for the context of a test send.
2238
-     */
2239
-    protected function noEventsErrorMessage($test_send = false)
2240
-    {
2241
-        $events_url = parent::add_query_args_and_nonce(
2242
-            [
2243
-                'action' => 'default',
2244
-                'page'   => 'espresso_events',
2245
-            ],
2246
-            admin_url('admin.php')
2247
-        );
2248
-        $message    = $test_send
2249
-            ? esc_html__(
2250
-                'A test message could not be sent for this message template because there are no events created yet. The preview system uses actual events for generating the test message. %1$sGo see your events%2$s!',
2251
-                'event_espresso'
2252
-            )
2253
-            : esc_html__(
2254
-                'There is no preview for this message template available because there are no events created yet. The preview system uses actual events for generating the preview. %1$sGo see your events%2$s!',
2255
-                'event_espresso'
2256
-            );
2257
-
2258
-        EE_Error::add_attention(
2259
-            sprintf(
2260
-                $message,
2261
-                "<a href='{$events_url}'>",
2262
-                '</a>'
2263
-            )
2264
-        );
2265
-    }
2266
-
2267
-
2268
-    /**
2269
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2270
-     * gets called automatically.
2271
-     *
2272
-     * @return void
2273
-     * @throws EE_Error
2274
-     * @since 4.5.0
2275
-     *
2276
-     */
2277
-    protected function _display_preview_message()
2278
-    {
2279
-        $this->display_admin_page_with_no_sidebar();
2280
-    }
2281
-
2282
-
2283
-    /**
2284
-     * registers metaboxes that should show up on the "edit_message_template" page
2285
-     *
2286
-     * @access protected
2287
-     * @return void
2288
-     */
2289
-    protected function _register_edit_meta_boxes()
2290
-    {
2291
-        add_meta_box(
2292
-            'mtp_valid_shortcodes',
2293
-            esc_html__('Valid Shortcodes', 'event_espresso'),
2294
-            [$this, 'shortcode_meta_box'],
2295
-            $this->_current_screen->id,
2296
-            'side'
2297
-        );
2298
-        add_meta_box(
2299
-            'mtp_extra_actions',
2300
-            esc_html__('Extra Actions', 'event_espresso'),
2301
-            [$this, 'extra_actions_meta_box'],
2302
-            $this->_current_screen->id,
2303
-            'side',
2304
-            'high'
2305
-        );
2306
-        add_meta_box(
2307
-            'mtp_templates',
2308
-            esc_html__('Template Styles', 'event_espresso'),
2309
-            [$this, 'template_pack_meta_box'],
2310
-            $this->_current_screen->id,
2311
-            'side',
2312
-            'high'
2313
-        );
2314
-    }
2315
-
2316
-
2317
-    /**
2318
-     * metabox content for all template pack and variation selection.
2319
-     *
2320
-     * @return void
2321
-     * @throws DomainException
2322
-     * @throws EE_Error
2323
-     * @throws InvalidArgumentException
2324
-     * @throws ReflectionException
2325
-     * @throws InvalidDataTypeException
2326
-     * @throws InvalidInterfaceException
2327
-     * @since 4.5.0
2328
-     */
2329
-    public function template_pack_meta_box()
2330
-    {
2331
-        $this->_set_message_template_group();
2332
-
2333
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
2334
-
2335
-        $tp_select_values = [];
2336
-
2337
-        foreach ($tp_collection as $tp) {
2338
-            // only include template packs that support this messenger and message type!
2339
-            $supports = $tp->get_supports();
2340
-            if (
2341
-                ! isset($supports[ $this->_message_template_group->messenger() ])
2342
-                || ! in_array(
2343
-                    $this->_message_template_group->message_type(),
2344
-                    $supports[ $this->_message_template_group->messenger() ],
2345
-                    true
2346
-                )
2347
-            ) {
2348
-                // not supported
2349
-                continue;
2350
-            }
2351
-
2352
-            $tp_select_values[] = [
2353
-                'text' => $tp->label,
2354
-                'id'   => $tp->dbref,
2355
-            ];
2356
-        }
2357
-
2358
-        // if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2359
-        // the default template pack.  This still allows for the odd template pack to override.
2360
-        if (empty($tp_select_values)) {
2361
-            $tp_select_values[] = [
2362
-                'text' => esc_html__('Default', 'event_espresso'),
2363
-                'id'   => 'default',
2364
-            ];
2365
-        }
2366
-
2367
-        // setup variation select values for the currently selected template.
2368
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
2369
-            $this->_message_template_group->messenger(),
2370
-            $this->_message_template_group->message_type()
2371
-        );
2372
-        $variations_select_values = [];
2373
-        foreach ($variations as $variation => $label) {
2374
-            $variations_select_values[] = [
2375
-                'text' => $label,
2376
-                'id'   => $variation,
2377
-            ];
2378
-        }
2379
-
2380
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2381
-
2382
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
2383
-            'MTP_template_pack',
2384
-            $tp_select_values,
2385
-            $this->_message_template_group->get_template_pack_name()
2386
-        );
2387
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
2388
-            'MTP_template_variation',
2389
-            $variations_select_values,
2390
-            $this->_message_template_group->get_template_pack_variation()
2391
-        );
2392
-        $template_args['template_pack_label']            = $template_pack_labels->template_pack;
2393
-        $template_args['template_variation_label']       = $template_pack_labels->template_variation;
2394
-        $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
2395
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2396
-
2397
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2398
-
2399
-        EEH_Template::display_template($template, $template_args);
2400
-    }
2401
-
2402
-
2403
-    /**
2404
-     * This meta box holds any extra actions related to Message Templates
2405
-     * For now, this includes Resetting templates to defaults and sending a test email.
2406
-     *
2407
-     * @access  public
2408
-     * @return void
2409
-     * @throws EE_Error
2410
-     */
2411
-    public function extra_actions_meta_box()
2412
-    {
2413
-        $template_form_fields = [];
2414
-
2415
-        $extra_args = [
2416
-            'msgr'   => $this->_message_template_group->messenger(),
2417
-            'mt'     => $this->_message_template_group->message_type(),
2418
-            'GRP_ID' => $this->_message_template_group->GRP_ID(),
2419
-        ];
2420
-        // first we need to see if there are any fields
2421
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2422
-
2423
-        if (! empty($fields)) {
2424
-            // yup there be fields
2425
-            foreach ($fields as $field => $config) {
2426
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2427
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2428
-                $default  = isset($config['default']) ? $config['default'] : '';
2429
-                $default  = isset($config['value']) ? $config['value'] : $default;
2430
-
2431
-                // if type is hidden and the value is empty
2432
-                // something may have gone wrong so let's correct with the defaults
2433
-                $fix                = $config['input'] === 'hidden'
2434
-                                      && isset($existing[ $field ])
2435
-                                      && empty($existing[ $field ])
2436
-                    ? $default
2437
-                    : '';
2438
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2439
-                    ? $existing[ $field ]
2440
-                    : $fix;
2441
-
2442
-                $template_form_fields[ $field_id ] = [
2443
-                    'name'       => 'test_settings_fld[' . $field . ']',
2444
-                    'label'      => $config['label'],
2445
-                    'input'      => $config['input'],
2446
-                    'type'       => $config['type'],
2447
-                    'required'   => $config['required'],
2448
-                    'validation' => $config['validation'],
2449
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2450
-                    'css_class'  => $config['css_class'],
2451
-                    'options'    => isset($config['options']) ? $config['options'] : [],
2452
-                    'default'    => $default,
2453
-                    'format'     => $config['format'],
2454
-                ];
2455
-            }
2456
-        }
2457
-
2458
-        $test_settings_html = ! empty($template_form_fields)
2459
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2460
-            : '';
2461
-
2462
-        // print out $test_settings_fields
2463
-        if (! empty($test_settings_html)) {
2464
-            $test_settings_html .= '<input type="submit" class="button-primary mtp-test-button alignright" ';
2465
-            $test_settings_html .= 'name="test_button" value="';
2466
-            $test_settings_html .= esc_html__('Test Send', 'event_espresso');
2467
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2468
-        }
2469
-
2470
-        // and button
2471
-        $test_settings_html .= '<p>';
2472
-        $test_settings_html .= esc_html__('Need to reset this message type and start over?', 'event_espresso');
2473
-        $test_settings_html .= '</p>';
2474
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2475
-        $test_settings_html .= $this->get_action_link_or_button(
2476
-            'reset_to_default',
2477
-            'reset',
2478
-            $extra_args,
2479
-            'button-primary reset-default-button'
2480
-        );
2481
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2482
-        echo $test_settings_html; // already escaped
2483
-    }
2484
-
2485
-
2486
-    /**
2487
-     * This returns the shortcode selector skeleton for a given context and field.
2488
-     *
2489
-     * @param string $field           The name of the field retrieving shortcodes for.
2490
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2491
-     * @return string
2492
-     * @throws DomainException
2493
-     * @throws EE_Error
2494
-     * @throws InvalidArgumentException
2495
-     * @throws ReflectionException
2496
-     * @throws InvalidDataTypeException
2497
-     * @throws InvalidInterfaceException
2498
-     * @since 4.9.rc.000
2499
-     */
2500
-    protected function _get_shortcode_selector($field, $linked_input_id)
2501
-    {
2502
-        $template_args = [
2503
-            'shortcodes'      => $this->_get_shortcodes([$field]),
2504
-            'fieldname'       => $field,
2505
-            'linked_input_id' => $linked_input_id,
2506
-        ];
2507
-
2508
-        return EEH_Template::display_template(
2509
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2510
-            $template_args,
2511
-            true
2512
-        );
2513
-    }
2514
-
2515
-
2516
-    /**
2517
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2518
-     * page)
2519
-     *
2520
-     * @access public
2521
-     * @return void
2522
-     * @throws EE_Error
2523
-     * @throws InvalidArgumentException
2524
-     * @throws ReflectionException
2525
-     * @throws InvalidDataTypeException
2526
-     * @throws InvalidInterfaceException
2527
-     */
2528
-    public function shortcode_meta_box()
2529
-    {
2530
-        $shortcodes = $this->_get_shortcodes([], false);
2531
-        // just make sure the shortcodes property is set
2532
-        // $messenger = $this->_message_template_group->messenger_obj();
2533
-        // now let's set the content depending on the status of the shortcodes array
2534
-        if (empty($shortcodes)) {
2535
-            echo '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2536
-            return;
2537
-        }
2538
-        ?>
19
+	/**
20
+	 * @var EEM_Message
21
+	 */
22
+	private $MSG_MODEL;
23
+
24
+	/**
25
+	 * @var EEM_Message_Template
26
+	 */
27
+	private $MTP_MODEL;
28
+
29
+	/**
30
+	 * @var EEM_Message_Template_Group
31
+	 */
32
+	private $MTG_MODEL;
33
+
34
+	/**
35
+	 * @var EE_Message_Resource_Manager $_message_resource_manager
36
+	 */
37
+	protected $_message_resource_manager;
38
+
39
+	/**
40
+	 * @var string
41
+	 */
42
+	protected $_active_message_type_name = '';
43
+
44
+	/**
45
+	 * @var string
46
+	 */
47
+	protected $_active_messenger_name = '';
48
+
49
+	/**
50
+	 * @var EE_messenger $_active_messenger
51
+	 */
52
+	protected $_active_messenger;
53
+
54
+	protected $_activate_meta_box_type;
55
+
56
+	protected $_current_message_meta_box;
57
+
58
+	protected $_current_message_meta_box_object;
59
+
60
+	protected $_context_switcher;
61
+
62
+	protected $_shortcodes           = [];
63
+
64
+	protected $_active_messengers    = [];
65
+
66
+	protected $_active_message_types = [];
67
+
68
+	/**
69
+	 * @var EE_Message_Template_Group $_message_template_group
70
+	 */
71
+	protected $_message_template_group;
72
+
73
+	protected $_m_mt_settings = [];
74
+
75
+
76
+	/**
77
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
78
+	 * IF there is no group then it gets automatically set to the Default template pack.
79
+	 *
80
+	 * @since 4.5.0
81
+	 *
82
+	 * @var EE_Messages_Template_Pack
83
+	 */
84
+	protected $_template_pack;
85
+
86
+
87
+	/**
88
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
89
+	 * group is.  If there is no group then it automatically gets set to default.
90
+	 *
91
+	 * @since 4.5.0
92
+	 *
93
+	 * @var string
94
+	 */
95
+	protected $_variation;
96
+
97
+
98
+	/**
99
+	 * @param bool $routing
100
+	 * @throws EE_Error
101
+	 * @throws ReflectionException
102
+	 */
103
+	public function __construct($routing = true)
104
+	{
105
+		// make sure messages autoloader is running
106
+		EED_Messages::set_autoloaders();
107
+		parent::__construct($routing);
108
+	}
109
+
110
+
111
+	/**
112
+	 * @return EEM_Message
113
+	 * @throws EE_Error
114
+	 */
115
+	public function getMsgModel()
116
+	{
117
+		if (! $this->MSG_MODEL instanceof EEM_Message) {
118
+			$this->MSG_MODEL = EEM_Message::instance();
119
+		}
120
+		return $this->MSG_MODEL;
121
+	}
122
+
123
+
124
+	/**
125
+	 * @return EEM_Message_Template
126
+	 * @throws EE_Error
127
+	 */
128
+	public function getMtpModel()
129
+	{
130
+		if (! $this->MTP_MODEL instanceof EEM_Message_Template) {
131
+			$this->MTP_MODEL = EEM_Message_Template::instance();
132
+		}
133
+		return $this->MTP_MODEL;
134
+	}
135
+
136
+
137
+	/**
138
+	 * @return EEM_Message_Template_Group
139
+	 * @throws EE_Error
140
+	 */
141
+	public function getMtgModel()
142
+	{
143
+		if (! $this->MTG_MODEL instanceof EEM_Message_Template_Group) {
144
+			$this->MTG_MODEL = EEM_Message_Template_Group::instance();
145
+		}
146
+		return $this->MTG_MODEL;
147
+	}
148
+
149
+
150
+	/**
151
+	 * @throws EE_Error
152
+	 * @throws ReflectionException
153
+	 */
154
+	protected function _init_page_props()
155
+	{
156
+		$this->page_slug        = EE_MSG_PG_SLUG;
157
+		$this->page_label       = esc_html__('Messages Settings', 'event_espresso');
158
+		$this->_admin_base_url  = EE_MSG_ADMIN_URL;
159
+		$this->_admin_base_path = EE_MSG_ADMIN;
160
+
161
+		$messenger    = $this->request->getRequestParam('messenger', '');
162
+		$message_type = $this->request->getRequestParam('message_type', '');
163
+		$this->_active_messenger_name    = $this->request->getRequestParam('MTP_messenger', $messenger);
164
+		$this->_active_message_type_name = $this->request->getRequestParam('MTP_message_type', $message_type);
165
+
166
+		$this->_load_message_resource_manager();
167
+	}
168
+
169
+
170
+	/**
171
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
172
+	 *
173
+	 * @throws EE_Error
174
+	 * @throws InvalidDataTypeException
175
+	 * @throws InvalidInterfaceException
176
+	 * @throws InvalidArgumentException
177
+	 * @throws ReflectionException
178
+	 */
179
+	protected function _load_message_resource_manager()
180
+	{
181
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
182
+	}
183
+
184
+
185
+	/**
186
+	 * @return array
187
+	 * @throws EE_Error
188
+	 * @throws InvalidArgumentException
189
+	 * @throws InvalidDataTypeException
190
+	 * @throws InvalidInterfaceException
191
+	 * @deprecated 4.9.9.rc.014
192
+	 */
193
+	public function get_messengers_for_list_table()
194
+	{
195
+		EE_Error::doing_it_wrong(
196
+			__METHOD__,
197
+			sprintf(
198
+				esc_html__(
199
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
200
+					'event_espresso'
201
+				),
202
+				'Messages_Admin_Page::get_messengers_select_input()'
203
+			),
204
+			'4.9.9.rc.014'
205
+		);
206
+
207
+		$m_values          = [];
208
+		$active_messengers = $this->getMsgModel()->get_all(['group_by' => 'MSG_messenger']);
209
+		// setup messengers for selects
210
+		$i = 1;
211
+		foreach ($active_messengers as $active_messenger) {
212
+			if ($active_messenger instanceof EE_Message) {
213
+				$m_values[ $i ]['id']   = $active_messenger->messenger();
214
+				$m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
215
+				$i++;
216
+			}
217
+		}
218
+
219
+		return $m_values;
220
+	}
221
+
222
+
223
+	/**
224
+	 * @return array
225
+	 * @throws EE_Error
226
+	 * @throws InvalidArgumentException
227
+	 * @throws InvalidDataTypeException
228
+	 * @throws InvalidInterfaceException
229
+	 * @deprecated 4.9.9.rc.014
230
+	 */
231
+	public function get_message_types_for_list_table()
232
+	{
233
+		EE_Error::doing_it_wrong(
234
+			__METHOD__,
235
+			sprintf(
236
+				esc_html__(
237
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
238
+					'event_espresso'
239
+				),
240
+				'Messages_Admin_Page::get_message_types_select_input()'
241
+			),
242
+			'4.9.9.rc.014'
243
+		);
244
+
245
+		$mt_values       = [];
246
+		$active_messages = $this->getMsgModel()->get_all(['group_by' => 'MSG_message_type']);
247
+		$i               = 1;
248
+		foreach ($active_messages as $active_message) {
249
+			if ($active_message instanceof EE_Message) {
250
+				$mt_values[ $i ]['id']   = $active_message->message_type();
251
+				$mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
252
+				$i++;
253
+			}
254
+		}
255
+
256
+		return $mt_values;
257
+	}
258
+
259
+
260
+	/**
261
+	 * @return array
262
+	 * @throws EE_Error
263
+	 * @throws InvalidArgumentException
264
+	 * @throws InvalidDataTypeException
265
+	 * @throws InvalidInterfaceException
266
+	 * @deprecated 4.9.9.rc.014
267
+	 */
268
+	public function get_contexts_for_message_types_for_list_table()
269
+	{
270
+		EE_Error::doing_it_wrong(
271
+			__METHOD__,
272
+			sprintf(
273
+				esc_html__(
274
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
275
+					'event_espresso'
276
+				),
277
+				'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
278
+			),
279
+			'4.9.9.rc.014'
280
+		);
281
+
282
+		$contexts                = [];
283
+		$active_message_contexts = $this->getMsgModel()->get_all(['group_by' => 'MSG_context']);
284
+		foreach ($active_message_contexts as $active_message) {
285
+			if ($active_message instanceof EE_Message) {
286
+				$message_type = $active_message->message_type_object();
287
+				if ($message_type instanceof EE_message_type) {
288
+					$message_type_contexts = $message_type->get_contexts();
289
+					foreach ($message_type_contexts as $context => $context_details) {
290
+						$contexts[ $context ] = $context_details['label'];
291
+					}
292
+				}
293
+			}
294
+		}
295
+
296
+		return $contexts;
297
+	}
298
+
299
+
300
+	/**
301
+	 * Generate select input with provided messenger options array.
302
+	 *
303
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
304
+	 *                                 labels.
305
+	 * @return string
306
+	 * @throws EE_Error
307
+	 */
308
+	public function get_messengers_select_input($messenger_options)
309
+	{
310
+		// if empty or just one value then just return an empty string
311
+		if (
312
+			empty($messenger_options)
313
+			|| ! is_array($messenger_options)
314
+			|| count($messenger_options) === 1
315
+		) {
316
+			return '';
317
+		}
318
+		// merge in default
319
+		$messenger_options = array_merge(
320
+			['none_selected' => esc_html__('Show All Messengers', 'event_espresso')],
321
+			$messenger_options
322
+		);
323
+		$input             = new EE_Select_Input(
324
+			$messenger_options,
325
+			[
326
+				'html_name'  => 'ee_messenger_filter_by',
327
+				'html_id'    => 'ee_messenger_filter_by',
328
+				'html_class' => 'wide',
329
+				'default'    => $this->request->getRequestParam('ee_messenger_filter_by', 'none_selected', 'title'),
330
+			]
331
+		);
332
+
333
+		return $input->get_html_for_input();
334
+	}
335
+
336
+
337
+	/**
338
+	 * Generate select input with provided message type options array.
339
+	 *
340
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
341
+	 *                                    message type labels
342
+	 * @return string
343
+	 * @throws EE_Error
344
+	 */
345
+	public function get_message_types_select_input($message_type_options)
346
+	{
347
+		// if empty or count of options is 1 then just return an empty string
348
+		if (
349
+			empty($message_type_options)
350
+			|| ! is_array($message_type_options)
351
+			|| count($message_type_options) === 1
352
+		) {
353
+			return '';
354
+		}
355
+		// merge in default
356
+		$message_type_options = array_merge(
357
+			['none_selected' => esc_html__('Show All Message Types', 'event_espresso')],
358
+			$message_type_options
359
+		);
360
+		$input                = new EE_Select_Input(
361
+			$message_type_options,
362
+			[
363
+				'html_name'  => 'ee_message_type_filter_by',
364
+				'html_id'    => 'ee_message_type_filter_by',
365
+				'html_class' => 'wide',
366
+				'default'    => $this->request->getRequestParam('ee_message_type_filter_by', 'none_selected', 'title'),
367
+			]
368
+		);
369
+
370
+		return $input->get_html_for_input();
371
+	}
372
+
373
+
374
+	/**
375
+	 * Generate select input with provide message type contexts array.
376
+	 *
377
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
378
+	 *                               context label.
379
+	 * @return string
380
+	 * @throws EE_Error
381
+	 */
382
+	public function get_contexts_for_message_types_select_input($context_options)
383
+	{
384
+		// if empty or count of options is one then just return empty string
385
+		if (
386
+			empty($context_options)
387
+			|| ! is_array($context_options)
388
+			|| count($context_options) === 1
389
+		) {
390
+			return '';
391
+		}
392
+		// merge in default
393
+		$context_options = array_merge(
394
+			['none_selected' => esc_html__('Show all Contexts', 'event_espresso')],
395
+			$context_options
396
+		);
397
+		$input           = new EE_Select_Input(
398
+			$context_options,
399
+			[
400
+				'html_name'  => 'ee_context_filter_by',
401
+				'html_id'    => 'ee_context_filter_by',
402
+				'html_class' => 'wide',
403
+				'default'    => $this->request->getRequestParam('ee_context_filter_by', 'none_selected', 'title'),
404
+			]
405
+		);
406
+
407
+		return $input->get_html_for_input();
408
+	}
409
+
410
+
411
+	protected function _ajax_hooks()
412
+	{
413
+		add_action('wp_ajax_activate_messenger', [$this, 'activate_messenger_toggle']);
414
+		add_action('wp_ajax_activate_mt', [$this, 'activate_mt_toggle']);
415
+		add_action('wp_ajax_ee_msgs_save_settings', [$this, 'save_settings']);
416
+		add_action('wp_ajax_ee_msgs_update_mt_form', [$this, 'update_mt_form']);
417
+		add_action('wp_ajax_switch_template_pack', [$this, 'switch_template_pack']);
418
+		add_action('wp_ajax_toggle_context_template', [$this, 'toggle_context_template']);
419
+	}
420
+
421
+
422
+	protected function _define_page_props()
423
+	{
424
+		$this->_admin_page_title = $this->page_label;
425
+		$this->_labels           = [
426
+			'buttons'    => [
427
+				'add'    => esc_html__('Add New Message Template', 'event_espresso'),
428
+				'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
429
+				'delete' => esc_html__('Delete Message Template', 'event_espresso'),
430
+			],
431
+			'publishbox' => esc_html__('Update Actions', 'event_espresso'),
432
+		];
433
+	}
434
+
435
+
436
+	/**
437
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
438
+	 *
439
+	 * @access protected
440
+	 * @return void
441
+	 */
442
+	protected function _set_page_routes()
443
+	{
444
+		$GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
445
+		$GRP_ID = $this->request->getRequestParam('id', $GRP_ID, 'int');
446
+		$MSG_ID = $this->request->getRequestParam('MSG_ID', 0, 'int');
447
+
448
+		$this->_page_routes = [
449
+			'default'                          => [
450
+				'func'       => '_message_queue_list_table',
451
+				'capability' => 'ee_read_global_messages',
452
+			],
453
+			'global_mtps'                      => [
454
+				'func'       => '_ee_default_messages_overview_list_table',
455
+				'capability' => 'ee_read_global_messages',
456
+			],
457
+			'custom_mtps'                      => [
458
+				'func'       => '_custom_mtps_preview',
459
+				'capability' => 'ee_read_messages',
460
+			],
461
+			'add_new_message_template'         => [
462
+				'func'       => 'add_message_template',
463
+				'capability' => 'ee_edit_messages',
464
+				'noheader'   => true,
465
+			],
466
+			'edit_message_template'            => [
467
+				'func'       => '_edit_message_template',
468
+				'capability' => 'ee_edit_message',
469
+				'obj_id'     => $GRP_ID,
470
+			],
471
+			'preview_message'                  => [
472
+				'func'               => '_preview_message',
473
+				'capability'         => 'ee_read_message',
474
+				'obj_id'             => $GRP_ID,
475
+				'noheader'           => true,
476
+				'headers_sent_route' => 'display_preview_message',
477
+			],
478
+			'display_preview_message'          => [
479
+				'func'       => '_display_preview_message',
480
+				'capability' => 'ee_read_message',
481
+				'obj_id'     => $GRP_ID,
482
+			],
483
+			'insert_message_template'          => [
484
+				'func'       => '_insert_or_update_message_template',
485
+				'capability' => 'ee_edit_messages',
486
+				'args'       => ['new' => true],
487
+				'noheader'   => true,
488
+			],
489
+			'update_message_template'          => [
490
+				'func'       => '_insert_or_update_message_template',
491
+				'capability' => 'ee_edit_message',
492
+				'obj_id'     => $GRP_ID,
493
+				'args'       => ['new' => false],
494
+				'noheader'   => true,
495
+			],
496
+			'trash_message_template'           => [
497
+				'func'       => '_trash_or_restore_message_template',
498
+				'capability' => 'ee_delete_message',
499
+				'obj_id'     => $GRP_ID,
500
+				'args'       => ['trash' => true, 'all' => true],
501
+				'noheader'   => true,
502
+			],
503
+			'trash_message_template_context'   => [
504
+				'func'       => '_trash_or_restore_message_template',
505
+				'capability' => 'ee_delete_message',
506
+				'obj_id'     => $GRP_ID,
507
+				'args'       => ['trash' => true],
508
+				'noheader'   => true,
509
+			],
510
+			'restore_message_template'         => [
511
+				'func'       => '_trash_or_restore_message_template',
512
+				'capability' => 'ee_delete_message',
513
+				'obj_id'     => $GRP_ID,
514
+				'args'       => ['trash' => false, 'all' => true],
515
+				'noheader'   => true,
516
+			],
517
+			'restore_message_template_context' => [
518
+				'func'       => '_trash_or_restore_message_template',
519
+				'capability' => 'ee_delete_message',
520
+				'obj_id'     => $GRP_ID,
521
+				'args'       => ['trash' => false],
522
+				'noheader'   => true,
523
+			],
524
+			'delete_message_template'          => [
525
+				'func'       => '_delete_message_template',
526
+				'capability' => 'ee_delete_message',
527
+				'obj_id'     => $GRP_ID,
528
+				'noheader'   => true,
529
+			],
530
+			'reset_to_default'                 => [
531
+				'func'       => '_reset_to_default_template',
532
+				'capability' => 'ee_edit_message',
533
+				'obj_id'     => $GRP_ID,
534
+				'noheader'   => true,
535
+			],
536
+			'settings'                         => [
537
+				'func'       => '_settings',
538
+				'capability' => 'manage_options',
539
+			],
540
+			'update_global_settings'           => [
541
+				'func'       => '_update_global_settings',
542
+				'capability' => 'manage_options',
543
+				'noheader'   => true,
544
+			],
545
+			'generate_now'                     => [
546
+				'func'       => '_generate_now',
547
+				'capability' => 'ee_send_message',
548
+				'noheader'   => true,
549
+			],
550
+			'generate_and_send_now'            => [
551
+				'func'       => '_generate_and_send_now',
552
+				'capability' => 'ee_send_message',
553
+				'noheader'   => true,
554
+			],
555
+			'queue_for_resending'              => [
556
+				'func'       => '_queue_for_resending',
557
+				'capability' => 'ee_send_message',
558
+				'noheader'   => true,
559
+			],
560
+			'send_now'                         => [
561
+				'func'       => '_send_now',
562
+				'capability' => 'ee_send_message',
563
+				'noheader'   => true,
564
+			],
565
+			'delete_ee_message'                => [
566
+				'func'       => '_delete_ee_messages',
567
+				'capability' => 'ee_delete_messages',
568
+				'noheader'   => true,
569
+			],
570
+			'delete_ee_messages'               => [
571
+				'func'       => '_delete_ee_messages',
572
+				'capability' => 'ee_delete_messages',
573
+				'noheader'   => true,
574
+				'obj_id'     => $MSG_ID,
575
+			],
576
+		];
577
+	}
578
+
579
+
580
+	protected function _set_page_config()
581
+	{
582
+		$this->_page_config = [
583
+			'default'                  => [
584
+				'nav'           => [
585
+					'label' => esc_html__('Message Activity', 'event_espresso'),
586
+					'order' => 10,
587
+				],
588
+				'list_table'    => 'EE_Message_List_Table',
589
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
590
+				'require_nonce' => false,
591
+			],
592
+			'global_mtps'              => [
593
+				'nav'           => [
594
+					'label' => esc_html__('Default Message Templates', 'event_espresso'),
595
+					'order' => 20,
596
+				],
597
+				'list_table'    => 'Messages_Template_List_Table',
598
+				'help_tabs'     => [
599
+					'messages_overview_help_tab'                                => [
600
+						'title'    => esc_html__('Messages Overview', 'event_espresso'),
601
+						'filename' => 'messages_overview',
602
+					],
603
+					'messages_overview_messages_table_column_headings_help_tab' => [
604
+						'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
605
+						'filename' => 'messages_overview_table_column_headings',
606
+					],
607
+					'messages_overview_messages_filters_help_tab'               => [
608
+						'title'    => esc_html__('Message Filters', 'event_espresso'),
609
+						'filename' => 'messages_overview_filters',
610
+					],
611
+					'messages_overview_messages_views_help_tab'                 => [
612
+						'title'    => esc_html__('Message Views', 'event_espresso'),
613
+						'filename' => 'messages_overview_views',
614
+					],
615
+					'message_overview_message_types_help_tab'                   => [
616
+						'title'    => esc_html__('Message Types', 'event_espresso'),
617
+						'filename' => 'messages_overview_types',
618
+					],
619
+					'messages_overview_messengers_help_tab'                     => [
620
+						'title'    => esc_html__('Messengers', 'event_espresso'),
621
+						'filename' => 'messages_overview_messengers',
622
+					],
623
+				],
624
+				'require_nonce' => false,
625
+			],
626
+			'custom_mtps'              => [
627
+				'nav'           => [
628
+					'label' => esc_html__('Custom Message Templates', 'event_espresso'),
629
+					'order' => 30,
630
+				],
631
+				'help_tabs'     => [],
632
+				'require_nonce' => false,
633
+			],
634
+			'add_new_message_template' => [
635
+				'nav'           => [
636
+					'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
637
+					'order'      => 5,
638
+					'persistent' => false,
639
+				],
640
+				'require_nonce' => false,
641
+			],
642
+			'edit_message_template'    => [
643
+				'labels'        => [
644
+					'buttons'    => [
645
+						'reset' => esc_html__('Reset Templates', 'event_espresso'),
646
+					],
647
+					'publishbox' => esc_html__('Update Actions', 'event_espresso'),
648
+				],
649
+				'nav'           => [
650
+					'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
651
+					'order'      => 5,
652
+					'persistent' => false,
653
+					'url'        => '',
654
+				],
655
+				'metaboxes'     => ['_publish_post_box', '_register_edit_meta_boxes'],
656
+				'has_metaboxes' => true,
657
+				'help_tabs'     => [
658
+					'edit_message_template'            => [
659
+						'title'    => esc_html__('Message Template Editor', 'event_espresso'),
660
+						'callback' => 'edit_message_template_help_tab',
661
+					],
662
+					'message_templates_help_tab'       => [
663
+						'title'    => esc_html__('Message Templates', 'event_espresso'),
664
+						'filename' => 'messages_templates',
665
+					],
666
+					'message_template_shortcodes'      => [
667
+						'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
668
+						'callback' => 'message_template_shortcodes_help_tab',
669
+					],
670
+					'message_preview_help_tab'         => [
671
+						'title'    => esc_html__('Message Preview', 'event_espresso'),
672
+						'filename' => 'messages_preview',
673
+					],
674
+					'messages_overview_other_help_tab' => [
675
+						'title'    => esc_html__('Messages Other', 'event_espresso'),
676
+						'filename' => 'messages_overview_other',
677
+					],
678
+				],
679
+				'require_nonce' => false,
680
+			],
681
+			'display_preview_message'  => [
682
+				'nav'           => [
683
+					'label'      => esc_html__('Message Preview', 'event_espresso'),
684
+					'order'      => 5,
685
+					'url'        => '',
686
+					'persistent' => false,
687
+				],
688
+				'help_tabs'     => [
689
+					'preview_message' => [
690
+						'title'    => esc_html__('About Previews', 'event_espresso'),
691
+						'callback' => 'preview_message_help_tab',
692
+					],
693
+				],
694
+				'require_nonce' => false,
695
+			],
696
+			'settings'                 => [
697
+				'nav'           => [
698
+					'label' => esc_html__('Settings', 'event_espresso'),
699
+					'order' => 40,
700
+				],
701
+				'metaboxes'     => ['_messages_settings_metaboxes'],
702
+				'help_tabs'     => [
703
+					'messages_settings_help_tab'               => [
704
+						'title'    => esc_html__('Messages Settings', 'event_espresso'),
705
+						'filename' => 'messages_settings',
706
+					],
707
+					'messages_settings_message_types_help_tab' => [
708
+						'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
709
+						'filename' => 'messages_settings_message_types',
710
+					],
711
+					'messages_settings_messengers_help_tab'    => [
712
+						'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
713
+						'filename' => 'messages_settings_messengers',
714
+					],
715
+				],
716
+				'require_nonce' => false,
717
+			],
718
+		];
719
+	}
720
+
721
+
722
+	protected function _add_screen_options()
723
+	{
724
+		// todo
725
+	}
726
+
727
+
728
+	protected function _add_screen_options_global_mtps()
729
+	{
730
+		/**
731
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
732
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
733
+		 */
734
+		$page_title              = $this->_admin_page_title;
735
+		$this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
736
+		$this->_per_page_screen_option();
737
+		$this->_admin_page_title = $page_title;
738
+	}
739
+
740
+
741
+	protected function _add_screen_options_default()
742
+	{
743
+		$this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
744
+		$this->_per_page_screen_option();
745
+	}
746
+
747
+
748
+	// none of the below group are currently used for Messages
749
+	protected function _add_feature_pointers()
750
+	{
751
+	}
752
+
753
+
754
+	public function admin_init()
755
+	{
756
+	}
757
+
758
+
759
+	public function admin_notices()
760
+	{
761
+	}
762
+
763
+
764
+	public function admin_footer_scripts()
765
+	{
766
+	}
767
+
768
+
769
+	public function messages_help_tab()
770
+	{
771
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
772
+	}
773
+
774
+
775
+	public function messengers_help_tab()
776
+	{
777
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
778
+	}
779
+
780
+
781
+	public function message_types_help_tab()
782
+	{
783
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
784
+	}
785
+
786
+
787
+	public function messages_overview_help_tab()
788
+	{
789
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
790
+	}
791
+
792
+
793
+	public function message_templates_help_tab()
794
+	{
795
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
796
+	}
797
+
798
+
799
+	public function edit_message_template_help_tab()
800
+	{
801
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
802
+						. esc_attr__('Editor Title', 'event_espresso')
803
+						. '" />';
804
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
805
+						. esc_attr__('Context Switcher and Preview', 'event_espresso')
806
+						. '" />';
807
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
808
+						. esc_attr__('Message Template Form Fields', 'event_espresso')
809
+						. '" />';
810
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
811
+						. esc_attr__('Shortcodes Metabox', 'event_espresso')
812
+						. '" />';
813
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
814
+						. esc_attr__('Publish Metabox', 'event_espresso')
815
+						. '" />';
816
+		EEH_Template::display_template(
817
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
818
+			$args
819
+		);
820
+	}
821
+
822
+
823
+	/**
824
+	 * @throws ReflectionException
825
+	 * @throws EE_Error
826
+	 */
827
+	public function message_template_shortcodes_help_tab()
828
+	{
829
+		$this->_set_shortcodes();
830
+		$args['shortcodes'] = $this->_shortcodes;
831
+		EEH_Template::display_template(
832
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
833
+			$args
834
+		);
835
+	}
836
+
837
+
838
+	public function preview_message_help_tab()
839
+	{
840
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
841
+	}
842
+
843
+
844
+	public function settings_help_tab()
845
+	{
846
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
847
+						. '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
848
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
849
+						. '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
850
+		$args['img3'] = '<div class="switch">'
851
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
852
+						. ' type="checkbox" checked="checked">'
853
+						. '<label for="ee-on-off-toggle-on"></label>'
854
+						. '</div>';
855
+		$args['img4'] = '<div class="switch">'
856
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
857
+						. ' type="checkbox">'
858
+						. '<label for="ee-on-off-toggle-on"></label>'
859
+						. '</div>';
860
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
861
+	}
862
+
863
+
864
+	public function load_scripts_styles()
865
+	{
866
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
867
+		wp_enqueue_style('espresso_ee_msg');
868
+
869
+		wp_register_script(
870
+			'ee-messages-settings',
871
+			EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
872
+			['jquery-ui-droppable', 'ee-serialize-full-array'],
873
+			EVENT_ESPRESSO_VERSION,
874
+			true
875
+		);
876
+		wp_register_script(
877
+			'ee-msg-list-table-js',
878
+			EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
879
+			['ee-dialog'],
880
+			EVENT_ESPRESSO_VERSION
881
+		);
882
+	}
883
+
884
+
885
+	public function load_scripts_styles_default()
886
+	{
887
+		wp_enqueue_script('ee-msg-list-table-js');
888
+	}
889
+
890
+
891
+	public function wp_editor_css($mce_css)
892
+	{
893
+		// if we're on the edit_message_template route
894
+		if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
895
+			$message_type_name = $this->_active_message_type_name;
896
+
897
+			// we're going to REPLACE the existing mce css
898
+			// we need to get the css file location from the active messenger
899
+			$mce_css = $this->_active_messenger->get_variation(
900
+				$this->_template_pack,
901
+				$message_type_name,
902
+				true,
903
+				'wpeditor',
904
+				$this->_variation
905
+			);
906
+		}
907
+
908
+		return $mce_css;
909
+	}
910
+
911
+
912
+	/**
913
+	 * @throws EE_Error
914
+	 * @throws ReflectionException
915
+	 */
916
+	public function load_scripts_styles_edit_message_template()
917
+	{
918
+
919
+		$this->_set_shortcodes();
920
+
921
+		EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
922
+			esc_html__(
923
+				'Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
924
+				'event_espresso'
925
+			),
926
+			$this->_message_template_group->messenger_obj()->label['singular'],
927
+			$this->_message_template_group->message_type_obj()->label['singular']
928
+		);
929
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
930
+			'Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
931
+			'event_espresso'
932
+		);
933
+		EE_Registry::$i18n_js_strings['server_error']                 = esc_html__(
934
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
935
+			'event_espresso'
936
+		);
937
+
938
+		wp_register_script(
939
+			'ee_msgs_edit_js',
940
+			EE_MSG_ASSETS_URL . 'ee_message_editor.js',
941
+			['jquery'],
942
+			EVENT_ESPRESSO_VERSION
943
+		);
944
+
945
+		wp_enqueue_script('ee_admin_js');
946
+		wp_enqueue_script('ee_msgs_edit_js');
947
+
948
+		// add in special css for tiny_mce
949
+		add_filter('mce_css', [$this, 'wp_editor_css']);
950
+	}
951
+
952
+
953
+	/**
954
+	 * @throws EE_Error
955
+	 * @throws ReflectionException
956
+	 */
957
+	public function load_scripts_styles_display_preview_message()
958
+	{
959
+		$this->_set_message_template_group();
960
+		if ($this->_active_messenger_name) {
961
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
962
+				$this->_active_messenger_name
963
+			);
964
+		}
965
+
966
+		wp_enqueue_style(
967
+			'espresso_preview_css',
968
+			$this->_active_messenger->get_variation(
969
+				$this->_template_pack,
970
+				$this->_active_message_type_name,
971
+				true,
972
+				'preview',
973
+				$this->_variation
974
+			)
975
+		);
976
+	}
977
+
978
+
979
+	public function load_scripts_styles_settings()
980
+	{
981
+		wp_register_style(
982
+			'ee-message-settings',
983
+			EE_MSG_ASSETS_URL . 'ee_message_settings.css',
984
+			[],
985
+			EVENT_ESPRESSO_VERSION
986
+		);
987
+		wp_enqueue_style('ee-text-links');
988
+		wp_enqueue_style('ee-message-settings');
989
+		wp_enqueue_script('ee-messages-settings');
990
+	}
991
+
992
+
993
+	/**
994
+	 * set views array for List Table
995
+	 */
996
+	public function _set_list_table_views_global_mtps()
997
+	{
998
+		$this->_views = [
999
+			'in_use' => [
1000
+				'slug'  => 'in_use',
1001
+				'label' => esc_html__('In Use', 'event_espresso'),
1002
+				'count' => 0,
1003
+			],
1004
+		];
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Set views array for the Custom Template List Table
1010
+	 */
1011
+	public function _set_list_table_views_custom_mtps()
1012
+	{
1013
+		$this->_set_list_table_views_global_mtps();
1014
+		$this->_views['in_use']['bulk_action'] = [
1015
+			'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
1016
+		];
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 * set views array for message queue list table
1022
+	 *
1023
+	 * @throws InvalidDataTypeException
1024
+	 * @throws InvalidInterfaceException
1025
+	 * @throws InvalidArgumentException
1026
+	 * @throws EE_Error
1027
+	 * @throws ReflectionException
1028
+	 */
1029
+	public function _set_list_table_views_default()
1030
+	{
1031
+		EE_Registry::instance()->load_helper('Template');
1032
+
1033
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
1034
+			'ee_send_message',
1035
+			'message_list_table_bulk_actions'
1036
+		)
1037
+			? [
1038
+				'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
1039
+				'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
1040
+				'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
1041
+				'send_now'              => esc_html__('Send Now', 'event_espresso'),
1042
+			]
1043
+			: [];
1044
+
1045
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
1046
+			'ee_delete_messages',
1047
+			'message_list_table_bulk_actions'
1048
+		)
1049
+			? ['delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso')]
1050
+			: [];
1051
+
1052
+
1053
+		$this->_views = [
1054
+			'all' => [
1055
+				'slug'        => 'all',
1056
+				'label'       => esc_html__('All', 'event_espresso'),
1057
+				'count'       => 0,
1058
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
1059
+			],
1060
+		];
1061
+
1062
+
1063
+		foreach ($this->getMsgModel()->all_statuses() as $status) {
1064
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
1065
+				continue;
1066
+			}
1067
+			$status_bulk_actions = $common_bulk_actions;
1068
+			// unset bulk actions not applying to status
1069
+			if (! empty($status_bulk_actions)) {
1070
+				switch ($status) {
1071
+					case EEM_Message::status_idle:
1072
+					case EEM_Message::status_resend:
1073
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1074
+						break;
1075
+
1076
+					case EEM_Message::status_failed:
1077
+					case EEM_Message::status_debug_only:
1078
+					case EEM_Message::status_messenger_executing:
1079
+						$status_bulk_actions = [];
1080
+						break;
1081
+
1082
+					case EEM_Message::status_incomplete:
1083
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1084
+						break;
1085
+
1086
+					case EEM_Message::status_retry:
1087
+					case EEM_Message::status_sent:
1088
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1089
+						break;
1090
+				}
1091
+			}
1092
+
1093
+			// skip adding messenger executing status to views because it will be included with the Failed view.
1094
+			if ($status === EEM_Message::status_messenger_executing) {
1095
+				continue;
1096
+			}
1097
+
1098
+			$this->_views[ strtolower($status) ] = [
1099
+				'slug'        => strtolower($status),
1100
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1101
+				'count'       => 0,
1102
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1103
+			];
1104
+		}
1105
+	}
1106
+
1107
+
1108
+	/**
1109
+	 * @throws EE_Error
1110
+	 */
1111
+	protected function _ee_default_messages_overview_list_table()
1112
+	{
1113
+		$this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1114
+		$this->display_admin_list_table_page_with_no_sidebar();
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * @throws EE_Error
1120
+	 * @throws ReflectionException
1121
+	 */
1122
+	protected function _message_queue_list_table()
1123
+	{
1124
+		$this->_search_btn_label                   = esc_html__('Message Activity', 'event_espresso');
1125
+		$this->_template_args['per_column']        = 6;
1126
+		$this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
1127
+		$this->_template_args['before_list_table'] = '<h3>'
1128
+													 . $this->getMsgModel()->get_pretty_label_for_results()
1129
+													 . '</h3>';
1130
+		$this->display_admin_list_table_page_with_no_sidebar();
1131
+	}
1132
+
1133
+
1134
+	/**
1135
+	 * @throws EE_Error
1136
+	 */
1137
+	protected function _message_legend_items()
1138
+	{
1139
+
1140
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
1141
+		$action_items       = [];
1142
+
1143
+		foreach ($action_css_classes as $action_item => $action_details) {
1144
+			if ($action_item === 'see_notifications_for') {
1145
+				continue;
1146
+			}
1147
+			$action_items[ $action_item ] = [
1148
+				'class' => $action_details['css_class'],
1149
+				'desc'  => $action_details['label'],
1150
+			];
1151
+		}
1152
+
1153
+		/** @var array $status_items status legend setup */
1154
+		$status_items = [
1155
+			'sent_status'                => [
1156
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1157
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1158
+			],
1159
+			'idle_status'                => [
1160
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1161
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1162
+			],
1163
+			'failed_status'              => [
1164
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1165
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1166
+			],
1167
+			'messenger_executing_status' => [
1168
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1169
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1170
+			],
1171
+			'resend_status'              => [
1172
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1173
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1174
+			],
1175
+			'incomplete_status'          => [
1176
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1177
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1178
+			],
1179
+			'retry_status'               => [
1180
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1181
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1182
+			],
1183
+		];
1184
+		if (EEM_Message::debug()) {
1185
+			$status_items['debug_only_status'] = [
1186
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1187
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1188
+			];
1189
+		}
1190
+
1191
+		return array_merge($action_items, $status_items);
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * @throws EE_Error
1197
+	 */
1198
+	protected function _custom_mtps_preview()
1199
+	{
1200
+		$this->_admin_page_title              = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1201
+		$this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1202
+												. ' alt="' . esc_attr__(
1203
+													'Preview Custom Message Templates screenshot',
1204
+													'event_espresso'
1205
+												) . '" />';
1206
+		$this->_template_args['preview_text'] = '<strong>'
1207
+												. esc_html__(
1208
+													'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1209
+													'event_espresso'
1210
+												)
1211
+												. '</strong>';
1212
+
1213
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1214
+	}
1215
+
1216
+
1217
+	/**
1218
+	 * get_message_templates
1219
+	 * This gets all the message templates for listing on the overview list.
1220
+	 *
1221
+	 * @access public
1222
+	 * @param int    $per_page the amount of templates groups to show per page
1223
+	 * @param string $type     the current _view we're getting templates for
1224
+	 * @param bool   $count    return count?
1225
+	 * @param bool   $all      disregard any paging info (get all data);
1226
+	 * @param bool   $global   whether to return just global (true) or custom templates (false)
1227
+	 * @return array
1228
+	 * @throws EE_Error
1229
+	 * @throws InvalidArgumentException
1230
+	 * @throws InvalidDataTypeException
1231
+	 * @throws InvalidInterfaceException
1232
+	 */
1233
+	public function get_message_templates(
1234
+		$per_page = 10,
1235
+		$type = 'in_use',
1236
+		$count = false,
1237
+		$all = false,
1238
+		$global = true
1239
+	) {
1240
+		$orderby = $this->request->getRequestParam('orderby', 'GRP_ID');
1241
+		$this->request->setRequestParam('orderby', $orderby);
1242
+
1243
+		$order        = $this->request->getRequestParam('order', 'ASC');
1244
+		$current_page = $this->request->getRequestParam('paged', 1, 'int');
1245
+		$per_page     = $this->request->getRequestParam('perpage', $per_page, 'int');
1246
+
1247
+		$offset = ($current_page - 1) * $per_page;
1248
+		$limit  = $all ? null : [$offset, $per_page];
1249
+
1250
+		// options will match what is in the _views array property
1251
+		return $type === 'in_use'
1252
+			? $this->getMtgModel()->get_all_active_message_templates(
1253
+				$orderby,
1254
+				$order,
1255
+				$limit,
1256
+				$count,
1257
+				$global,
1258
+				true
1259
+			)
1260
+			: $this->getMtgModel()->get_all_trashed_grouped_message_templates(
1261
+				$orderby,
1262
+				$order,
1263
+				$limit,
1264
+				$count,
1265
+				$global
1266
+			);
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * filters etc might need a list of installed message_types
1272
+	 *
1273
+	 * @return array an array of message type objects
1274
+	 */
1275
+	public function get_installed_message_types()
1276
+	{
1277
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1278
+		$installed               = [];
1279
+
1280
+		foreach ($installed_message_types as $message_type) {
1281
+			$installed[ $message_type->name ] = $message_type;
1282
+		}
1283
+
1284
+		return $installed;
1285
+	}
1286
+
1287
+
1288
+	/**
1289
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1290
+	 *
1291
+	 * @param string $message_type
1292
+	 * @param string $messenger
1293
+	 * @param string $GRP_ID
1294
+	 *
1295
+	 * @throws EE_error
1296
+	 * @throws ReflectionException
1297
+	 */
1298
+	public function add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1299
+	{
1300
+		// set values override any request data
1301
+		$message_type = ! empty($message_type) ? $message_type : $this->_active_message_type_name;
1302
+		$messenger    = ! empty($messenger) ? $messenger : $this->_active_messenger_name;
1303
+		$GRP_ID       = ! empty($GRP_ID) ? $GRP_ID : $this->request->getRequestParam('GRP_ID', 0, 'int');
1304
+
1305
+		// we need messenger and message type.  They should be coming from the event editor. If not here then return error
1306
+		if (empty($message_type) || empty($messenger)) {
1307
+			throw new EE_Error(
1308
+				esc_html__(
1309
+					'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1310
+					'event_espresso'
1311
+				)
1312
+			);
1313
+		}
1314
+
1315
+		// we need the GRP_ID for the template being used as the base for the new template
1316
+		if (empty($GRP_ID)) {
1317
+			throw new EE_Error(
1318
+				esc_html__(
1319
+					'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1320
+					'event_espresso'
1321
+				)
1322
+			);
1323
+		}
1324
+
1325
+		// let's just make sure the template gets generated!
1326
+
1327
+		// we need to reassign some variables for what the insert is expecting
1328
+		$this->request->setRequestParam('MTP_messenger', $messenger);
1329
+		$this->request->setRequestParam('MTP_message_type', $message_type);
1330
+		$this->request->setRequestParam('GRP_ID', $GRP_ID);
1331
+
1332
+		$this->_insert_or_update_message_template(true);
1333
+	}
1334
+
1335
+
1336
+	/**
1337
+	 * @param string $message_type     message type slug
1338
+	 * @param string $messenger        messenger slug
1339
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1340
+	 *                                 off of.
1341
+	 * @throws EE_error
1342
+	 * @throws ReflectionException
1343
+	 * @deprecated $VID:$
1344
+	 */
1345
+	protected function _add_message_template($message_type, $messenger, $GRP_ID)
1346
+	{
1347
+		$this->add_message_template($message_type, $messenger, $GRP_ID);
1348
+	}
1349
+
1350
+
1351
+	/**
1352
+	 * _edit_message_template
1353
+	 *
1354
+	 * @access protected
1355
+	 * @return void
1356
+	 * @throws InvalidIdentifierException
1357
+	 * @throws DomainException
1358
+	 * @throws EE_Error
1359
+	 * @throws InvalidArgumentException
1360
+	 * @throws ReflectionException
1361
+	 * @throws InvalidDataTypeException
1362
+	 * @throws InvalidInterfaceException
1363
+	 */
1364
+	protected function _edit_message_template()
1365
+	{
1366
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1367
+		$template_fields = '';
1368
+		$sidebar_fields  = '';
1369
+		// we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1370
+		// valid html in the templates.
1371
+		add_filter('tiny_mce_before_init', [$this, 'filter_tinymce_init'], 10, 2);
1372
+
1373
+		$GRP_ID = $this->request->getRequestParam('id', 0, 'int');
1374
+		$EVT_ID = $this->request->getRequestParam('evt_id', 0, 'int');
1375
+
1376
+		$this->_set_shortcodes(); // this also sets the _message_template property.
1377
+		$message_template_group = $this->_message_template_group;
1378
+		$c_label                = $message_template_group->context_label();
1379
+		$c_config               = $message_template_group->contexts_config();
1380
+
1381
+		reset($c_config);
1382
+		$context = $this->request->getRequestParam('context', key($c_config));
1383
+		$context = strtolower($context);
1384
+
1385
+		$action = empty($GRP_ID) ? 'insert_message_template' : 'update_message_template';
1386
+
1387
+		$edit_message_template_form_url = add_query_arg(
1388
+			['action' => $action, 'noheader' => true],
1389
+			EE_MSG_ADMIN_URL
1390
+		);
1391
+
1392
+		// set active messenger for this view
1393
+		$this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1394
+			$message_template_group->messenger()
1395
+		);
1396
+		$this->_active_message_type_name = $message_template_group->message_type();
1397
+
1398
+
1399
+		// Do we have any validation errors?
1400
+		$validators = $this->_get_transient();
1401
+		$v_fields   = ! empty($validators) ? array_keys($validators) : [];
1402
+
1403
+
1404
+		// we need to assemble the title from Various details
1405
+		$context_label = sprintf(
1406
+			esc_html__('(%s %s)', 'event_espresso'),
1407
+			$c_config[ $context ]['label'],
1408
+			ucwords($c_label['label'])
1409
+		);
1410
+
1411
+		$title = sprintf(
1412
+			esc_html__(' %s %s Template %s', 'event_espresso'),
1413
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1414
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1415
+			$context_label
1416
+		);
1417
+
1418
+		$this->_template_args['GRP_ID']           = $GRP_ID;
1419
+		$this->_template_args['message_template'] = $message_template_group;
1420
+		$this->_template_args['is_extra_fields']  = false;
1421
+
1422
+
1423
+		// let's get EEH_MSG_Template so we can get template form fields
1424
+		$template_field_structure = EEH_MSG_Template::get_fields(
1425
+			$message_template_group->messenger(),
1426
+			$message_template_group->message_type()
1427
+		);
1428
+
1429
+		if (! $template_field_structure) {
1430
+			$template_field_structure = false;
1431
+			$template_fields          = esc_html__(
1432
+				'There was an error in assembling the fields for this display (you should see an error message)',
1433
+				'event_espresso'
1434
+			);
1435
+		}
1436
+
1437
+
1438
+		$message_templates = $message_template_group->context_templates();
1439
+
1440
+
1441
+		// if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1442
+		// will get handled in the "extra" array.
1443
+		if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1444
+			foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1445
+				unset($template_field_structure[ $context ][ $reference_field ]);
1446
+			}
1447
+		}
1448
+
1449
+		// let's loop through the template_field_structure and actually assemble the input fields!
1450
+		if (! empty($template_field_structure)) {
1451
+			foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1452
+				// if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1453
+				// the extra array and reset them.
1454
+				if ($template_field === 'extra') {
1455
+					$this->_template_args['is_extra_fields'] = true;
1456
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1457
+						$message_template = $message_templates[ $context ][ $reference_field ];
1458
+						$content          = $message_template instanceof EE_Message_Template
1459
+							? $message_template->get('MTP_content')
1460
+							: '';
1461
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1462
+							// let's verify if we need this extra field via the shortcodes parameter.
1463
+							$continue = false;
1464
+							if (isset($extra_array['shortcodes_required'])) {
1465
+								foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1466
+									if (! array_key_exists($shortcode, $this->_shortcodes)) {
1467
+										$continue = true;
1468
+									}
1469
+								}
1470
+								if ($continue) {
1471
+									continue;
1472
+								}
1473
+							}
1474
+
1475
+							$field_id = $reference_field . '-' . $extra_field . '-content';
1476
+
1477
+							$template_form_fields[ $field_id ]         = $extra_array;
1478
+							$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1479
+																		 . $reference_field
1480
+																		 . '][content]['
1481
+																		 . $extra_field . ']';
1482
+							$css_class                                 = isset($extra_array['css_class'])
1483
+								? $extra_array['css_class']
1484
+								: '';
1485
+
1486
+							$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1487
+																			  && in_array($extra_field, $v_fields, true)
1488
+																			  && (
1489
+																				  is_array($validators[ $extra_field ])
1490
+																				  && isset($validators[ $extra_field ]['msg'])
1491
+																			  )
1492
+								? 'validate-error ' . $css_class
1493
+								: $css_class;
1494
+
1495
+							$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1496
+																		  && isset($content[ $extra_field ])
1497
+								? $content[ $extra_field ]
1498
+								: '';
1499
+
1500
+							// do we have a validation error?  if we do then let's use that value instead
1501
+							$template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1502
+								? $validators[ $extra_field ]['value']
1503
+								: $template_form_fields[ $field_id ]['value'];
1504
+
1505
+
1506
+							$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1507
+
1508
+							// shortcode selector
1509
+							$field_name_to_use                                   = $extra_field === 'main'
1510
+								? 'content'
1511
+								: $extra_field;
1512
+							$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1513
+								$field_name_to_use,
1514
+								$field_id
1515
+							);
1516
+						}
1517
+						$template_field_MTP_id           = $reference_field . '-MTP_ID';
1518
+						$template_field_template_name_id = $reference_field . '-name';
1519
+
1520
+						$template_form_fields[ $template_field_MTP_id ] = [
1521
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1522
+							'label'      => null,
1523
+							'input'      => 'hidden',
1524
+							'type'       => 'int',
1525
+							'required'   => false,
1526
+							'validation' => false,
1527
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1528
+							'css_class'  => '',
1529
+							'format'     => '%d',
1530
+							'db-col'     => 'MTP_ID',
1531
+						];
1532
+
1533
+						$template_form_fields[ $template_field_template_name_id ] = [
1534
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1535
+							'label'      => null,
1536
+							'input'      => 'hidden',
1537
+							'type'       => 'string',
1538
+							'required'   => false,
1539
+							'validation' => true,
1540
+							'value'      => $reference_field,
1541
+							'css_class'  => '',
1542
+							'format'     => '%s',
1543
+							'db-col'     => 'MTP_template_field',
1544
+						];
1545
+					}
1546
+					continue; // skip the next stuff, we got the necessary fields here for this dataset.
1547
+				} else {
1548
+					$field_id                                   = $template_field . '-content';
1549
+					$template_form_fields[ $field_id ]          = $field_setup_array;
1550
+					$template_form_fields[ $field_id ]['name']  =
1551
+						'MTP_template_fields[' . $template_field . '][content]';
1552
+					$message_template                           =
1553
+						isset($message_templates[ $context ][ $template_field ])
1554
+							? $message_templates[ $context ][ $template_field ]
1555
+							: null;
1556
+					$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1557
+																  && is_array($message_templates[ $context ])
1558
+																  && $message_template instanceof EE_Message_Template
1559
+						? $message_template->get('MTP_content')
1560
+						: '';
1561
+
1562
+					// do we have a validator error for this field?  if we do then we'll use that value instead
1563
+					$template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1564
+						? $validators[ $template_field ]['value']
1565
+						: $template_form_fields[ $field_id ]['value'];
1566
+
1567
+
1568
+					$template_form_fields[ $field_id ]['db-col']    = 'MTP_content';
1569
+					$css_class                                      = isset($field_setup_array['css_class'])
1570
+						? $field_setup_array['css_class']
1571
+						: '';
1572
+					$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1573
+																	  && in_array($template_field, $v_fields, true)
1574
+																	  && isset($validators[ $template_field ]['msg'])
1575
+						? 'validate-error ' . $css_class
1576
+						: $css_class;
1577
+
1578
+					// shortcode selector
1579
+					$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1580
+						$template_field,
1581
+						$field_id
1582
+					);
1583
+				}
1584
+
1585
+				// k took care of content field(s) now let's take care of others.
1586
+
1587
+				$template_field_MTP_id                 = $template_field . '-MTP_ID';
1588
+				$template_field_field_template_name_id = $template_field . '-name';
1589
+
1590
+				// foreach template field there are actually two form fields created
1591
+				$template_form_fields[ $template_field_MTP_id ] = [
1592
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1593
+					'label'      => null,
1594
+					'input'      => 'hidden',
1595
+					'type'       => 'int',
1596
+					'required'   => false,
1597
+					'validation' => true,
1598
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1599
+					'css_class'  => '',
1600
+					'format'     => '%d',
1601
+					'db-col'     => 'MTP_ID',
1602
+				];
1603
+
1604
+				$template_form_fields[ $template_field_field_template_name_id ] = [
1605
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1606
+					'label'      => null,
1607
+					'input'      => 'hidden',
1608
+					'type'       => 'string',
1609
+					'required'   => false,
1610
+					'validation' => true,
1611
+					'value'      => $template_field,
1612
+					'css_class'  => '',
1613
+					'format'     => '%s',
1614
+					'db-col'     => 'MTP_template_field',
1615
+				];
1616
+			}
1617
+
1618
+			// add other fields
1619
+			$template_form_fields['ee-msg-current-context'] = [
1620
+				'name'       => 'MTP_context',
1621
+				'label'      => null,
1622
+				'input'      => 'hidden',
1623
+				'type'       => 'string',
1624
+				'required'   => false,
1625
+				'validation' => true,
1626
+				'value'      => $context,
1627
+				'css_class'  => '',
1628
+				'format'     => '%s',
1629
+				'db-col'     => 'MTP_context',
1630
+			];
1631
+
1632
+			$template_form_fields['ee-msg-grp-id'] = [
1633
+				'name'       => 'GRP_ID',
1634
+				'label'      => null,
1635
+				'input'      => 'hidden',
1636
+				'type'       => 'int',
1637
+				'required'   => false,
1638
+				'validation' => true,
1639
+				'value'      => $GRP_ID,
1640
+				'css_class'  => '',
1641
+				'format'     => '%d',
1642
+				'db-col'     => 'GRP_ID',
1643
+			];
1644
+
1645
+			$template_form_fields['ee-msg-messenger'] = [
1646
+				'name'       => 'MTP_messenger',
1647
+				'label'      => null,
1648
+				'input'      => 'hidden',
1649
+				'type'       => 'string',
1650
+				'required'   => false,
1651
+				'validation' => true,
1652
+				'value'      => $message_template_group->messenger(),
1653
+				'css_class'  => '',
1654
+				'format'     => '%s',
1655
+				'db-col'     => 'MTP_messenger',
1656
+			];
1657
+
1658
+			$template_form_fields['ee-msg-message-type'] = [
1659
+				'name'       => 'MTP_message_type',
1660
+				'label'      => null,
1661
+				'input'      => 'hidden',
1662
+				'type'       => 'string',
1663
+				'required'   => false,
1664
+				'validation' => true,
1665
+				'value'      => $message_template_group->message_type(),
1666
+				'css_class'  => '',
1667
+				'format'     => '%s',
1668
+				'db-col'     => 'MTP_message_type',
1669
+			];
1670
+
1671
+			$sidebar_form_fields['ee-msg-is-global'] = [
1672
+				'name'       => 'MTP_is_global',
1673
+				'label'      => esc_html__('Global Template', 'event_espresso'),
1674
+				'input'      => 'hidden',
1675
+				'type'       => 'int',
1676
+				'required'   => false,
1677
+				'validation' => true,
1678
+				'value'      => $message_template_group->get('MTP_is_global'),
1679
+				'css_class'  => '',
1680
+				'format'     => '%d',
1681
+				'db-col'     => 'MTP_is_global',
1682
+			];
1683
+
1684
+			$sidebar_form_fields['ee-msg-is-override'] = [
1685
+				'name'       => 'MTP_is_override',
1686
+				'label'      => esc_html__('Override all custom', 'event_espresso'),
1687
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1688
+				'type'       => 'int',
1689
+				'required'   => false,
1690
+				'validation' => true,
1691
+				'value'      => $message_template_group->get('MTP_is_override'),
1692
+				'css_class'  => '',
1693
+				'format'     => '%d',
1694
+				'db-col'     => 'MTP_is_override',
1695
+			];
1696
+
1697
+			$sidebar_form_fields['ee-msg-is-active'] = [
1698
+				'name'       => 'MTP_is_active',
1699
+				'label'      => esc_html__('Active Template', 'event_espresso'),
1700
+				'input'      => 'hidden',
1701
+				'type'       => 'int',
1702
+				'required'   => false,
1703
+				'validation' => true,
1704
+				'value'      => $message_template_group->is_active(),
1705
+				'css_class'  => '',
1706
+				'format'     => '%d',
1707
+				'db-col'     => 'MTP_is_active',
1708
+			];
1709
+
1710
+			$sidebar_form_fields['ee-msg-deleted'] = [
1711
+				'name'       => 'MTP_deleted',
1712
+				'label'      => null,
1713
+				'input'      => 'hidden',
1714
+				'type'       => 'int',
1715
+				'required'   => false,
1716
+				'validation' => true,
1717
+				'value'      => $message_template_group->get('MTP_deleted'),
1718
+				'css_class'  => '',
1719
+				'format'     => '%d',
1720
+				'db-col'     => 'MTP_deleted',
1721
+			];
1722
+			$sidebar_form_fields['ee-msg-author']  = [
1723
+				'name'       => 'MTP_user_id',
1724
+				'label'      => esc_html__('Author', 'event_espresso'),
1725
+				'input'      => 'hidden',
1726
+				'type'       => 'int',
1727
+				'required'   => false,
1728
+				'validation' => false,
1729
+				'value'      => $message_template_group->user(),
1730
+				'format'     => '%d',
1731
+				'db-col'     => 'MTP_user_id',
1732
+			];
1733
+
1734
+			$sidebar_form_fields['ee-msg-route'] = [
1735
+				'name'  => 'action',
1736
+				'input' => 'hidden',
1737
+				'type'  => 'string',
1738
+				'value' => $action,
1739
+			];
1740
+
1741
+			$sidebar_form_fields['ee-msg-id']        = [
1742
+				'name'  => 'id',
1743
+				'input' => 'hidden',
1744
+				'type'  => 'int',
1745
+				'value' => $GRP_ID,
1746
+			];
1747
+			$sidebar_form_fields['ee-msg-evt-nonce'] = [
1748
+				'name'  => $action . '_nonce',
1749
+				'input' => 'hidden',
1750
+				'type'  => 'string',
1751
+				'value' => wp_create_nonce($action . '_nonce'),
1752
+			];
1753
+
1754
+			$template_switch = $this->request->getRequestParam('template_switch');
1755
+			if ($template_switch) {
1756
+				$sidebar_form_fields['ee-msg-template-switch'] = [
1757
+					'name'  => 'template_switch',
1758
+					'input' => 'hidden',
1759
+					'type'  => 'int',
1760
+					'value' => 1,
1761
+				];
1762
+			}
1763
+
1764
+
1765
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1766
+			$sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1767
+		} //end if ( !empty($template_field_structure) )
1768
+
1769
+		// set extra content for publish box
1770
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1771
+		$this->_set_publish_post_box_vars(
1772
+			'id',
1773
+			$GRP_ID,
1774
+			false,
1775
+			add_query_arg(
1776
+				['action' => 'global_mtps'],
1777
+				$this->_admin_base_url
1778
+			)
1779
+		);
1780
+
1781
+		// add preview button
1782
+		$preview_url    = parent::add_query_args_and_nonce(
1783
+			[
1784
+				'message_type' => $message_template_group->message_type(),
1785
+				'messenger'    => $message_template_group->messenger(),
1786
+				'context'      => $context,
1787
+				'GRP_ID'       => $GRP_ID,
1788
+				'evt_id'       => $EVT_ID ?: false,
1789
+				'action'       => 'preview_message',
1790
+			],
1791
+			$this->_admin_base_url
1792
+		);
1793
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1794
+						  . esc_html__('Preview', 'event_espresso')
1795
+						  . '</a>';
1796
+
1797
+
1798
+		// setup context switcher
1799
+		$this->_set_context_switcher(
1800
+			$message_template_group,
1801
+			[
1802
+				'page'    => 'espresso_messages',
1803
+				'action'  => 'edit_message_template',
1804
+				'id'      => $GRP_ID,
1805
+				'evt_id'  => $EVT_ID,
1806
+				'context' => $context,
1807
+				'extra'   => $preview_button,
1808
+			]
1809
+		);
1810
+
1811
+
1812
+		// main box
1813
+		$this->_template_args['template_fields']                         = $template_fields;
1814
+		$this->_template_args['sidebar_box_id']                          = 'details';
1815
+		$this->_template_args['action']                                  = $action;
1816
+		$this->_template_args['context']                                 = $context;
1817
+		$this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1818
+		$this->_template_args['learn_more_about_message_templates_link'] =
1819
+			$this->_learn_more_about_message_templates_link();
1820
+
1821
+
1822
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1823
+		$this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1824
+			$message_template_group,
1825
+			$context,
1826
+			$context_label
1827
+		);
1828
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1829
+		$this->_template_args['after_admin_page_content']  = $this->_add_form_element_after();
1830
+
1831
+		$this->_template_path = $this->_template_args['GRP_ID']
1832
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1833
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1834
+
1835
+		// send along EE_Message_Template_Group object for further template use.
1836
+		$this->_template_args['MTP'] = $message_template_group;
1837
+
1838
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1839
+			$this->_template_path,
1840
+			$this->_template_args,
1841
+			true
1842
+		);
1843
+
1844
+
1845
+		// finally, let's set the admin_page title
1846
+		$this->_admin_page_title = sprintf(esc_html__('Editing %s', 'event_espresso'), $title);
1847
+
1848
+
1849
+		// we need to take care of setting the shortcodes property for use elsewhere.
1850
+		$this->_set_shortcodes();
1851
+
1852
+
1853
+		// final template wrapper
1854
+		$this->display_admin_page_with_sidebar();
1855
+	}
1856
+
1857
+
1858
+	public function filter_tinymce_init($mceInit, $editor_id)
1859
+	{
1860
+		return $mceInit;
1861
+	}
1862
+
1863
+
1864
+	public function add_context_switcher()
1865
+	{
1866
+		return $this->_context_switcher;
1867
+	}
1868
+
1869
+
1870
+	/**
1871
+	 * Adds the activation/deactivation toggle for the message template context.
1872
+	 *
1873
+	 * @param EE_Message_Template_Group $message_template_group
1874
+	 * @param string                    $context
1875
+	 * @param string                    $context_label
1876
+	 * @return string
1877
+	 * @throws DomainException
1878
+	 * @throws EE_Error
1879
+	 * @throws InvalidIdentifierException
1880
+	 * @throws ReflectionException
1881
+	 */
1882
+	protected function add_active_context_element(
1883
+		EE_Message_Template_Group $message_template_group,
1884
+		$context,
1885
+		$context_label
1886
+	) {
1887
+		$template_args = [
1888
+			'context'                   => $context,
1889
+			'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1890
+			'is_active'                 => $message_template_group->is_context_active($context),
1891
+			'on_off_action'             => $message_template_group->is_context_active($context)
1892
+				? 'context-off'
1893
+				: 'context-on',
1894
+			'context_label'             => str_replace(['(', ')'], '', $context_label),
1895
+			'message_template_group_id' => $message_template_group->ID(),
1896
+		];
1897
+		return EEH_Template::display_template(
1898
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1899
+			$template_args,
1900
+			true
1901
+		);
1902
+	}
1903
+
1904
+
1905
+	/**
1906
+	 * Ajax callback for `toggle_context_template` ajax action.
1907
+	 * Handles toggling the message context on or off.
1908
+	 *
1909
+	 * @throws EE_Error
1910
+	 * @throws InvalidArgumentException
1911
+	 * @throws InvalidDataTypeException
1912
+	 * @throws InvalidIdentifierException
1913
+	 * @throws InvalidInterfaceException
1914
+	 */
1915
+	public function toggle_context_template()
1916
+	{
1917
+		$success = true;
1918
+		// check for required data
1919
+		if (
1920
+			! (
1921
+				$this->request->requestParamIsSet('message_template_group_id')
1922
+				&& $this->request->requestParamIsSet('context')
1923
+				&& $this->request->requestParamIsSet('status')
1924
+			)
1925
+		) {
1926
+			EE_Error::add_error(
1927
+				esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1928
+				__FILE__,
1929
+				__FUNCTION__,
1930
+				__LINE__
1931
+			);
1932
+			$success = false;
1933
+		}
1934
+
1935
+		$nonce   = $this->request->getRequestParam('toggle_context_nonce', '');
1936
+		$context = $this->request->getRequestParam('context', '');
1937
+		$status  = $this->request->getRequestParam('status', '');
1938
+
1939
+		$this->_verify_nonce($nonce, "activate_{$context}_toggle_nonce");
1940
+
1941
+		if ($status !== 'off' && $status !== 'on') {
1942
+			EE_Error::add_error(
1943
+				sprintf(
1944
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1945
+					$status
1946
+				),
1947
+				__FILE__,
1948
+				__FUNCTION__,
1949
+				__LINE__
1950
+			);
1951
+			$success = false;
1952
+		}
1953
+		$message_template_group_id = $this->request->getRequestParam('message_template_group_id', 0, 'int');
1954
+		$message_template_group    = $this->getMtgModel()->get_one_by_ID($message_template_group_id);
1955
+		if (! $message_template_group instanceof EE_Message_Template_Group) {
1956
+			EE_Error::add_error(
1957
+				sprintf(
1958
+					esc_html__(
1959
+						'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1960
+						'event_espresso'
1961
+					),
1962
+					$message_template_group_id,
1963
+					'EE_Message_Template_Group'
1964
+				),
1965
+				__FILE__,
1966
+				__FUNCTION__,
1967
+				__LINE__
1968
+			);
1969
+			$success = false;
1970
+		}
1971
+		if ($success) {
1972
+			$success = $status === 'off'
1973
+				? $message_template_group->deactivate_context($context)
1974
+				: $message_template_group->activate_context($context);
1975
+		}
1976
+		$this->_template_args['success'] = $success;
1977
+		$this->_return_json();
1978
+	}
1979
+
1980
+
1981
+	public function _add_form_element_before()
1982
+	{
1983
+		return '<form method="post" action="'
1984
+			   . $this->_template_args['edit_message_template_form_url']
1985
+			   . '" id="ee-msg-edit-frm">';
1986
+	}
1987
+
1988
+
1989
+	public function _add_form_element_after()
1990
+	{
1991
+		return '</form>';
1992
+	}
1993
+
1994
+
1995
+	/**
1996
+	 * This executes switching the template pack for a message template.
1997
+	 *
1998
+	 * @throws EE_Error
1999
+	 * @throws InvalidDataTypeException
2000
+	 * @throws InvalidInterfaceException
2001
+	 * @throws InvalidArgumentException
2002
+	 * @throws ReflectionException
2003
+	 * @since 4.5.0
2004
+	 */
2005
+	public function switch_template_pack()
2006
+	{
2007
+
2008
+		$GRP_ID        = $this->request->getRequestParam('GRP_ID', 0, 'int');
2009
+		$template_pack = $this->request->getRequestParam('template_pack', '');
2010
+
2011
+		// verify we have needed values.
2012
+		if (empty($GRP_ID) || empty($template_pack)) {
2013
+			$this->_template_args['error'] = true;
2014
+			EE_Error::add_error(
2015
+				esc_html__('The required date for switching templates is not available.', 'event_espresso'),
2016
+				__FILE__,
2017
+				__FUNCTION__,
2018
+				__LINE__
2019
+			);
2020
+		} else {
2021
+			// get template, set the new template_pack and then reset to default
2022
+			/** @var EE_Message_Template_Group $message_template_group */
2023
+			$message_template_group = $this->getMtgModel()->get_one_by_ID($GRP_ID);
2024
+
2025
+			$message_template_group->set_template_pack_name($template_pack);
2026
+			$this->request->setRequestParam('msgr', $message_template_group->messenger());
2027
+			$this->request->setRequestParam('mt', $message_template_group->message_type());
2028
+
2029
+			$query_args = $this->_reset_to_default_template();
2030
+
2031
+			if (empty($query_args['id'])) {
2032
+				EE_Error::add_error(
2033
+					esc_html__(
2034
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
2035
+						'event_espresso'
2036
+					),
2037
+					__FILE__,
2038
+					__FUNCTION__,
2039
+					__LINE__
2040
+				);
2041
+				$this->_template_args['error'] = true;
2042
+			} else {
2043
+				$template_label       = $message_template_group->get_template_pack()->label;
2044
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
2045
+				EE_Error::add_success(
2046
+					sprintf(
2047
+						esc_html__(
2048
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
2049
+							'event_espresso'
2050
+						),
2051
+						$template_label,
2052
+						$template_pack_labels->template_pack
2053
+					)
2054
+				);
2055
+				// generate the redirect url for js.
2056
+				$url = self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2057
+
2058
+				$this->_template_args['data']['redirect_url'] = $url;
2059
+				$this->_template_args['success']              = true;
2060
+			}
2061
+
2062
+			$this->_return_json();
2063
+		}
2064
+	}
2065
+
2066
+
2067
+	/**
2068
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2069
+	 * they want.
2070
+	 *
2071
+	 * @access protected
2072
+	 * @return array|void
2073
+	 * @throws EE_Error
2074
+	 * @throws InvalidArgumentException
2075
+	 * @throws InvalidDataTypeException
2076
+	 * @throws InvalidInterfaceException
2077
+	 * @throws ReflectionException
2078
+	 */
2079
+	protected function _reset_to_default_template()
2080
+	{
2081
+		$templates    = [];
2082
+		$GRP_ID       = $this->request->getRequestParam('GRP_ID', 0, 'int');
2083
+		$messenger    = $this->request->getRequestParam('msgr');
2084
+		$message_type = $this->request->getRequestParam('mt');
2085
+		// we need to make sure we've got the info we need.
2086
+		if (! ($GRP_ID && $messenger && $message_type)) {
2087
+			EE_Error::add_error(
2088
+				esc_html__(
2089
+					'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
2090
+					'event_espresso'
2091
+				),
2092
+				__FILE__,
2093
+				__FUNCTION__,
2094
+				__LINE__
2095
+			);
2096
+		}
2097
+
2098
+		// all templates will be reset to whatever the defaults are
2099
+		// for the global template matching the messenger and message type.
2100
+		$success = ! empty($GRP_ID);
2101
+
2102
+		if ($success) {
2103
+			// let's first determine if the incoming template is a global template,
2104
+			// if it isn't then we need to get the global template matching messenger and message type.
2105
+			// $MTPG = $this->getMtgModel()->get_one_by_ID( $GRP_ID );
2106
+
2107
+
2108
+			// note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2109
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
2110
+
2111
+			if ($success) {
2112
+				// if successfully deleted, lets generate the new ones.
2113
+				// Note. We set GLOBAL to true, because resets on ANY template
2114
+				// will use the related global template defaults for regeneration.
2115
+				// This means that if a custom template is reset it resets to whatever the related global template is.
2116
+				// HOWEVER, we DO keep the template pack and template variation set
2117
+				// for the current custom template when resetting.
2118
+				$templates = $this->_generate_new_templates($messenger, $message_type, $GRP_ID, true);
2119
+			}
2120
+		}
2121
+
2122
+		// any error messages?
2123
+		if (! $success) {
2124
+			EE_Error::add_error(
2125
+				esc_html__(
2126
+					'Something went wrong with deleting existing templates. Unable to reset to default',
2127
+					'event_espresso'
2128
+				),
2129
+				__FILE__,
2130
+				__FUNCTION__,
2131
+				__LINE__
2132
+			);
2133
+		}
2134
+
2135
+		// all good, let's add a success message!
2136
+		if ($success && ! empty($templates)) {
2137
+			// the info for the template we generated is the first element in the returned array
2138
+			EE_Error::overwrite_success();
2139
+			EE_Error::add_success(esc_html__('Templates have been reset to defaults.', 'event_espresso'));
2140
+		}
2141
+
2142
+
2143
+		$query_args = [
2144
+			'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
2145
+			'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
2146
+			'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2147
+		];
2148
+
2149
+		// if called via ajax then we return query args otherwise redirect
2150
+		if ($this->request->isAjax()) {
2151
+			return $query_args;
2152
+		}
2153
+		$this->_redirect_after_action(false, '', '', $query_args, true);
2154
+	}
2155
+
2156
+
2157
+	/**
2158
+	 * Retrieve and set the message preview for display.
2159
+	 *
2160
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2161
+	 * @return string
2162
+	 * @throws ReflectionException
2163
+	 * @throws EE_Error
2164
+	 * @throws InvalidArgumentException
2165
+	 * @throws InvalidDataTypeException
2166
+	 * @throws InvalidInterfaceException
2167
+	 */
2168
+	public function _preview_message($send = false)
2169
+	{
2170
+		// first make sure we've got the necessary parameters
2171
+		$GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
2172
+		if (! ($GRP_ID && $this->_active_messenger_name && $this->_active_message_type_name)) {
2173
+			EE_Error::add_error(
2174
+				esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2175
+				__FILE__,
2176
+				__FUNCTION__,
2177
+				__LINE__
2178
+			);
2179
+		}
2180
+
2181
+		$context = $this->request->getRequestParam('context');
2182
+		// get the preview!
2183
+		$preview = EED_Messages::preview_message(
2184
+			$this->_active_message_type_name,
2185
+			$context,
2186
+			$this->_active_messenger_name,
2187
+			$send
2188
+		);
2189
+
2190
+		if ($send) {
2191
+			return $preview;
2192
+		}
2193
+
2194
+		// if we have an evt_id set on the request, use it.
2195
+		$EVT_ID = $this->request->getRequestParam('evt_id', 0, 'int');
2196
+
2197
+		// let's add a button to go back to the edit view
2198
+		$query_args             = [
2199
+			'id'      => $GRP_ID,
2200
+			'evt_id'  => $EVT_ID,
2201
+			'context' => $context,
2202
+			'action'  => 'edit_message_template',
2203
+		];
2204
+		$go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2205
+		$preview_button         = '<a href="'
2206
+								  . $go_back_url
2207
+								  . '" class="button-secondary messages-preview-go-back-button">'
2208
+								  . esc_html__('Go Back to Edit', 'event_espresso')
2209
+								  . '</a>';
2210
+		$message_types          = $this->get_installed_message_types();
2211
+		$active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_active_messenger_name);
2212
+		$active_messenger_label = $active_messenger instanceof EE_messenger
2213
+			? ucwords($active_messenger->label['singular'])
2214
+			: esc_html__('Unknown Messenger', 'event_espresso');
2215
+		// let's provide a helpful title for context
2216
+		$preview_title = sprintf(
2217
+			esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2218
+			$active_messenger_label,
2219
+			ucwords($message_types[ $this->_active_message_type_name ]->label['singular'])
2220
+		);
2221
+		if (empty($preview)) {
2222
+			$this->noEventsErrorMessage();
2223
+		}
2224
+		// setup display of preview.
2225
+		$this->_admin_page_title                    = $preview_title;
2226
+		$this->_template_args['admin_page_title']   = $preview_title;
2227
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2228
+		$this->_template_args['data']['force_json'] = true;
2229
+
2230
+		return '';
2231
+	}
2232
+
2233
+
2234
+	/**
2235
+	 * Used to set an error if there are no events available for generating a preview/test send.
2236
+	 *
2237
+	 * @param bool $test_send Whether the error should be generated for the context of a test send.
2238
+	 */
2239
+	protected function noEventsErrorMessage($test_send = false)
2240
+	{
2241
+		$events_url = parent::add_query_args_and_nonce(
2242
+			[
2243
+				'action' => 'default',
2244
+				'page'   => 'espresso_events',
2245
+			],
2246
+			admin_url('admin.php')
2247
+		);
2248
+		$message    = $test_send
2249
+			? esc_html__(
2250
+				'A test message could not be sent for this message template because there are no events created yet. The preview system uses actual events for generating the test message. %1$sGo see your events%2$s!',
2251
+				'event_espresso'
2252
+			)
2253
+			: esc_html__(
2254
+				'There is no preview for this message template available because there are no events created yet. The preview system uses actual events for generating the preview. %1$sGo see your events%2$s!',
2255
+				'event_espresso'
2256
+			);
2257
+
2258
+		EE_Error::add_attention(
2259
+			sprintf(
2260
+				$message,
2261
+				"<a href='{$events_url}'>",
2262
+				'</a>'
2263
+			)
2264
+		);
2265
+	}
2266
+
2267
+
2268
+	/**
2269
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2270
+	 * gets called automatically.
2271
+	 *
2272
+	 * @return void
2273
+	 * @throws EE_Error
2274
+	 * @since 4.5.0
2275
+	 *
2276
+	 */
2277
+	protected function _display_preview_message()
2278
+	{
2279
+		$this->display_admin_page_with_no_sidebar();
2280
+	}
2281
+
2282
+
2283
+	/**
2284
+	 * registers metaboxes that should show up on the "edit_message_template" page
2285
+	 *
2286
+	 * @access protected
2287
+	 * @return void
2288
+	 */
2289
+	protected function _register_edit_meta_boxes()
2290
+	{
2291
+		add_meta_box(
2292
+			'mtp_valid_shortcodes',
2293
+			esc_html__('Valid Shortcodes', 'event_espresso'),
2294
+			[$this, 'shortcode_meta_box'],
2295
+			$this->_current_screen->id,
2296
+			'side'
2297
+		);
2298
+		add_meta_box(
2299
+			'mtp_extra_actions',
2300
+			esc_html__('Extra Actions', 'event_espresso'),
2301
+			[$this, 'extra_actions_meta_box'],
2302
+			$this->_current_screen->id,
2303
+			'side',
2304
+			'high'
2305
+		);
2306
+		add_meta_box(
2307
+			'mtp_templates',
2308
+			esc_html__('Template Styles', 'event_espresso'),
2309
+			[$this, 'template_pack_meta_box'],
2310
+			$this->_current_screen->id,
2311
+			'side',
2312
+			'high'
2313
+		);
2314
+	}
2315
+
2316
+
2317
+	/**
2318
+	 * metabox content for all template pack and variation selection.
2319
+	 *
2320
+	 * @return void
2321
+	 * @throws DomainException
2322
+	 * @throws EE_Error
2323
+	 * @throws InvalidArgumentException
2324
+	 * @throws ReflectionException
2325
+	 * @throws InvalidDataTypeException
2326
+	 * @throws InvalidInterfaceException
2327
+	 * @since 4.5.0
2328
+	 */
2329
+	public function template_pack_meta_box()
2330
+	{
2331
+		$this->_set_message_template_group();
2332
+
2333
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
2334
+
2335
+		$tp_select_values = [];
2336
+
2337
+		foreach ($tp_collection as $tp) {
2338
+			// only include template packs that support this messenger and message type!
2339
+			$supports = $tp->get_supports();
2340
+			if (
2341
+				! isset($supports[ $this->_message_template_group->messenger() ])
2342
+				|| ! in_array(
2343
+					$this->_message_template_group->message_type(),
2344
+					$supports[ $this->_message_template_group->messenger() ],
2345
+					true
2346
+				)
2347
+			) {
2348
+				// not supported
2349
+				continue;
2350
+			}
2351
+
2352
+			$tp_select_values[] = [
2353
+				'text' => $tp->label,
2354
+				'id'   => $tp->dbref,
2355
+			];
2356
+		}
2357
+
2358
+		// if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2359
+		// the default template pack.  This still allows for the odd template pack to override.
2360
+		if (empty($tp_select_values)) {
2361
+			$tp_select_values[] = [
2362
+				'text' => esc_html__('Default', 'event_espresso'),
2363
+				'id'   => 'default',
2364
+			];
2365
+		}
2366
+
2367
+		// setup variation select values for the currently selected template.
2368
+		$variations               = $this->_message_template_group->get_template_pack()->get_variations(
2369
+			$this->_message_template_group->messenger(),
2370
+			$this->_message_template_group->message_type()
2371
+		);
2372
+		$variations_select_values = [];
2373
+		foreach ($variations as $variation => $label) {
2374
+			$variations_select_values[] = [
2375
+				'text' => $label,
2376
+				'id'   => $variation,
2377
+			];
2378
+		}
2379
+
2380
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2381
+
2382
+		$template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
2383
+			'MTP_template_pack',
2384
+			$tp_select_values,
2385
+			$this->_message_template_group->get_template_pack_name()
2386
+		);
2387
+		$template_args['variations_selector']            = EEH_Form_Fields::select_input(
2388
+			'MTP_template_variation',
2389
+			$variations_select_values,
2390
+			$this->_message_template_group->get_template_pack_variation()
2391
+		);
2392
+		$template_args['template_pack_label']            = $template_pack_labels->template_pack;
2393
+		$template_args['template_variation_label']       = $template_pack_labels->template_variation;
2394
+		$template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
2395
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2396
+
2397
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2398
+
2399
+		EEH_Template::display_template($template, $template_args);
2400
+	}
2401
+
2402
+
2403
+	/**
2404
+	 * This meta box holds any extra actions related to Message Templates
2405
+	 * For now, this includes Resetting templates to defaults and sending a test email.
2406
+	 *
2407
+	 * @access  public
2408
+	 * @return void
2409
+	 * @throws EE_Error
2410
+	 */
2411
+	public function extra_actions_meta_box()
2412
+	{
2413
+		$template_form_fields = [];
2414
+
2415
+		$extra_args = [
2416
+			'msgr'   => $this->_message_template_group->messenger(),
2417
+			'mt'     => $this->_message_template_group->message_type(),
2418
+			'GRP_ID' => $this->_message_template_group->GRP_ID(),
2419
+		];
2420
+		// first we need to see if there are any fields
2421
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2422
+
2423
+		if (! empty($fields)) {
2424
+			// yup there be fields
2425
+			foreach ($fields as $field => $config) {
2426
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2427
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2428
+				$default  = isset($config['default']) ? $config['default'] : '';
2429
+				$default  = isset($config['value']) ? $config['value'] : $default;
2430
+
2431
+				// if type is hidden and the value is empty
2432
+				// something may have gone wrong so let's correct with the defaults
2433
+				$fix                = $config['input'] === 'hidden'
2434
+									  && isset($existing[ $field ])
2435
+									  && empty($existing[ $field ])
2436
+					? $default
2437
+					: '';
2438
+				$existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2439
+					? $existing[ $field ]
2440
+					: $fix;
2441
+
2442
+				$template_form_fields[ $field_id ] = [
2443
+					'name'       => 'test_settings_fld[' . $field . ']',
2444
+					'label'      => $config['label'],
2445
+					'input'      => $config['input'],
2446
+					'type'       => $config['type'],
2447
+					'required'   => $config['required'],
2448
+					'validation' => $config['validation'],
2449
+					'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2450
+					'css_class'  => $config['css_class'],
2451
+					'options'    => isset($config['options']) ? $config['options'] : [],
2452
+					'default'    => $default,
2453
+					'format'     => $config['format'],
2454
+				];
2455
+			}
2456
+		}
2457
+
2458
+		$test_settings_html = ! empty($template_form_fields)
2459
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2460
+			: '';
2461
+
2462
+		// print out $test_settings_fields
2463
+		if (! empty($test_settings_html)) {
2464
+			$test_settings_html .= '<input type="submit" class="button-primary mtp-test-button alignright" ';
2465
+			$test_settings_html .= 'name="test_button" value="';
2466
+			$test_settings_html .= esc_html__('Test Send', 'event_espresso');
2467
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2468
+		}
2469
+
2470
+		// and button
2471
+		$test_settings_html .= '<p>';
2472
+		$test_settings_html .= esc_html__('Need to reset this message type and start over?', 'event_espresso');
2473
+		$test_settings_html .= '</p>';
2474
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2475
+		$test_settings_html .= $this->get_action_link_or_button(
2476
+			'reset_to_default',
2477
+			'reset',
2478
+			$extra_args,
2479
+			'button-primary reset-default-button'
2480
+		);
2481
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2482
+		echo $test_settings_html; // already escaped
2483
+	}
2484
+
2485
+
2486
+	/**
2487
+	 * This returns the shortcode selector skeleton for a given context and field.
2488
+	 *
2489
+	 * @param string $field           The name of the field retrieving shortcodes for.
2490
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2491
+	 * @return string
2492
+	 * @throws DomainException
2493
+	 * @throws EE_Error
2494
+	 * @throws InvalidArgumentException
2495
+	 * @throws ReflectionException
2496
+	 * @throws InvalidDataTypeException
2497
+	 * @throws InvalidInterfaceException
2498
+	 * @since 4.9.rc.000
2499
+	 */
2500
+	protected function _get_shortcode_selector($field, $linked_input_id)
2501
+	{
2502
+		$template_args = [
2503
+			'shortcodes'      => $this->_get_shortcodes([$field]),
2504
+			'fieldname'       => $field,
2505
+			'linked_input_id' => $linked_input_id,
2506
+		];
2507
+
2508
+		return EEH_Template::display_template(
2509
+			EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2510
+			$template_args,
2511
+			true
2512
+		);
2513
+	}
2514
+
2515
+
2516
+	/**
2517
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2518
+	 * page)
2519
+	 *
2520
+	 * @access public
2521
+	 * @return void
2522
+	 * @throws EE_Error
2523
+	 * @throws InvalidArgumentException
2524
+	 * @throws ReflectionException
2525
+	 * @throws InvalidDataTypeException
2526
+	 * @throws InvalidInterfaceException
2527
+	 */
2528
+	public function shortcode_meta_box()
2529
+	{
2530
+		$shortcodes = $this->_get_shortcodes([], false);
2531
+		// just make sure the shortcodes property is set
2532
+		// $messenger = $this->_message_template_group->messenger_obj();
2533
+		// now let's set the content depending on the status of the shortcodes array
2534
+		if (empty($shortcodes)) {
2535
+			echo '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2536
+			return;
2537
+		}
2538
+		?>
2539 2539
         <div style="float:right; margin-top:10px">
2540 2540
             <?php echo $this->_get_help_tab_link('message_template_shortcodes'); // already escaped
2541
-            ?>
2541
+			?>
2542 2542
         </div>
2543 2543
         <p class="small-text">
2544 2544
             <?php printf(
2545
-                esc_html__(
2546
-                    'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2547
-                    'event_espresso'
2548
-                ),
2549
-                '<span class="dashicons dashicons-menu"></span>'
2550
-            ); ?>
2545
+				esc_html__(
2546
+					'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2547
+					'event_espresso'
2548
+				),
2549
+				'<span class="dashicons dashicons-menu"></span>'
2550
+			); ?>
2551 2551
         </p>
2552 2552
         <?php
2553
-    }
2554
-
2555
-
2556
-    /**
2557
-     * used to set the $_shortcodes property for when its needed elsewhere.
2558
-     *
2559
-     * @access protected
2560
-     * @return void
2561
-     * @throws EE_Error
2562
-     * @throws InvalidArgumentException
2563
-     * @throws ReflectionException
2564
-     * @throws InvalidDataTypeException
2565
-     * @throws InvalidInterfaceException
2566
-     */
2567
-    protected function _set_shortcodes()
2568
-    {
2569
-
2570
-        // no need to run this if the property is already set
2571
-        if (! empty($this->_shortcodes)) {
2572
-            return;
2573
-        }
2574
-
2575
-        $this->_shortcodes = $this->_get_shortcodes();
2576
-    }
2577
-
2578
-
2579
-    /**
2580
-     * gets all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2581
-     * property)
2582
-     *
2583
-     * @access  protected
2584
-     * @param array   $fields  include an array of specific field names that you want to be used to get the shortcodes
2585
-     *                         for. Defaults to all (for the given context)
2586
-     * @param boolean $merged  Whether to merge all the shortcodes into one list of unique shortcodes
2587
-     * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2588
-     *                         true just an array of shortcode/label pairs.
2589
-     * @throws EE_Error
2590
-     * @throws InvalidArgumentException
2591
-     * @throws ReflectionException
2592
-     * @throws InvalidDataTypeException
2593
-     * @throws InvalidInterfaceException
2594
-     */
2595
-    protected function _get_shortcodes($fields = [], $merged = true)
2596
-    {
2597
-        $this->_set_message_template_group();
2598
-
2599
-        // we need the messenger and message template to retrieve the valid shortcodes array.
2600
-        $GRP_ID = $this->request->getRequestParam('id', 0, 'int');
2601
-        if (empty($GRP_ID)) {
2602
-            return [];
2603
-        }
2604
-        $context = $this->request->getRequestParam(
2605
-            'messenger',
2606
-            key($this->_message_template_group->contexts_config())
2607
-        );
2608
-        return $this->_message_template_group->get_shortcodes($context, $fields, $merged);
2609
-    }
2610
-
2611
-
2612
-    /**
2613
-     * This sets the _message_template property (containing the called message_template object)
2614
-     *
2615
-     * @access protected
2616
-     * @return void
2617
-     * @throws EE_Error
2618
-     * @throws InvalidArgumentException
2619
-     * @throws ReflectionException
2620
-     * @throws InvalidDataTypeException
2621
-     * @throws InvalidInterfaceException
2622
-     */
2623
-    protected function _set_message_template_group()
2624
-    {
2625
-        // get out if this is already set.
2626
-        if (! empty($this->_message_template_group)) {
2627
-            return;
2628
-        }
2629
-
2630
-        $GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
2631
-        $GRP_ID = $this->request->getRequestParam('id', $GRP_ID, 'int');
2632
-
2633
-        // let's get the message templates
2634
-        $this->_message_template_group = ! empty($GRP_ID)
2635
-            ? $this->getMtgModel()->get_one_by_ID($GRP_ID)
2636
-            : $this->getMtgModel()->create_default_object();
2637
-
2638
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2639
-        $this->_variation     = $this->_message_template_group->get_template_pack_variation();
2640
-    }
2641
-
2642
-
2643
-    /**
2644
-     * sets up a context switcher for edit forms
2645
-     *
2646
-     * @access  protected
2647
-     * @param EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2648
-     * @param array                     $args                  various things the context switcher needs.
2649
-     * @throws EE_Error
2650
-     */
2651
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2652
-    {
2653
-        $context_details = $template_group_object->contexts_config();
2654
-        $context_label   = $template_group_object->context_label();
2655
-        ob_start();
2656
-        ?>
2553
+	}
2554
+
2555
+
2556
+	/**
2557
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2558
+	 *
2559
+	 * @access protected
2560
+	 * @return void
2561
+	 * @throws EE_Error
2562
+	 * @throws InvalidArgumentException
2563
+	 * @throws ReflectionException
2564
+	 * @throws InvalidDataTypeException
2565
+	 * @throws InvalidInterfaceException
2566
+	 */
2567
+	protected function _set_shortcodes()
2568
+	{
2569
+
2570
+		// no need to run this if the property is already set
2571
+		if (! empty($this->_shortcodes)) {
2572
+			return;
2573
+		}
2574
+
2575
+		$this->_shortcodes = $this->_get_shortcodes();
2576
+	}
2577
+
2578
+
2579
+	/**
2580
+	 * gets all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2581
+	 * property)
2582
+	 *
2583
+	 * @access  protected
2584
+	 * @param array   $fields  include an array of specific field names that you want to be used to get the shortcodes
2585
+	 *                         for. Defaults to all (for the given context)
2586
+	 * @param boolean $merged  Whether to merge all the shortcodes into one list of unique shortcodes
2587
+	 * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2588
+	 *                         true just an array of shortcode/label pairs.
2589
+	 * @throws EE_Error
2590
+	 * @throws InvalidArgumentException
2591
+	 * @throws ReflectionException
2592
+	 * @throws InvalidDataTypeException
2593
+	 * @throws InvalidInterfaceException
2594
+	 */
2595
+	protected function _get_shortcodes($fields = [], $merged = true)
2596
+	{
2597
+		$this->_set_message_template_group();
2598
+
2599
+		// we need the messenger and message template to retrieve the valid shortcodes array.
2600
+		$GRP_ID = $this->request->getRequestParam('id', 0, 'int');
2601
+		if (empty($GRP_ID)) {
2602
+			return [];
2603
+		}
2604
+		$context = $this->request->getRequestParam(
2605
+			'messenger',
2606
+			key($this->_message_template_group->contexts_config())
2607
+		);
2608
+		return $this->_message_template_group->get_shortcodes($context, $fields, $merged);
2609
+	}
2610
+
2611
+
2612
+	/**
2613
+	 * This sets the _message_template property (containing the called message_template object)
2614
+	 *
2615
+	 * @access protected
2616
+	 * @return void
2617
+	 * @throws EE_Error
2618
+	 * @throws InvalidArgumentException
2619
+	 * @throws ReflectionException
2620
+	 * @throws InvalidDataTypeException
2621
+	 * @throws InvalidInterfaceException
2622
+	 */
2623
+	protected function _set_message_template_group()
2624
+	{
2625
+		// get out if this is already set.
2626
+		if (! empty($this->_message_template_group)) {
2627
+			return;
2628
+		}
2629
+
2630
+		$GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
2631
+		$GRP_ID = $this->request->getRequestParam('id', $GRP_ID, 'int');
2632
+
2633
+		// let's get the message templates
2634
+		$this->_message_template_group = ! empty($GRP_ID)
2635
+			? $this->getMtgModel()->get_one_by_ID($GRP_ID)
2636
+			: $this->getMtgModel()->create_default_object();
2637
+
2638
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2639
+		$this->_variation     = $this->_message_template_group->get_template_pack_variation();
2640
+	}
2641
+
2642
+
2643
+	/**
2644
+	 * sets up a context switcher for edit forms
2645
+	 *
2646
+	 * @access  protected
2647
+	 * @param EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2648
+	 * @param array                     $args                  various things the context switcher needs.
2649
+	 * @throws EE_Error
2650
+	 */
2651
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2652
+	{
2653
+		$context_details = $template_group_object->contexts_config();
2654
+		$context_label   = $template_group_object->context_label();
2655
+		ob_start();
2656
+		?>
2657 2657
         <div class="ee-msg-switcher-container">
2658 2658
             <form method="get" action="<?php echo esc_url_raw(EE_MSG_ADMIN_URL); ?>" id="ee-msg-context-switcher-frm">
2659 2659
                 <?php
2660
-                foreach ($args as $name => $value) {
2661
-                    if ($name === 'context' || empty($value) || $name === 'extra') {
2662
-                        continue;
2663
-                    }
2664
-                    ?>
2660
+				foreach ($args as $name => $value) {
2661
+					if ($name === 'context' || empty($value) || $name === 'extra') {
2662
+						continue;
2663
+					}
2664
+					?>
2665 2665
                     <input type="hidden"
2666 2666
                            name="<?php echo esc_attr($name); ?>"
2667 2667
                            value="<?php echo esc_attr($value); ?>"
2668 2668
                     />
2669 2669
                     <?php
2670
-                }
2671
-                // setup nonce_url
2672
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2673
-                $id = 'ee-' . sanitize_key($context_label['label']) . '-select';
2674
-                ?>
2670
+				}
2671
+				// setup nonce_url
2672
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2673
+				$id = 'ee-' . sanitize_key($context_label['label']) . '-select';
2674
+				?>
2675 2675
                 <label for='<?php echo esc_attr($id); ?>' class='screen-reader-text'>
2676 2676
                     <?php esc_html_e('message context options', 'event_espresso'); ?>
2677 2677
                 </label>
2678 2678
                 <select id="<?php echo esc_attr($id); ?>" name="context">
2679 2679
                     <?php
2680
-                    $context_templates = $template_group_object->context_templates();
2681
-                    if (is_array($context_templates)) :
2682
-                        foreach ($context_templates as $context => $template_fields) :
2683
-                            $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2684
-                            ?>
2680
+					$context_templates = $template_group_object->context_templates();
2681
+					if (is_array($context_templates)) :
2682
+						foreach ($context_templates as $context => $template_fields) :
2683
+							$checked = ($context === $args['context']) ? 'selected="selected"' : '';
2684
+							?>
2685 2685
                             <option value="<?php echo esc_attr($context); ?>" <?php echo esc_attr($checked); ?>>
2686 2686
                                 <?php echo $context_details[ $context ]['label']; // already escaped
2687
-                                ?>
2687
+								?>
2688 2688
                             </option>
2689 2689
                         <?php endforeach;
2690
-                    endif; ?>
2690
+					endif; ?>
2691 2691
                 </select>
2692 2692
                 <?php $button_text = sprintf(
2693
-                    esc_html__('Switch %s', 'event_espresso'),
2694
-                    ucwords($context_label['label'])
2695
-                ); ?>
2693
+					esc_html__('Switch %s', 'event_espresso'),
2694
+					ucwords($context_label['label'])
2695
+				); ?>
2696 2696
                 <input class='button-secondary'
2697 2697
                        id="submit-msg-context-switcher-sbmt"
2698 2698
                        type="submit"
@@ -2700,1995 +2700,1995 @@  discard block
 block discarded – undo
2700 2700
                 />
2701 2701
             </form>
2702 2702
             <?php echo $args['extra']; // already escaped
2703
-            ?>
2703
+			?>
2704 2704
         </div> <!-- end .ee-msg-switcher-container -->
2705 2705
         <?php
2706
-        $this->_context_switcher = ob_get_clean();
2707
-    }
2708
-
2709
-
2710
-    /**
2711
-     * @param bool $new
2712
-     * @throws EE_Error
2713
-     * @throws ReflectionException
2714
-     */
2715
-    protected function _insert_or_update_message_template($new = false)
2716
-    {
2717
-        $form_data    = $this->getMessageTemplateFormData();
2718
-        $GRP_ID       = $form_data['GRP_ID'];
2719
-        $messenger    = $form_data['MTP_messenger'];
2720
-        $message_type = $form_data['MTP_message_type'];
2721
-        $context      = $form_data['MTP_context'];
2722
-
2723
-        // if this is "new" then we need to generate the default contexts
2724
-        // for the selected messenger/message_type for user to edit.
2725
-        list($success, $query_args) = $new
2726
-            ? $this->generateNewTemplates($GRP_ID, $messenger, $message_type)
2727
-            : $this->updateExistingTemplates($GRP_ID, $messenger, $message_type, $context, $form_data);
2728
-
2729
-        $success     = $success ? 1 : 0;
2730
-        $action_desc = $new ? 'created' : 'updated';
2731
-        $item_desc   = $this->generateUpdateDescription($messenger, $message_type, $context);
2732
-        $override    = $this->performTestSendAfterUpdate($messenger, $message_type, $context);
2733
-
2734
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2735
-    }
2736
-
2737
-
2738
-    /**
2739
-     * retrieve and sanitize form data
2740
-     *
2741
-     * @return array
2742
-     * @since $VID:$
2743
-     */
2744
-    protected function getMessageTemplateFormData()
2745
-    {
2746
-        return [
2747
-            'GRP_ID'           => $this->request->getRequestParam('GRP_ID', 0, 'int'),
2748
-            'MTP_context'      => strtolower($this->request->getRequestParam('MTP_context', '')),
2749
-            'MTP_messenger'    => strtolower($this->request->getRequestParam('MTP_messenger', '')),
2750
-            'MTP_message_type' => strtolower($this->request->getRequestParam('MTP_message_type', '')),
2751
-            'MTP_user_id'      => $this->request->getRequestParam('MTP_user_id', 0, 'int'),
2752
-            'MTP_is_global'    => $this->request->getRequestParam('MTP_is_global', 0, 'int'),
2753
-            'MTP_is_override'  => $this->request->getRequestParam('MTP_is_override', 0, 'int'),
2754
-            'MTP_deleted'      => $this->request->getRequestParam('MTP_deleted', 0, 'int'),
2755
-            'MTP_is_active'    => $this->request->getRequestParam('MTP_is_active', 0, 'int'),
2756
-        ];
2757
-    }
2758
-
2759
-
2760
-    /**
2761
-     * @param int    $GRP_ID
2762
-     * @param string $messenger
2763
-     * @param string $message_type
2764
-     * @return array no return on AJAX requests
2765
-     * @throws EE_Error
2766
-     * @throws ReflectionException
2767
-     * @since $VID:$
2768
-     */
2769
-    private function generateNewTemplates($GRP_ID, $messenger, $message_type)
2770
-    {
2771
-        $new_templates = $this->_generate_new_templates($messenger, [$message_type], $GRP_ID);
2772
-        $success       = ! empty($new_templates);
2773
-
2774
-        // we return things differently if doing ajax
2775
-        if ($this->request->isAjax()) {
2776
-            $this->_template_args['success'] = $success;
2777
-            $this->_template_args['error']   = ! $success;
2778
-            $this->_template_args['content'] = '';
2779
-            $this->_template_args['data']    = [
2780
-                'grpID'        => $new_templates['GRP_ID'],
2781
-                'templateName' => $new_templates['template_name'],
2782
-            ];
2783
-            if ($success) {
2784
-                EE_Error::overwrite_success();
2785
-                EE_Error::add_success(
2786
-                    esc_html__(
2787
-                        'The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2788
-                        'event_espresso'
2789
-                    )
2790
-                );
2791
-            }
2792
-            $this->_return_json();
2793
-        }
2794
-        return [
2795
-            $success,
2796
-            // 'query_args'
2797
-            [
2798
-                'id'      => $new_templates['GRP_ID'],
2799
-                'context' => $new_templates['MTP_context'],
2800
-                'action'  => 'edit_message_template',
2801
-            ],
2802
-        ];
2803
-    }
2804
-
2805
-
2806
-    /**
2807
-     * @param int    $GRP_ID
2808
-     * @param string $messenger
2809
-     * @param string $message_type
2810
-     * @param string $context
2811
-     * @param array  $form_data
2812
-     * @return array
2813
-     * @throws EE_Error
2814
-     * @since $VID:$
2815
-     */
2816
-    private function updateExistingTemplates(
2817
-        $GRP_ID,
2818
-        $messenger,
2819
-        $message_type,
2820
-        $context,
2821
-        array $form_data
2822
-    ) {
2823
-        $success         = false;
2824
-        $template_fields = $this->getTemplateFields();
2825
-        if ($template_fields) {
2826
-            // if field data is valid, then success will be true
2827
-            $success = $this->validateTemplateFields(
2828
-                $messenger,
2829
-                $message_type,
2830
-                $context,
2831
-                $template_fields
2832
-            );
2833
-            if ($success) {
2834
-                $field_data = [];
2835
-                foreach ($template_fields as $template_field => $content) {
2836
-                    // combine top-level form data with content for this field
2837
-                    $field_data = $this->getTemplateFieldFormData($content, $form_data);
2838
-                    $success    = $this->updateMessageTemplates($template_field, $field_data) ? $success : false;
2839
-                }
2840
-                // we can use the last set_column_values for the MTPG update
2841
-                // (because its the same for all of these specific MTPs)
2842
-                $success = $this->updateMessageTemplateGroup($field_data) ? $success : false;
2843
-            }
2844
-        }
2845
-
2846
-        return [
2847
-            $success,
2848
-            // 'query_args'
2849
-            [
2850
-                'id'      => $GRP_ID,
2851
-                'context' => $context,
2852
-                'action'  => 'edit_message_template',
2853
-            ],
2854
-        ];
2855
-    }
2856
-
2857
-
2858
-    /**
2859
-     * @return array
2860
-     * @since $VID:$
2861
-     */
2862
-    private function getTemplateFields()
2863
-    {
2864
-        $template_fields = $this->request->getRequestParam('MTP_template_fields', null, 'html', true);
2865
-        if (empty($template_fields)) {
2866
-            EE_Error::add_error(
2867
-                esc_html__(
2868
-                    'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2869
-                    'event_espresso'
2870
-                ),
2871
-                __FILE__,
2872
-                __FUNCTION__,
2873
-                __LINE__
2874
-            );
2875
-            return null;
2876
-        }
2877
-        // messages content is expected to be escaped
2878
-        return EEH_Array::addSlashesRecursively($template_fields);
2879
-    }
2880
-
2881
-
2882
-    /**
2883
-     * @param string $messenger
2884
-     * @param string $message_type
2885
-     * @param string $context
2886
-     * @param array  $template_fields
2887
-     * @return bool
2888
-     * @throws EE_Error
2889
-     * @since   $VID:$
2890
-     */
2891
-    private function validateTemplateFields(
2892
-        $messenger,
2893
-        $message_type,
2894
-        $context,
2895
-        array $template_fields
2896
-    ) {
2897
-        // first validate all fields!
2898
-        // this filter allows client code to add its own validation to the template fields as well.
2899
-        // returning an empty array means everything passed validation.
2900
-        // errors in validation should be represented in an array with the following shape:
2901
-        // array(
2902
-        //   'fieldname' => array(
2903
-        //          'msg' => 'error message'
2904
-        //          'value' => 'value for field producing error'
2905
-        // )
2906
-        $custom_validation = (array) apply_filters(
2907
-            'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2908
-            [],
2909
-            $template_fields,
2910
-            $context,
2911
-            $messenger,
2912
-            $message_type
2913
-        );
2914
-
2915
-        $system_validation = $this->getMtgModel()->validate(
2916
-            $template_fields,
2917
-            $context,
2918
-            $messenger,
2919
-            $message_type
2920
-        );
2921
-
2922
-        $system_validation = ! is_array($system_validation) && $system_validation ? [] : $system_validation;
2923
-        $validates         = array_merge($custom_validation, $system_validation);
2924
-
2925
-        // if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2926
-        // appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2927
-        //  WE need to make sure there is no actual error messages in validates.
2928
-        if (empty($validates)) {
2929
-            return true;
2930
-        }
2931
-
2932
-        // add the transient so when the form loads we know which fields to highlight
2933
-        $this->_add_transient('edit_message_template', $validates);
2934
-        // setup notices
2935
-        foreach ($validates as $error) {
2936
-            if (isset($error['msg'])) {
2937
-                EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2938
-            }
2939
-        }
2940
-        return false;
2941
-    }
2942
-
2943
-
2944
-    /**
2945
-     * @param array $field_data
2946
-     * @param array $form_data
2947
-     * @return array
2948
-     * @since   $VID:$
2949
-     */
2950
-    private function getTemplateFieldFormData(array $field_data, array $form_data)
2951
-    {
2952
-        return $form_data + [
2953
-                'MTP_ID'             => $field_data['MTP_ID'],
2954
-                'MTP_template_field' => $field_data['name'],
2955
-                // if they aren't allowed to use all JS, restrict them to standard allowed post tags
2956
-                'MTP_content'        => ! current_user_can('unfiltered_html')
2957
-                    ? $this->sanitizeMessageTemplateContent($field_data['content'])
2958
-                    : $field_data['content'],
2959
-            ];
2960
-    }
2961
-
2962
-
2963
-    /**
2964
-     * @param string $template_field
2965
-     * @param array  $form_data
2966
-     * @return bool
2967
-     * @throws EE_Error
2968
-     * @since $VID:$
2969
-     */
2970
-    private function updateMessageTemplates($template_field, array $form_data)
2971
-    {
2972
-        $MTP_ID                  = $form_data['MTP_ID'];
2973
-        $message_template_fields = [
2974
-            'GRP_ID'             => $form_data['GRP_ID'],
2975
-            'MTP_template_field' => $form_data['MTP_template_field'],
2976
-            'MTP_context'        => $form_data['MTP_context'],
2977
-            'MTP_content'        => $form_data['MTP_content'],
2978
-        ];
2979
-
2980
-        $hasMtpID = ! empty($MTP_ID);
2981
-        // if we have a MTP_ID for this field then update it, otherwise insert.
2982
-        // this has already been through the template field validator and sanitized, so it will be
2983
-        // safe to insert this field.  Why insert?  This typically happens when we introduce a new
2984
-        // message template field in a messenger/message type and existing users don't have the
2985
-        // default setup for it.
2986
-        // @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2987
-        $updated = $hasMtpID
2988
-            ? $this->getMtpModel()->update($message_template_fields, [['MTP_ID' => $MTP_ID]])
2989
-            : $this->getMtpModel()->insert($message_template_fields);
2990
-
2991
-        $insert_failed = ! $hasMtpID && ! $updated;
2992
-        // updates will return 0 if the field was not changed (ie: no changes = nothing actually updated)
2993
-        // but we won't consider that a problem, but if it returns false, then something went BOOM!
2994
-        $update_failed = $hasMtpID && $updated === false;
2995
-
2996
-        if ($insert_failed || $update_failed) {
2997
-            EE_Error::add_error(
2998
-                sprintf(
2999
-                    esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
3000
-                    $template_field
3001
-                ),
3002
-                __FILE__,
3003
-                __FUNCTION__,
3004
-                __LINE__
3005
-            );
3006
-            return false;
3007
-        }
3008
-        return true;
3009
-    }
3010
-
3011
-
3012
-    /**
3013
-     * @param array $form_data
3014
-     * @return bool
3015
-     * @throws EE_Error
3016
-     * @since $VID:$
3017
-     */
3018
-    private function updateMessageTemplateGroup(array $form_data)
3019
-    {
3020
-        $GRP_ID  = $form_data['GRP_ID'];
3021
-        $updated = $this->getMtgModel()->update(
3022
-        // fields and values
3023
-            [
3024
-                'MTP_user_id'      => $form_data['MTP_user_id'],
3025
-                'MTP_messenger'    => $form_data['MTP_messenger'],
3026
-                'MTP_message_type' => $form_data['MTP_message_type'],
3027
-                'MTP_is_global'    => $form_data['MTP_is_global'],
3028
-                'MTP_is_override'  => $form_data['MTP_is_override'],
3029
-                'MTP_deleted'      => $form_data['MTP_deleted'],
3030
-                'MTP_is_active'    => $form_data['MTP_is_active'],
3031
-                'MTP_name'         => $this->request->getRequestParam('ee_msg_non_global_fields[MTP_name]', ''),
3032
-                'MTP_description'  => $this->request->getRequestParam(
3033
-                    'ee_msg_non_global_fields[MTP_description]',
3034
-                    ''
3035
-                ),
3036
-            ],
3037
-            // where
3038
-            [['GRP_ID' => $GRP_ID]]
3039
-        );
3040
-
3041
-        if ($updated === false) {
3042
-            EE_Error::add_error(
3043
-                sprintf(
3044
-                    esc_html__(
3045
-                        'The Message Template Group (%d) was NOT updated for some reason',
3046
-                        'event_espresso'
3047
-                    ),
3048
-                    $form_data['GRP_ID']
3049
-                ),
3050
-                __FILE__,
3051
-                __FUNCTION__,
3052
-                __LINE__
3053
-            );
3054
-            return false;
3055
-        }
3056
-        // k now we need to ensure the template_pack and template_variation fields are set.
3057
-        $template_pack      = $this->request->getRequestParam('MTP_template_pack', 'default');
3058
-        $template_variation = $this->request->getRequestParam('MTP_template_variation', 'default');
3059
-
3060
-        $message_template_group = $this->getMtgModel()->get_one_by_ID($GRP_ID);
3061
-        if ($message_template_group instanceof EE_Message_Template_Group) {
3062
-            $message_template_group->set_template_pack_name($template_pack);
3063
-            $message_template_group->set_template_pack_variation($template_variation);
3064
-        }
3065
-        return true;
3066
-    }
3067
-
3068
-
3069
-    /**
3070
-     * recursively runs wp_kses() on message template content in a model safe manner
3071
-     *
3072
-     * @param array|string $content
3073
-     * @return array|string
3074
-     * @since   $VID:$
3075
-     */
3076
-    private function sanitizeMessageTemplateContent($content)
3077
-    {
3078
-        if (is_array($content)) {
3079
-            foreach ($content as $key => $value) {
3080
-                $content[ $key ] = $this->sanitizeMessageTemplateContent($value);
3081
-            }
3082
-            return $content;
3083
-        }
3084
-        // remove slashes so wp_kses() works properly
3085
-        // wp_kses_stripslashes() only removes slashes from double-quotes,
3086
-        // so attributes using single quotes always appear invalid.
3087
-        $content = stripslashes($content);
3088
-        $content = wp_kses($content, wp_kses_allowed_html('post'));
3089
-        // But currently the models expect slashed data, so after wp_kses()
3090
-        // runs we need to re-slash the data. Sheesh.
3091
-        // See https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
3092
-        return addslashes($content);
3093
-    }
3094
-
3095
-
3096
-    /**
3097
-     * @param string $messenger
3098
-     * @param string $message_type
3099
-     * @param string $context
3100
-     * @return string
3101
-     * @since $VID:$
3102
-     */
3103
-    private function generateUpdateDescription($messenger, $message_type, $context)
3104
-    {
3105
-        // need the message type and messenger objects to be able to use the labels for the notices
3106
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger);
3107
-        $messenger_label  = $messenger_object instanceof EE_messenger
3108
-            ? ucwords($messenger_object->label['singular'])
3109
-            : '';
3110
-
3111
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type);
3112
-        $message_type_label  = $message_type_object instanceof EE_message_type
3113
-            ? ucwords($message_type_object->label['singular'])
3114
-            : '';
3115
-
3116
-        $context   = ucwords(str_replace('_', ' ', $context));
3117
-        $item_desc = $messenger_label && $message_type_label
3118
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
3119
-            : '';
3120
-        $item_desc .= 'Message Template';
3121
-        return $item_desc;
3122
-    }
3123
-
3124
-
3125
-    /**
3126
-     * @param string $messenger
3127
-     * @param string $message_type
3128
-     * @param string $context
3129
-     * @return bool
3130
-     * @throws EE_Error
3131
-     * @throws ReflectionException
3132
-     * @since $VID:$
3133
-     */
3134
-    private function performTestSendAfterUpdate($messenger, $message_type, $context)
3135
-    {
3136
-        // was a test send triggered?
3137
-        if ($this->request->requestParamIsSet('test_button')) {
3138
-            EE_Error::overwrite_success();
3139
-            $this->_do_test_send($context, $messenger, $message_type);
3140
-            return true;
3141
-        }
3142
-        return false;
3143
-    }
3144
-
3145
-
3146
-    /**
3147
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
3148
-     *
3149
-     * @param string $context      what context being tested
3150
-     * @param string $messenger    messenger being tested
3151
-     * @param string $message_type message type being tested
3152
-     * @throws EE_Error
3153
-     * @throws InvalidArgumentException
3154
-     * @throws InvalidDataTypeException
3155
-     * @throws InvalidInterfaceException
3156
-     * @throws ReflectionException
3157
-     */
3158
-    protected function _do_test_send($context, $messenger, $message_type)
3159
-    {
3160
-        // set things up for preview
3161
-        $this->request->setRequestParam('messenger', $messenger);
3162
-        $this->request->setRequestParam('message_type', $message_type);
3163
-        $this->request->setRequestParam('context', $context);
3164
-        $GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
3165
-        $this->request->setRequestParam('GRP_ID', $GRP_ID);
3166
-
3167
-        $active_messenger  = $this->_message_resource_manager->get_active_messenger($messenger);
3168
-        $test_settings_fld = $this->request->getRequestParam('test_settings_fld', [], 'string', true);
3169
-
3170
-        // let's save any existing fields that might be required by the messenger
3171
-        if (
3172
-            ! empty($test_settings_fld)
3173
-            && $active_messenger instanceof EE_messenger
3174
-            && apply_filters(
3175
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3176
-                true,
3177
-                $test_settings_fld,
3178
-                $active_messenger
3179
-            )
3180
-        ) {
3181
-            $active_messenger->set_existing_test_settings($test_settings_fld);
3182
-        }
3183
-
3184
-        /**
3185
-         * Use filter to add additional controls on whether message can send or not
3186
-         */
3187
-        if (
3188
-            apply_filters(
3189
-                'FHEE__Messages_Admin_Page__do_test_send__can_send',
3190
-                true,
3191
-                $context,
3192
-                $this->request->requestParams(),
3193
-                $messenger,
3194
-                $message_type
3195
-            )
3196
-        ) {
3197
-            if (EEM_Event::instance()->count() > 0) {
3198
-                $success = $this->_preview_message(true);
3199
-                if ($success) {
3200
-                    EE_Error::add_success(esc_html__('Test message sent', 'event_espresso'));
3201
-                } else {
3202
-                    EE_Error::add_error(
3203
-                        esc_html__('The test message was not sent', 'event_espresso'),
3204
-                        __FILE__,
3205
-                        __FUNCTION__,
3206
-                        __LINE__
3207
-                    );
3208
-                }
3209
-            } else {
3210
-                $this->noEventsErrorMessage(true);
3211
-            }
3212
-        }
3213
-    }
3214
-
3215
-
3216
-    /**
3217
-     * _generate_new_templates
3218
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3219
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3220
-     * for the event.
3221
-     *
3222
-     *
3223
-     * @param string $messenger      the messenger we are generating templates for
3224
-     * @param array  $message_types  array of message types that the templates are generated for.
3225
-     * @param int    $GRP_ID         If this is a custom template being generated then a GRP_ID needs to be included to
3226
-     *                               indicate the message_template_group being used as the base.
3227
-     *
3228
-     * @param bool   $global
3229
-     *
3230
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
3231
-     *                               encountering problems.
3232
-     * @throws EE_Error
3233
-     * @throws ReflectionException
3234
-     */
3235
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3236
-    {
3237
-        // if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3238
-        // just don't generate any templates.
3239
-        if (empty($message_types)) {
3240
-            return [];
3241
-        }
3242
-
3243
-        $templates = EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3244
-        return $templates[0];
3245
-    }
3246
-
3247
-
3248
-    /**
3249
-     * [_trash_or_restore_message_template]
3250
-     *
3251
-     * @param boolean $trash  whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3252
-     * @param boolean $all    whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3253
-     *                        an individual context (FALSE).
3254
-     * @return void
3255
-     * @throws EE_Error
3256
-     * @throws InvalidArgumentException
3257
-     * @throws InvalidDataTypeException
3258
-     * @throws InvalidInterfaceException
3259
-     */
3260
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
3261
-    {
3262
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3263
-
3264
-        $success = 1;
3265
-
3266
-        // incoming GRP_IDs
3267
-        if ($all) {
3268
-            // Checkboxes
3269
-            $checkboxes = $this->request->getRequestParam('checkbox', [], 'int', true);
3270
-            if (! empty($checkboxes)) {
3271
-                // if array has more than one element then success message should be plural.
3272
-                // todo: what about nonce?
3273
-                $success = count($checkboxes) > 1 ? 2 : 1;
3274
-
3275
-                // cycle through checkboxes
3276
-                while (list($GRP_ID, $value) = each($checkboxes)) {
3277
-                    $trashed_or_restored = $trash
3278
-                        ? $this->getMtgModel()->delete_by_ID($GRP_ID)
3279
-                        : $this->getMtgModel()->restore_by_ID($GRP_ID);
3280
-                    if (! $trashed_or_restored) {
3281
-                        $success = 0;
3282
-                    }
3283
-                }
3284
-            } else {
3285
-                // grab single GRP_ID and handle
3286
-                $GRP_ID = $this->request->getRequestParam('id', 0, 'int');
3287
-                if (! empty($GRP_ID)) {
3288
-                    $trashed_or_restored = $trash
3289
-                        ? $this->getMtgModel()->delete_by_ID($GRP_ID)
3290
-                        : $this->getMtgModel()->restore_by_ID($GRP_ID);
3291
-                    if (! $trashed_or_restored) {
3292
-                        $success = 0;
3293
-                    }
3294
-                } else {
3295
-                    $success = 0;
3296
-                }
3297
-            }
3298
-        }
3299
-
3300
-        $action_desc = $trash
3301
-            ? esc_html__('moved to the trash', 'event_espresso')
3302
-            : esc_html__('restored', 'event_espresso');
3303
-
3304
-        $template_switch = $this->request->getRequestParam('template_switch', false, 'bool');
3305
-        $action_desc     = $template_switch ? esc_html__('switched', 'event_espresso') : $action_desc;
3306
-
3307
-        $item_desc = $all ? _n(
3308
-            'Message Template Group',
3309
-            'Message Template Groups',
3310
-            $success,
3311
-            'event_espresso'
3312
-        ) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3313
-
3314
-        $item_desc = $template_switch
3315
-            ? _n('template', 'templates', $success, 'event_espresso')
3316
-            : $item_desc;
3317
-
3318
-        $this->_redirect_after_action($success, $item_desc, $action_desc, []);
3319
-    }
3320
-
3321
-
3322
-    /**
3323
-     * [_delete_message_template]
3324
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3325
-     *
3326
-     * @return void
3327
-     * @throws EE_Error
3328
-     * @throws InvalidArgumentException
3329
-     * @throws InvalidDataTypeException
3330
-     * @throws InvalidInterfaceException
3331
-     * @throws ReflectionException
3332
-     */
3333
-    protected function _delete_message_template()
3334
-    {
3335
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3336
-
3337
-        // checkboxes
3338
-        $checkboxes = $this->request->getRequestParam('checkbox', [], 'int', true);
3339
-        if (! empty($checkboxes)) {
3340
-            // if array has more than one element then success message should be plural
3341
-            $success = count($checkboxes) > 1 ? 2 : 1;
3342
-
3343
-            // cycle through bulk action checkboxes
3344
-            while (list($GRP_ID, $value) = each($checkboxes)) {
3345
-                $success = $this->_delete_mtp_permanently($GRP_ID) ? $success : false;
3346
-            }
3347
-        } else {
3348
-            // grab single grp_id and delete
3349
-            $GRP_ID  = $this->request->getRequestParam('id', 0, 'int');
3350
-            $success = $this->_delete_mtp_permanently($GRP_ID);
3351
-        }
3352
-
3353
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', []);
3354
-    }
3355
-
3356
-
3357
-    /**
3358
-     * helper for permanently deleting a mtP group and all related message_templates
3359
-     *
3360
-     * @param int  $GRP_ID        The group being deleted
3361
-     * @param bool $include_group whether to delete the Message Template Group as well.
3362
-     * @return bool boolean to indicate the success of the deletes or not.
3363
-     * @throws EE_Error
3364
-     * @throws InvalidArgumentException
3365
-     * @throws InvalidDataTypeException
3366
-     * @throws InvalidInterfaceException
3367
-     * @throws ReflectionException
3368
-     * @throws ReflectionException
3369
-     */
3370
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3371
-    {
3372
-        $success = true;
3373
-        // first let's GET this group
3374
-        $MTG = $this->getMtgModel()->get_one_by_ID($GRP_ID);
3375
-        // then delete permanently all the related Message Templates
3376
-        $deleted = $MTG->delete_related_permanently('Message_Template');
3377
-
3378
-        if ($deleted === 0) {
3379
-            $success = false;
3380
-        }
3381
-
3382
-        // now delete permanently this particular group
3383
-
3384
-        if ($include_group && ! $MTG->delete_permanently()) {
3385
-            $success = false;
3386
-        }
3387
-
3388
-        return $success;
3389
-    }
3390
-
3391
-
3392
-    /**
3393
-     *    _learn_more_about_message_templates_link
3394
-     *
3395
-     * @access protected
3396
-     * @return string
3397
-     */
3398
-    protected function _learn_more_about_message_templates_link()
3399
-    {
3400
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3401
-               . esc_html__('learn more about how message templates works', 'event_espresso')
3402
-               . '</a>';
3403
-    }
3404
-
3405
-
3406
-    /**
3407
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3408
-     * ajax and other routes.
3409
-     *
3410
-     * @return void
3411
-     * @throws DomainException
3412
-     * @throws EE_Error
3413
-     */
3414
-    protected function _settings()
3415
-    {
3416
-        $this->_set_m_mt_settings();
3417
-
3418
-        // let's setup the messenger tabs
3419
-        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3420
-            $this->_m_mt_settings['messenger_tabs'],
3421
-            'messenger_links',
3422
-            '|',
3423
-            $this->request->getRequestParam('selected_messenger', 'email')
3424
-        );
3425
-
3426
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3427
-        $this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
3428
-
3429
-        $this->display_admin_page_with_sidebar();
3430
-    }
3431
-
3432
-
3433
-    /**
3434
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3435
-     *
3436
-     * @access protected
3437
-     * @return void
3438
-     * @throws DomainException
3439
-     */
3440
-    protected function _set_m_mt_settings()
3441
-    {
3442
-        // first if this is already set then lets get out no need to regenerate data.
3443
-        if (! empty($this->_m_mt_settings)) {
3444
-            return;
3445
-        }
3446
-
3447
-        // get all installed messengers and message_types
3448
-        $messengers    = $this->_message_resource_manager->installed_messengers();
3449
-        $message_types = $this->_message_resource_manager->installed_message_types();
3450
-
3451
-
3452
-        // assemble the array for the _tab_text_links helper
3453
-
3454
-        foreach ($messengers as $messenger) {
3455
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = [
3456
-                'label' => ucwords($messenger->label['singular']),
3457
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3458
-                    ? 'messenger-active'
3459
-                    : '',
3460
-                'href'  => $messenger->name,
3461
-                'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3462
-                'slug'  => $messenger->name,
3463
-                'obj'   => $messenger,
3464
-            ];
3465
-
3466
-
3467
-            $message_types_for_messenger = $messenger->get_valid_message_types();
3468
-
3469
-            foreach ($message_types as $message_type) {
3470
-                // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3471
-                // it shouldn't show in either the inactive OR active metabox.
3472
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3473
-                    continue;
3474
-                }
3475
-
3476
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3477
-                    $messenger->name,
3478
-                    $message_type->name
3479
-                )
3480
-                    ? 'active'
3481
-                    : 'inactive';
3482
-
3483
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = [
3484
-                    'label'    => ucwords($message_type->label['singular']),
3485
-                    'class'    => 'message-type-' . $a_or_i,
3486
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3487
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3488
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3489
-                    'title'    => $a_or_i === 'active'
3490
-                        ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3491
-                        : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3492
-                    'content'  => $a_or_i === 'active'
3493
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
3494
-                        : $this->_message_type_settings_content($message_type, $messenger),
3495
-                    'slug'     => $message_type->name,
3496
-                    'active'   => $a_or_i === 'active',
3497
-                    'obj'      => $message_type,
3498
-                ];
3499
-            }
3500
-        }
3501
-    }
3502
-
3503
-
3504
-    /**
3505
-     * This just prepares the content for the message type settings
3506
-     *
3507
-     * @param EE_message_type $message_type The message type object
3508
-     * @param EE_messenger    $messenger    The messenger object
3509
-     * @param boolean         $active       Whether the message type is active or not
3510
-     * @return string html output for the content
3511
-     * @throws DomainException
3512
-     */
3513
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
3514
-    {
3515
-        // get message type fields
3516
-        $fields                                         = $message_type->get_admin_settings_fields();
3517
-        $settings_template_args['template_form_fields'] = '';
3518
-
3519
-        if (! empty($fields) && $active) {
3520
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3521
-            foreach ($fields as $fldname => $fldprops) {
3522
-                $field_id                         = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3523
-                $template_form_field[ $field_id ] = [
3524
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3525
-                    'label'      => $fldprops['label'],
3526
-                    'input'      => $fldprops['field_type'],
3527
-                    'type'       => $fldprops['value_type'],
3528
-                    'required'   => $fldprops['required'],
3529
-                    'validation' => $fldprops['validation'],
3530
-                    'value'      => isset($existing_settings[ $fldname ])
3531
-                        ? $existing_settings[ $fldname ]
3532
-                        : $fldprops['default'],
3533
-                    'options'    => isset($fldprops['options'])
3534
-                        ? $fldprops['options']
3535
-                        : [],
3536
-                    'default'    => isset($existing_settings[ $fldname ])
3537
-                        ? $existing_settings[ $fldname ]
3538
-                        : $fldprops['default'],
3539
-                    'css_class'  => 'no-drag',
3540
-                    'format'     => $fldprops['format'],
3541
-                ];
3542
-            }
3543
-
3544
-
3545
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3546
-                ? $this->_generate_admin_form_fields(
3547
-                    $template_form_field,
3548
-                    'string',
3549
-                    'ee_mt_activate_form'
3550
-                )
3551
-                : '';
3552
-        }
3553
-
3554
-        $settings_template_args['description'] = $message_type->description;
3555
-        // we also need some hidden fields
3556
-        $hidden_fields = [
3557
-            'message_type_settings[messenger]' . $message_type->name    => [
3558
-                'type'  => 'hidden',
3559
-                'value' => $messenger->name,
3560
-            ],
3561
-            'message_type_settings[message_type]' . $message_type->name => [
3562
-                'type'  => 'hidden',
3563
-                'value' => $message_type->name,
3564
-            ],
3565
-            'type' . $message_type->name                                => [
3566
-                'type'  => 'hidden',
3567
-                'value' => 'message_type',
3568
-            ],
3569
-        ];
3570
-
3571
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3572
-            $hidden_fields,
3573
-            'array'
3574
-        );
3575
-        $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields'])
3576
-            ? ' hidden'
3577
-            : '';
3578
-
3579
-
3580
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3581
-        return EEH_Template::display_template($template, $settings_template_args, true);
3582
-    }
3583
-
3584
-
3585
-    /**
3586
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
3587
-     *
3588
-     * @access protected
3589
-     * @return void
3590
-     * @throws DomainException
3591
-     */
3592
-    protected function _messages_settings_metaboxes()
3593
-    {
3594
-        $this->_set_m_mt_settings();
3595
-        $m_boxes         = $mt_boxes = [];
3596
-        $m_template_args = $mt_template_args = [];
3597
-
3598
-        $selected_messenger = $this->request->getRequestParam('selected_messenger', 'email');
3599
-
3600
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
3601
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3602
-                $is_messenger_active = $this->_message_resource_manager->is_messenger_active($messenger);
3603
-                $hide_on_message     = $is_messenger_active ? '' : 'hidden';
3604
-                $hide_off_message    = $is_messenger_active ? 'hidden' : '';
3605
-
3606
-                // messenger meta boxes
3607
-                $active         = $selected_messenger === $messenger;
3608
-                $active_mt_tabs = isset($this->_m_mt_settings['message_type_tabs'][ $messenger ]['active'])
3609
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3610
-                    : '';
3611
-
3612
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3613
-                    esc_html__('%s Settings', 'event_espresso'),
3614
-                    $tab_array['label']
3615
-                );
3616
-
3617
-                $m_template_args[ $messenger . '_a_box' ] = [
3618
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3619
-                    'inactive_message_types' => isset(
3620
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3621
-                    )
3622
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3623
-                        : '',
3624
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3625
-                    'hidden'                 => $active ? '' : ' hidden',
3626
-                    'hide_on_message'        => $hide_on_message,
3627
-                    'messenger'              => $messenger,
3628
-                    'active'                 => $active,
3629
-                ];
3630
-
3631
-                // message type meta boxes
3632
-                // (which is really just the inactive container for each messenger
3633
-                // showing inactive message types for that messenger)
3634
-                $mt_boxes[ $messenger . '_i_box' ]         = esc_html__('Inactive Message Types', 'event_espresso');
3635
-                $mt_template_args[ $messenger . '_i_box' ] = [
3636
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3637
-                    'inactive_message_types' => isset(
3638
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3639
-                    )
3640
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3641
-                        : '',
3642
-                    'hidden'                 => $active ? '' : ' hidden',
3643
-                    'hide_on_message'        => $hide_on_message,
3644
-                    'hide_off_message'       => $hide_off_message,
3645
-                    'messenger'              => $messenger,
3646
-                    'active'                 => $active,
3647
-                ];
3648
-            }
3649
-        }
3650
-
3651
-
3652
-        // register messenger metaboxes
3653
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3654
-        foreach ($m_boxes as $box => $label) {
3655
-            $callback_args = ['template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]];
3656
-            $msgr          = str_replace('_a_box', '', $box);
3657
-            add_meta_box(
3658
-                'espresso_' . $msgr . '_settings',
3659
-                $label,
3660
-                function ($post, $metabox) {
3661
-                    EEH_Template::display_template(
3662
-                        $metabox['args']['template_path'],
3663
-                        $metabox['args']['template_args']
3664
-                    );
3665
-                },
3666
-                $this->_current_screen->id,
3667
-                'normal',
3668
-                'high',
3669
-                $callback_args
3670
-            );
3671
-        }
3672
-
3673
-        // register message type metaboxes
3674
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3675
-        foreach ($mt_boxes as $box => $label) {
3676
-            $callback_args = [
3677
-                'template_path' => $mt_template_path,
3678
-                'template_args' => $mt_template_args[ $box ],
3679
-            ];
3680
-            $mt            = str_replace('_i_box', '', $box);
3681
-            add_meta_box(
3682
-                'espresso_' . $mt . '_inactive_mts',
3683
-                $label,
3684
-                function ($post, $metabox) {
3685
-                    EEH_Template::display_template(
3686
-                        $metabox['args']['template_path'],
3687
-                        $metabox['args']['template_args']
3688
-                    );
3689
-                },
3690
-                $this->_current_screen->id,
3691
-                'side',
3692
-                'high',
3693
-                $callback_args
3694
-            );
3695
-        }
3696
-
3697
-        // register metabox for global messages settings but only when on the main site.  On single site installs this
3698
-        // will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3699
-        if (is_main_site()) {
3700
-            add_meta_box(
3701
-                'espresso_global_message_settings',
3702
-                esc_html__('Global Message Settings', 'event_espresso'),
3703
-                [$this, 'global_messages_settings_metabox_content'],
3704
-                $this->_current_screen->id,
3705
-                'normal',
3706
-                'low',
3707
-                []
3708
-            );
3709
-        }
3710
-    }
3711
-
3712
-
3713
-    /**
3714
-     *  This generates the content for the global messages settings metabox.
3715
-     *
3716
-     * @return void
3717
-     * @throws EE_Error
3718
-     * @throws InvalidArgumentException
3719
-     * @throws ReflectionException
3720
-     * @throws InvalidDataTypeException
3721
-     * @throws InvalidInterfaceException
3722
-     */
3723
-    public function global_messages_settings_metabox_content()
3724
-    {
3725
-        $form = $this->_generate_global_settings_form();
3726
-        // already escaped
3727
-        echo $form->form_open(
3728
-            $this->add_query_args_and_nonce(['action' => 'update_global_settings'], EE_MSG_ADMIN_URL),
3729
-            'POST'
3730
-        );
3731
-        echo $form->get_html();
3732
-        echo $form->form_close();
3733
-    }
3734
-
3735
-
3736
-    /**
3737
-     * This generates and returns the form object for the global messages settings.
3738
-     *
3739
-     * @return EE_Form_Section_Proper
3740
-     * @throws EE_Error
3741
-     * @throws InvalidArgumentException
3742
-     * @throws ReflectionException
3743
-     * @throws InvalidDataTypeException
3744
-     * @throws InvalidInterfaceException
3745
-     */
3746
-    protected function _generate_global_settings_form()
3747
-    {
3748
-        /** @var EE_Network_Core_Config $network_config */
3749
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3750
-
3751
-        return new EE_Form_Section_Proper(
3752
-            [
3753
-                'name'            => 'global_messages_settings',
3754
-                'html_id'         => 'global_messages_settings',
3755
-                'html_class'      => 'form-table',
3756
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3757
-                'subsections'     => apply_filters(
3758
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3759
-                    [
3760
-                        'do_messages_on_same_request' => new EE_Select_Input(
3761
-                            [
3762
-                                true  => esc_html__('On the same request', 'event_espresso'),
3763
-                                false => esc_html__('On a separate request', 'event_espresso'),
3764
-                            ],
3765
-                            [
3766
-                                'default'         => $network_config->do_messages_on_same_request,
3767
-                                'html_label_text' => esc_html__(
3768
-                                    'Generate and send all messages:',
3769
-                                    'event_espresso'
3770
-                                ),
3771
-                                'html_help_text'  => esc_html__(
3772
-                                    'By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3773
-                                    'event_espresso'
3774
-                                ),
3775
-                            ]
3776
-                        ),
3777
-                        'delete_threshold'            => new EE_Select_Input(
3778
-                            [
3779
-                                0  => esc_html__('Forever', 'event_espresso'),
3780
-                                3  => esc_html__('3 Months', 'event_espresso'),
3781
-                                6  => esc_html__('6 Months', 'event_espresso'),
3782
-                                9  => esc_html__('9 Months', 'event_espresso'),
3783
-                                12 => esc_html__('12 Months', 'event_espresso'),
3784
-                                24 => esc_html__('24 Months', 'event_espresso'),
3785
-                                36 => esc_html__('36 Months', 'event_espresso'),
3786
-                            ],
3787
-                            [
3788
-                                'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3789
-                                'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3790
-                                'html_help_text'  => esc_html__(
3791
-                                    'You can control how long a record of processed messages is kept via this option.',
3792
-                                    'event_espresso'
3793
-                                ),
3794
-                            ]
3795
-                        ),
3796
-                        'update_settings'             => new EE_Submit_Input(
3797
-                            [
3798
-                                'default'         => esc_html__('Update', 'event_espresso'),
3799
-                                'html_label_text' => '&nbsp',
3800
-                            ]
3801
-                        ),
3802
-                    ]
3803
-                ),
3804
-            ]
3805
-        );
3806
-    }
3807
-
3808
-
3809
-    /**
3810
-     * This handles updating the global settings set on the admin page.
3811
-     *
3812
-     * @throws EE_Error
3813
-     * @throws InvalidDataTypeException
3814
-     * @throws InvalidInterfaceException
3815
-     * @throws InvalidArgumentException
3816
-     * @throws ReflectionException
3817
-     */
3818
-    protected function _update_global_settings()
3819
-    {
3820
-        /** @var EE_Network_Core_Config $network_config */
3821
-        $network_config  = EE_Registry::instance()->NET_CFG->core;
3822
-        $messages_config = EE_Registry::instance()->CFG->messages;
3823
-        $form            = $this->_generate_global_settings_form();
3824
-        if ($form->was_submitted()) {
3825
-            $form->receive_form_submission();
3826
-            if ($form->is_valid()) {
3827
-                $valid_data = $form->valid_data();
3828
-                foreach ($valid_data as $property => $value) {
3829
-                    $setter = 'set_' . $property;
3830
-                    if (method_exists($network_config, $setter)) {
3831
-                        $network_config->{$setter}($value);
3832
-                    } elseif (
3833
-                        property_exists($network_config, $property)
3834
-                        && $network_config->{$property} !== $value
3835
-                    ) {
3836
-                        $network_config->{$property} = $value;
3837
-                    } elseif (
3838
-                        property_exists($messages_config, $property)
3839
-                        && $messages_config->{$property} !== $value
3840
-                    ) {
3841
-                        $messages_config->{$property} = $value;
3842
-                    }
3843
-                }
3844
-                // only update if the form submission was valid!
3845
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3846
-                EE_Registry::instance()->CFG->update_espresso_config();
3847
-                EE_Error::overwrite_success();
3848
-                EE_Error::add_success(esc_html__('Global message settings were updated', 'event_espresso'));
3849
-            }
3850
-        }
3851
-        $this->_redirect_after_action(0, '', '', ['action' => 'settings'], true);
3852
-    }
3853
-
3854
-
3855
-    /**
3856
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3857
-     *
3858
-     * @param array $tab_array This is an array of message type tab details used to generate the tabs
3859
-     * @return string html formatted tabs
3860
-     * @throws DomainException
3861
-     */
3862
-    protected function _get_mt_tabs($tab_array)
3863
-    {
3864
-        $tab_array = (array) $tab_array;
3865
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3866
-        $tabs      = '';
3867
-
3868
-        foreach ($tab_array as $tab) {
3869
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3870
-        }
3871
-
3872
-        return $tabs;
3873
-    }
3874
-
3875
-
3876
-    /**
3877
-     * This prepares the content of the messenger meta box admin settings
3878
-     *
3879
-     * @param EE_messenger $messenger The messenger we're setting up content for
3880
-     * @return string html formatted content
3881
-     * @throws DomainException
3882
-     */
3883
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3884
-    {
3885
-
3886
-        $fields                                         = $messenger->get_admin_settings_fields();
3887
-        $settings_template_args['template_form_fields'] = '';
3888
-
3889
-        // is $messenger active?
3890
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3891
-
3892
-
3893
-        if (! empty($fields)) {
3894
-            $existing_settings = $messenger->get_existing_admin_settings();
3895
-
3896
-            foreach ($fields as $fldname => $fldprops) {
3897
-                $field_id                         = $messenger->name . '-' . $fldname;
3898
-                $template_form_field[ $field_id ] = [
3899
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3900
-                    'label'      => $fldprops['label'],
3901
-                    'input'      => $fldprops['field_type'],
3902
-                    'type'       => $fldprops['value_type'],
3903
-                    'required'   => $fldprops['required'],
3904
-                    'validation' => $fldprops['validation'],
3905
-                    'value'      => isset($existing_settings[ $field_id ])
3906
-                        ? $existing_settings[ $field_id ]
3907
-                        : $fldprops['default'],
3908
-                    'css_class'  => '',
3909
-                    'format'     => $fldprops['format'],
3910
-                ];
3911
-            }
3912
-
3913
-
3914
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3915
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3916
-                : '';
3917
-        }
3918
-
3919
-        // we also need some hidden fields
3920
-        $settings_template_args['hidden_fields'] = [
3921
-            'messenger_settings[messenger]' . $messenger->name => [
3922
-                'type'  => 'hidden',
3923
-                'value' => $messenger->name,
3924
-            ],
3925
-            'type' . $messenger->name                          => [
3926
-                'type'  => 'hidden',
3927
-                'value' => 'messenger',
3928
-            ],
3929
-        ];
3930
-
3931
-        // make sure any active message types that are existing are included in the hidden fields
3932
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3933
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3934
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = [
3935
-                    'type'  => 'hidden',
3936
-                    'value' => $mt,
3937
-                ];
3938
-            }
3939
-        }
3940
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3941
-            $settings_template_args['hidden_fields'],
3942
-            'array'
3943
-        );
3944
-        $active                                  =
3945
-            $this->_message_resource_manager->is_messenger_active($messenger->name);
3946
-
3947
-        $settings_template_args['messenger']           = $messenger->name;
3948
-        $settings_template_args['description']         = $messenger->description;
3949
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3950
-
3951
-
3952
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3953
-            $messenger->name
3954
-        )
3955
-            ? $settings_template_args['show_hide_edit_form']
3956
-            : ' hidden';
3957
-
3958
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3959
-            ? ' hidden'
3960
-            : $settings_template_args['show_hide_edit_form'];
3961
-
3962
-
3963
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3964
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3965
-        $settings_template_args['on_off_status'] = $active;
3966
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3967
-        return EEH_Template::display_template(
3968
-            $template,
3969
-            $settings_template_args,
3970
-            true
3971
-        );
3972
-    }
3973
-
3974
-
3975
-    /**
3976
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3977
-     *
3978
-     * @throws DomainException
3979
-     * @throws EE_Error
3980
-     * @throws InvalidDataTypeException
3981
-     * @throws InvalidInterfaceException
3982
-     * @throws InvalidArgumentException
3983
-     * @throws ReflectionException
3984
-     */
3985
-    public function activate_messenger_toggle()
3986
-    {
3987
-        $success = true;
3988
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3989
-        // let's check that we have required data
3990
-
3991
-        if (! $this->_active_messenger_name) {
3992
-            EE_Error::add_error(
3993
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3994
-                __FILE__,
3995
-                __FUNCTION__,
3996
-                __LINE__
3997
-            );
3998
-            $success = false;
3999
-        }
4000
-
4001
-        // do a nonce check here since we're not arriving via a normal route
4002
-        $nonce     = $this->request->getRequestParam('activate_nonce', '');
4003
-        $nonce_ref = "activate_{$this->_active_messenger_name}_toggle_nonce";
4004
-
4005
-        $this->_verify_nonce($nonce, $nonce_ref);
4006
-
4007
-
4008
-        $status = $this->request->getRequestParam('status');
4009
-        if (! $status) {
4010
-            EE_Error::add_error(
4011
-                esc_html__(
4012
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
4013
-                    'event_espresso'
4014
-                ),
4015
-                __FILE__,
4016
-                __FUNCTION__,
4017
-                __LINE__
4018
-            );
4019
-            $success = false;
4020
-        }
4021
-
4022
-        // do check to verify we have a valid status.
4023
-        if ($status !== 'off' && $status !== 'on') {
4024
-            EE_Error::add_error(
4025
-                sprintf(
4026
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
4027
-                    $status
4028
-                ),
4029
-                __FILE__,
4030
-                __FUNCTION__,
4031
-                __LINE__
4032
-            );
4033
-            $success = false;
4034
-        }
4035
-
4036
-        if ($success) {
4037
-            // made it here?  Stop dawdling then!!
4038
-            $success = $status === 'off'
4039
-                ? $this->_deactivate_messenger($this->_active_messenger_name)
4040
-                : $this->_activate_messenger($this->_active_messenger_name);
4041
-        }
4042
-
4043
-        $this->_template_args['success'] = $success;
4044
-
4045
-        // no special instructions so let's just do the json return (which should automatically do all the special stuff).
4046
-        $this->_return_json();
4047
-    }
4048
-
4049
-
4050
-    /**
4051
-     * used by ajax from the messages settings page to activate|deactivate a message type
4052
-     *
4053
-     * @throws DomainException
4054
-     * @throws EE_Error
4055
-     * @throws ReflectionException
4056
-     * @throws InvalidDataTypeException
4057
-     * @throws InvalidInterfaceException
4058
-     * @throws InvalidArgumentException
4059
-     */
4060
-    public function activate_mt_toggle()
4061
-    {
4062
-        $success = true;
4063
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
4064
-
4065
-        // let's make sure we have the necessary data
4066
-        if (! $this->_active_message_type_name) {
4067
-            EE_Error::add_error(
4068
-                esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
4069
-                __FILE__,
4070
-                __FUNCTION__,
4071
-                __LINE__
4072
-            );
4073
-            $success = false;
4074
-        }
4075
-
4076
-        if (! $this->_active_messenger_name) {
4077
-            EE_Error::add_error(
4078
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
4079
-                __FILE__,
4080
-                __FUNCTION__,
4081
-                __LINE__
4082
-            );
4083
-            $success = false;
4084
-        }
4085
-
4086
-        $status = $this->request->getRequestParam('status');
4087
-        if (! $status) {
4088
-            EE_Error::add_error(
4089
-                esc_html__(
4090
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
4091
-                    'event_espresso'
4092
-                ),
4093
-                __FILE__,
4094
-                __FUNCTION__,
4095
-                __LINE__
4096
-            );
4097
-            $success = false;
4098
-        }
4099
-
4100
-
4101
-        // do check to verify we have a valid status.
4102
-        if ($status !== 'activate' && $status !== 'deactivate') {
4103
-            EE_Error::add_error(
4104
-                sprintf(
4105
-                    esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
4106
-                    $status
4107
-                ),
4108
-                __FILE__,
4109
-                __FUNCTION__,
4110
-                __LINE__
4111
-            );
4112
-            $success = false;
4113
-        }
4114
-
4115
-
4116
-        // do a nonce check here since we're not arriving via a normal route
4117
-        $nonce = $this->request->getRequestParam('mt_nonce', '');
4118
-        $this->_verify_nonce($nonce, "{$this->_active_message_type_name}_nonce");
4119
-
4120
-        if ($success) {
4121
-            // made it here? um, what are you waiting for then?
4122
-            $success = $status === 'deactivate'
4123
-                ? $this->_deactivate_message_type_for_messenger(
4124
-                    $this->_active_messenger_name,
4125
-                    $this->_active_message_type_name
4126
-                )
4127
-                : $this->_activate_message_type_for_messenger(
4128
-                    $this->_active_messenger_name,
4129
-                    $this->_active_message_type_name
4130
-                );
4131
-        }
4132
-
4133
-        $this->_template_args['success'] = $success;
4134
-        $this->_return_json();
4135
-    }
4136
-
4137
-
4138
-    /**
4139
-     * Takes care of processing activating a messenger and preparing the appropriate response.
4140
-     *
4141
-     * @param string $messenger_name The name of the messenger being activated
4142
-     * @return bool
4143
-     * @throws DomainException
4144
-     * @throws EE_Error
4145
-     * @throws InvalidArgumentException
4146
-     * @throws ReflectionException
4147
-     * @throws InvalidDataTypeException
4148
-     * @throws InvalidInterfaceException
4149
-     */
4150
-    protected function _activate_messenger($messenger_name)
4151
-    {
4152
-        $active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
4153
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger
4154
-            ? $active_messenger->get_default_message_types()
4155
-            : [];
4156
-
4157
-        // ensure is active
4158
-        $this->_message_resource_manager->activate_messenger($active_messenger, $message_types_to_activate);
4159
-
4160
-        // set response_data for reload
4161
-        foreach ($message_types_to_activate as $message_type_name) {
4162
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4163
-            if (
4164
-                $this->_message_resource_manager->is_message_type_active_for_messenger(
4165
-                    $messenger_name,
4166
-                    $message_type_name
4167
-                )
4168
-                && $message_type instanceof EE_message_type
4169
-            ) {
4170
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
4171
-                if ($message_type->get_admin_settings_fields()) {
4172
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
4173
-                }
4174
-            }
4175
-        }
4176
-
4177
-        // add success message for activating messenger
4178
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4179
-    }
4180
-
4181
-
4182
-    /**
4183
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
4184
-     *
4185
-     * @param string $messenger_name The name of the messenger being activated
4186
-     * @return bool
4187
-     * @throws DomainException
4188
-     * @throws EE_Error
4189
-     * @throws InvalidArgumentException
4190
-     * @throws ReflectionException
4191
-     * @throws InvalidDataTypeException
4192
-     * @throws InvalidInterfaceException
4193
-     */
4194
-    protected function _deactivate_messenger($messenger_name)
4195
-    {
4196
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4197
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
4198
-
4199
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4200
-    }
4201
-
4202
-
4203
-    /**
4204
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4205
-     *
4206
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
4207
-     * @param string $message_type_name The name of the message type being activated for the messenger
4208
-     * @return bool
4209
-     * @throws DomainException
4210
-     * @throws EE_Error
4211
-     * @throws InvalidArgumentException
4212
-     * @throws ReflectionException
4213
-     * @throws InvalidDataTypeException
4214
-     * @throws InvalidInterfaceException
4215
-     */
4216
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4217
-    {
4218
-        $active_messenger         = $this->_message_resource_manager->get_messenger($messenger_name);
4219
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4220
-
4221
-        // ensure is active
4222
-        $this->_message_resource_manager->activate_messenger($active_messenger, $message_type_name);
4223
-
4224
-        // set response for load
4225
-        if (
4226
-            $this->_message_resource_manager->is_message_type_active_for_messenger(
4227
-                $messenger_name,
4228
-                $message_type_name
4229
-            )
4230
-        ) {
4231
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
4232
-            if ($message_type_to_activate->get_admin_settings_fields()) {
4233
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
4234
-            }
4235
-        }
4236
-
4237
-        return $this->_setup_response_message_for_activating_messenger_with_message_types(
4238
-            $active_messenger,
4239
-            $message_type_to_activate
4240
-        );
4241
-    }
4242
-
4243
-
4244
-    /**
4245
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4246
-     *
4247
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4248
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
4249
-     * @return bool
4250
-     * @throws DomainException
4251
-     * @throws EE_Error
4252
-     * @throws InvalidArgumentException
4253
-     * @throws ReflectionException
4254
-     * @throws InvalidDataTypeException
4255
-     * @throws InvalidInterfaceException
4256
-     */
4257
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4258
-    {
4259
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4260
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4261
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4262
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4263
-
4264
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4265
-            $active_messenger,
4266
-            $message_type_to_deactivate
4267
-        );
4268
-    }
4269
-
4270
-
4271
-    /**
4272
-     * This just initializes the defaults for activating messenger and message type responses.
4273
-     */
4274
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
4275
-    {
4276
-        $this->_template_args['data']['active_mts'] = [];
4277
-        $this->_template_args['data']['mt_reload']  = [];
4278
-    }
4279
-
4280
-
4281
-    /**
4282
-     * Setup appropriate response for activating a messenger and/or message types
4283
-     *
4284
-     * @param EE_messenger         $messenger
4285
-     * @param EE_message_type|null $message_type
4286
-     * @return bool
4287
-     * @throws DomainException
4288
-     * @throws EE_Error
4289
-     * @throws InvalidArgumentException
4290
-     * @throws ReflectionException
4291
-     * @throws InvalidDataTypeException
4292
-     * @throws InvalidInterfaceException
4293
-     */
4294
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
4295
-        $messenger,
4296
-        EE_Message_Type $message_type = null
4297
-    ) {
4298
-        // if $messenger isn't a valid messenger object then get out.
4299
-        if (! $messenger instanceof EE_Messenger) {
4300
-            EE_Error::add_error(
4301
-                esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4302
-                __FILE__,
4303
-                __FUNCTION__,
4304
-                __LINE__
4305
-            );
4306
-            return false;
4307
-        }
4308
-        // activated
4309
-        if ($this->_template_args['data']['active_mts']) {
4310
-            EE_Error::overwrite_success();
4311
-            // activated a message type with the messenger
4312
-            if ($message_type instanceof EE_message_type) {
4313
-                EE_Error::add_success(
4314
-                    sprintf(
4315
-                        esc_html__(
4316
-                            '%s message type has been successfully activated with the %s messenger',
4317
-                            'event_espresso'
4318
-                        ),
4319
-                        ucwords($message_type->label['singular']),
4320
-                        ucwords($messenger->label['singular'])
4321
-                    )
4322
-                );
4323
-
4324
-                // if message type was invoice then let's make sure we activate the invoice payment method.
4325
-                if ($message_type->name === 'invoice') {
4326
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
4327
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4328
-                    if ($pm instanceof EE_Payment_Method) {
4329
-                        EE_Error::add_attention(
4330
-                            esc_html__(
4331
-                                'Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
4332
-                                'event_espresso'
4333
-                            )
4334
-                        );
4335
-                    }
4336
-                }
4337
-                // just toggles the entire messenger
4338
-            } else {
4339
-                EE_Error::add_success(
4340
-                    sprintf(
4341
-                        esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4342
-                        ucwords($messenger->label['singular'])
4343
-                    )
4344
-                );
4345
-            }
4346
-
4347
-            return true;
4348
-
4349
-            // possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4350
-            // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4351
-            // in which case we just give a success message for the messenger being successfully activated.
4352
-        } else {
4353
-            if (! $messenger->get_default_message_types()) {
4354
-                // messenger doesn't have any default message types so still a success.
4355
-                EE_Error::add_success(
4356
-                    sprintf(
4357
-                        esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4358
-                        ucwords($messenger->label['singular'])
4359
-                    )
4360
-                );
4361
-
4362
-                return true;
4363
-            } else {
4364
-                EE_Error::add_error(
4365
-                    $message_type instanceof EE_message_type
4366
-                    ? sprintf(
4367
-                        esc_html__(
4368
-                            '%s message type was not successfully activated with the %s messenger',
4369
-                            'event_espresso'
4370
-                        ),
4371
-                        ucwords($message_type->label['singular']),
4372
-                        ucwords($messenger->label['singular'])
4373
-                    )
4374
-                    : sprintf(
4375
-                        esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4376
-                        ucwords($messenger->label['singular'])
4377
-                    ),
4378
-                    __FILE__,
4379
-                    __FUNCTION__,
4380
-                    __LINE__
4381
-                );
4382
-
4383
-                return false;
4384
-            }
4385
-        }
4386
-    }
4387
-
4388
-
4389
-    /**
4390
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
4391
-     *
4392
-     * @param EE_messenger         $messenger
4393
-     * @param EE_message_type|null $message_type
4394
-     * @return bool
4395
-     * @throws DomainException
4396
-     * @throws EE_Error
4397
-     * @throws InvalidArgumentException
4398
-     * @throws ReflectionException
4399
-     * @throws InvalidDataTypeException
4400
-     * @throws InvalidInterfaceException
4401
-     */
4402
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4403
-        $messenger,
4404
-        EE_message_type $message_type = null
4405
-    ) {
4406
-        EE_Error::overwrite_success();
4407
-
4408
-        // if $messenger isn't a valid messenger object then get out.
4409
-        if (! $messenger instanceof EE_Messenger) {
4410
-            EE_Error::add_error(
4411
-                esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4412
-                __FILE__,
4413
-                __FUNCTION__,
4414
-                __LINE__
4415
-            );
4416
-
4417
-            return false;
4418
-        }
4419
-
4420
-        if ($message_type instanceof EE_message_type) {
4421
-            $message_type_name = $message_type->name;
4422
-            EE_Error::add_success(
4423
-                sprintf(
4424
-                    esc_html__(
4425
-                        '%s message type has been successfully deactivated for the %s messenger.',
4426
-                        'event_espresso'
4427
-                    ),
4428
-                    ucwords($message_type->label['singular']),
4429
-                    ucwords($messenger->label['singular'])
4430
-                )
4431
-            );
4432
-        } else {
4433
-            $message_type_name = '';
4434
-            EE_Error::add_success(
4435
-                sprintf(
4436
-                    esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4437
-                    ucwords($messenger->label['singular'])
4438
-                )
4439
-            );
4440
-        }
4441
-
4442
-        // if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4443
-        if (
4444
-            $messenger->name === 'html'
4445
-            && (
4446
-                is_null($message_type)
4447
-                || $message_type_name === 'invoice'
4448
-            )
4449
-        ) {
4450
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
4451
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4452
-            if ($count_updated > 0) {
4453
-                $msg = $message_type_name === 'invoice'
4454
-                    ? esc_html__(
4455
-                        'Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
4456
-                        'event_espresso'
4457
-                    )
4458
-                    : esc_html__(
4459
-                        'Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
4460
-                        'event_espresso'
4461
-                    );
4462
-                EE_Error::add_attention($msg);
4463
-            }
4464
-        }
4465
-
4466
-        return true;
4467
-    }
4468
-
4469
-
4470
-    /**
4471
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4472
-     *
4473
-     * @throws DomainException
4474
-     * @throws EE_Error
4475
-     * @throws EE_Error
4476
-     */
4477
-    public function update_mt_form()
4478
-    {
4479
-        if (! $this->_active_messenger_name || ! $this->_active_message_type_name) {
4480
-            EE_Error::add_error(
4481
-                esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4482
-                __FILE__,
4483
-                __FUNCTION__,
4484
-                __LINE__
4485
-            );
4486
-            $this->_return_json();
4487
-        }
4488
-
4489
-        $message_types = $this->get_installed_message_types();
4490
-        $message_type  = $message_types[ $this->_active_message_type_name ];
4491
-        $messenger     = $this->_message_resource_manager->get_active_messenger($this->_active_messenger_name);
4492
-        $content       = $this->_message_type_settings_content($message_type, $messenger, true);
4493
-
4494
-        $this->_template_args['success'] = true;
4495
-        $this->_template_args['content'] = $content;
4496
-        $this->_return_json();
4497
-    }
4498
-
4499
-
4500
-    /**
4501
-     * this handles saving the settings for a messenger or message type
4502
-     *
4503
-     * @throws EE_Error
4504
-     * @throws EE_Error
4505
-     */
4506
-    public function save_settings()
4507
-    {
4508
-        $type = $this->request->getRequestParam('type');
4509
-        if (! $type) {
4510
-            EE_Error::add_error(
4511
-                esc_html__(
4512
-                    'Cannot save settings because type is unknown (messenger settings or message type settings?)',
4513
-                    'event_espresso'
4514
-                ),
4515
-                __FILE__,
4516
-                __FUNCTION__,
4517
-                __LINE__
4518
-            );
4519
-            $this->_template_args['error'] = true;
4520
-            $this->_return_json();
4521
-        }
4522
-
4523
-
4524
-        if ($type === 'messenger') {
4525
-            // this should be an array.
4526
-            $settings  = $this->request->getRequestParam('messenger_settings', [], 'string', true);
4527
-            $messenger = $settings['messenger'];
4528
-            // remove messenger and message_types from settings array
4529
-            unset($settings['messenger'], $settings['message_types']);
4530
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4531
-        } elseif ($type === 'message_type') {
4532
-            $settings     = $this->request->getRequestParam('message_type_settings', [], 'string', true);
4533
-            $messenger    = $settings['messenger'];
4534
-            $message_type = $settings['message_type'];
4535
-            // remove messenger and message_types from settings array
4536
-            unset($settings['messenger'], $settings['message_types']);
4537
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4538
-        }
4539
-
4540
-        // okay we should have the data all setup.  Now we just update!
4541
-        $success = $this->_message_resource_manager->update_active_messengers_option();
4542
-
4543
-        if ($success) {
4544
-            EE_Error::add_success(esc_html__('Settings updated', 'event_espresso'));
4545
-        } else {
4546
-            EE_Error::add_error(
4547
-                esc_html__('Settings did not get updated', 'event_espresso'),
4548
-                __FILE__,
4549
-                __FUNCTION__,
4550
-                __LINE__
4551
-            );
4552
-        }
4553
-
4554
-        $this->_template_args['success'] = $success;
4555
-        $this->_return_json();
4556
-    }
4557
-
4558
-
4559
-
4560
-
4561
-    /**  EE MESSAGE PROCESSING ACTIONS **/
4562
-
4563
-
4564
-    /**
4565
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4566
-     * However, this does not send immediately, it just queues for sending.
4567
-     *
4568
-     * @throws EE_Error
4569
-     * @throws InvalidDataTypeException
4570
-     * @throws InvalidInterfaceException
4571
-     * @throws InvalidArgumentException
4572
-     * @throws ReflectionException
4573
-     * @since 4.9.0
4574
-     */
4575
-    protected function _generate_now()
4576
-    {
4577
-        EED_Messages::generate_now($this->_get_msg_ids_from_request());
4578
-        $this->_redirect_after_action(false, '', '', [], true);
4579
-    }
4580
-
4581
-
4582
-    /**
4583
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4584
-     * are EEM_Message::status_resend or EEM_Message::status_idle
4585
-     *
4586
-     * @throws EE_Error
4587
-     * @throws InvalidDataTypeException
4588
-     * @throws InvalidInterfaceException
4589
-     * @throws InvalidArgumentException
4590
-     * @throws ReflectionException
4591
-     * @since 4.9.0
4592
-     */
4593
-    protected function _generate_and_send_now()
4594
-    {
4595
-        EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4596
-        $this->_redirect_after_action(false, '', '', [], true);
4597
-    }
4598
-
4599
-
4600
-    /**
4601
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4602
-     *
4603
-     * @throws EE_Error
4604
-     * @throws InvalidDataTypeException
4605
-     * @throws InvalidInterfaceException
4606
-     * @throws InvalidArgumentException
4607
-     * @throws ReflectionException
4608
-     * @since 4.9.0
4609
-     */
4610
-    protected function _queue_for_resending()
4611
-    {
4612
-        EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4613
-        $this->_redirect_after_action(false, '', '', [], true);
4614
-    }
4615
-
4616
-
4617
-    /**
4618
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4619
-     *
4620
-     * @throws EE_Error
4621
-     * @throws InvalidDataTypeException
4622
-     * @throws InvalidInterfaceException
4623
-     * @throws InvalidArgumentException
4624
-     * @throws ReflectionException
4625
-     * @since 4.9.0
4626
-     */
4627
-    protected function _send_now()
4628
-    {
4629
-        EED_Messages::send_now($this->_get_msg_ids_from_request());
4630
-        $this->_redirect_after_action(false, '', '', [], true);
4631
-    }
4632
-
4633
-
4634
-    /**
4635
-     * Deletes EE_messages for IDs in the request.
4636
-     *
4637
-     * @throws EE_Error
4638
-     * @throws InvalidDataTypeException
4639
-     * @throws InvalidInterfaceException
4640
-     * @throws InvalidArgumentException
4641
-     * @since 4.9.0
4642
-     */
4643
-    protected function _delete_ee_messages()
4644
-    {
4645
-        $MSG_IDs       = $this->_get_msg_ids_from_request();
4646
-        $deleted_count = 0;
4647
-        foreach ($MSG_IDs as $MSG_ID) {
4648
-            if ($this->getMsgModel()->delete_by_ID($MSG_ID)) {
4649
-                $deleted_count++;
4650
-            }
4651
-        }
4652
-        if ($deleted_count) {
4653
-            EE_Error::add_success(
4654
-                esc_html(
4655
-                    _n(
4656
-                        'Message successfully deleted',
4657
-                        'Messages successfully deleted',
4658
-                        $deleted_count,
4659
-                        'event_espresso'
4660
-                    )
4661
-                )
4662
-            );
4663
-        } else {
4664
-            EE_Error::add_error(
4665
-                _n('The message was not deleted.', 'The messages were not deleted', count($MSG_IDs), 'event_espresso'),
4666
-                __FILE__,
4667
-                __FUNCTION__,
4668
-                __LINE__
4669
-            );
4670
-        }
4671
-        $this->_redirect_after_action(false, '', '', [], true);
4672
-    }
4673
-
4674
-
4675
-    /**
4676
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4677
-     *
4678
-     * @return array
4679
-     * @since 4.9.0
4680
-     */
4681
-    protected function _get_msg_ids_from_request()
4682
-    {
4683
-        $MSG_IDs = $this->request->getRequestParam('MSG_ID', [], 'string', true);
4684
-        if (empty($MSG_IDs)) {
4685
-            return [];
4686
-        }
4687
-        // if 'MSG_ID' was just a single ID (not an array)
4688
-        // then $MSG_IDs will be something like [123] so $MSG_IDs[0] should be 123
4689
-        // otherwise, $MSG_IDs was already an array where message IDs were used as the keys
4690
-        return count($MSG_IDs) === 1 && isset($MSG_IDs[0])
4691
-            ? $MSG_IDs
4692
-            : array_keys($MSG_IDs);
4693
-    }
2706
+		$this->_context_switcher = ob_get_clean();
2707
+	}
2708
+
2709
+
2710
+	/**
2711
+	 * @param bool $new
2712
+	 * @throws EE_Error
2713
+	 * @throws ReflectionException
2714
+	 */
2715
+	protected function _insert_or_update_message_template($new = false)
2716
+	{
2717
+		$form_data    = $this->getMessageTemplateFormData();
2718
+		$GRP_ID       = $form_data['GRP_ID'];
2719
+		$messenger    = $form_data['MTP_messenger'];
2720
+		$message_type = $form_data['MTP_message_type'];
2721
+		$context      = $form_data['MTP_context'];
2722
+
2723
+		// if this is "new" then we need to generate the default contexts
2724
+		// for the selected messenger/message_type for user to edit.
2725
+		list($success, $query_args) = $new
2726
+			? $this->generateNewTemplates($GRP_ID, $messenger, $message_type)
2727
+			: $this->updateExistingTemplates($GRP_ID, $messenger, $message_type, $context, $form_data);
2728
+
2729
+		$success     = $success ? 1 : 0;
2730
+		$action_desc = $new ? 'created' : 'updated';
2731
+		$item_desc   = $this->generateUpdateDescription($messenger, $message_type, $context);
2732
+		$override    = $this->performTestSendAfterUpdate($messenger, $message_type, $context);
2733
+
2734
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2735
+	}
2736
+
2737
+
2738
+	/**
2739
+	 * retrieve and sanitize form data
2740
+	 *
2741
+	 * @return array
2742
+	 * @since $VID:$
2743
+	 */
2744
+	protected function getMessageTemplateFormData()
2745
+	{
2746
+		return [
2747
+			'GRP_ID'           => $this->request->getRequestParam('GRP_ID', 0, 'int'),
2748
+			'MTP_context'      => strtolower($this->request->getRequestParam('MTP_context', '')),
2749
+			'MTP_messenger'    => strtolower($this->request->getRequestParam('MTP_messenger', '')),
2750
+			'MTP_message_type' => strtolower($this->request->getRequestParam('MTP_message_type', '')),
2751
+			'MTP_user_id'      => $this->request->getRequestParam('MTP_user_id', 0, 'int'),
2752
+			'MTP_is_global'    => $this->request->getRequestParam('MTP_is_global', 0, 'int'),
2753
+			'MTP_is_override'  => $this->request->getRequestParam('MTP_is_override', 0, 'int'),
2754
+			'MTP_deleted'      => $this->request->getRequestParam('MTP_deleted', 0, 'int'),
2755
+			'MTP_is_active'    => $this->request->getRequestParam('MTP_is_active', 0, 'int'),
2756
+		];
2757
+	}
2758
+
2759
+
2760
+	/**
2761
+	 * @param int    $GRP_ID
2762
+	 * @param string $messenger
2763
+	 * @param string $message_type
2764
+	 * @return array no return on AJAX requests
2765
+	 * @throws EE_Error
2766
+	 * @throws ReflectionException
2767
+	 * @since $VID:$
2768
+	 */
2769
+	private function generateNewTemplates($GRP_ID, $messenger, $message_type)
2770
+	{
2771
+		$new_templates = $this->_generate_new_templates($messenger, [$message_type], $GRP_ID);
2772
+		$success       = ! empty($new_templates);
2773
+
2774
+		// we return things differently if doing ajax
2775
+		if ($this->request->isAjax()) {
2776
+			$this->_template_args['success'] = $success;
2777
+			$this->_template_args['error']   = ! $success;
2778
+			$this->_template_args['content'] = '';
2779
+			$this->_template_args['data']    = [
2780
+				'grpID'        => $new_templates['GRP_ID'],
2781
+				'templateName' => $new_templates['template_name'],
2782
+			];
2783
+			if ($success) {
2784
+				EE_Error::overwrite_success();
2785
+				EE_Error::add_success(
2786
+					esc_html__(
2787
+						'The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2788
+						'event_espresso'
2789
+					)
2790
+				);
2791
+			}
2792
+			$this->_return_json();
2793
+		}
2794
+		return [
2795
+			$success,
2796
+			// 'query_args'
2797
+			[
2798
+				'id'      => $new_templates['GRP_ID'],
2799
+				'context' => $new_templates['MTP_context'],
2800
+				'action'  => 'edit_message_template',
2801
+			],
2802
+		];
2803
+	}
2804
+
2805
+
2806
+	/**
2807
+	 * @param int    $GRP_ID
2808
+	 * @param string $messenger
2809
+	 * @param string $message_type
2810
+	 * @param string $context
2811
+	 * @param array  $form_data
2812
+	 * @return array
2813
+	 * @throws EE_Error
2814
+	 * @since $VID:$
2815
+	 */
2816
+	private function updateExistingTemplates(
2817
+		$GRP_ID,
2818
+		$messenger,
2819
+		$message_type,
2820
+		$context,
2821
+		array $form_data
2822
+	) {
2823
+		$success         = false;
2824
+		$template_fields = $this->getTemplateFields();
2825
+		if ($template_fields) {
2826
+			// if field data is valid, then success will be true
2827
+			$success = $this->validateTemplateFields(
2828
+				$messenger,
2829
+				$message_type,
2830
+				$context,
2831
+				$template_fields
2832
+			);
2833
+			if ($success) {
2834
+				$field_data = [];
2835
+				foreach ($template_fields as $template_field => $content) {
2836
+					// combine top-level form data with content for this field
2837
+					$field_data = $this->getTemplateFieldFormData($content, $form_data);
2838
+					$success    = $this->updateMessageTemplates($template_field, $field_data) ? $success : false;
2839
+				}
2840
+				// we can use the last set_column_values for the MTPG update
2841
+				// (because its the same for all of these specific MTPs)
2842
+				$success = $this->updateMessageTemplateGroup($field_data) ? $success : false;
2843
+			}
2844
+		}
2845
+
2846
+		return [
2847
+			$success,
2848
+			// 'query_args'
2849
+			[
2850
+				'id'      => $GRP_ID,
2851
+				'context' => $context,
2852
+				'action'  => 'edit_message_template',
2853
+			],
2854
+		];
2855
+	}
2856
+
2857
+
2858
+	/**
2859
+	 * @return array
2860
+	 * @since $VID:$
2861
+	 */
2862
+	private function getTemplateFields()
2863
+	{
2864
+		$template_fields = $this->request->getRequestParam('MTP_template_fields', null, 'html', true);
2865
+		if (empty($template_fields)) {
2866
+			EE_Error::add_error(
2867
+				esc_html__(
2868
+					'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2869
+					'event_espresso'
2870
+				),
2871
+				__FILE__,
2872
+				__FUNCTION__,
2873
+				__LINE__
2874
+			);
2875
+			return null;
2876
+		}
2877
+		// messages content is expected to be escaped
2878
+		return EEH_Array::addSlashesRecursively($template_fields);
2879
+	}
2880
+
2881
+
2882
+	/**
2883
+	 * @param string $messenger
2884
+	 * @param string $message_type
2885
+	 * @param string $context
2886
+	 * @param array  $template_fields
2887
+	 * @return bool
2888
+	 * @throws EE_Error
2889
+	 * @since   $VID:$
2890
+	 */
2891
+	private function validateTemplateFields(
2892
+		$messenger,
2893
+		$message_type,
2894
+		$context,
2895
+		array $template_fields
2896
+	) {
2897
+		// first validate all fields!
2898
+		// this filter allows client code to add its own validation to the template fields as well.
2899
+		// returning an empty array means everything passed validation.
2900
+		// errors in validation should be represented in an array with the following shape:
2901
+		// array(
2902
+		//   'fieldname' => array(
2903
+		//          'msg' => 'error message'
2904
+		//          'value' => 'value for field producing error'
2905
+		// )
2906
+		$custom_validation = (array) apply_filters(
2907
+			'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2908
+			[],
2909
+			$template_fields,
2910
+			$context,
2911
+			$messenger,
2912
+			$message_type
2913
+		);
2914
+
2915
+		$system_validation = $this->getMtgModel()->validate(
2916
+			$template_fields,
2917
+			$context,
2918
+			$messenger,
2919
+			$message_type
2920
+		);
2921
+
2922
+		$system_validation = ! is_array($system_validation) && $system_validation ? [] : $system_validation;
2923
+		$validates         = array_merge($custom_validation, $system_validation);
2924
+
2925
+		// if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2926
+		// appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2927
+		//  WE need to make sure there is no actual error messages in validates.
2928
+		if (empty($validates)) {
2929
+			return true;
2930
+		}
2931
+
2932
+		// add the transient so when the form loads we know which fields to highlight
2933
+		$this->_add_transient('edit_message_template', $validates);
2934
+		// setup notices
2935
+		foreach ($validates as $error) {
2936
+			if (isset($error['msg'])) {
2937
+				EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2938
+			}
2939
+		}
2940
+		return false;
2941
+	}
2942
+
2943
+
2944
+	/**
2945
+	 * @param array $field_data
2946
+	 * @param array $form_data
2947
+	 * @return array
2948
+	 * @since   $VID:$
2949
+	 */
2950
+	private function getTemplateFieldFormData(array $field_data, array $form_data)
2951
+	{
2952
+		return $form_data + [
2953
+				'MTP_ID'             => $field_data['MTP_ID'],
2954
+				'MTP_template_field' => $field_data['name'],
2955
+				// if they aren't allowed to use all JS, restrict them to standard allowed post tags
2956
+				'MTP_content'        => ! current_user_can('unfiltered_html')
2957
+					? $this->sanitizeMessageTemplateContent($field_data['content'])
2958
+					: $field_data['content'],
2959
+			];
2960
+	}
2961
+
2962
+
2963
+	/**
2964
+	 * @param string $template_field
2965
+	 * @param array  $form_data
2966
+	 * @return bool
2967
+	 * @throws EE_Error
2968
+	 * @since $VID:$
2969
+	 */
2970
+	private function updateMessageTemplates($template_field, array $form_data)
2971
+	{
2972
+		$MTP_ID                  = $form_data['MTP_ID'];
2973
+		$message_template_fields = [
2974
+			'GRP_ID'             => $form_data['GRP_ID'],
2975
+			'MTP_template_field' => $form_data['MTP_template_field'],
2976
+			'MTP_context'        => $form_data['MTP_context'],
2977
+			'MTP_content'        => $form_data['MTP_content'],
2978
+		];
2979
+
2980
+		$hasMtpID = ! empty($MTP_ID);
2981
+		// if we have a MTP_ID for this field then update it, otherwise insert.
2982
+		// this has already been through the template field validator and sanitized, so it will be
2983
+		// safe to insert this field.  Why insert?  This typically happens when we introduce a new
2984
+		// message template field in a messenger/message type and existing users don't have the
2985
+		// default setup for it.
2986
+		// @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2987
+		$updated = $hasMtpID
2988
+			? $this->getMtpModel()->update($message_template_fields, [['MTP_ID' => $MTP_ID]])
2989
+			: $this->getMtpModel()->insert($message_template_fields);
2990
+
2991
+		$insert_failed = ! $hasMtpID && ! $updated;
2992
+		// updates will return 0 if the field was not changed (ie: no changes = nothing actually updated)
2993
+		// but we won't consider that a problem, but if it returns false, then something went BOOM!
2994
+		$update_failed = $hasMtpID && $updated === false;
2995
+
2996
+		if ($insert_failed || $update_failed) {
2997
+			EE_Error::add_error(
2998
+				sprintf(
2999
+					esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
3000
+					$template_field
3001
+				),
3002
+				__FILE__,
3003
+				__FUNCTION__,
3004
+				__LINE__
3005
+			);
3006
+			return false;
3007
+		}
3008
+		return true;
3009
+	}
3010
+
3011
+
3012
+	/**
3013
+	 * @param array $form_data
3014
+	 * @return bool
3015
+	 * @throws EE_Error
3016
+	 * @since $VID:$
3017
+	 */
3018
+	private function updateMessageTemplateGroup(array $form_data)
3019
+	{
3020
+		$GRP_ID  = $form_data['GRP_ID'];
3021
+		$updated = $this->getMtgModel()->update(
3022
+		// fields and values
3023
+			[
3024
+				'MTP_user_id'      => $form_data['MTP_user_id'],
3025
+				'MTP_messenger'    => $form_data['MTP_messenger'],
3026
+				'MTP_message_type' => $form_data['MTP_message_type'],
3027
+				'MTP_is_global'    => $form_data['MTP_is_global'],
3028
+				'MTP_is_override'  => $form_data['MTP_is_override'],
3029
+				'MTP_deleted'      => $form_data['MTP_deleted'],
3030
+				'MTP_is_active'    => $form_data['MTP_is_active'],
3031
+				'MTP_name'         => $this->request->getRequestParam('ee_msg_non_global_fields[MTP_name]', ''),
3032
+				'MTP_description'  => $this->request->getRequestParam(
3033
+					'ee_msg_non_global_fields[MTP_description]',
3034
+					''
3035
+				),
3036
+			],
3037
+			// where
3038
+			[['GRP_ID' => $GRP_ID]]
3039
+		);
3040
+
3041
+		if ($updated === false) {
3042
+			EE_Error::add_error(
3043
+				sprintf(
3044
+					esc_html__(
3045
+						'The Message Template Group (%d) was NOT updated for some reason',
3046
+						'event_espresso'
3047
+					),
3048
+					$form_data['GRP_ID']
3049
+				),
3050
+				__FILE__,
3051
+				__FUNCTION__,
3052
+				__LINE__
3053
+			);
3054
+			return false;
3055
+		}
3056
+		// k now we need to ensure the template_pack and template_variation fields are set.
3057
+		$template_pack      = $this->request->getRequestParam('MTP_template_pack', 'default');
3058
+		$template_variation = $this->request->getRequestParam('MTP_template_variation', 'default');
3059
+
3060
+		$message_template_group = $this->getMtgModel()->get_one_by_ID($GRP_ID);
3061
+		if ($message_template_group instanceof EE_Message_Template_Group) {
3062
+			$message_template_group->set_template_pack_name($template_pack);
3063
+			$message_template_group->set_template_pack_variation($template_variation);
3064
+		}
3065
+		return true;
3066
+	}
3067
+
3068
+
3069
+	/**
3070
+	 * recursively runs wp_kses() on message template content in a model safe manner
3071
+	 *
3072
+	 * @param array|string $content
3073
+	 * @return array|string
3074
+	 * @since   $VID:$
3075
+	 */
3076
+	private function sanitizeMessageTemplateContent($content)
3077
+	{
3078
+		if (is_array($content)) {
3079
+			foreach ($content as $key => $value) {
3080
+				$content[ $key ] = $this->sanitizeMessageTemplateContent($value);
3081
+			}
3082
+			return $content;
3083
+		}
3084
+		// remove slashes so wp_kses() works properly
3085
+		// wp_kses_stripslashes() only removes slashes from double-quotes,
3086
+		// so attributes using single quotes always appear invalid.
3087
+		$content = stripslashes($content);
3088
+		$content = wp_kses($content, wp_kses_allowed_html('post'));
3089
+		// But currently the models expect slashed data, so after wp_kses()
3090
+		// runs we need to re-slash the data. Sheesh.
3091
+		// See https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
3092
+		return addslashes($content);
3093
+	}
3094
+
3095
+
3096
+	/**
3097
+	 * @param string $messenger
3098
+	 * @param string $message_type
3099
+	 * @param string $context
3100
+	 * @return string
3101
+	 * @since $VID:$
3102
+	 */
3103
+	private function generateUpdateDescription($messenger, $message_type, $context)
3104
+	{
3105
+		// need the message type and messenger objects to be able to use the labels for the notices
3106
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger);
3107
+		$messenger_label  = $messenger_object instanceof EE_messenger
3108
+			? ucwords($messenger_object->label['singular'])
3109
+			: '';
3110
+
3111
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type);
3112
+		$message_type_label  = $message_type_object instanceof EE_message_type
3113
+			? ucwords($message_type_object->label['singular'])
3114
+			: '';
3115
+
3116
+		$context   = ucwords(str_replace('_', ' ', $context));
3117
+		$item_desc = $messenger_label && $message_type_label
3118
+			? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
3119
+			: '';
3120
+		$item_desc .= 'Message Template';
3121
+		return $item_desc;
3122
+	}
3123
+
3124
+
3125
+	/**
3126
+	 * @param string $messenger
3127
+	 * @param string $message_type
3128
+	 * @param string $context
3129
+	 * @return bool
3130
+	 * @throws EE_Error
3131
+	 * @throws ReflectionException
3132
+	 * @since $VID:$
3133
+	 */
3134
+	private function performTestSendAfterUpdate($messenger, $message_type, $context)
3135
+	{
3136
+		// was a test send triggered?
3137
+		if ($this->request->requestParamIsSet('test_button')) {
3138
+			EE_Error::overwrite_success();
3139
+			$this->_do_test_send($context, $messenger, $message_type);
3140
+			return true;
3141
+		}
3142
+		return false;
3143
+	}
3144
+
3145
+
3146
+	/**
3147
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
3148
+	 *
3149
+	 * @param string $context      what context being tested
3150
+	 * @param string $messenger    messenger being tested
3151
+	 * @param string $message_type message type being tested
3152
+	 * @throws EE_Error
3153
+	 * @throws InvalidArgumentException
3154
+	 * @throws InvalidDataTypeException
3155
+	 * @throws InvalidInterfaceException
3156
+	 * @throws ReflectionException
3157
+	 */
3158
+	protected function _do_test_send($context, $messenger, $message_type)
3159
+	{
3160
+		// set things up for preview
3161
+		$this->request->setRequestParam('messenger', $messenger);
3162
+		$this->request->setRequestParam('message_type', $message_type);
3163
+		$this->request->setRequestParam('context', $context);
3164
+		$GRP_ID = $this->request->getRequestParam('GRP_ID', 0, 'int');
3165
+		$this->request->setRequestParam('GRP_ID', $GRP_ID);
3166
+
3167
+		$active_messenger  = $this->_message_resource_manager->get_active_messenger($messenger);
3168
+		$test_settings_fld = $this->request->getRequestParam('test_settings_fld', [], 'string', true);
3169
+
3170
+		// let's save any existing fields that might be required by the messenger
3171
+		if (
3172
+			! empty($test_settings_fld)
3173
+			&& $active_messenger instanceof EE_messenger
3174
+			&& apply_filters(
3175
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3176
+				true,
3177
+				$test_settings_fld,
3178
+				$active_messenger
3179
+			)
3180
+		) {
3181
+			$active_messenger->set_existing_test_settings($test_settings_fld);
3182
+		}
3183
+
3184
+		/**
3185
+		 * Use filter to add additional controls on whether message can send or not
3186
+		 */
3187
+		if (
3188
+			apply_filters(
3189
+				'FHEE__Messages_Admin_Page__do_test_send__can_send',
3190
+				true,
3191
+				$context,
3192
+				$this->request->requestParams(),
3193
+				$messenger,
3194
+				$message_type
3195
+			)
3196
+		) {
3197
+			if (EEM_Event::instance()->count() > 0) {
3198
+				$success = $this->_preview_message(true);
3199
+				if ($success) {
3200
+					EE_Error::add_success(esc_html__('Test message sent', 'event_espresso'));
3201
+				} else {
3202
+					EE_Error::add_error(
3203
+						esc_html__('The test message was not sent', 'event_espresso'),
3204
+						__FILE__,
3205
+						__FUNCTION__,
3206
+						__LINE__
3207
+					);
3208
+				}
3209
+			} else {
3210
+				$this->noEventsErrorMessage(true);
3211
+			}
3212
+		}
3213
+	}
3214
+
3215
+
3216
+	/**
3217
+	 * _generate_new_templates
3218
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3219
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3220
+	 * for the event.
3221
+	 *
3222
+	 *
3223
+	 * @param string $messenger      the messenger we are generating templates for
3224
+	 * @param array  $message_types  array of message types that the templates are generated for.
3225
+	 * @param int    $GRP_ID         If this is a custom template being generated then a GRP_ID needs to be included to
3226
+	 *                               indicate the message_template_group being used as the base.
3227
+	 *
3228
+	 * @param bool   $global
3229
+	 *
3230
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
3231
+	 *                               encountering problems.
3232
+	 * @throws EE_Error
3233
+	 * @throws ReflectionException
3234
+	 */
3235
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3236
+	{
3237
+		// if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3238
+		// just don't generate any templates.
3239
+		if (empty($message_types)) {
3240
+			return [];
3241
+		}
3242
+
3243
+		$templates = EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3244
+		return $templates[0];
3245
+	}
3246
+
3247
+
3248
+	/**
3249
+	 * [_trash_or_restore_message_template]
3250
+	 *
3251
+	 * @param boolean $trash  whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3252
+	 * @param boolean $all    whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3253
+	 *                        an individual context (FALSE).
3254
+	 * @return void
3255
+	 * @throws EE_Error
3256
+	 * @throws InvalidArgumentException
3257
+	 * @throws InvalidDataTypeException
3258
+	 * @throws InvalidInterfaceException
3259
+	 */
3260
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
3261
+	{
3262
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3263
+
3264
+		$success = 1;
3265
+
3266
+		// incoming GRP_IDs
3267
+		if ($all) {
3268
+			// Checkboxes
3269
+			$checkboxes = $this->request->getRequestParam('checkbox', [], 'int', true);
3270
+			if (! empty($checkboxes)) {
3271
+				// if array has more than one element then success message should be plural.
3272
+				// todo: what about nonce?
3273
+				$success = count($checkboxes) > 1 ? 2 : 1;
3274
+
3275
+				// cycle through checkboxes
3276
+				while (list($GRP_ID, $value) = each($checkboxes)) {
3277
+					$trashed_or_restored = $trash
3278
+						? $this->getMtgModel()->delete_by_ID($GRP_ID)
3279
+						: $this->getMtgModel()->restore_by_ID($GRP_ID);
3280
+					if (! $trashed_or_restored) {
3281
+						$success = 0;
3282
+					}
3283
+				}
3284
+			} else {
3285
+				// grab single GRP_ID and handle
3286
+				$GRP_ID = $this->request->getRequestParam('id', 0, 'int');
3287
+				if (! empty($GRP_ID)) {
3288
+					$trashed_or_restored = $trash
3289
+						? $this->getMtgModel()->delete_by_ID($GRP_ID)
3290
+						: $this->getMtgModel()->restore_by_ID($GRP_ID);
3291
+					if (! $trashed_or_restored) {
3292
+						$success = 0;
3293
+					}
3294
+				} else {
3295
+					$success = 0;
3296
+				}
3297
+			}
3298
+		}
3299
+
3300
+		$action_desc = $trash
3301
+			? esc_html__('moved to the trash', 'event_espresso')
3302
+			: esc_html__('restored', 'event_espresso');
3303
+
3304
+		$template_switch = $this->request->getRequestParam('template_switch', false, 'bool');
3305
+		$action_desc     = $template_switch ? esc_html__('switched', 'event_espresso') : $action_desc;
3306
+
3307
+		$item_desc = $all ? _n(
3308
+			'Message Template Group',
3309
+			'Message Template Groups',
3310
+			$success,
3311
+			'event_espresso'
3312
+		) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3313
+
3314
+		$item_desc = $template_switch
3315
+			? _n('template', 'templates', $success, 'event_espresso')
3316
+			: $item_desc;
3317
+
3318
+		$this->_redirect_after_action($success, $item_desc, $action_desc, []);
3319
+	}
3320
+
3321
+
3322
+	/**
3323
+	 * [_delete_message_template]
3324
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3325
+	 *
3326
+	 * @return void
3327
+	 * @throws EE_Error
3328
+	 * @throws InvalidArgumentException
3329
+	 * @throws InvalidDataTypeException
3330
+	 * @throws InvalidInterfaceException
3331
+	 * @throws ReflectionException
3332
+	 */
3333
+	protected function _delete_message_template()
3334
+	{
3335
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3336
+
3337
+		// checkboxes
3338
+		$checkboxes = $this->request->getRequestParam('checkbox', [], 'int', true);
3339
+		if (! empty($checkboxes)) {
3340
+			// if array has more than one element then success message should be plural
3341
+			$success = count($checkboxes) > 1 ? 2 : 1;
3342
+
3343
+			// cycle through bulk action checkboxes
3344
+			while (list($GRP_ID, $value) = each($checkboxes)) {
3345
+				$success = $this->_delete_mtp_permanently($GRP_ID) ? $success : false;
3346
+			}
3347
+		} else {
3348
+			// grab single grp_id and delete
3349
+			$GRP_ID  = $this->request->getRequestParam('id', 0, 'int');
3350
+			$success = $this->_delete_mtp_permanently($GRP_ID);
3351
+		}
3352
+
3353
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', []);
3354
+	}
3355
+
3356
+
3357
+	/**
3358
+	 * helper for permanently deleting a mtP group and all related message_templates
3359
+	 *
3360
+	 * @param int  $GRP_ID        The group being deleted
3361
+	 * @param bool $include_group whether to delete the Message Template Group as well.
3362
+	 * @return bool boolean to indicate the success of the deletes or not.
3363
+	 * @throws EE_Error
3364
+	 * @throws InvalidArgumentException
3365
+	 * @throws InvalidDataTypeException
3366
+	 * @throws InvalidInterfaceException
3367
+	 * @throws ReflectionException
3368
+	 * @throws ReflectionException
3369
+	 */
3370
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3371
+	{
3372
+		$success = true;
3373
+		// first let's GET this group
3374
+		$MTG = $this->getMtgModel()->get_one_by_ID($GRP_ID);
3375
+		// then delete permanently all the related Message Templates
3376
+		$deleted = $MTG->delete_related_permanently('Message_Template');
3377
+
3378
+		if ($deleted === 0) {
3379
+			$success = false;
3380
+		}
3381
+
3382
+		// now delete permanently this particular group
3383
+
3384
+		if ($include_group && ! $MTG->delete_permanently()) {
3385
+			$success = false;
3386
+		}
3387
+
3388
+		return $success;
3389
+	}
3390
+
3391
+
3392
+	/**
3393
+	 *    _learn_more_about_message_templates_link
3394
+	 *
3395
+	 * @access protected
3396
+	 * @return string
3397
+	 */
3398
+	protected function _learn_more_about_message_templates_link()
3399
+	{
3400
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3401
+			   . esc_html__('learn more about how message templates works', 'event_espresso')
3402
+			   . '</a>';
3403
+	}
3404
+
3405
+
3406
+	/**
3407
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3408
+	 * ajax and other routes.
3409
+	 *
3410
+	 * @return void
3411
+	 * @throws DomainException
3412
+	 * @throws EE_Error
3413
+	 */
3414
+	protected function _settings()
3415
+	{
3416
+		$this->_set_m_mt_settings();
3417
+
3418
+		// let's setup the messenger tabs
3419
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3420
+			$this->_m_mt_settings['messenger_tabs'],
3421
+			'messenger_links',
3422
+			'|',
3423
+			$this->request->getRequestParam('selected_messenger', 'email')
3424
+		);
3425
+
3426
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3427
+		$this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
3428
+
3429
+		$this->display_admin_page_with_sidebar();
3430
+	}
3431
+
3432
+
3433
+	/**
3434
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3435
+	 *
3436
+	 * @access protected
3437
+	 * @return void
3438
+	 * @throws DomainException
3439
+	 */
3440
+	protected function _set_m_mt_settings()
3441
+	{
3442
+		// first if this is already set then lets get out no need to regenerate data.
3443
+		if (! empty($this->_m_mt_settings)) {
3444
+			return;
3445
+		}
3446
+
3447
+		// get all installed messengers and message_types
3448
+		$messengers    = $this->_message_resource_manager->installed_messengers();
3449
+		$message_types = $this->_message_resource_manager->installed_message_types();
3450
+
3451
+
3452
+		// assemble the array for the _tab_text_links helper
3453
+
3454
+		foreach ($messengers as $messenger) {
3455
+			$this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = [
3456
+				'label' => ucwords($messenger->label['singular']),
3457
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3458
+					? 'messenger-active'
3459
+					: '',
3460
+				'href'  => $messenger->name,
3461
+				'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3462
+				'slug'  => $messenger->name,
3463
+				'obj'   => $messenger,
3464
+			];
3465
+
3466
+
3467
+			$message_types_for_messenger = $messenger->get_valid_message_types();
3468
+
3469
+			foreach ($message_types as $message_type) {
3470
+				// first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3471
+				// it shouldn't show in either the inactive OR active metabox.
3472
+				if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3473
+					continue;
3474
+				}
3475
+
3476
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3477
+					$messenger->name,
3478
+					$message_type->name
3479
+				)
3480
+					? 'active'
3481
+					: 'inactive';
3482
+
3483
+				$this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = [
3484
+					'label'    => ucwords($message_type->label['singular']),
3485
+					'class'    => 'message-type-' . $a_or_i,
3486
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3487
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3488
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3489
+					'title'    => $a_or_i === 'active'
3490
+						? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3491
+						: esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3492
+					'content'  => $a_or_i === 'active'
3493
+						? $this->_message_type_settings_content($message_type, $messenger, true)
3494
+						: $this->_message_type_settings_content($message_type, $messenger),
3495
+					'slug'     => $message_type->name,
3496
+					'active'   => $a_or_i === 'active',
3497
+					'obj'      => $message_type,
3498
+				];
3499
+			}
3500
+		}
3501
+	}
3502
+
3503
+
3504
+	/**
3505
+	 * This just prepares the content for the message type settings
3506
+	 *
3507
+	 * @param EE_message_type $message_type The message type object
3508
+	 * @param EE_messenger    $messenger    The messenger object
3509
+	 * @param boolean         $active       Whether the message type is active or not
3510
+	 * @return string html output for the content
3511
+	 * @throws DomainException
3512
+	 */
3513
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
3514
+	{
3515
+		// get message type fields
3516
+		$fields                                         = $message_type->get_admin_settings_fields();
3517
+		$settings_template_args['template_form_fields'] = '';
3518
+
3519
+		if (! empty($fields) && $active) {
3520
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3521
+			foreach ($fields as $fldname => $fldprops) {
3522
+				$field_id                         = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3523
+				$template_form_field[ $field_id ] = [
3524
+					'name'       => 'message_type_settings[' . $fldname . ']',
3525
+					'label'      => $fldprops['label'],
3526
+					'input'      => $fldprops['field_type'],
3527
+					'type'       => $fldprops['value_type'],
3528
+					'required'   => $fldprops['required'],
3529
+					'validation' => $fldprops['validation'],
3530
+					'value'      => isset($existing_settings[ $fldname ])
3531
+						? $existing_settings[ $fldname ]
3532
+						: $fldprops['default'],
3533
+					'options'    => isset($fldprops['options'])
3534
+						? $fldprops['options']
3535
+						: [],
3536
+					'default'    => isset($existing_settings[ $fldname ])
3537
+						? $existing_settings[ $fldname ]
3538
+						: $fldprops['default'],
3539
+					'css_class'  => 'no-drag',
3540
+					'format'     => $fldprops['format'],
3541
+				];
3542
+			}
3543
+
3544
+
3545
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3546
+				? $this->_generate_admin_form_fields(
3547
+					$template_form_field,
3548
+					'string',
3549
+					'ee_mt_activate_form'
3550
+				)
3551
+				: '';
3552
+		}
3553
+
3554
+		$settings_template_args['description'] = $message_type->description;
3555
+		// we also need some hidden fields
3556
+		$hidden_fields = [
3557
+			'message_type_settings[messenger]' . $message_type->name    => [
3558
+				'type'  => 'hidden',
3559
+				'value' => $messenger->name,
3560
+			],
3561
+			'message_type_settings[message_type]' . $message_type->name => [
3562
+				'type'  => 'hidden',
3563
+				'value' => $message_type->name,
3564
+			],
3565
+			'type' . $message_type->name                                => [
3566
+				'type'  => 'hidden',
3567
+				'value' => 'message_type',
3568
+			],
3569
+		];
3570
+
3571
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3572
+			$hidden_fields,
3573
+			'array'
3574
+		);
3575
+		$settings_template_args['show_form']     = empty($settings_template_args['template_form_fields'])
3576
+			? ' hidden'
3577
+			: '';
3578
+
3579
+
3580
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3581
+		return EEH_Template::display_template($template, $settings_template_args, true);
3582
+	}
3583
+
3584
+
3585
+	/**
3586
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
3587
+	 *
3588
+	 * @access protected
3589
+	 * @return void
3590
+	 * @throws DomainException
3591
+	 */
3592
+	protected function _messages_settings_metaboxes()
3593
+	{
3594
+		$this->_set_m_mt_settings();
3595
+		$m_boxes         = $mt_boxes = [];
3596
+		$m_template_args = $mt_template_args = [];
3597
+
3598
+		$selected_messenger = $this->request->getRequestParam('selected_messenger', 'email');
3599
+
3600
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
3601
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3602
+				$is_messenger_active = $this->_message_resource_manager->is_messenger_active($messenger);
3603
+				$hide_on_message     = $is_messenger_active ? '' : 'hidden';
3604
+				$hide_off_message    = $is_messenger_active ? 'hidden' : '';
3605
+
3606
+				// messenger meta boxes
3607
+				$active         = $selected_messenger === $messenger;
3608
+				$active_mt_tabs = isset($this->_m_mt_settings['message_type_tabs'][ $messenger ]['active'])
3609
+					? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3610
+					: '';
3611
+
3612
+				$m_boxes[ $messenger . '_a_box' ] = sprintf(
3613
+					esc_html__('%s Settings', 'event_espresso'),
3614
+					$tab_array['label']
3615
+				);
3616
+
3617
+				$m_template_args[ $messenger . '_a_box' ] = [
3618
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3619
+					'inactive_message_types' => isset(
3620
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3621
+					)
3622
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3623
+						: '',
3624
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3625
+					'hidden'                 => $active ? '' : ' hidden',
3626
+					'hide_on_message'        => $hide_on_message,
3627
+					'messenger'              => $messenger,
3628
+					'active'                 => $active,
3629
+				];
3630
+
3631
+				// message type meta boxes
3632
+				// (which is really just the inactive container for each messenger
3633
+				// showing inactive message types for that messenger)
3634
+				$mt_boxes[ $messenger . '_i_box' ]         = esc_html__('Inactive Message Types', 'event_espresso');
3635
+				$mt_template_args[ $messenger . '_i_box' ] = [
3636
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3637
+					'inactive_message_types' => isset(
3638
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3639
+					)
3640
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3641
+						: '',
3642
+					'hidden'                 => $active ? '' : ' hidden',
3643
+					'hide_on_message'        => $hide_on_message,
3644
+					'hide_off_message'       => $hide_off_message,
3645
+					'messenger'              => $messenger,
3646
+					'active'                 => $active,
3647
+				];
3648
+			}
3649
+		}
3650
+
3651
+
3652
+		// register messenger metaboxes
3653
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3654
+		foreach ($m_boxes as $box => $label) {
3655
+			$callback_args = ['template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]];
3656
+			$msgr          = str_replace('_a_box', '', $box);
3657
+			add_meta_box(
3658
+				'espresso_' . $msgr . '_settings',
3659
+				$label,
3660
+				function ($post, $metabox) {
3661
+					EEH_Template::display_template(
3662
+						$metabox['args']['template_path'],
3663
+						$metabox['args']['template_args']
3664
+					);
3665
+				},
3666
+				$this->_current_screen->id,
3667
+				'normal',
3668
+				'high',
3669
+				$callback_args
3670
+			);
3671
+		}
3672
+
3673
+		// register message type metaboxes
3674
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3675
+		foreach ($mt_boxes as $box => $label) {
3676
+			$callback_args = [
3677
+				'template_path' => $mt_template_path,
3678
+				'template_args' => $mt_template_args[ $box ],
3679
+			];
3680
+			$mt            = str_replace('_i_box', '', $box);
3681
+			add_meta_box(
3682
+				'espresso_' . $mt . '_inactive_mts',
3683
+				$label,
3684
+				function ($post, $metabox) {
3685
+					EEH_Template::display_template(
3686
+						$metabox['args']['template_path'],
3687
+						$metabox['args']['template_args']
3688
+					);
3689
+				},
3690
+				$this->_current_screen->id,
3691
+				'side',
3692
+				'high',
3693
+				$callback_args
3694
+			);
3695
+		}
3696
+
3697
+		// register metabox for global messages settings but only when on the main site.  On single site installs this
3698
+		// will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3699
+		if (is_main_site()) {
3700
+			add_meta_box(
3701
+				'espresso_global_message_settings',
3702
+				esc_html__('Global Message Settings', 'event_espresso'),
3703
+				[$this, 'global_messages_settings_metabox_content'],
3704
+				$this->_current_screen->id,
3705
+				'normal',
3706
+				'low',
3707
+				[]
3708
+			);
3709
+		}
3710
+	}
3711
+
3712
+
3713
+	/**
3714
+	 *  This generates the content for the global messages settings metabox.
3715
+	 *
3716
+	 * @return void
3717
+	 * @throws EE_Error
3718
+	 * @throws InvalidArgumentException
3719
+	 * @throws ReflectionException
3720
+	 * @throws InvalidDataTypeException
3721
+	 * @throws InvalidInterfaceException
3722
+	 */
3723
+	public function global_messages_settings_metabox_content()
3724
+	{
3725
+		$form = $this->_generate_global_settings_form();
3726
+		// already escaped
3727
+		echo $form->form_open(
3728
+			$this->add_query_args_and_nonce(['action' => 'update_global_settings'], EE_MSG_ADMIN_URL),
3729
+			'POST'
3730
+		);
3731
+		echo $form->get_html();
3732
+		echo $form->form_close();
3733
+	}
3734
+
3735
+
3736
+	/**
3737
+	 * This generates and returns the form object for the global messages settings.
3738
+	 *
3739
+	 * @return EE_Form_Section_Proper
3740
+	 * @throws EE_Error
3741
+	 * @throws InvalidArgumentException
3742
+	 * @throws ReflectionException
3743
+	 * @throws InvalidDataTypeException
3744
+	 * @throws InvalidInterfaceException
3745
+	 */
3746
+	protected function _generate_global_settings_form()
3747
+	{
3748
+		/** @var EE_Network_Core_Config $network_config */
3749
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3750
+
3751
+		return new EE_Form_Section_Proper(
3752
+			[
3753
+				'name'            => 'global_messages_settings',
3754
+				'html_id'         => 'global_messages_settings',
3755
+				'html_class'      => 'form-table',
3756
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3757
+				'subsections'     => apply_filters(
3758
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3759
+					[
3760
+						'do_messages_on_same_request' => new EE_Select_Input(
3761
+							[
3762
+								true  => esc_html__('On the same request', 'event_espresso'),
3763
+								false => esc_html__('On a separate request', 'event_espresso'),
3764
+							],
3765
+							[
3766
+								'default'         => $network_config->do_messages_on_same_request,
3767
+								'html_label_text' => esc_html__(
3768
+									'Generate and send all messages:',
3769
+									'event_espresso'
3770
+								),
3771
+								'html_help_text'  => esc_html__(
3772
+									'By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3773
+									'event_espresso'
3774
+								),
3775
+							]
3776
+						),
3777
+						'delete_threshold'            => new EE_Select_Input(
3778
+							[
3779
+								0  => esc_html__('Forever', 'event_espresso'),
3780
+								3  => esc_html__('3 Months', 'event_espresso'),
3781
+								6  => esc_html__('6 Months', 'event_espresso'),
3782
+								9  => esc_html__('9 Months', 'event_espresso'),
3783
+								12 => esc_html__('12 Months', 'event_espresso'),
3784
+								24 => esc_html__('24 Months', 'event_espresso'),
3785
+								36 => esc_html__('36 Months', 'event_espresso'),
3786
+							],
3787
+							[
3788
+								'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3789
+								'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3790
+								'html_help_text'  => esc_html__(
3791
+									'You can control how long a record of processed messages is kept via this option.',
3792
+									'event_espresso'
3793
+								),
3794
+							]
3795
+						),
3796
+						'update_settings'             => new EE_Submit_Input(
3797
+							[
3798
+								'default'         => esc_html__('Update', 'event_espresso'),
3799
+								'html_label_text' => '&nbsp',
3800
+							]
3801
+						),
3802
+					]
3803
+				),
3804
+			]
3805
+		);
3806
+	}
3807
+
3808
+
3809
+	/**
3810
+	 * This handles updating the global settings set on the admin page.
3811
+	 *
3812
+	 * @throws EE_Error
3813
+	 * @throws InvalidDataTypeException
3814
+	 * @throws InvalidInterfaceException
3815
+	 * @throws InvalidArgumentException
3816
+	 * @throws ReflectionException
3817
+	 */
3818
+	protected function _update_global_settings()
3819
+	{
3820
+		/** @var EE_Network_Core_Config $network_config */
3821
+		$network_config  = EE_Registry::instance()->NET_CFG->core;
3822
+		$messages_config = EE_Registry::instance()->CFG->messages;
3823
+		$form            = $this->_generate_global_settings_form();
3824
+		if ($form->was_submitted()) {
3825
+			$form->receive_form_submission();
3826
+			if ($form->is_valid()) {
3827
+				$valid_data = $form->valid_data();
3828
+				foreach ($valid_data as $property => $value) {
3829
+					$setter = 'set_' . $property;
3830
+					if (method_exists($network_config, $setter)) {
3831
+						$network_config->{$setter}($value);
3832
+					} elseif (
3833
+						property_exists($network_config, $property)
3834
+						&& $network_config->{$property} !== $value
3835
+					) {
3836
+						$network_config->{$property} = $value;
3837
+					} elseif (
3838
+						property_exists($messages_config, $property)
3839
+						&& $messages_config->{$property} !== $value
3840
+					) {
3841
+						$messages_config->{$property} = $value;
3842
+					}
3843
+				}
3844
+				// only update if the form submission was valid!
3845
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3846
+				EE_Registry::instance()->CFG->update_espresso_config();
3847
+				EE_Error::overwrite_success();
3848
+				EE_Error::add_success(esc_html__('Global message settings were updated', 'event_espresso'));
3849
+			}
3850
+		}
3851
+		$this->_redirect_after_action(0, '', '', ['action' => 'settings'], true);
3852
+	}
3853
+
3854
+
3855
+	/**
3856
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3857
+	 *
3858
+	 * @param array $tab_array This is an array of message type tab details used to generate the tabs
3859
+	 * @return string html formatted tabs
3860
+	 * @throws DomainException
3861
+	 */
3862
+	protected function _get_mt_tabs($tab_array)
3863
+	{
3864
+		$tab_array = (array) $tab_array;
3865
+		$template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3866
+		$tabs      = '';
3867
+
3868
+		foreach ($tab_array as $tab) {
3869
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3870
+		}
3871
+
3872
+		return $tabs;
3873
+	}
3874
+
3875
+
3876
+	/**
3877
+	 * This prepares the content of the messenger meta box admin settings
3878
+	 *
3879
+	 * @param EE_messenger $messenger The messenger we're setting up content for
3880
+	 * @return string html formatted content
3881
+	 * @throws DomainException
3882
+	 */
3883
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3884
+	{
3885
+
3886
+		$fields                                         = $messenger->get_admin_settings_fields();
3887
+		$settings_template_args['template_form_fields'] = '';
3888
+
3889
+		// is $messenger active?
3890
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3891
+
3892
+
3893
+		if (! empty($fields)) {
3894
+			$existing_settings = $messenger->get_existing_admin_settings();
3895
+
3896
+			foreach ($fields as $fldname => $fldprops) {
3897
+				$field_id                         = $messenger->name . '-' . $fldname;
3898
+				$template_form_field[ $field_id ] = [
3899
+					'name'       => 'messenger_settings[' . $field_id . ']',
3900
+					'label'      => $fldprops['label'],
3901
+					'input'      => $fldprops['field_type'],
3902
+					'type'       => $fldprops['value_type'],
3903
+					'required'   => $fldprops['required'],
3904
+					'validation' => $fldprops['validation'],
3905
+					'value'      => isset($existing_settings[ $field_id ])
3906
+						? $existing_settings[ $field_id ]
3907
+						: $fldprops['default'],
3908
+					'css_class'  => '',
3909
+					'format'     => $fldprops['format'],
3910
+				];
3911
+			}
3912
+
3913
+
3914
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3915
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3916
+				: '';
3917
+		}
3918
+
3919
+		// we also need some hidden fields
3920
+		$settings_template_args['hidden_fields'] = [
3921
+			'messenger_settings[messenger]' . $messenger->name => [
3922
+				'type'  => 'hidden',
3923
+				'value' => $messenger->name,
3924
+			],
3925
+			'type' . $messenger->name                          => [
3926
+				'type'  => 'hidden',
3927
+				'value' => 'messenger',
3928
+			],
3929
+		];
3930
+
3931
+		// make sure any active message types that are existing are included in the hidden fields
3932
+		if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3933
+			foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3934
+				$settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = [
3935
+					'type'  => 'hidden',
3936
+					'value' => $mt,
3937
+				];
3938
+			}
3939
+		}
3940
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3941
+			$settings_template_args['hidden_fields'],
3942
+			'array'
3943
+		);
3944
+		$active                                  =
3945
+			$this->_message_resource_manager->is_messenger_active($messenger->name);
3946
+
3947
+		$settings_template_args['messenger']           = $messenger->name;
3948
+		$settings_template_args['description']         = $messenger->description;
3949
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3950
+
3951
+
3952
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3953
+			$messenger->name
3954
+		)
3955
+			? $settings_template_args['show_hide_edit_form']
3956
+			: ' hidden';
3957
+
3958
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3959
+			? ' hidden'
3960
+			: $settings_template_args['show_hide_edit_form'];
3961
+
3962
+
3963
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3964
+		$settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3965
+		$settings_template_args['on_off_status'] = $active;
3966
+		$template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3967
+		return EEH_Template::display_template(
3968
+			$template,
3969
+			$settings_template_args,
3970
+			true
3971
+		);
3972
+	}
3973
+
3974
+
3975
+	/**
3976
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3977
+	 *
3978
+	 * @throws DomainException
3979
+	 * @throws EE_Error
3980
+	 * @throws InvalidDataTypeException
3981
+	 * @throws InvalidInterfaceException
3982
+	 * @throws InvalidArgumentException
3983
+	 * @throws ReflectionException
3984
+	 */
3985
+	public function activate_messenger_toggle()
3986
+	{
3987
+		$success = true;
3988
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3989
+		// let's check that we have required data
3990
+
3991
+		if (! $this->_active_messenger_name) {
3992
+			EE_Error::add_error(
3993
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3994
+				__FILE__,
3995
+				__FUNCTION__,
3996
+				__LINE__
3997
+			);
3998
+			$success = false;
3999
+		}
4000
+
4001
+		// do a nonce check here since we're not arriving via a normal route
4002
+		$nonce     = $this->request->getRequestParam('activate_nonce', '');
4003
+		$nonce_ref = "activate_{$this->_active_messenger_name}_toggle_nonce";
4004
+
4005
+		$this->_verify_nonce($nonce, $nonce_ref);
4006
+
4007
+
4008
+		$status = $this->request->getRequestParam('status');
4009
+		if (! $status) {
4010
+			EE_Error::add_error(
4011
+				esc_html__(
4012
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
4013
+					'event_espresso'
4014
+				),
4015
+				__FILE__,
4016
+				__FUNCTION__,
4017
+				__LINE__
4018
+			);
4019
+			$success = false;
4020
+		}
4021
+
4022
+		// do check to verify we have a valid status.
4023
+		if ($status !== 'off' && $status !== 'on') {
4024
+			EE_Error::add_error(
4025
+				sprintf(
4026
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
4027
+					$status
4028
+				),
4029
+				__FILE__,
4030
+				__FUNCTION__,
4031
+				__LINE__
4032
+			);
4033
+			$success = false;
4034
+		}
4035
+
4036
+		if ($success) {
4037
+			// made it here?  Stop dawdling then!!
4038
+			$success = $status === 'off'
4039
+				? $this->_deactivate_messenger($this->_active_messenger_name)
4040
+				: $this->_activate_messenger($this->_active_messenger_name);
4041
+		}
4042
+
4043
+		$this->_template_args['success'] = $success;
4044
+
4045
+		// no special instructions so let's just do the json return (which should automatically do all the special stuff).
4046
+		$this->_return_json();
4047
+	}
4048
+
4049
+
4050
+	/**
4051
+	 * used by ajax from the messages settings page to activate|deactivate a message type
4052
+	 *
4053
+	 * @throws DomainException
4054
+	 * @throws EE_Error
4055
+	 * @throws ReflectionException
4056
+	 * @throws InvalidDataTypeException
4057
+	 * @throws InvalidInterfaceException
4058
+	 * @throws InvalidArgumentException
4059
+	 */
4060
+	public function activate_mt_toggle()
4061
+	{
4062
+		$success = true;
4063
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
4064
+
4065
+		// let's make sure we have the necessary data
4066
+		if (! $this->_active_message_type_name) {
4067
+			EE_Error::add_error(
4068
+				esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
4069
+				__FILE__,
4070
+				__FUNCTION__,
4071
+				__LINE__
4072
+			);
4073
+			$success = false;
4074
+		}
4075
+
4076
+		if (! $this->_active_messenger_name) {
4077
+			EE_Error::add_error(
4078
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
4079
+				__FILE__,
4080
+				__FUNCTION__,
4081
+				__LINE__
4082
+			);
4083
+			$success = false;
4084
+		}
4085
+
4086
+		$status = $this->request->getRequestParam('status');
4087
+		if (! $status) {
4088
+			EE_Error::add_error(
4089
+				esc_html__(
4090
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
4091
+					'event_espresso'
4092
+				),
4093
+				__FILE__,
4094
+				__FUNCTION__,
4095
+				__LINE__
4096
+			);
4097
+			$success = false;
4098
+		}
4099
+
4100
+
4101
+		// do check to verify we have a valid status.
4102
+		if ($status !== 'activate' && $status !== 'deactivate') {
4103
+			EE_Error::add_error(
4104
+				sprintf(
4105
+					esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
4106
+					$status
4107
+				),
4108
+				__FILE__,
4109
+				__FUNCTION__,
4110
+				__LINE__
4111
+			);
4112
+			$success = false;
4113
+		}
4114
+
4115
+
4116
+		// do a nonce check here since we're not arriving via a normal route
4117
+		$nonce = $this->request->getRequestParam('mt_nonce', '');
4118
+		$this->_verify_nonce($nonce, "{$this->_active_message_type_name}_nonce");
4119
+
4120
+		if ($success) {
4121
+			// made it here? um, what are you waiting for then?
4122
+			$success = $status === 'deactivate'
4123
+				? $this->_deactivate_message_type_for_messenger(
4124
+					$this->_active_messenger_name,
4125
+					$this->_active_message_type_name
4126
+				)
4127
+				: $this->_activate_message_type_for_messenger(
4128
+					$this->_active_messenger_name,
4129
+					$this->_active_message_type_name
4130
+				);
4131
+		}
4132
+
4133
+		$this->_template_args['success'] = $success;
4134
+		$this->_return_json();
4135
+	}
4136
+
4137
+
4138
+	/**
4139
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
4140
+	 *
4141
+	 * @param string $messenger_name The name of the messenger being activated
4142
+	 * @return bool
4143
+	 * @throws DomainException
4144
+	 * @throws EE_Error
4145
+	 * @throws InvalidArgumentException
4146
+	 * @throws ReflectionException
4147
+	 * @throws InvalidDataTypeException
4148
+	 * @throws InvalidInterfaceException
4149
+	 */
4150
+	protected function _activate_messenger($messenger_name)
4151
+	{
4152
+		$active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
4153
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger
4154
+			? $active_messenger->get_default_message_types()
4155
+			: [];
4156
+
4157
+		// ensure is active
4158
+		$this->_message_resource_manager->activate_messenger($active_messenger, $message_types_to_activate);
4159
+
4160
+		// set response_data for reload
4161
+		foreach ($message_types_to_activate as $message_type_name) {
4162
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4163
+			if (
4164
+				$this->_message_resource_manager->is_message_type_active_for_messenger(
4165
+					$messenger_name,
4166
+					$message_type_name
4167
+				)
4168
+				&& $message_type instanceof EE_message_type
4169
+			) {
4170
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
4171
+				if ($message_type->get_admin_settings_fields()) {
4172
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
4173
+				}
4174
+			}
4175
+		}
4176
+
4177
+		// add success message for activating messenger
4178
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4179
+	}
4180
+
4181
+
4182
+	/**
4183
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
4184
+	 *
4185
+	 * @param string $messenger_name The name of the messenger being activated
4186
+	 * @return bool
4187
+	 * @throws DomainException
4188
+	 * @throws EE_Error
4189
+	 * @throws InvalidArgumentException
4190
+	 * @throws ReflectionException
4191
+	 * @throws InvalidDataTypeException
4192
+	 * @throws InvalidInterfaceException
4193
+	 */
4194
+	protected function _deactivate_messenger($messenger_name)
4195
+	{
4196
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4197
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
4198
+
4199
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4200
+	}
4201
+
4202
+
4203
+	/**
4204
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4205
+	 *
4206
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
4207
+	 * @param string $message_type_name The name of the message type being activated for the messenger
4208
+	 * @return bool
4209
+	 * @throws DomainException
4210
+	 * @throws EE_Error
4211
+	 * @throws InvalidArgumentException
4212
+	 * @throws ReflectionException
4213
+	 * @throws InvalidDataTypeException
4214
+	 * @throws InvalidInterfaceException
4215
+	 */
4216
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4217
+	{
4218
+		$active_messenger         = $this->_message_resource_manager->get_messenger($messenger_name);
4219
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4220
+
4221
+		// ensure is active
4222
+		$this->_message_resource_manager->activate_messenger($active_messenger, $message_type_name);
4223
+
4224
+		// set response for load
4225
+		if (
4226
+			$this->_message_resource_manager->is_message_type_active_for_messenger(
4227
+				$messenger_name,
4228
+				$message_type_name
4229
+			)
4230
+		) {
4231
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
4232
+			if ($message_type_to_activate->get_admin_settings_fields()) {
4233
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
4234
+			}
4235
+		}
4236
+
4237
+		return $this->_setup_response_message_for_activating_messenger_with_message_types(
4238
+			$active_messenger,
4239
+			$message_type_to_activate
4240
+		);
4241
+	}
4242
+
4243
+
4244
+	/**
4245
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4246
+	 *
4247
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4248
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
4249
+	 * @return bool
4250
+	 * @throws DomainException
4251
+	 * @throws EE_Error
4252
+	 * @throws InvalidArgumentException
4253
+	 * @throws ReflectionException
4254
+	 * @throws InvalidDataTypeException
4255
+	 * @throws InvalidInterfaceException
4256
+	 */
4257
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4258
+	{
4259
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4260
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4261
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4262
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4263
+
4264
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4265
+			$active_messenger,
4266
+			$message_type_to_deactivate
4267
+		);
4268
+	}
4269
+
4270
+
4271
+	/**
4272
+	 * This just initializes the defaults for activating messenger and message type responses.
4273
+	 */
4274
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
4275
+	{
4276
+		$this->_template_args['data']['active_mts'] = [];
4277
+		$this->_template_args['data']['mt_reload']  = [];
4278
+	}
4279
+
4280
+
4281
+	/**
4282
+	 * Setup appropriate response for activating a messenger and/or message types
4283
+	 *
4284
+	 * @param EE_messenger         $messenger
4285
+	 * @param EE_message_type|null $message_type
4286
+	 * @return bool
4287
+	 * @throws DomainException
4288
+	 * @throws EE_Error
4289
+	 * @throws InvalidArgumentException
4290
+	 * @throws ReflectionException
4291
+	 * @throws InvalidDataTypeException
4292
+	 * @throws InvalidInterfaceException
4293
+	 */
4294
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
4295
+		$messenger,
4296
+		EE_Message_Type $message_type = null
4297
+	) {
4298
+		// if $messenger isn't a valid messenger object then get out.
4299
+		if (! $messenger instanceof EE_Messenger) {
4300
+			EE_Error::add_error(
4301
+				esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4302
+				__FILE__,
4303
+				__FUNCTION__,
4304
+				__LINE__
4305
+			);
4306
+			return false;
4307
+		}
4308
+		// activated
4309
+		if ($this->_template_args['data']['active_mts']) {
4310
+			EE_Error::overwrite_success();
4311
+			// activated a message type with the messenger
4312
+			if ($message_type instanceof EE_message_type) {
4313
+				EE_Error::add_success(
4314
+					sprintf(
4315
+						esc_html__(
4316
+							'%s message type has been successfully activated with the %s messenger',
4317
+							'event_espresso'
4318
+						),
4319
+						ucwords($message_type->label['singular']),
4320
+						ucwords($messenger->label['singular'])
4321
+					)
4322
+				);
4323
+
4324
+				// if message type was invoice then let's make sure we activate the invoice payment method.
4325
+				if ($message_type->name === 'invoice') {
4326
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
4327
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4328
+					if ($pm instanceof EE_Payment_Method) {
4329
+						EE_Error::add_attention(
4330
+							esc_html__(
4331
+								'Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
4332
+								'event_espresso'
4333
+							)
4334
+						);
4335
+					}
4336
+				}
4337
+				// just toggles the entire messenger
4338
+			} else {
4339
+				EE_Error::add_success(
4340
+					sprintf(
4341
+						esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4342
+						ucwords($messenger->label['singular'])
4343
+					)
4344
+				);
4345
+			}
4346
+
4347
+			return true;
4348
+
4349
+			// possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4350
+			// message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4351
+			// in which case we just give a success message for the messenger being successfully activated.
4352
+		} else {
4353
+			if (! $messenger->get_default_message_types()) {
4354
+				// messenger doesn't have any default message types so still a success.
4355
+				EE_Error::add_success(
4356
+					sprintf(
4357
+						esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4358
+						ucwords($messenger->label['singular'])
4359
+					)
4360
+				);
4361
+
4362
+				return true;
4363
+			} else {
4364
+				EE_Error::add_error(
4365
+					$message_type instanceof EE_message_type
4366
+					? sprintf(
4367
+						esc_html__(
4368
+							'%s message type was not successfully activated with the %s messenger',
4369
+							'event_espresso'
4370
+						),
4371
+						ucwords($message_type->label['singular']),
4372
+						ucwords($messenger->label['singular'])
4373
+					)
4374
+					: sprintf(
4375
+						esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4376
+						ucwords($messenger->label['singular'])
4377
+					),
4378
+					__FILE__,
4379
+					__FUNCTION__,
4380
+					__LINE__
4381
+				);
4382
+
4383
+				return false;
4384
+			}
4385
+		}
4386
+	}
4387
+
4388
+
4389
+	/**
4390
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
4391
+	 *
4392
+	 * @param EE_messenger         $messenger
4393
+	 * @param EE_message_type|null $message_type
4394
+	 * @return bool
4395
+	 * @throws DomainException
4396
+	 * @throws EE_Error
4397
+	 * @throws InvalidArgumentException
4398
+	 * @throws ReflectionException
4399
+	 * @throws InvalidDataTypeException
4400
+	 * @throws InvalidInterfaceException
4401
+	 */
4402
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4403
+		$messenger,
4404
+		EE_message_type $message_type = null
4405
+	) {
4406
+		EE_Error::overwrite_success();
4407
+
4408
+		// if $messenger isn't a valid messenger object then get out.
4409
+		if (! $messenger instanceof EE_Messenger) {
4410
+			EE_Error::add_error(
4411
+				esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4412
+				__FILE__,
4413
+				__FUNCTION__,
4414
+				__LINE__
4415
+			);
4416
+
4417
+			return false;
4418
+		}
4419
+
4420
+		if ($message_type instanceof EE_message_type) {
4421
+			$message_type_name = $message_type->name;
4422
+			EE_Error::add_success(
4423
+				sprintf(
4424
+					esc_html__(
4425
+						'%s message type has been successfully deactivated for the %s messenger.',
4426
+						'event_espresso'
4427
+					),
4428
+					ucwords($message_type->label['singular']),
4429
+					ucwords($messenger->label['singular'])
4430
+				)
4431
+			);
4432
+		} else {
4433
+			$message_type_name = '';
4434
+			EE_Error::add_success(
4435
+				sprintf(
4436
+					esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4437
+					ucwords($messenger->label['singular'])
4438
+				)
4439
+			);
4440
+		}
4441
+
4442
+		// if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4443
+		if (
4444
+			$messenger->name === 'html'
4445
+			&& (
4446
+				is_null($message_type)
4447
+				|| $message_type_name === 'invoice'
4448
+			)
4449
+		) {
4450
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
4451
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4452
+			if ($count_updated > 0) {
4453
+				$msg = $message_type_name === 'invoice'
4454
+					? esc_html__(
4455
+						'Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
4456
+						'event_espresso'
4457
+					)
4458
+					: esc_html__(
4459
+						'Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
4460
+						'event_espresso'
4461
+					);
4462
+				EE_Error::add_attention($msg);
4463
+			}
4464
+		}
4465
+
4466
+		return true;
4467
+	}
4468
+
4469
+
4470
+	/**
4471
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4472
+	 *
4473
+	 * @throws DomainException
4474
+	 * @throws EE_Error
4475
+	 * @throws EE_Error
4476
+	 */
4477
+	public function update_mt_form()
4478
+	{
4479
+		if (! $this->_active_messenger_name || ! $this->_active_message_type_name) {
4480
+			EE_Error::add_error(
4481
+				esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4482
+				__FILE__,
4483
+				__FUNCTION__,
4484
+				__LINE__
4485
+			);
4486
+			$this->_return_json();
4487
+		}
4488
+
4489
+		$message_types = $this->get_installed_message_types();
4490
+		$message_type  = $message_types[ $this->_active_message_type_name ];
4491
+		$messenger     = $this->_message_resource_manager->get_active_messenger($this->_active_messenger_name);
4492
+		$content       = $this->_message_type_settings_content($message_type, $messenger, true);
4493
+
4494
+		$this->_template_args['success'] = true;
4495
+		$this->_template_args['content'] = $content;
4496
+		$this->_return_json();
4497
+	}
4498
+
4499
+
4500
+	/**
4501
+	 * this handles saving the settings for a messenger or message type
4502
+	 *
4503
+	 * @throws EE_Error
4504
+	 * @throws EE_Error
4505
+	 */
4506
+	public function save_settings()
4507
+	{
4508
+		$type = $this->request->getRequestParam('type');
4509
+		if (! $type) {
4510
+			EE_Error::add_error(
4511
+				esc_html__(
4512
+					'Cannot save settings because type is unknown (messenger settings or message type settings?)',
4513
+					'event_espresso'
4514
+				),
4515
+				__FILE__,
4516
+				__FUNCTION__,
4517
+				__LINE__
4518
+			);
4519
+			$this->_template_args['error'] = true;
4520
+			$this->_return_json();
4521
+		}
4522
+
4523
+
4524
+		if ($type === 'messenger') {
4525
+			// this should be an array.
4526
+			$settings  = $this->request->getRequestParam('messenger_settings', [], 'string', true);
4527
+			$messenger = $settings['messenger'];
4528
+			// remove messenger and message_types from settings array
4529
+			unset($settings['messenger'], $settings['message_types']);
4530
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4531
+		} elseif ($type === 'message_type') {
4532
+			$settings     = $this->request->getRequestParam('message_type_settings', [], 'string', true);
4533
+			$messenger    = $settings['messenger'];
4534
+			$message_type = $settings['message_type'];
4535
+			// remove messenger and message_types from settings array
4536
+			unset($settings['messenger'], $settings['message_types']);
4537
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4538
+		}
4539
+
4540
+		// okay we should have the data all setup.  Now we just update!
4541
+		$success = $this->_message_resource_manager->update_active_messengers_option();
4542
+
4543
+		if ($success) {
4544
+			EE_Error::add_success(esc_html__('Settings updated', 'event_espresso'));
4545
+		} else {
4546
+			EE_Error::add_error(
4547
+				esc_html__('Settings did not get updated', 'event_espresso'),
4548
+				__FILE__,
4549
+				__FUNCTION__,
4550
+				__LINE__
4551
+			);
4552
+		}
4553
+
4554
+		$this->_template_args['success'] = $success;
4555
+		$this->_return_json();
4556
+	}
4557
+
4558
+
4559
+
4560
+
4561
+	/**  EE MESSAGE PROCESSING ACTIONS **/
4562
+
4563
+
4564
+	/**
4565
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4566
+	 * However, this does not send immediately, it just queues for sending.
4567
+	 *
4568
+	 * @throws EE_Error
4569
+	 * @throws InvalidDataTypeException
4570
+	 * @throws InvalidInterfaceException
4571
+	 * @throws InvalidArgumentException
4572
+	 * @throws ReflectionException
4573
+	 * @since 4.9.0
4574
+	 */
4575
+	protected function _generate_now()
4576
+	{
4577
+		EED_Messages::generate_now($this->_get_msg_ids_from_request());
4578
+		$this->_redirect_after_action(false, '', '', [], true);
4579
+	}
4580
+
4581
+
4582
+	/**
4583
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4584
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
4585
+	 *
4586
+	 * @throws EE_Error
4587
+	 * @throws InvalidDataTypeException
4588
+	 * @throws InvalidInterfaceException
4589
+	 * @throws InvalidArgumentException
4590
+	 * @throws ReflectionException
4591
+	 * @since 4.9.0
4592
+	 */
4593
+	protected function _generate_and_send_now()
4594
+	{
4595
+		EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4596
+		$this->_redirect_after_action(false, '', '', [], true);
4597
+	}
4598
+
4599
+
4600
+	/**
4601
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4602
+	 *
4603
+	 * @throws EE_Error
4604
+	 * @throws InvalidDataTypeException
4605
+	 * @throws InvalidInterfaceException
4606
+	 * @throws InvalidArgumentException
4607
+	 * @throws ReflectionException
4608
+	 * @since 4.9.0
4609
+	 */
4610
+	protected function _queue_for_resending()
4611
+	{
4612
+		EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4613
+		$this->_redirect_after_action(false, '', '', [], true);
4614
+	}
4615
+
4616
+
4617
+	/**
4618
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4619
+	 *
4620
+	 * @throws EE_Error
4621
+	 * @throws InvalidDataTypeException
4622
+	 * @throws InvalidInterfaceException
4623
+	 * @throws InvalidArgumentException
4624
+	 * @throws ReflectionException
4625
+	 * @since 4.9.0
4626
+	 */
4627
+	protected function _send_now()
4628
+	{
4629
+		EED_Messages::send_now($this->_get_msg_ids_from_request());
4630
+		$this->_redirect_after_action(false, '', '', [], true);
4631
+	}
4632
+
4633
+
4634
+	/**
4635
+	 * Deletes EE_messages for IDs in the request.
4636
+	 *
4637
+	 * @throws EE_Error
4638
+	 * @throws InvalidDataTypeException
4639
+	 * @throws InvalidInterfaceException
4640
+	 * @throws InvalidArgumentException
4641
+	 * @since 4.9.0
4642
+	 */
4643
+	protected function _delete_ee_messages()
4644
+	{
4645
+		$MSG_IDs       = $this->_get_msg_ids_from_request();
4646
+		$deleted_count = 0;
4647
+		foreach ($MSG_IDs as $MSG_ID) {
4648
+			if ($this->getMsgModel()->delete_by_ID($MSG_ID)) {
4649
+				$deleted_count++;
4650
+			}
4651
+		}
4652
+		if ($deleted_count) {
4653
+			EE_Error::add_success(
4654
+				esc_html(
4655
+					_n(
4656
+						'Message successfully deleted',
4657
+						'Messages successfully deleted',
4658
+						$deleted_count,
4659
+						'event_espresso'
4660
+					)
4661
+				)
4662
+			);
4663
+		} else {
4664
+			EE_Error::add_error(
4665
+				_n('The message was not deleted.', 'The messages were not deleted', count($MSG_IDs), 'event_espresso'),
4666
+				__FILE__,
4667
+				__FUNCTION__,
4668
+				__LINE__
4669
+			);
4670
+		}
4671
+		$this->_redirect_after_action(false, '', '', [], true);
4672
+	}
4673
+
4674
+
4675
+	/**
4676
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4677
+	 *
4678
+	 * @return array
4679
+	 * @since 4.9.0
4680
+	 */
4681
+	protected function _get_msg_ids_from_request()
4682
+	{
4683
+		$MSG_IDs = $this->request->getRequestParam('MSG_ID', [], 'string', true);
4684
+		if (empty($MSG_IDs)) {
4685
+			return [];
4686
+		}
4687
+		// if 'MSG_ID' was just a single ID (not an array)
4688
+		// then $MSG_IDs will be something like [123] so $MSG_IDs[0] should be 123
4689
+		// otherwise, $MSG_IDs was already an array where message IDs were used as the keys
4690
+		return count($MSG_IDs) === 1 && isset($MSG_IDs[0])
4691
+			? $MSG_IDs
4692
+			: array_keys($MSG_IDs);
4693
+	}
4694 4694
 }
Please login to merge, or discard this patch.
messages/templates/ee_msg_messages_templates_editor_help_tab.template.php 1 patch
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -11,121 +11,121 @@
 block discarded – undo
11 11
 <p><strong><?php esc_html_e('Message Template Editor', 'event_espresso'); ?></strong></p>
12 12
 <p>
13 13
     <?php esc_html_e(
14
-        'Here are a few things that you should know about the Message Template Editor:',
15
-        'event_espresso'
16
-    ); ?>
14
+		'Here are a few things that you should know about the Message Template Editor:',
15
+		'event_espresso'
16
+	); ?>
17 17
 </p>
18 18
 <p><strong><?php esc_html_e('1. The Event Editor Title', 'event_espresso'); ?></strong></p>
19 19
 <p><?php echo esc_html($img1); ?></p>
20 20
 <p>
21 21
     <?php printf(
22
-        esc_html__(
23
-            'The Event Editor title is very helpful in indicating which template you are currently editing.  In the example above, we can see that we are editing the template that for the %1$sEmail%2$s messenger, the %1$sPayment%2$s message type, and the %1$sEvent Admin%2$s context (which for this message type means "recipient").',
24
-            'event_espresso'
25
-        ),
26
-        '<strong>',
27
-        '</strong>'
28
-    ); ?>
22
+		esc_html__(
23
+			'The Event Editor title is very helpful in indicating which template you are currently editing.  In the example above, we can see that we are editing the template that for the %1$sEmail%2$s messenger, the %1$sPayment%2$s message type, and the %1$sEvent Admin%2$s context (which for this message type means "recipient").',
24
+			'event_espresso'
25
+		),
26
+		'<strong>',
27
+		'</strong>'
28
+	); ?>
29 29
 </p>
30 30
 <p><strong><?php esc_html_e('2. "Context Switcher" and Preview Button', 'event_espresso'); ?></strong></p>
31 31
 <p><?php echo esc_html($img2); ?></p>
32 32
 <p>
33 33
     <?php esc_html_e(
34
-        'The context switcher allows you to quickly switch between templates. The current context you are working on is displayed in the dropdown. You can switch to any other template for contexts available to the messenger and message type template group you are working on.',
35
-        'event_espresso'
36
-    ); ?>
34
+		'The context switcher allows you to quickly switch between templates. The current context you are working on is displayed in the dropdown. You can switch to any other template for contexts available to the messenger and message type template group you are working on.',
35
+		'event_espresso'
36
+	); ?>
37 37
 </p>
38 38
 <p>
39 39
     <?php esc_html_e(
40
-        'Remember that contexts can represent different things. In this example they represent "recipients" and so they are labelled as such. In this example (for email payment confirmations), you may want Event Administrators to receive different information than Primary Registrants (the other context available to edit).',
41
-        'event_espresso'
42
-    ); ?>
40
+		'Remember that contexts can represent different things. In this example they represent "recipients" and so they are labelled as such. In this example (for email payment confirmations), you may want Event Administrators to receive different information than Primary Registrants (the other context available to edit).',
41
+		'event_espresso'
42
+	); ?>
43 43
 </p>
44 44
 <p>
45 45
     <?php printf(
46
-        esc_html__(
47
-            'The %sPreview%s button is simply a link to a special view of the current template displayed to give you an idea of how the actual message will look when delivered. More information on what the preview displays is available in the content of the help tab on the preview page.',
48
-            'event_espresso'
49
-        ),
50
-        '<strong>',
51
-        '</strong>'
52
-    ); ?>
46
+		esc_html__(
47
+			'The %sPreview%s button is simply a link to a special view of the current template displayed to give you an idea of how the actual message will look when delivered. More information on what the preview displays is available in the content of the help tab on the preview page.',
48
+			'event_espresso'
49
+		),
50
+		'<strong>',
51
+		'</strong>'
52
+	); ?>
53 53
 </p>
54 54
 <p><strong><?php esc_html_e('3. Template Form Fields', 'event_espresso'); ?></strong></p>
55 55
 <p>
56 56
     <?php
57
-    echo esc_html($img3);
58
-    esc_html_e(
59
-        'The middle area of the page is dedicated to all the fields related to the message template. These fields are dynamic in the sense that different messengers may require different fields (and sometimes different message types will add or subtract fields as well.',
60
-        'event_espresso'
61
-    );
62
-    ?>
57
+	echo esc_html($img3);
58
+	esc_html_e(
59
+		'The middle area of the page is dedicated to all the fields related to the message template. These fields are dynamic in the sense that different messengers may require different fields (and sometimes different message types will add or subtract fields as well.',
60
+		'event_espresso'
61
+	);
62
+	?>
63 63
 </p>
64 64
 <p>
65 65
     <?php printf(
66
-        esc_html__(
67
-            'When editing a "Email Payment Template", you will notice that there is a field labelled "Event List" along with "Main Content". The Event List field is a special field that holds the template for whenever the %1$s[EVENT_LIST]%2$s shortcode is used in the "Main Content" field. This is so you can more finely control how each "event" in the event list displays when shown in the Main content. The "Email Registration Template", has an additional field called "Registration List". It functions much the same except that the contents of the "Registration List" field are used to indicate how each registrant is listed in the Main Content when the %1$s[ATTENDEE_LIST]%2$s shortcode is parsed.',
68
-            'event_espresso'
69
-        ),
70
-        '<strong>',
71
-        '</strong>'
72
-    ); ?>
66
+		esc_html__(
67
+			'When editing a "Email Payment Template", you will notice that there is a field labelled "Event List" along with "Main Content". The Event List field is a special field that holds the template for whenever the %1$s[EVENT_LIST]%2$s shortcode is used in the "Main Content" field. This is so you can more finely control how each "event" in the event list displays when shown in the Main content. The "Email Registration Template", has an additional field called "Registration List". It functions much the same except that the contents of the "Registration List" field are used to indicate how each registrant is listed in the Main Content when the %1$s[ATTENDEE_LIST]%2$s shortcode is parsed.',
68
+			'event_espresso'
69
+		),
70
+		'<strong>',
71
+		'</strong>'
72
+	); ?>
73 73
 </p>
74 74
 <div style="clear:both"></div>
75 75
 <p><strong><?php esc_html_e('4. Valid Shortcodes Metabox', 'event_espresso'); ?></strong></p>
76 76
 <p>
77 77
     <?php
78
-    echo esc_html($img4);
79
-    esc_html_e(
80
-        'The "Valid Shortcodes" metabox contains a list of all the shortcodes that can be used for the displayed template. This list is dynamic and will vary between templates.',
81
-        'event_espresso'
82
-    );
83
-    ?>
78
+	echo esc_html($img4);
79
+	esc_html_e(
80
+		'The "Valid Shortcodes" metabox contains a list of all the shortcodes that can be used for the displayed template. This list is dynamic and will vary between templates.',
81
+		'event_espresso'
82
+	);
83
+	?>
84 84
 </p>
85 85
 <p>
86 86
     <?php esc_html_e(
87
-        'This box is at a fixed height, but contents are scrollable. You can click the question mark to find out what the given shortcode will parse to when used in your template.',
88
-        'event_espresso'
89
-    ); ?>
87
+		'This box is at a fixed height, but contents are scrollable. You can click the question mark to find out what the given shortcode will parse to when used in your template.',
88
+		'event_espresso'
89
+	); ?>
90 90
 </p>
91 91
 <p>
92 92
     <?php printf(
93
-        esc_html__(
94
-            '%sAn important note:%s The system has been designed so that when you save the template, checks will be performed on each field to make sure that only valid shortcodes (or values) are used within them.  You will get a warning box with clear instructions if you\'ve tried to use a particular shortcode in a field that does not support it.  Also, you\'ll want to try the Preview button if you\'ve made any changes to the template to see if the changes are as you expected!',
95
-            'event_espresso'
96
-        ),
97
-        '<strong>',
98
-        '</strong>'
99
-    ); ?>
93
+		esc_html__(
94
+			'%sAn important note:%s The system has been designed so that when you save the template, checks will be performed on each field to make sure that only valid shortcodes (or values) are used within them.  You will get a warning box with clear instructions if you\'ve tried to use a particular shortcode in a field that does not support it.  Also, you\'ll want to try the Preview button if you\'ve made any changes to the template to see if the changes are as you expected!',
95
+			'event_espresso'
96
+		),
97
+		'<strong>',
98
+		'</strong>'
99
+	); ?>
100 100
 </p>
101 101
 <div style="clear:both"></div>
102 102
 <p><strong><?php esc_html_e('5. Override All Custom', 'event_espresso'); ?></strong></p>
103 103
 <p>
104 104
     <?php
105
-    echo esc_html($img5);
106
-    printf(
107
-        esc_html__(
108
-            'When you are editing a template that is a global template (not a custom event template), you\'ll see an option in the Publish metabox in the right column labelled "Override all custom". When this option is selected, custom event templates for that %1$smessenger%2$s, %1$smessage type%2$s, and %1$scontext%2$s will be ignored and the global template will be used. Why would you want to do this? For this given example, you may want to be able to allow custom event templates to be able to modify the looks and content of what goes out to Primary Registrant but to never affect what the Event Administrator receives (as set by the global template).',
109
-            'event_espresso'
110
-        ),
111
-        '<em>',
112
-        '</em>'
113
-    );
114
-    ?>
105
+	echo esc_html($img5);
106
+	printf(
107
+		esc_html__(
108
+			'When you are editing a template that is a global template (not a custom event template), you\'ll see an option in the Publish metabox in the right column labelled "Override all custom". When this option is selected, custom event templates for that %1$smessenger%2$s, %1$smessage type%2$s, and %1$scontext%2$s will be ignored and the global template will be used. Why would you want to do this? For this given example, you may want to be able to allow custom event templates to be able to modify the looks and content of what goes out to Primary Registrant but to never affect what the Event Administrator receives (as set by the global template).',
109
+			'event_espresso'
110
+		),
111
+		'<em>',
112
+		'</em>'
113
+	);
114
+	?>
115 115
 </p>
116 116
 <p>
117 117
     <strong><?php esc_html_e('Recommendations', 'event_espresso'); ?></strong>
118 118
     <br />
119 119
     <?php esc_html_e(
120
-        'To learn more about the options on this page, take a look at the different tabs that appear on the left side of the page.',
121
-        'event_espresso'
122
-    ); ?>
120
+		'To learn more about the options on this page, take a look at the different tabs that appear on the left side of the page.',
121
+		'event_espresso'
122
+	); ?>
123 123
 </p>
124 124
 <p>
125 125
     <strong><?php esc_html_e('Screen Options', 'event_espresso'); ?></strong>
126 126
     <br />
127 127
     <?php esc_html_e(
128
-        'You can customize the information that is shown on this page by toggling the Screen Options tab. Then you can add or remove checkmarks to hide or show certain content.',
129
-        'event_espresso'
130
-    ); ?>
128
+		'You can customize the information that is shown on this page by toggling the Screen Options tab. Then you can add or remove checkmarks to hide or show certain content.',
129
+		'event_espresso'
130
+	); ?>
131 131
 </p>
132 132
\ No newline at end of file
Please login to merge, or discard this patch.
admin_pages/messages/help_tabs/messages_settings.help_tab.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -3,23 +3,23 @@
 block discarded – undo
3 3
 </p>
4 4
 <p>
5 5
     <?php esc_html_e(
6
-        'On its first activation, Event Espresso will automatically setup the core messenger (email) and message types (registration and payment).',
7
-        'event_espresso'
8
-    ); ?>
6
+		'On its first activation, Event Espresso will automatically setup the core messenger (email) and message types (registration and payment).',
7
+		'event_espresso'
8
+	); ?>
9 9
 </p>
10 10
 <p>
11 11
     <strong><?php esc_html_e('Recommendations', 'event_espresso'); ?></strong>
12 12
     <br />
13 13
     <?php esc_html__(
14
-        'To learn more about the options on this page, take a look at the different tabs that appear on the left side of the page.',
15
-        'event_espresso'
16
-    ); ?>
14
+		'To learn more about the options on this page, take a look at the different tabs that appear on the left side of the page.',
15
+		'event_espresso'
16
+	); ?>
17 17
 </p>
18 18
 <p>
19 19
     <strong><?php esc_html_e('Screen Options', 'event_espresso'); ?></strong>
20 20
     <br />
21 21
     <?php esc_html_e(
22
-        'You can customize the information that is shown on this page by toggling the Screen Options tab. Then you can add or remove checkmarks to hide or show certain content.',
23
-        'event_espresso'
24
-    ); ?>
22
+		'You can customize the information that is shown on this page by toggling the Screen Options tab. Then you can add or remove checkmarks to hide or show certain content.',
23
+		'event_espresso'
24
+	); ?>
25 25
 </p>
26 26
\ No newline at end of file
Please login to merge, or discard this patch.
admin_pages/messages/help_tabs/messages_overview.help_tab.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -3,26 +3,26 @@
 block discarded – undo
3 3
 </p>
4 4
 <p>
5 5
     <?php printf(
6
-        esc_html__(
7
-            'The Messages system is used by Event Espresso to prepare messages for different uses (Message Types) and these messages are delivered by different Messengers. %1$sThis framework offers a large amount of flexibility. This page shows message templates that have been created with Event Espresso and are currently enable for at least one event.',
8
-            'event_espresso'
9
-        ),
10
-        '<br />'
11
-    ); ?>
6
+		esc_html__(
7
+			'The Messages system is used by Event Espresso to prepare messages for different uses (Message Types) and these messages are delivered by different Messengers. %1$sThis framework offers a large amount of flexibility. This page shows message templates that have been created with Event Espresso and are currently enable for at least one event.',
8
+			'event_espresso'
9
+		),
10
+		'<br />'
11
+	); ?>
12 12
 </p>
13 13
 <p>
14 14
     <strong><?php esc_html_e('Recommendations', 'event_espresso'); ?></strong>
15 15
     <br />
16 16
     <?php esc_html_e(
17
-        'To learn more about the options on this page, take a look at the different tabs that appear on the left side of the page.',
18
-        'event_espresso'
19
-    ); ?>
17
+		'To learn more about the options on this page, take a look at the different tabs that appear on the left side of the page.',
18
+		'event_espresso'
19
+	); ?>
20 20
 </p>
21 21
 <p>
22 22
     <strong><?php esc_html_e('Screen Options', 'event_espresso'); ?></strong>
23 23
     <br />
24 24
     <?php esc_html_e(
25
-        'You can customize the information that is shown on this page by toggling the Screen Options tab. Then you can add or remove checkmarks to hide or show certain content and even adjust the pagination for message templates.',
26
-        'event_espresso'
27
-    ); ?>
25
+		'You can customize the information that is shown on this page by toggling the Screen Options tab. Then you can add or remove checkmarks to hide or show certain content and even adjust the pagination for message templates.',
26
+		'event_espresso'
27
+	); ?>
28 28
 </p>
29 29
\ No newline at end of file
Please login to merge, or discard this patch.
caffeinated/admin/extend/messages/Extend_Messages_Admin_Page.core.php 1 patch
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -18,190 +18,190 @@
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    public function __construct($routing = true)
22
-    {
23
-        parent::__construct($routing);
24
-        if (! defined('EE_MSG_CAF_ASSETS_PATH')) {
25
-            define('EE_MSG_CAF_ASSETS_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'messages/assets/');
26
-            define('EE_MSG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'messages/assets/');
27
-            define('EE_MSG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'messages/templates/');
28
-            define('EE_MSG_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'messages/templates/');
29
-        }
30
-    }
31
-
32
-    protected function _extend_page_config()
33
-    {
34
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'messages';
35
-        $this->_page_routes['custom_mtps'] = array(
36
-            'func'       => '_ee_custom_messages_overview_list_table',
37
-            'capability' => 'ee_read_messages',
38
-        );
39
-        $this->_page_config['custom_mtps'] = array(
40
-            'nav'           => array(
41
-                'label' => esc_html__('Custom Message Templates', 'event_espresso'),
42
-                'order' => 30,
43
-            ),
44
-            'list_table'    => 'Custom_Messages_Template_List_Table',
45
-            'help_tabs'     => array(
46
-                'message_overview_message_types_help_tab' => array(
47
-                    'title'    => esc_html__('Message Types', 'event_espresso'),
48
-                    'filename' => 'messages_overview_types',
49
-                ),
50
-                'messages_overview_messengers_help_tab'   => array(
51
-                    'title'    => esc_html__('Messengers', 'event_espresso'),
52
-                    'filename' => 'messages_overview_messengers',
53
-                ),
54
-                'messages_overview_other_help_tab'        => array(
55
-                    'title'    => esc_html__('Messages Other', 'event_espresso'),
56
-                    'filename' => 'messages_overview_other',
57
-                ),
58
-            ),
59
-            'require_nonce' => false,
60
-        );
61
-
62
-        add_action('current_screen', array($this, 'dynamic_screen_hooks'), 10);
63
-    }
64
-
65
-
66
-    /**
67
-     * Callback for current_screen action
68
-     * This is used for any filters and/or actions that require the dynamic screen hook_prefix to be correct.
69
-     *
70
-     * @since 4.5.0
71
-     *
72
-     * @return void
73
-     */
74
-    public function dynamic_screen_hooks()
75
-    {
76
-        global $admin_page_hooks;
77
-
78
-        if (! empty($admin_page_hooks['espresso_events'])) {
79
-            // we're on a EE specific page... good stuff!
80
-            $hook_prefix = $admin_page_hooks['espresso_events'];
81
-            $filter_ref = $hook_prefix . '_page_' . $this->page_slug;
82
-            add_filter('FHEE_manage_' . $filter_ref . '_columns', array($this, 'add_custom_mtps_columns'), 10, 2);
83
-            add_action(
84
-                'AHEE__EE_Admin_List_Table__column_actions__' . $filter_ref,
85
-                array($this, 'custom_mtp_create_button_column'),
86
-                10,
87
-                2
88
-            );
89
-        }
90
-    }
91
-
92
-
93
-    /**
94
-     * This is the callback for the FHEE__manage_event-espresso_page_espresso_messages_columns to register the
95
-     * caffeinated columns for the global message templates list table.
96
-     *
97
-     * @since 4.3.2
98
-     *
99
-     * @param array  $columns   Original defined list of columns
100
-     * @param string $screen_id The unique screen id for the page.
101
-     */
102
-    public function add_custom_mtps_columns($columns, $screen_id)
103
-    {
104
-        if ($screen_id !== 'espresso_messages_global_mtps') {
105
-            return $columns;
106
-        }
107
-
108
-        $columns['actions'] = '';
109
-        return $columns;
110
-    }
111
-
112
-
113
-    /**
114
-     * Callback for FHEE__EE_Admin_List_Table__column_actions__event-espresso_page_espresso_messages action that allows
115
-     * for adding the content for the registered "action" column.
116
-     *
117
-     * @since 4.3.2
118
-     *
119
-     * @param EE_Base_Class
120
-     * @param string $screen_id Unique screen id for the page
121
-     *
122
-     * @return string html content for the page.
123
-     */
124
-    public function custom_mtp_create_button_column($item, $screen_id)
125
-    {
126
-        if (
127
-            $screen_id !== 'espresso_messages_global_mtps' || ! EE_Registry::instance()->CAP->current_user_can(
128
-                'ee_edit_messages',
129
-                'espresso_messages_add_new_message_template'
130
-            )
131
-        ) {
132
-            return '';
133
-        }
134
-
135
-        // first we consider whether this template has override set.  If it does then that means no custom templates can be created from this template as a base.  So let's just skip the button creation.
136
-        if ($item->get('MTP_is_override')) {
137
-            return '';
138
-        }
139
-
140
-
141
-        $create_args = array(
142
-            'GRP_ID'       => $item->ID(),
143
-            'messenger'    => $item->messenger(),
144
-            'message_type' => $item->message_type(),
145
-            'action'       => 'add_new_message_template',
146
-        );
147
-        $create_link = EE_Admin_Page::add_query_args_and_nonce($create_args, EE_MSG_ADMIN_URL);
148
-        echo sprintf(
149
-            '<a href="%s" class="button button-small">%s</a>',
150
-            $create_link,
151
-            esc_html__('Create Custom', 'event_espresso')
152
-        );
153
-    }
154
-
155
-
156
-    protected function _add_screen_options_custom_mtps()
157
-    {
158
-        $page_title = $this->_admin_page_title;
159
-        $this->_admin_page_title = esc_html__('Custom Message Templates', 'event_espresso');
160
-        $this->_per_page_screen_option();
161
-        $this->_admin_page_title = $page_title;
162
-    }
163
-
164
-
165
-    /**
166
-     * set views array for Custom Templates list table
167
-     *
168
-     * @access public
169
-     * @return void
170
-     */
171
-    public function _set_list_table_views_custom_mtps()
172
-    {
173
-        $this->_views = array(
174
-            'in_use' => array(
175
-                'slug'        => 'in_use',
176
-                'label'       => esc_html__('In Use', 'event_espresso'),
177
-                'count'       => 0,
178
-                'bulk_action' => array(
179
-                    'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
180
-                ),
181
-            ),
182
-        );
183
-        if (
184
-            EE_Registry::instance()->CAP->current_user_can(
185
-                'ee_delete_messages',
186
-                'espresso_messages_trash_message_template'
187
-            )
188
-        ) {
189
-            $this->_views['trashed'] = array(
190
-                'slug'        => 'trashed',
191
-                'label'       => esc_html__('Trash', 'event_espresso'),
192
-                'count'       => 0,
193
-                'bulk_action' => array(
194
-                    'restore_message_template' => esc_html__('Restore From Trash', 'event_espresso'),
195
-                    'delete_message_template'  => esc_html__('Delete Permanently', 'event_espresso'),
196
-                ),
197
-            );
198
-        }
199
-    }
200
-
201
-
202
-    protected function _ee_custom_messages_overview_list_table()
203
-    {
204
-        $this->_admin_page_title = esc_html__('Custom Message Templates', 'event_espresso');
205
-        $this->display_admin_list_table_page_with_no_sidebar();
206
-    }
21
+	public function __construct($routing = true)
22
+	{
23
+		parent::__construct($routing);
24
+		if (! defined('EE_MSG_CAF_ASSETS_PATH')) {
25
+			define('EE_MSG_CAF_ASSETS_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'messages/assets/');
26
+			define('EE_MSG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'messages/assets/');
27
+			define('EE_MSG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'messages/templates/');
28
+			define('EE_MSG_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'messages/templates/');
29
+		}
30
+	}
31
+
32
+	protected function _extend_page_config()
33
+	{
34
+		$this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'messages';
35
+		$this->_page_routes['custom_mtps'] = array(
36
+			'func'       => '_ee_custom_messages_overview_list_table',
37
+			'capability' => 'ee_read_messages',
38
+		);
39
+		$this->_page_config['custom_mtps'] = array(
40
+			'nav'           => array(
41
+				'label' => esc_html__('Custom Message Templates', 'event_espresso'),
42
+				'order' => 30,
43
+			),
44
+			'list_table'    => 'Custom_Messages_Template_List_Table',
45
+			'help_tabs'     => array(
46
+				'message_overview_message_types_help_tab' => array(
47
+					'title'    => esc_html__('Message Types', 'event_espresso'),
48
+					'filename' => 'messages_overview_types',
49
+				),
50
+				'messages_overview_messengers_help_tab'   => array(
51
+					'title'    => esc_html__('Messengers', 'event_espresso'),
52
+					'filename' => 'messages_overview_messengers',
53
+				),
54
+				'messages_overview_other_help_tab'        => array(
55
+					'title'    => esc_html__('Messages Other', 'event_espresso'),
56
+					'filename' => 'messages_overview_other',
57
+				),
58
+			),
59
+			'require_nonce' => false,
60
+		);
61
+
62
+		add_action('current_screen', array($this, 'dynamic_screen_hooks'), 10);
63
+	}
64
+
65
+
66
+	/**
67
+	 * Callback for current_screen action
68
+	 * This is used for any filters and/or actions that require the dynamic screen hook_prefix to be correct.
69
+	 *
70
+	 * @since 4.5.0
71
+	 *
72
+	 * @return void
73
+	 */
74
+	public function dynamic_screen_hooks()
75
+	{
76
+		global $admin_page_hooks;
77
+
78
+		if (! empty($admin_page_hooks['espresso_events'])) {
79
+			// we're on a EE specific page... good stuff!
80
+			$hook_prefix = $admin_page_hooks['espresso_events'];
81
+			$filter_ref = $hook_prefix . '_page_' . $this->page_slug;
82
+			add_filter('FHEE_manage_' . $filter_ref . '_columns', array($this, 'add_custom_mtps_columns'), 10, 2);
83
+			add_action(
84
+				'AHEE__EE_Admin_List_Table__column_actions__' . $filter_ref,
85
+				array($this, 'custom_mtp_create_button_column'),
86
+				10,
87
+				2
88
+			);
89
+		}
90
+	}
91
+
92
+
93
+	/**
94
+	 * This is the callback for the FHEE__manage_event-espresso_page_espresso_messages_columns to register the
95
+	 * caffeinated columns for the global message templates list table.
96
+	 *
97
+	 * @since 4.3.2
98
+	 *
99
+	 * @param array  $columns   Original defined list of columns
100
+	 * @param string $screen_id The unique screen id for the page.
101
+	 */
102
+	public function add_custom_mtps_columns($columns, $screen_id)
103
+	{
104
+		if ($screen_id !== 'espresso_messages_global_mtps') {
105
+			return $columns;
106
+		}
107
+
108
+		$columns['actions'] = '';
109
+		return $columns;
110
+	}
111
+
112
+
113
+	/**
114
+	 * Callback for FHEE__EE_Admin_List_Table__column_actions__event-espresso_page_espresso_messages action that allows
115
+	 * for adding the content for the registered "action" column.
116
+	 *
117
+	 * @since 4.3.2
118
+	 *
119
+	 * @param EE_Base_Class
120
+	 * @param string $screen_id Unique screen id for the page
121
+	 *
122
+	 * @return string html content for the page.
123
+	 */
124
+	public function custom_mtp_create_button_column($item, $screen_id)
125
+	{
126
+		if (
127
+			$screen_id !== 'espresso_messages_global_mtps' || ! EE_Registry::instance()->CAP->current_user_can(
128
+				'ee_edit_messages',
129
+				'espresso_messages_add_new_message_template'
130
+			)
131
+		) {
132
+			return '';
133
+		}
134
+
135
+		// first we consider whether this template has override set.  If it does then that means no custom templates can be created from this template as a base.  So let's just skip the button creation.
136
+		if ($item->get('MTP_is_override')) {
137
+			return '';
138
+		}
139
+
140
+
141
+		$create_args = array(
142
+			'GRP_ID'       => $item->ID(),
143
+			'messenger'    => $item->messenger(),
144
+			'message_type' => $item->message_type(),
145
+			'action'       => 'add_new_message_template',
146
+		);
147
+		$create_link = EE_Admin_Page::add_query_args_and_nonce($create_args, EE_MSG_ADMIN_URL);
148
+		echo sprintf(
149
+			'<a href="%s" class="button button-small">%s</a>',
150
+			$create_link,
151
+			esc_html__('Create Custom', 'event_espresso')
152
+		);
153
+	}
154
+
155
+
156
+	protected function _add_screen_options_custom_mtps()
157
+	{
158
+		$page_title = $this->_admin_page_title;
159
+		$this->_admin_page_title = esc_html__('Custom Message Templates', 'event_espresso');
160
+		$this->_per_page_screen_option();
161
+		$this->_admin_page_title = $page_title;
162
+	}
163
+
164
+
165
+	/**
166
+	 * set views array for Custom Templates list table
167
+	 *
168
+	 * @access public
169
+	 * @return void
170
+	 */
171
+	public function _set_list_table_views_custom_mtps()
172
+	{
173
+		$this->_views = array(
174
+			'in_use' => array(
175
+				'slug'        => 'in_use',
176
+				'label'       => esc_html__('In Use', 'event_espresso'),
177
+				'count'       => 0,
178
+				'bulk_action' => array(
179
+					'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
180
+				),
181
+			),
182
+		);
183
+		if (
184
+			EE_Registry::instance()->CAP->current_user_can(
185
+				'ee_delete_messages',
186
+				'espresso_messages_trash_message_template'
187
+			)
188
+		) {
189
+			$this->_views['trashed'] = array(
190
+				'slug'        => 'trashed',
191
+				'label'       => esc_html__('Trash', 'event_espresso'),
192
+				'count'       => 0,
193
+				'bulk_action' => array(
194
+					'restore_message_template' => esc_html__('Restore From Trash', 'event_espresso'),
195
+					'delete_message_template'  => esc_html__('Delete Permanently', 'event_espresso'),
196
+				),
197
+			);
198
+		}
199
+	}
200
+
201
+
202
+	protected function _ee_custom_messages_overview_list_table()
203
+	{
204
+		$this->_admin_page_title = esc_html__('Custom Message Templates', 'event_espresso');
205
+		$this->display_admin_list_table_page_with_no_sidebar();
206
+	}
207 207
 }
Please login to merge, or discard this patch.
caffeinated/admin/new/pricing/Pricing_Admin_Page.core.php 1 patch
Indentation   +1403 added lines, -1403 removed lines patch added patch discarded remove patch
@@ -12,1411 +12,1411 @@
 block discarded – undo
12 12
 class Pricing_Admin_Page extends EE_Admin_Page
13 13
 {
14 14
 
15
-    /**
16
-     *    constructor
17
-     *
18
-     * @Constructor
19
-     * @access public
20
-     * @param bool $routing
21
-     * @return Pricing_Admin_Page
22
-     */
23
-    public function __construct($routing = true)
24
-    {
25
-        parent::__construct($routing);
26
-    }
27
-
28
-
29
-    protected function _init_page_props()
30
-    {
31
-        $this->page_slug = PRICING_PG_SLUG;
32
-        $this->page_label = PRICING_LABEL;
33
-        $this->_admin_base_url = PRICING_ADMIN_URL;
34
-        $this->_admin_base_path = PRICING_ADMIN;
35
-    }
36
-
37
-
38
-    protected function _ajax_hooks()
39
-    {
40
-        add_action('wp_ajax_espresso_update_prices_order', array($this, 'update_price_order'));
41
-    }
42
-
43
-
44
-    protected function _define_page_props()
45
-    {
46
-        $this->_admin_page_title = PRICING_LABEL;
47
-        $this->_labels = array(
48
-            'buttons' => array(
49
-                'add'         => esc_html__('Add New Default Price', 'event_espresso'),
50
-                'edit'        => esc_html__('Edit Default Price', 'event_espresso'),
51
-                'delete'      => esc_html__('Delete Default Price', 'event_espresso'),
52
-                'add_type'    => esc_html__('Add New Default Price Type', 'event_espresso'),
53
-                'edit_type'   => esc_html__('Edit Price Type', 'event_espresso'),
54
-                'delete_type' => esc_html__('Delete Price Type', 'event_espresso'),
55
-            ),
56
-        );
57
-    }
58
-
59
-
60
-    /**
61
-     *        an array for storing request actions and their corresponding methods
62
-     *
63
-     * @access private
64
-     * @return void
65
-     */
66
-    protected function _set_page_routes()
67
-    {
68
-        $prc_id = ! empty($this->_req_data['PRC_ID']) && ! is_array($this->_req_data['PRC_ID'])
69
-            ? $this->_req_data['PRC_ID'] : 0;
70
-        $prt_id = ! empty($this->_req_data['PRT_ID']) && ! is_array($this->_req_data['PRT_ID'])
71
-            ? $this->_req_data['PRT_ID'] : 0;
72
-        $this->_page_routes = array(
73
-            'default'                     => array(
74
-                'func'       => '_price_overview_list_table',
75
-                'capability' => 'ee_read_default_prices',
76
-            ),
77
-            'add_new_price'               => array(
78
-                'func'       => '_edit_price_details',
79
-                'args'       => array('new_price' => true),
80
-                'capability' => 'ee_edit_default_prices',
81
-            ),
82
-            'edit_price'                  => array(
83
-                'func'       => '_edit_price_details',
84
-                'args'       => array('new_price' => false),
85
-                'capability' => 'ee_edit_default_price',
86
-                'obj_id'     => $prc_id,
87
-            ),
88
-            'insert_price'                => array(
89
-                'func'       => '_insert_or_update_price',
90
-                'args'       => array('new_price' => true),
91
-                'noheader'   => true,
92
-                'capability' => 'ee_edit_default_prices',
93
-            ),
94
-            'update_price'                => array(
95
-                'func'       => '_insert_or_update_price',
96
-                'args'       => array('new_price' => false),
97
-                'noheader'   => true,
98
-                'capability' => 'ee_edit_default_price',
99
-                'obj_id'     => $prc_id,
100
-            ),
101
-            'trash_price'                 => array(
102
-                'func'       => '_trash_or_restore_price',
103
-                'args'       => array('trash' => true),
104
-                'noheader'   => true,
105
-                'capability' => 'ee_delete_default_price',
106
-                'obj_id'     => $prc_id,
107
-            ),
108
-            'restore_price'               => array(
109
-                'func'       => '_trash_or_restore_price',
110
-                'args'       => array('trash' => false),
111
-                'noheader'   => true,
112
-                'capability' => 'ee_delete_default_price',
113
-                'obj_id'     => $prc_id,
114
-            ),
115
-            'delete_price'                => array(
116
-                'func'       => '_delete_price',
117
-                'noheader'   => true,
118
-                'capability' => 'ee_delete_default_price',
119
-                'obj_id'     => $prc_id,
120
-            ),
121
-            'espresso_update_price_order' => array(
122
-                'func'       => 'update_price_order',
123
-                'noheader'   => true,
124
-                'capability' => 'ee_edit_default_prices',
125
-            ),
126
-            // price types
127
-            'price_types'                 => array(
128
-                'func'       => '_price_types_overview_list_table',
129
-                'capability' => 'ee_read_default_price_types',
130
-            ),
131
-            'add_new_price_type'          => array(
132
-                'func'       => '_edit_price_type_details',
133
-                'capability' => 'ee_edit_default_price_types',
134
-            ),
135
-            'edit_price_type'             => array(
136
-                'func'       => '_edit_price_type_details',
137
-                'capability' => 'ee_edit_default_price_type',
138
-                'obj_id'     => $prt_id,
139
-            ),
140
-            'insert_price_type'           => array(
141
-                'func'       => '_insert_or_update_price_type',
142
-                'args'       => array('new_price_type' => true),
143
-                'noheader'   => true,
144
-                'capability' => 'ee_edit_default_price_types',
145
-            ),
146
-            'update_price_type'           => array(
147
-                'func'       => '_insert_or_update_price_type',
148
-                'args'       => array('new_price_type' => false),
149
-                'noheader'   => true,
150
-                'capability' => 'ee_edit_default_price_type',
151
-                'obj_id'     => $prt_id,
152
-            ),
153
-            'trash_price_type'            => array(
154
-                'func'       => '_trash_or_restore_price_type',
155
-                'args'       => array('trash' => true),
156
-                'noheader'   => true,
157
-                'capability' => 'ee_delete_default_price_type',
158
-                'obj_id'     => $prt_id,
159
-            ),
160
-            'restore_price_type'          => array(
161
-                'func'       => '_trash_or_restore_price_type',
162
-                'args'       => array('trash' => false),
163
-                'noheader'   => true,
164
-                'capability' => 'ee_delete_default_price_type',
165
-                'obj_id'     => $prt_id,
166
-            ),
167
-            'delete_price_type'           => array(
168
-                'func'       => '_delete_price_type',
169
-                'noheader'   => true,
170
-                'capability' => 'ee_delete_default_price_type',
171
-                'obj_id'     => $prt_id,
172
-            ),
173
-            'tax_settings'                => array(
174
-                'func'       => '_tax_settings',
175
-                'capability' => 'manage_options',
176
-            ),
177
-            'update_tax_settings'         => array(
178
-                'func'       => '_update_tax_settings',
179
-                'capability' => 'manage_options',
180
-                'noheader'   => true,
181
-            ),
182
-        );
183
-    }
184
-
185
-
186
-    protected function _set_page_config()
187
-    {
188
-
189
-        $this->_page_config = array(
190
-            'default'            => array(
191
-                'nav'           => array(
192
-                    'label' => esc_html__('Default Pricing', 'event_espresso'),
193
-                    'order' => 10,
194
-                ),
195
-                'list_table'    => 'Prices_List_Table',
196
-                'help_tabs'     => array(
197
-                    'pricing_default_pricing_help_tab'                           => array(
198
-                        'title'    => esc_html__('Default Pricing', 'event_espresso'),
199
-                        'filename' => 'pricing_default_pricing',
200
-                    ),
201
-                    'pricing_default_pricing_table_column_headings_help_tab'     => array(
202
-                        'title'    => esc_html__('Default Pricing Table Column Headings', 'event_espresso'),
203
-                        'filename' => 'pricing_default_pricing_table_column_headings',
204
-                    ),
205
-                    'pricing_default_pricing_views_bulk_actions_search_help_tab' => array(
206
-                        'title'    => esc_html__('Default Pricing Views & Bulk Actions & Search', 'event_espresso'),
207
-                        'filename' => 'pricing_default_pricing_views_bulk_actions_search',
208
-                    ),
209
-                ),
210
-                'require_nonce' => false,
211
-            ),
212
-            'add_new_price'      => array(
213
-                'nav'           => array(
214
-                    'label'      => esc_html__('Add New Default Price', 'event_espresso'),
215
-                    'order'      => 20,
216
-                    'persistent' => false,
217
-                ),
218
-                'help_tabs'     => array(
219
-                    'add_new_default_price_help_tab' => array(
220
-                        'title'    => esc_html__('Add New Default Price', 'event_espresso'),
221
-                        'filename' => 'pricing_add_new_default_price',
222
-                    ),
223
-                ),
224
-                'metaboxes'     => array('_publish_post_box', '_espresso_news_post_box', '_price_details_meta_boxes'),
225
-                'require_nonce' => false,
226
-            ),
227
-            'edit_price'         => array(
228
-                'nav'           => array(
229
-                    'label'      => esc_html__('Edit Default Price', 'event_espresso'),
230
-                    'order'      => 20,
231
-                    'url'        => isset($this->_req_data['id']) ? add_query_arg(
232
-                        array('id' => $this->_req_data['id']),
233
-                        $this->_current_page_view_url
234
-                    ) : $this->_admin_base_url,
235
-                    'persistent' => false,
236
-                ),
237
-                'metaboxes'     => array('_publish_post_box', '_espresso_news_post_box', '_price_details_meta_boxes'),
238
-                'help_tabs'     => array(
239
-                    'edit_default_price_help_tab' => array(
240
-                        'title'    => esc_html__('Edit Default Price', 'event_espresso'),
241
-                        'filename' => 'pricing_edit_default_price',
242
-                    ),
243
-                ),
244
-                'require_nonce' => false,
245
-            ),
246
-            'price_types'        => array(
247
-                'nav'           => array(
248
-                    'label' => esc_html__('Price Types', 'event_espresso'),
249
-                    'order' => 30,
250
-                ),
251
-                'list_table'    => 'Price_Types_List_Table',
252
-                'help_tabs'     => array(
253
-                    'pricing_price_types_help_tab'                           => array(
254
-                        'title'    => esc_html__('Price Types', 'event_espresso'),
255
-                        'filename' => 'pricing_price_types',
256
-                    ),
257
-                    'pricing_price_types_table_column_headings_help_tab'     => array(
258
-                        'title'    => esc_html__('Price Types Table Column Headings', 'event_espresso'),
259
-                        'filename' => 'pricing_price_types_table_column_headings',
260
-                    ),
261
-                    'pricing_price_types_views_bulk_actions_search_help_tab' => array(
262
-                        'title'    => esc_html__('Price Types Views & Bulk Actions & Search', 'event_espresso'),
263
-                        'filename' => 'pricing_price_types_views_bulk_actions_search',
264
-                    ),
265
-                ),
266
-                'metaboxes'     => array('_espresso_news_post_box', '_espresso_links_post_box'),
267
-                'require_nonce' => false,
268
-            ),
269
-            'add_new_price_type' => array(
270
-                'nav'           => array(
271
-                    'label'      => esc_html__('Add New Price Type', 'event_espresso'),
272
-                    'order'      => 40,
273
-                    'persistent' => false,
274
-                ),
275
-                'help_tabs'     => array(
276
-                    'add_new_price_type_help_tab' => array(
277
-                        'title'    => esc_html__('Add New Price Type', 'event_espresso'),
278
-                        'filename' => 'pricing_add_new_price_type',
279
-                    ),
280
-                ),
281
-                'metaboxes'     => array(
282
-                    '_publish_post_box',
283
-                    '_espresso_news_post_box',
284
-                    '_price_type_details_meta_boxes',
285
-                ),
286
-                'require_nonce' => false,
287
-            ),
288
-            'edit_price_type'    => array(
289
-                'nav'       => array(
290
-                    'label'      => esc_html__('Edit Price Type', 'event_espresso'),
291
-                    'order'      => 40,
292
-                    'persistent' => false,
293
-                ),
294
-                'help_tabs' => array(
295
-                    'edit_price_type_help_tab' => array(
296
-                        'title'    => esc_html__('Edit Price Type', 'event_espresso'),
297
-                        'filename' => 'pricing_edit_price_type',
298
-                    ),
299
-                ),
300
-                'metaboxes' => array('_publish_post_box', '_espresso_news_post_box', '_price_type_details_meta_boxes'),
301
-
302
-                'require_nonce' => false,
303
-            ),
304
-            'tax_settings'       => array(
305
-                'nav'           => array(
306
-                    'label' => esc_html__('Tax Settings', 'event_espresso'),
307
-                    'order' => 40,
308
-                ),
309
-                'labels'        => array(
310
-                    'publishbox' => esc_html__('Update Tax Settings', 'event_espresso'),
311
-                ),
312
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
313
-                'require_nonce' => true,
314
-            ),
315
-        );
316
-    }
317
-
318
-
319
-    protected function _add_screen_options()
320
-    {
321
-        // todo
322
-    }
323
-
324
-
325
-    protected function _add_screen_options_default()
326
-    {
327
-        $this->_per_page_screen_option();
328
-    }
329
-
330
-
331
-    protected function _add_screen_options_price_types()
332
-    {
333
-        $page_title = $this->_admin_page_title;
334
-        $this->_admin_page_title = esc_html__('Price Types', 'event_espresso');
335
-        $this->_per_page_screen_option();
336
-        $this->_admin_page_title = $page_title;
337
-    }
338
-
339
-
340
-    protected function _add_feature_pointers()
341
-    {
342
-    }
343
-
344
-
345
-    public function load_scripts_styles()
346
-    {
347
-        // styles
348
-        wp_enqueue_style('espresso-ui-theme');
349
-        wp_register_style(
350
-            'espresso_PRICING',
351
-            PRICING_ASSETS_URL . 'espresso_pricing_admin.css',
352
-            array(),
353
-            EVENT_ESPRESSO_VERSION
354
-        );
355
-        wp_enqueue_style('espresso_PRICING');
356
-
357
-        // scripts
358
-        wp_enqueue_script('ee_admin_js');
359
-        wp_enqueue_script('jquery-ui-position');
360
-        wp_enqueue_script('jquery-ui-widget');
361
-        // wp_enqueue_script('jquery-ui-dialog');
362
-        // wp_enqueue_script('jquery-ui-draggable');
363
-        // wp_enqueue_script('jquery-ui-datepicker');
364
-        wp_register_script(
365
-            'espresso_PRICING',
366
-            PRICING_ASSETS_URL . 'espresso_pricing_admin.js',
367
-            array('jquery'),
368
-            EVENT_ESPRESSO_VERSION,
369
-            true
370
-        );
371
-        wp_enqueue_script('espresso_PRICING');
372
-    }
373
-
374
-
375
-    public function load_scripts_styles_default()
376
-    {
377
-        wp_enqueue_script('espresso_ajax_table_sorting');
378
-    }
379
-
380
-
381
-    public function admin_footer_scripts()
382
-    {
383
-    }
384
-
385
-    public function admin_init()
386
-    {
387
-    }
388
-
389
-    public function admin_notices()
390
-    {
391
-    }
392
-
393
-
394
-    protected function _set_list_table_views_default()
395
-    {
396
-        $this->_views = array(
397
-            'all' => array(
398
-                'slug'        => 'all',
399
-                'label'       => esc_html__('View All Default Pricing', 'event_espresso'),
400
-                'count'       => 0,
401
-                'bulk_action' => array(
402
-                    'trash_price' => esc_html__('Move to Trash', 'event_espresso'),
403
-                ),
404
-            ),
405
-        );
406
-
407
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_default_prices', 'pricing_trash_price')) {
408
-            $this->_views['trashed'] = array(
409
-                'slug'        => 'trashed',
410
-                'label'       => esc_html__('Trash', 'event_espresso'),
411
-                'count'       => 0,
412
-                'bulk_action' => array(
413
-                    'restore_price' => esc_html__('Restore from Trash', 'event_espresso'),
414
-                    'delete_price'  => esc_html__('Delete Permanently', 'event_espresso'),
415
-                ),
416
-            );
417
-        }
418
-    }
419
-
420
-
421
-    protected function _set_list_table_views_price_types()
422
-    {
423
-        $this->_views = array(
424
-            'all' => array(
425
-                'slug'        => 'all',
426
-                'label'       => esc_html__('All', 'event_espresso'),
427
-                'count'       => 0,
428
-                'bulk_action' => array(
429
-                    'trash_price_type' => esc_html__('Move to Trash', 'event_espresso'),
430
-                ),
431
-            ),
432
-        );
433
-
434
-        if (
435
-            EE_Registry::instance()->CAP->current_user_can(
436
-                'ee_delete_default_price_types',
437
-                'pricing_trash_price_type'
438
-            )
439
-        ) {
440
-            $this->_views['trashed'] = array(
441
-                'slug'        => 'trashed',
442
-                'label'       => esc_html__('Trash', 'event_espresso'),
443
-                'count'       => 0,
444
-                'bulk_action' => array(
445
-                    'restore_price_type' => esc_html__('Restore from Trash', 'event_espresso'),
446
-                    'delete_price_type'  => esc_html__('Delete Permanently', 'event_espresso'),
447
-                ),
448
-            );
449
-        }
450
-    }
451
-
452
-
453
-    /**
454
-     *        generates HTML for main Prices Admin page
455
-     *
456
-     * @access protected
457
-     * @return void
458
-     */
459
-    protected function _price_overview_list_table()
460
-    {
461
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
462
-            'add_new_price',
463
-            'add',
464
-            array(),
465
-            'add-new-h2'
466
-        );
467
-        $this->admin_page_title .= $this->_learn_more_about_pricing_link();
468
-        $this->_search_btn_label = esc_html__('Default Prices', 'event_espresso');
469
-        $this->display_admin_list_table_page_with_no_sidebar();
470
-    }
471
-
472
-
473
-    /**
474
-     *    retrieve data for Prices List table
475
-     *
476
-     * @access public
477
-     * @param  int     $per_page how many prices displayed per page
478
-     * @param  boolean $count    return the count or objects
479
-     * @param  boolean $trashed  whether the current view is of the trash can - eww yuck!
480
-     * @return mixed (int|array)  int = count || array of price objects
481
-     */
482
-    public function get_prices_overview_data($per_page = 10, $count = false, $trashed = false)
483
-    {
484
-
485
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
486
-        // start with an empty array
487
-        $event_pricing = array();
488
-
489
-        require_once(PRICING_ADMIN . 'Prices_List_Table.class.php');
490
-        require_once(EE_MODELS . 'EEM_Price.model.php');
491
-        // $PRC = EEM_Price::instance();
492
-
493
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? '' : $this->_req_data['orderby'];
494
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
495
-            : 'ASC';
496
-
497
-        switch ($this->_req_data['orderby']) {
498
-            case 'name':
499
-                $orderby = array('PRC_name' => $order);
500
-                break;
501
-            case 'type':
502
-                $orderby = array('Price_Type.PRT_name' => $order);
503
-                break;
504
-            case 'amount':
505
-                $orderby = array('PRC_amount' => $order);
506
-                break;
507
-            default:
508
-                $orderby = array('PRC_order' => $order, 'Price_Type.PRT_order' => $order, 'PRC_ID' => $order);
509
-        }
510
-
511
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
512
-            ? $this->_req_data['paged'] : 1;
513
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
514
-            ? $this->_req_data['perpage'] : $per_page;
515
-
516
-        $_where = array(
517
-            'PRC_is_default' => 1,
518
-            'PRC_deleted'    => $trashed,
519
-        );
520
-
521
-        $offset = ($current_page - 1) * $per_page;
522
-        $limit = array($offset, $per_page);
523
-
524
-        if (isset($this->_req_data['s'])) {
525
-            $sstr = '%' . $this->_req_data['s'] . '%';
526
-            $_where['OR'] = array(
527
-                'PRC_name'            => array('LIKE', $sstr),
528
-                'PRC_desc'            => array('LIKE', $sstr),
529
-                'PRC_amount'          => array('LIKE', $sstr),
530
-                'Price_Type.PRT_name' => array('LIKE', $sstr),
531
-            );
532
-        }
533
-
534
-        $query_params = array(
535
-            $_where,
536
-            'order_by' => $orderby,
537
-            'limit'    => $limit,
538
-            'group_by' => 'PRC_ID',
539
-        );
540
-
541
-        if ($count) {
542
-            return $trashed ? EEM_Price::instance()->count(array($_where))
543
-                : EEM_Price::instance()->count_deleted_and_undeleted(array($_where));
544
-        } else {
545
-            return EEM_Price::instance()->get_all_deleted_and_undeleted($query_params);
546
-        }
547
-    }
548
-
549
-
550
-    /**
551
-     *        _price_details
552
-     *
553
-     * @access protected
554
-     * @return void
555
-     */
556
-    protected function _edit_price_details()
557
-    {
558
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
559
-        // grab price ID
560
-        $PRC_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id'])
561
-            : false;
562
-        // change page title based on request action
563
-        switch ($this->_req_action) {
564
-            case 'add_new_price':
565
-                $this->_admin_page_title = esc_html__('Add New Price', 'event_espresso');
566
-                break;
567
-            case 'edit_price':
568
-                $this->_admin_page_title = esc_html__('Edit Price', 'event_espresso');
569
-                break;
570
-            default:
571
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
572
-        }
573
-        // add PRC_ID to title if editing
574
-        $this->_admin_page_title = $PRC_ID ? $this->_admin_page_title . ' # ' . $PRC_ID : $this->_admin_page_title;
575
-
576
-        // get prices
577
-        require_once(EE_MODELS . 'EEM_Price.model.php');
578
-        $PRC = EEM_Price::instance();
579
-
580
-        if ($PRC_ID) {
581
-            $price = $PRC->get_one_by_ID($PRC_ID);
582
-            $additional_hidden_fields = array(
583
-                'PRC_ID' => array('type' => 'hidden', 'value' => $PRC_ID),
584
-            );
585
-            $this->_set_add_edit_form_tags('update_price', $additional_hidden_fields);
586
-        } else {
587
-            $price = $PRC->get_new_price();
588
-            $this->_set_add_edit_form_tags('insert_price');
589
-        }
590
-
591
-        $this->_template_args['PRC_ID'] = $PRC_ID;
592
-        $this->_template_args['price'] = $price;
593
-
594
-        // get price types
595
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
596
-        $PRT = EEM_Price_Type::instance();
597
-        $price_types = $PRT->get_all(array(array('PBT_ID' => array('!=', 1))));
598
-        $price_type_names = array();
599
-        if (empty($price_types)) {
600
-            $msg = esc_html__(
601
-                'You have no price types defined. Please add a price type before adding a price.',
602
-                'event_espresso'
603
-            );
604
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
605
-            exit();
606
-        } else {
607
-            foreach ($price_types as $type) {
608
-                // if ($type->is_global()) {
609
-                $price_type_names[] = array('id' => $type->ID(), 'text' => $type->name());
610
-            // }
611
-            }
612
-        }
613
-
614
-        $this->_template_args['price_types'] = $price_type_names;
615
-        $this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
616
-
617
-        $this->_set_publish_post_box_vars('id', $PRC_ID);
618
-        // the details template wrapper
619
-        $this->display_admin_page_with_sidebar();
620
-    }
621
-
622
-
623
-    /**
624
-     *        declare price details page metaboxes
625
-     *
626
-     * @access protected
627
-     * @return void
628
-     */
629
-    protected function _price_details_meta_boxes()
630
-    {
631
-        add_meta_box(
632
-            'edit-price-details-mbox',
633
-            esc_html__('Default Price Details', 'event_espresso'),
634
-            array($this, '_edit_price_details_meta_box'),
635
-            $this->wp_page_slug,
636
-            'normal',
637
-            'high'
638
-        );
639
-    }
640
-
641
-
642
-    /**
643
-     *        _edit_price_details_meta_box
644
-     *
645
-     * @access public
646
-     * @return void
647
-     */
648
-    public function _edit_price_details_meta_box()
649
-    {
650
-        echo EEH_Template::display_template(
651
-            PRICING_TEMPLATE_PATH . 'pricing_details_main_meta_box.template.php',
652
-            $this->_template_args,
653
-            true
654
-        );
655
-    }
656
-
657
-
658
-    /**
659
-     *        set_price_column_values
660
-     *
661
-     * @access protected
662
-     * @return array
663
-     */
664
-    protected function set_price_column_values()
665
-    {
666
-
667
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
668
-
669
-        $set_column_values = array(
670
-            'PRT_ID'         => absint($this->_req_data['PRT_ID']),
671
-            'PRC_amount'     => $this->_req_data['PRC_amount'],
672
-            'PRC_name'       => $this->_req_data['PRC_name'],
673
-            'PRC_desc'       => $this->_req_data['PRC_desc'],
674
-            'PRC_is_default' => 1,
675
-            'PRC_overrides'  => null,
676
-            'PRC_order'      => 0,
677
-            'PRC_deleted'    => 0,
678
-            'PRC_parent'     => 0,
679
-        );
680
-        return $set_column_values;
681
-    }
682
-
683
-
684
-    /**
685
-     *        insert_or_update_price
686
-     *
687
-     * @param boolean $insert - whether to insert or update
688
-     * @access protected
689
-     * @return void
690
-     */
691
-    protected function _insert_or_update_price($insert = false)
692
-    {
693
-
694
-        // echo '<h3>'. __CLASS__ . '->' . __FUNCTION__ . ' <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h3>';
695
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
696
-
697
-        require_once(EE_MODELS . 'EEM_Price.model.php');
698
-        $PRC = EEM_Price::instance();
699
-
700
-        // why be so pessimistic ???  : (
701
-        $success = 0;
702
-
703
-        $set_column_values = $this->set_price_column_values();
704
-        // is this a new Price ?
705
-        if ($insert) {
706
-            // run the insert
707
-            if ($PRC_ID = $PRC->insert($set_column_values)) {
708
-                // make sure this new price modifier is attached to the ticket but ONLY if it is not a tax type
709
-                $PR = EEM_price::instance()->get_one_by_ID($PRC_ID);
710
-                if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
711
-                    $ticket = EEM_Ticket::instance()->get_one_by_ID(1);
712
-                    $ticket->_add_relation_to($PR, 'Price');
713
-                    $ticket->save();
714
-                }
715
-                $success = 1;
716
-            } else {
717
-                $PRC_ID = false;
718
-                $success = 0;
719
-            }
720
-            $action_desc = 'created';
721
-        } else {
722
-            $PRC_ID = absint($this->_req_data['PRC_ID']);
723
-            // run the update
724
-            $where_cols_n_values = array('PRC_ID' => $PRC_ID);
725
-            if ($PRC->update($set_column_values, array($where_cols_n_values))) {
726
-                $success = 1;
727
-            }
728
-
729
-            $PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
730
-            if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
731
-                // if this is $PRC_ID == 1, then we need to update the default ticket attached to this price so the TKT_price value is updated.
732
-                if ($PRC_ID === 1) {
733
-                    $ticket = $PR->get_first_related('Ticket');
734
-                    if ($ticket) {
735
-                        $ticket->set('TKT_price', $PR->get('PRC_amount'));
736
-                        $ticket->set('TKT_name', $PR->get('PRC_name'));
737
-                        $ticket->set('TKT_description', $PR->get('PRC_desc'));
738
-                        $ticket->save();
739
-                    }
740
-                } else {
741
-                    // we make sure this price is attached to base ticket. but ONLY if its not a tax ticket type.
742
-                    $ticket = EEM_Ticket::instance()->get_one_by_ID(1);
743
-                    $ticket->_add_relation_to($PRC_ID, 'Price');
744
-                    $ticket->save();
745
-                }
746
-            }
747
-
748
-            $action_desc = 'updated';
749
-        }
750
-
751
-        $query_args = array('action' => 'edit_price', 'id' => $PRC_ID);
752
-
753
-        $this->_redirect_after_action($success, 'Prices', $action_desc, $query_args);
754
-    }
755
-
756
-
757
-    /**
758
-     *        _trash_or_restore_price
759
-     *
760
-     * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
761
-     * @access protected
762
-     * @return void
763
-     */
764
-    protected function _trash_or_restore_price($trash = true)
765
-    {
766
-
767
-        // echo '<h3>'. __CLASS__ . '->' . __FUNCTION__ . ' <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h3>';
768
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
769
-
770
-        require_once(EE_MODELS . 'EEM_Price.model.php');
771
-        $PRC = EEM_Price::instance();
772
-
773
-        $success = 1;
774
-        $PRC_deleted = $trash ? true : false;
775
-
776
-        // get base ticket for updating
777
-        $ticket = EEM_Ticket::instance()->get_one_by_ID(1);
778
-        // Checkboxes
779
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
780
-            // if array has more than one element than success message should be plural
781
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
782
-            // cycle thru checkboxes
783
-            while (list($PRC_ID, $value) = each($this->_req_data['checkbox'])) {
784
-                if (! $PRC->update_by_ID(array('PRC_deleted' => $PRC_deleted), absint($PRC_ID))) {
785
-                    $success = 0;
786
-                } else {
787
-                    $PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
788
-                    if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
789
-                        // if trashing then remove relations to base default ticket.  If restoring then add back to base default ticket
790
-                        if ($PRC_deleted) {
791
-                            $ticket->_remove_relation_to($PRC_ID, 'Price');
792
-                        } else {
793
-                            $ticket->_add_relation_to($PRC_ID, 'Price');
794
-                        }
795
-                        $ticket->save();
796
-                    }
797
-                }
798
-            }
799
-        } else {
800
-            // grab single id and delete
801
-            $PRC_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
802
-            if (empty($PRC_ID) || ! $PRC->update_by_ID(array('PRC_deleted' => $PRC_deleted), $PRC_ID)) {
803
-                $success = 0;
804
-            } else {
805
-                $PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
806
-                if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
807
-                    // if trashing then remove relations to base default ticket.  If restoring then add back to base default ticket
808
-                    if ($PRC_deleted) {
809
-                        $ticket->_remove_relation_to($PRC_ID, 'Price');
810
-                    } else {
811
-                        $ticket->_add_relation_to($PRC_ID, 'Price');
812
-                    }
813
-                    $ticket->save();
814
-                }
815
-            }
816
-        }
817
-        $query_args = array(
818
-            'action' => 'default',
819
-        );
820
-
821
-        if ($success) {
822
-            if ($trash) {
823
-                $msg = $success == 2
824
-                    ? esc_html__('The Prices have been trashed.', 'event_espresso')
825
-                    : esc_html__(
826
-                        'The Price has been trashed.',
827
-                        'event_espresso'
828
-                    );
829
-            } else {
830
-                $msg = $success == 2
831
-                    ? esc_html__('The Prices have been restored.', 'event_espresso')
832
-                    : esc_html__(
833
-                        'The Price has been restored.',
834
-                        'event_espresso'
835
-                    );
836
-            }
837
-
838
-            EE_Error::add_success($msg);
839
-        }
840
-
841
-        $this->_redirect_after_action(false, '', '', $query_args, true);
842
-    }
843
-
844
-
845
-    /**
846
-     *        _delete_price
847
-     *
848
-     * @access protected
849
-     * @return void
850
-     */
851
-    protected function _delete_price()
852
-    {
853
-
854
-        // echo '<h3>'. __CLASS__ . '->' . __FUNCTION__ . ' <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h3>';
855
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
856
-
857
-        require_once(EE_MODELS . 'EEM_Price.model.php');
858
-        $PRC = EEM_Price::instance();
859
-
860
-        $success = 1;
861
-        // Checkboxes
862
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
863
-            // if array has more than one element than success message should be plural
864
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
865
-            // cycle thru bulk action checkboxes
866
-            while (list($PRC_ID, $value) = each($this->_req_data['checkbox'])) {
867
-                if (! $PRC->delete_permanently_by_ID(absint($PRC_ID))) {
868
-                    $success = 0;
869
-                }
870
-            }
871
-        } else {
872
-            // grab single id and delete
873
-            $PRC_ID = absint($this->_req_data['id']);
874
-            if (! $PRC->delete_permanently_by_ID($PRC_ID)) {
875
-                $success = 0;
876
-            }
877
-        }
878
-
879
-        $this->_redirect_after_action($success, 'Prices', 'deleted', array());
880
-    }
881
-
882
-
883
-    public function update_price_order()
884
-    {
885
-        $success = esc_html__('Price order was updated successfully.', 'event_espresso');
886
-
887
-        // grab our row IDs
888
-        $row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids']) ? explode(
889
-            ',',
890
-            rtrim(
891
-                $this->_req_data['row_ids'],
892
-                ','
893
-            )
894
-        ) : false;
895
-
896
-        if (is_array($row_ids)) {
897
-            for ($i = 0; $i < count($row_ids); $i++) {
898
-                // Update the prices when re-ordering
899
-                $id = absint($row_ids[ $i ]);
900
-                if (
901
-                    EEM_Price::instance()->update(
902
-                        array('PRC_order' => $i + 1),
903
-                        array(array('PRC_ID' => $id))
904
-                    ) === false
905
-                ) {
906
-                    $success = false;
907
-                }
908
-            }
909
-        } else {
910
-            $success = false;
911
-        }
912
-
913
-        $errors = ! $success ? esc_html__('An error occurred. The price order was not updated.', 'event_espresso') : false;
914
-
915
-        echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
916
-        die();
917
-    }
918
-
919
-
920
-
921
-
922
-
923
-
924
-    /**************************************************************************************************************************************************************
15
+	/**
16
+	 *    constructor
17
+	 *
18
+	 * @Constructor
19
+	 * @access public
20
+	 * @param bool $routing
21
+	 * @return Pricing_Admin_Page
22
+	 */
23
+	public function __construct($routing = true)
24
+	{
25
+		parent::__construct($routing);
26
+	}
27
+
28
+
29
+	protected function _init_page_props()
30
+	{
31
+		$this->page_slug = PRICING_PG_SLUG;
32
+		$this->page_label = PRICING_LABEL;
33
+		$this->_admin_base_url = PRICING_ADMIN_URL;
34
+		$this->_admin_base_path = PRICING_ADMIN;
35
+	}
36
+
37
+
38
+	protected function _ajax_hooks()
39
+	{
40
+		add_action('wp_ajax_espresso_update_prices_order', array($this, 'update_price_order'));
41
+	}
42
+
43
+
44
+	protected function _define_page_props()
45
+	{
46
+		$this->_admin_page_title = PRICING_LABEL;
47
+		$this->_labels = array(
48
+			'buttons' => array(
49
+				'add'         => esc_html__('Add New Default Price', 'event_espresso'),
50
+				'edit'        => esc_html__('Edit Default Price', 'event_espresso'),
51
+				'delete'      => esc_html__('Delete Default Price', 'event_espresso'),
52
+				'add_type'    => esc_html__('Add New Default Price Type', 'event_espresso'),
53
+				'edit_type'   => esc_html__('Edit Price Type', 'event_espresso'),
54
+				'delete_type' => esc_html__('Delete Price Type', 'event_espresso'),
55
+			),
56
+		);
57
+	}
58
+
59
+
60
+	/**
61
+	 *        an array for storing request actions and their corresponding methods
62
+	 *
63
+	 * @access private
64
+	 * @return void
65
+	 */
66
+	protected function _set_page_routes()
67
+	{
68
+		$prc_id = ! empty($this->_req_data['PRC_ID']) && ! is_array($this->_req_data['PRC_ID'])
69
+			? $this->_req_data['PRC_ID'] : 0;
70
+		$prt_id = ! empty($this->_req_data['PRT_ID']) && ! is_array($this->_req_data['PRT_ID'])
71
+			? $this->_req_data['PRT_ID'] : 0;
72
+		$this->_page_routes = array(
73
+			'default'                     => array(
74
+				'func'       => '_price_overview_list_table',
75
+				'capability' => 'ee_read_default_prices',
76
+			),
77
+			'add_new_price'               => array(
78
+				'func'       => '_edit_price_details',
79
+				'args'       => array('new_price' => true),
80
+				'capability' => 'ee_edit_default_prices',
81
+			),
82
+			'edit_price'                  => array(
83
+				'func'       => '_edit_price_details',
84
+				'args'       => array('new_price' => false),
85
+				'capability' => 'ee_edit_default_price',
86
+				'obj_id'     => $prc_id,
87
+			),
88
+			'insert_price'                => array(
89
+				'func'       => '_insert_or_update_price',
90
+				'args'       => array('new_price' => true),
91
+				'noheader'   => true,
92
+				'capability' => 'ee_edit_default_prices',
93
+			),
94
+			'update_price'                => array(
95
+				'func'       => '_insert_or_update_price',
96
+				'args'       => array('new_price' => false),
97
+				'noheader'   => true,
98
+				'capability' => 'ee_edit_default_price',
99
+				'obj_id'     => $prc_id,
100
+			),
101
+			'trash_price'                 => array(
102
+				'func'       => '_trash_or_restore_price',
103
+				'args'       => array('trash' => true),
104
+				'noheader'   => true,
105
+				'capability' => 'ee_delete_default_price',
106
+				'obj_id'     => $prc_id,
107
+			),
108
+			'restore_price'               => array(
109
+				'func'       => '_trash_or_restore_price',
110
+				'args'       => array('trash' => false),
111
+				'noheader'   => true,
112
+				'capability' => 'ee_delete_default_price',
113
+				'obj_id'     => $prc_id,
114
+			),
115
+			'delete_price'                => array(
116
+				'func'       => '_delete_price',
117
+				'noheader'   => true,
118
+				'capability' => 'ee_delete_default_price',
119
+				'obj_id'     => $prc_id,
120
+			),
121
+			'espresso_update_price_order' => array(
122
+				'func'       => 'update_price_order',
123
+				'noheader'   => true,
124
+				'capability' => 'ee_edit_default_prices',
125
+			),
126
+			// price types
127
+			'price_types'                 => array(
128
+				'func'       => '_price_types_overview_list_table',
129
+				'capability' => 'ee_read_default_price_types',
130
+			),
131
+			'add_new_price_type'          => array(
132
+				'func'       => '_edit_price_type_details',
133
+				'capability' => 'ee_edit_default_price_types',
134
+			),
135
+			'edit_price_type'             => array(
136
+				'func'       => '_edit_price_type_details',
137
+				'capability' => 'ee_edit_default_price_type',
138
+				'obj_id'     => $prt_id,
139
+			),
140
+			'insert_price_type'           => array(
141
+				'func'       => '_insert_or_update_price_type',
142
+				'args'       => array('new_price_type' => true),
143
+				'noheader'   => true,
144
+				'capability' => 'ee_edit_default_price_types',
145
+			),
146
+			'update_price_type'           => array(
147
+				'func'       => '_insert_or_update_price_type',
148
+				'args'       => array('new_price_type' => false),
149
+				'noheader'   => true,
150
+				'capability' => 'ee_edit_default_price_type',
151
+				'obj_id'     => $prt_id,
152
+			),
153
+			'trash_price_type'            => array(
154
+				'func'       => '_trash_or_restore_price_type',
155
+				'args'       => array('trash' => true),
156
+				'noheader'   => true,
157
+				'capability' => 'ee_delete_default_price_type',
158
+				'obj_id'     => $prt_id,
159
+			),
160
+			'restore_price_type'          => array(
161
+				'func'       => '_trash_or_restore_price_type',
162
+				'args'       => array('trash' => false),
163
+				'noheader'   => true,
164
+				'capability' => 'ee_delete_default_price_type',
165
+				'obj_id'     => $prt_id,
166
+			),
167
+			'delete_price_type'           => array(
168
+				'func'       => '_delete_price_type',
169
+				'noheader'   => true,
170
+				'capability' => 'ee_delete_default_price_type',
171
+				'obj_id'     => $prt_id,
172
+			),
173
+			'tax_settings'                => array(
174
+				'func'       => '_tax_settings',
175
+				'capability' => 'manage_options',
176
+			),
177
+			'update_tax_settings'         => array(
178
+				'func'       => '_update_tax_settings',
179
+				'capability' => 'manage_options',
180
+				'noheader'   => true,
181
+			),
182
+		);
183
+	}
184
+
185
+
186
+	protected function _set_page_config()
187
+	{
188
+
189
+		$this->_page_config = array(
190
+			'default'            => array(
191
+				'nav'           => array(
192
+					'label' => esc_html__('Default Pricing', 'event_espresso'),
193
+					'order' => 10,
194
+				),
195
+				'list_table'    => 'Prices_List_Table',
196
+				'help_tabs'     => array(
197
+					'pricing_default_pricing_help_tab'                           => array(
198
+						'title'    => esc_html__('Default Pricing', 'event_espresso'),
199
+						'filename' => 'pricing_default_pricing',
200
+					),
201
+					'pricing_default_pricing_table_column_headings_help_tab'     => array(
202
+						'title'    => esc_html__('Default Pricing Table Column Headings', 'event_espresso'),
203
+						'filename' => 'pricing_default_pricing_table_column_headings',
204
+					),
205
+					'pricing_default_pricing_views_bulk_actions_search_help_tab' => array(
206
+						'title'    => esc_html__('Default Pricing Views & Bulk Actions & Search', 'event_espresso'),
207
+						'filename' => 'pricing_default_pricing_views_bulk_actions_search',
208
+					),
209
+				),
210
+				'require_nonce' => false,
211
+			),
212
+			'add_new_price'      => array(
213
+				'nav'           => array(
214
+					'label'      => esc_html__('Add New Default Price', 'event_espresso'),
215
+					'order'      => 20,
216
+					'persistent' => false,
217
+				),
218
+				'help_tabs'     => array(
219
+					'add_new_default_price_help_tab' => array(
220
+						'title'    => esc_html__('Add New Default Price', 'event_espresso'),
221
+						'filename' => 'pricing_add_new_default_price',
222
+					),
223
+				),
224
+				'metaboxes'     => array('_publish_post_box', '_espresso_news_post_box', '_price_details_meta_boxes'),
225
+				'require_nonce' => false,
226
+			),
227
+			'edit_price'         => array(
228
+				'nav'           => array(
229
+					'label'      => esc_html__('Edit Default Price', 'event_espresso'),
230
+					'order'      => 20,
231
+					'url'        => isset($this->_req_data['id']) ? add_query_arg(
232
+						array('id' => $this->_req_data['id']),
233
+						$this->_current_page_view_url
234
+					) : $this->_admin_base_url,
235
+					'persistent' => false,
236
+				),
237
+				'metaboxes'     => array('_publish_post_box', '_espresso_news_post_box', '_price_details_meta_boxes'),
238
+				'help_tabs'     => array(
239
+					'edit_default_price_help_tab' => array(
240
+						'title'    => esc_html__('Edit Default Price', 'event_espresso'),
241
+						'filename' => 'pricing_edit_default_price',
242
+					),
243
+				),
244
+				'require_nonce' => false,
245
+			),
246
+			'price_types'        => array(
247
+				'nav'           => array(
248
+					'label' => esc_html__('Price Types', 'event_espresso'),
249
+					'order' => 30,
250
+				),
251
+				'list_table'    => 'Price_Types_List_Table',
252
+				'help_tabs'     => array(
253
+					'pricing_price_types_help_tab'                           => array(
254
+						'title'    => esc_html__('Price Types', 'event_espresso'),
255
+						'filename' => 'pricing_price_types',
256
+					),
257
+					'pricing_price_types_table_column_headings_help_tab'     => array(
258
+						'title'    => esc_html__('Price Types Table Column Headings', 'event_espresso'),
259
+						'filename' => 'pricing_price_types_table_column_headings',
260
+					),
261
+					'pricing_price_types_views_bulk_actions_search_help_tab' => array(
262
+						'title'    => esc_html__('Price Types Views & Bulk Actions & Search', 'event_espresso'),
263
+						'filename' => 'pricing_price_types_views_bulk_actions_search',
264
+					),
265
+				),
266
+				'metaboxes'     => array('_espresso_news_post_box', '_espresso_links_post_box'),
267
+				'require_nonce' => false,
268
+			),
269
+			'add_new_price_type' => array(
270
+				'nav'           => array(
271
+					'label'      => esc_html__('Add New Price Type', 'event_espresso'),
272
+					'order'      => 40,
273
+					'persistent' => false,
274
+				),
275
+				'help_tabs'     => array(
276
+					'add_new_price_type_help_tab' => array(
277
+						'title'    => esc_html__('Add New Price Type', 'event_espresso'),
278
+						'filename' => 'pricing_add_new_price_type',
279
+					),
280
+				),
281
+				'metaboxes'     => array(
282
+					'_publish_post_box',
283
+					'_espresso_news_post_box',
284
+					'_price_type_details_meta_boxes',
285
+				),
286
+				'require_nonce' => false,
287
+			),
288
+			'edit_price_type'    => array(
289
+				'nav'       => array(
290
+					'label'      => esc_html__('Edit Price Type', 'event_espresso'),
291
+					'order'      => 40,
292
+					'persistent' => false,
293
+				),
294
+				'help_tabs' => array(
295
+					'edit_price_type_help_tab' => array(
296
+						'title'    => esc_html__('Edit Price Type', 'event_espresso'),
297
+						'filename' => 'pricing_edit_price_type',
298
+					),
299
+				),
300
+				'metaboxes' => array('_publish_post_box', '_espresso_news_post_box', '_price_type_details_meta_boxes'),
301
+
302
+				'require_nonce' => false,
303
+			),
304
+			'tax_settings'       => array(
305
+				'nav'           => array(
306
+					'label' => esc_html__('Tax Settings', 'event_espresso'),
307
+					'order' => 40,
308
+				),
309
+				'labels'        => array(
310
+					'publishbox' => esc_html__('Update Tax Settings', 'event_espresso'),
311
+				),
312
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
313
+				'require_nonce' => true,
314
+			),
315
+		);
316
+	}
317
+
318
+
319
+	protected function _add_screen_options()
320
+	{
321
+		// todo
322
+	}
323
+
324
+
325
+	protected function _add_screen_options_default()
326
+	{
327
+		$this->_per_page_screen_option();
328
+	}
329
+
330
+
331
+	protected function _add_screen_options_price_types()
332
+	{
333
+		$page_title = $this->_admin_page_title;
334
+		$this->_admin_page_title = esc_html__('Price Types', 'event_espresso');
335
+		$this->_per_page_screen_option();
336
+		$this->_admin_page_title = $page_title;
337
+	}
338
+
339
+
340
+	protected function _add_feature_pointers()
341
+	{
342
+	}
343
+
344
+
345
+	public function load_scripts_styles()
346
+	{
347
+		// styles
348
+		wp_enqueue_style('espresso-ui-theme');
349
+		wp_register_style(
350
+			'espresso_PRICING',
351
+			PRICING_ASSETS_URL . 'espresso_pricing_admin.css',
352
+			array(),
353
+			EVENT_ESPRESSO_VERSION
354
+		);
355
+		wp_enqueue_style('espresso_PRICING');
356
+
357
+		// scripts
358
+		wp_enqueue_script('ee_admin_js');
359
+		wp_enqueue_script('jquery-ui-position');
360
+		wp_enqueue_script('jquery-ui-widget');
361
+		// wp_enqueue_script('jquery-ui-dialog');
362
+		// wp_enqueue_script('jquery-ui-draggable');
363
+		// wp_enqueue_script('jquery-ui-datepicker');
364
+		wp_register_script(
365
+			'espresso_PRICING',
366
+			PRICING_ASSETS_URL . 'espresso_pricing_admin.js',
367
+			array('jquery'),
368
+			EVENT_ESPRESSO_VERSION,
369
+			true
370
+		);
371
+		wp_enqueue_script('espresso_PRICING');
372
+	}
373
+
374
+
375
+	public function load_scripts_styles_default()
376
+	{
377
+		wp_enqueue_script('espresso_ajax_table_sorting');
378
+	}
379
+
380
+
381
+	public function admin_footer_scripts()
382
+	{
383
+	}
384
+
385
+	public function admin_init()
386
+	{
387
+	}
388
+
389
+	public function admin_notices()
390
+	{
391
+	}
392
+
393
+
394
+	protected function _set_list_table_views_default()
395
+	{
396
+		$this->_views = array(
397
+			'all' => array(
398
+				'slug'        => 'all',
399
+				'label'       => esc_html__('View All Default Pricing', 'event_espresso'),
400
+				'count'       => 0,
401
+				'bulk_action' => array(
402
+					'trash_price' => esc_html__('Move to Trash', 'event_espresso'),
403
+				),
404
+			),
405
+		);
406
+
407
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_default_prices', 'pricing_trash_price')) {
408
+			$this->_views['trashed'] = array(
409
+				'slug'        => 'trashed',
410
+				'label'       => esc_html__('Trash', 'event_espresso'),
411
+				'count'       => 0,
412
+				'bulk_action' => array(
413
+					'restore_price' => esc_html__('Restore from Trash', 'event_espresso'),
414
+					'delete_price'  => esc_html__('Delete Permanently', 'event_espresso'),
415
+				),
416
+			);
417
+		}
418
+	}
419
+
420
+
421
+	protected function _set_list_table_views_price_types()
422
+	{
423
+		$this->_views = array(
424
+			'all' => array(
425
+				'slug'        => 'all',
426
+				'label'       => esc_html__('All', 'event_espresso'),
427
+				'count'       => 0,
428
+				'bulk_action' => array(
429
+					'trash_price_type' => esc_html__('Move to Trash', 'event_espresso'),
430
+				),
431
+			),
432
+		);
433
+
434
+		if (
435
+			EE_Registry::instance()->CAP->current_user_can(
436
+				'ee_delete_default_price_types',
437
+				'pricing_trash_price_type'
438
+			)
439
+		) {
440
+			$this->_views['trashed'] = array(
441
+				'slug'        => 'trashed',
442
+				'label'       => esc_html__('Trash', 'event_espresso'),
443
+				'count'       => 0,
444
+				'bulk_action' => array(
445
+					'restore_price_type' => esc_html__('Restore from Trash', 'event_espresso'),
446
+					'delete_price_type'  => esc_html__('Delete Permanently', 'event_espresso'),
447
+				),
448
+			);
449
+		}
450
+	}
451
+
452
+
453
+	/**
454
+	 *        generates HTML for main Prices Admin page
455
+	 *
456
+	 * @access protected
457
+	 * @return void
458
+	 */
459
+	protected function _price_overview_list_table()
460
+	{
461
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
462
+			'add_new_price',
463
+			'add',
464
+			array(),
465
+			'add-new-h2'
466
+		);
467
+		$this->admin_page_title .= $this->_learn_more_about_pricing_link();
468
+		$this->_search_btn_label = esc_html__('Default Prices', 'event_espresso');
469
+		$this->display_admin_list_table_page_with_no_sidebar();
470
+	}
471
+
472
+
473
+	/**
474
+	 *    retrieve data for Prices List table
475
+	 *
476
+	 * @access public
477
+	 * @param  int     $per_page how many prices displayed per page
478
+	 * @param  boolean $count    return the count or objects
479
+	 * @param  boolean $trashed  whether the current view is of the trash can - eww yuck!
480
+	 * @return mixed (int|array)  int = count || array of price objects
481
+	 */
482
+	public function get_prices_overview_data($per_page = 10, $count = false, $trashed = false)
483
+	{
484
+
485
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
486
+		// start with an empty array
487
+		$event_pricing = array();
488
+
489
+		require_once(PRICING_ADMIN . 'Prices_List_Table.class.php');
490
+		require_once(EE_MODELS . 'EEM_Price.model.php');
491
+		// $PRC = EEM_Price::instance();
492
+
493
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? '' : $this->_req_data['orderby'];
494
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
495
+			: 'ASC';
496
+
497
+		switch ($this->_req_data['orderby']) {
498
+			case 'name':
499
+				$orderby = array('PRC_name' => $order);
500
+				break;
501
+			case 'type':
502
+				$orderby = array('Price_Type.PRT_name' => $order);
503
+				break;
504
+			case 'amount':
505
+				$orderby = array('PRC_amount' => $order);
506
+				break;
507
+			default:
508
+				$orderby = array('PRC_order' => $order, 'Price_Type.PRT_order' => $order, 'PRC_ID' => $order);
509
+		}
510
+
511
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
512
+			? $this->_req_data['paged'] : 1;
513
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
514
+			? $this->_req_data['perpage'] : $per_page;
515
+
516
+		$_where = array(
517
+			'PRC_is_default' => 1,
518
+			'PRC_deleted'    => $trashed,
519
+		);
520
+
521
+		$offset = ($current_page - 1) * $per_page;
522
+		$limit = array($offset, $per_page);
523
+
524
+		if (isset($this->_req_data['s'])) {
525
+			$sstr = '%' . $this->_req_data['s'] . '%';
526
+			$_where['OR'] = array(
527
+				'PRC_name'            => array('LIKE', $sstr),
528
+				'PRC_desc'            => array('LIKE', $sstr),
529
+				'PRC_amount'          => array('LIKE', $sstr),
530
+				'Price_Type.PRT_name' => array('LIKE', $sstr),
531
+			);
532
+		}
533
+
534
+		$query_params = array(
535
+			$_where,
536
+			'order_by' => $orderby,
537
+			'limit'    => $limit,
538
+			'group_by' => 'PRC_ID',
539
+		);
540
+
541
+		if ($count) {
542
+			return $trashed ? EEM_Price::instance()->count(array($_where))
543
+				: EEM_Price::instance()->count_deleted_and_undeleted(array($_where));
544
+		} else {
545
+			return EEM_Price::instance()->get_all_deleted_and_undeleted($query_params);
546
+		}
547
+	}
548
+
549
+
550
+	/**
551
+	 *        _price_details
552
+	 *
553
+	 * @access protected
554
+	 * @return void
555
+	 */
556
+	protected function _edit_price_details()
557
+	{
558
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
559
+		// grab price ID
560
+		$PRC_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id'])
561
+			: false;
562
+		// change page title based on request action
563
+		switch ($this->_req_action) {
564
+			case 'add_new_price':
565
+				$this->_admin_page_title = esc_html__('Add New Price', 'event_espresso');
566
+				break;
567
+			case 'edit_price':
568
+				$this->_admin_page_title = esc_html__('Edit Price', 'event_espresso');
569
+				break;
570
+			default:
571
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
572
+		}
573
+		// add PRC_ID to title if editing
574
+		$this->_admin_page_title = $PRC_ID ? $this->_admin_page_title . ' # ' . $PRC_ID : $this->_admin_page_title;
575
+
576
+		// get prices
577
+		require_once(EE_MODELS . 'EEM_Price.model.php');
578
+		$PRC = EEM_Price::instance();
579
+
580
+		if ($PRC_ID) {
581
+			$price = $PRC->get_one_by_ID($PRC_ID);
582
+			$additional_hidden_fields = array(
583
+				'PRC_ID' => array('type' => 'hidden', 'value' => $PRC_ID),
584
+			);
585
+			$this->_set_add_edit_form_tags('update_price', $additional_hidden_fields);
586
+		} else {
587
+			$price = $PRC->get_new_price();
588
+			$this->_set_add_edit_form_tags('insert_price');
589
+		}
590
+
591
+		$this->_template_args['PRC_ID'] = $PRC_ID;
592
+		$this->_template_args['price'] = $price;
593
+
594
+		// get price types
595
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
596
+		$PRT = EEM_Price_Type::instance();
597
+		$price_types = $PRT->get_all(array(array('PBT_ID' => array('!=', 1))));
598
+		$price_type_names = array();
599
+		if (empty($price_types)) {
600
+			$msg = esc_html__(
601
+				'You have no price types defined. Please add a price type before adding a price.',
602
+				'event_espresso'
603
+			);
604
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
605
+			exit();
606
+		} else {
607
+			foreach ($price_types as $type) {
608
+				// if ($type->is_global()) {
609
+				$price_type_names[] = array('id' => $type->ID(), 'text' => $type->name());
610
+			// }
611
+			}
612
+		}
613
+
614
+		$this->_template_args['price_types'] = $price_type_names;
615
+		$this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
616
+
617
+		$this->_set_publish_post_box_vars('id', $PRC_ID);
618
+		// the details template wrapper
619
+		$this->display_admin_page_with_sidebar();
620
+	}
621
+
622
+
623
+	/**
624
+	 *        declare price details page metaboxes
625
+	 *
626
+	 * @access protected
627
+	 * @return void
628
+	 */
629
+	protected function _price_details_meta_boxes()
630
+	{
631
+		add_meta_box(
632
+			'edit-price-details-mbox',
633
+			esc_html__('Default Price Details', 'event_espresso'),
634
+			array($this, '_edit_price_details_meta_box'),
635
+			$this->wp_page_slug,
636
+			'normal',
637
+			'high'
638
+		);
639
+	}
640
+
641
+
642
+	/**
643
+	 *        _edit_price_details_meta_box
644
+	 *
645
+	 * @access public
646
+	 * @return void
647
+	 */
648
+	public function _edit_price_details_meta_box()
649
+	{
650
+		echo EEH_Template::display_template(
651
+			PRICING_TEMPLATE_PATH . 'pricing_details_main_meta_box.template.php',
652
+			$this->_template_args,
653
+			true
654
+		);
655
+	}
656
+
657
+
658
+	/**
659
+	 *        set_price_column_values
660
+	 *
661
+	 * @access protected
662
+	 * @return array
663
+	 */
664
+	protected function set_price_column_values()
665
+	{
666
+
667
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
668
+
669
+		$set_column_values = array(
670
+			'PRT_ID'         => absint($this->_req_data['PRT_ID']),
671
+			'PRC_amount'     => $this->_req_data['PRC_amount'],
672
+			'PRC_name'       => $this->_req_data['PRC_name'],
673
+			'PRC_desc'       => $this->_req_data['PRC_desc'],
674
+			'PRC_is_default' => 1,
675
+			'PRC_overrides'  => null,
676
+			'PRC_order'      => 0,
677
+			'PRC_deleted'    => 0,
678
+			'PRC_parent'     => 0,
679
+		);
680
+		return $set_column_values;
681
+	}
682
+
683
+
684
+	/**
685
+	 *        insert_or_update_price
686
+	 *
687
+	 * @param boolean $insert - whether to insert or update
688
+	 * @access protected
689
+	 * @return void
690
+	 */
691
+	protected function _insert_or_update_price($insert = false)
692
+	{
693
+
694
+		// echo '<h3>'. __CLASS__ . '->' . __FUNCTION__ . ' <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h3>';
695
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
696
+
697
+		require_once(EE_MODELS . 'EEM_Price.model.php');
698
+		$PRC = EEM_Price::instance();
699
+
700
+		// why be so pessimistic ???  : (
701
+		$success = 0;
702
+
703
+		$set_column_values = $this->set_price_column_values();
704
+		// is this a new Price ?
705
+		if ($insert) {
706
+			// run the insert
707
+			if ($PRC_ID = $PRC->insert($set_column_values)) {
708
+				// make sure this new price modifier is attached to the ticket but ONLY if it is not a tax type
709
+				$PR = EEM_price::instance()->get_one_by_ID($PRC_ID);
710
+				if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
711
+					$ticket = EEM_Ticket::instance()->get_one_by_ID(1);
712
+					$ticket->_add_relation_to($PR, 'Price');
713
+					$ticket->save();
714
+				}
715
+				$success = 1;
716
+			} else {
717
+				$PRC_ID = false;
718
+				$success = 0;
719
+			}
720
+			$action_desc = 'created';
721
+		} else {
722
+			$PRC_ID = absint($this->_req_data['PRC_ID']);
723
+			// run the update
724
+			$where_cols_n_values = array('PRC_ID' => $PRC_ID);
725
+			if ($PRC->update($set_column_values, array($where_cols_n_values))) {
726
+				$success = 1;
727
+			}
728
+
729
+			$PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
730
+			if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
731
+				// if this is $PRC_ID == 1, then we need to update the default ticket attached to this price so the TKT_price value is updated.
732
+				if ($PRC_ID === 1) {
733
+					$ticket = $PR->get_first_related('Ticket');
734
+					if ($ticket) {
735
+						$ticket->set('TKT_price', $PR->get('PRC_amount'));
736
+						$ticket->set('TKT_name', $PR->get('PRC_name'));
737
+						$ticket->set('TKT_description', $PR->get('PRC_desc'));
738
+						$ticket->save();
739
+					}
740
+				} else {
741
+					// we make sure this price is attached to base ticket. but ONLY if its not a tax ticket type.
742
+					$ticket = EEM_Ticket::instance()->get_one_by_ID(1);
743
+					$ticket->_add_relation_to($PRC_ID, 'Price');
744
+					$ticket->save();
745
+				}
746
+			}
747
+
748
+			$action_desc = 'updated';
749
+		}
750
+
751
+		$query_args = array('action' => 'edit_price', 'id' => $PRC_ID);
752
+
753
+		$this->_redirect_after_action($success, 'Prices', $action_desc, $query_args);
754
+	}
755
+
756
+
757
+	/**
758
+	 *        _trash_or_restore_price
759
+	 *
760
+	 * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
761
+	 * @access protected
762
+	 * @return void
763
+	 */
764
+	protected function _trash_or_restore_price($trash = true)
765
+	{
766
+
767
+		// echo '<h3>'. __CLASS__ . '->' . __FUNCTION__ . ' <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h3>';
768
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
769
+
770
+		require_once(EE_MODELS . 'EEM_Price.model.php');
771
+		$PRC = EEM_Price::instance();
772
+
773
+		$success = 1;
774
+		$PRC_deleted = $trash ? true : false;
775
+
776
+		// get base ticket for updating
777
+		$ticket = EEM_Ticket::instance()->get_one_by_ID(1);
778
+		// Checkboxes
779
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
780
+			// if array has more than one element than success message should be plural
781
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
782
+			// cycle thru checkboxes
783
+			while (list($PRC_ID, $value) = each($this->_req_data['checkbox'])) {
784
+				if (! $PRC->update_by_ID(array('PRC_deleted' => $PRC_deleted), absint($PRC_ID))) {
785
+					$success = 0;
786
+				} else {
787
+					$PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
788
+					if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
789
+						// if trashing then remove relations to base default ticket.  If restoring then add back to base default ticket
790
+						if ($PRC_deleted) {
791
+							$ticket->_remove_relation_to($PRC_ID, 'Price');
792
+						} else {
793
+							$ticket->_add_relation_to($PRC_ID, 'Price');
794
+						}
795
+						$ticket->save();
796
+					}
797
+				}
798
+			}
799
+		} else {
800
+			// grab single id and delete
801
+			$PRC_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
802
+			if (empty($PRC_ID) || ! $PRC->update_by_ID(array('PRC_deleted' => $PRC_deleted), $PRC_ID)) {
803
+				$success = 0;
804
+			} else {
805
+				$PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
806
+				if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
807
+					// if trashing then remove relations to base default ticket.  If restoring then add back to base default ticket
808
+					if ($PRC_deleted) {
809
+						$ticket->_remove_relation_to($PRC_ID, 'Price');
810
+					} else {
811
+						$ticket->_add_relation_to($PRC_ID, 'Price');
812
+					}
813
+					$ticket->save();
814
+				}
815
+			}
816
+		}
817
+		$query_args = array(
818
+			'action' => 'default',
819
+		);
820
+
821
+		if ($success) {
822
+			if ($trash) {
823
+				$msg = $success == 2
824
+					? esc_html__('The Prices have been trashed.', 'event_espresso')
825
+					: esc_html__(
826
+						'The Price has been trashed.',
827
+						'event_espresso'
828
+					);
829
+			} else {
830
+				$msg = $success == 2
831
+					? esc_html__('The Prices have been restored.', 'event_espresso')
832
+					: esc_html__(
833
+						'The Price has been restored.',
834
+						'event_espresso'
835
+					);
836
+			}
837
+
838
+			EE_Error::add_success($msg);
839
+		}
840
+
841
+		$this->_redirect_after_action(false, '', '', $query_args, true);
842
+	}
843
+
844
+
845
+	/**
846
+	 *        _delete_price
847
+	 *
848
+	 * @access protected
849
+	 * @return void
850
+	 */
851
+	protected function _delete_price()
852
+	{
853
+
854
+		// echo '<h3>'. __CLASS__ . '->' . __FUNCTION__ . ' <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h3>';
855
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
856
+
857
+		require_once(EE_MODELS . 'EEM_Price.model.php');
858
+		$PRC = EEM_Price::instance();
859
+
860
+		$success = 1;
861
+		// Checkboxes
862
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
863
+			// if array has more than one element than success message should be plural
864
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
865
+			// cycle thru bulk action checkboxes
866
+			while (list($PRC_ID, $value) = each($this->_req_data['checkbox'])) {
867
+				if (! $PRC->delete_permanently_by_ID(absint($PRC_ID))) {
868
+					$success = 0;
869
+				}
870
+			}
871
+		} else {
872
+			// grab single id and delete
873
+			$PRC_ID = absint($this->_req_data['id']);
874
+			if (! $PRC->delete_permanently_by_ID($PRC_ID)) {
875
+				$success = 0;
876
+			}
877
+		}
878
+
879
+		$this->_redirect_after_action($success, 'Prices', 'deleted', array());
880
+	}
881
+
882
+
883
+	public function update_price_order()
884
+	{
885
+		$success = esc_html__('Price order was updated successfully.', 'event_espresso');
886
+
887
+		// grab our row IDs
888
+		$row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids']) ? explode(
889
+			',',
890
+			rtrim(
891
+				$this->_req_data['row_ids'],
892
+				','
893
+			)
894
+		) : false;
895
+
896
+		if (is_array($row_ids)) {
897
+			for ($i = 0; $i < count($row_ids); $i++) {
898
+				// Update the prices when re-ordering
899
+				$id = absint($row_ids[ $i ]);
900
+				if (
901
+					EEM_Price::instance()->update(
902
+						array('PRC_order' => $i + 1),
903
+						array(array('PRC_ID' => $id))
904
+					) === false
905
+				) {
906
+					$success = false;
907
+				}
908
+			}
909
+		} else {
910
+			$success = false;
911
+		}
912
+
913
+		$errors = ! $success ? esc_html__('An error occurred. The price order was not updated.', 'event_espresso') : false;
914
+
915
+		echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
916
+		die();
917
+	}
918
+
919
+
920
+
921
+
922
+
923
+
924
+	/**************************************************************************************************************************************************************
925 925
      ********************************************************************  TICKET PRICE TYPES  ******************************************************************
926 926
      **************************************************************************************************************************************************************/
927 927
 
928 928
 
929
-    /**
930
-     *        generates HTML for main Prices Admin page
931
-     *
932
-     * @access protected
933
-     * @return void
934
-     */
935
-    protected function _price_types_overview_list_table()
936
-    {
937
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
938
-            'add_new_price_type',
939
-            'add_type',
940
-            array(),
941
-            'add-new-h2'
942
-        );
943
-        $this->admin_page_title .= $this->_learn_more_about_pricing_link();
944
-        $this->_search_btn_label = esc_html__('Price Types', 'event_espresso');
945
-        $this->display_admin_list_table_page_with_no_sidebar();
946
-    }
947
-
948
-
949
-    /**
950
-     *    retrieve data for Price Types List table
951
-     *
952
-     * @access public
953
-     * @param  int     $per_page how many prices displayed per page
954
-     * @param  boolean $count    return the count or objects
955
-     * @param  boolean $trashed  whether the current view is of the trash can - eww yuck!
956
-     * @return mixed (int|array)  int = count || array of price objects
957
-     */
958
-    public function get_price_types_overview_data($per_page = 10, $count = false, $trashed = false)
959
-    {
960
-
961
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
962
-        // start with an empty array
963
-
964
-        require_once(PRICING_ADMIN . 'Price_Types_List_Table.class.php');
965
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
966
-
967
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? '' : $this->_req_data['orderby'];
968
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
969
-            : 'ASC';
970
-        switch ($this->_req_data['orderby']) {
971
-            case 'name':
972
-                $orderby = array('PRT_name' => $order);
973
-                break;
974
-            default:
975
-                $orderby = array('PRT_order' => $order);
976
-        }
977
-
978
-
979
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
980
-            ? $this->_req_data['paged'] : 1;
981
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
982
-            ? $this->_req_data['perpage'] : $per_page;
983
-
984
-        $offset = ($current_page - 1) * $per_page;
985
-        $limit = array($offset, $per_page);
986
-
987
-        $_where = array('PRT_deleted' => $trashed, 'PBT_ID' => array('!=', 1));
988
-
989
-        if (isset($this->_req_data['s'])) {
990
-            $sstr = '%' . $this->_req_data['s'] . '%';
991
-            $_where['OR'] = array(
992
-                'PRT_name' => array('LIKE', $sstr),
993
-            );
994
-        }
995
-        $query_params = array(
996
-            $_where,
997
-            'order_by' => $orderby,
998
-            'limit'    => $limit,
999
-        );
1000
-        if ($count) {
1001
-            return EEM_Price_Type::instance()->count_deleted_and_undeleted($query_params);
1002
-        } else {
1003
-            return EEM_Price_Type::instance()->get_all_deleted_and_undeleted($query_params);
1004
-        }
1005
-
1006
-        // EEH_Debug_Tools::printr( $price_types, '$price_types  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
1007
-    }
1008
-
1009
-
1010
-    /**
1011
-     *        _edit_price_type_details
1012
-     *
1013
-     * @access protected
1014
-     * @return void
1015
-     */
1016
-    protected function _edit_price_type_details()
1017
-    {
1018
-
1019
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1020
-
1021
-
1022
-        // grab price type ID
1023
-        $PRT_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id'])
1024
-            : false;
1025
-        // change page title based on request action
1026
-        switch ($this->_req_action) {
1027
-            case 'add_new_price_type':
1028
-                $this->_admin_page_title = esc_html__('Add New Price Type', 'event_espresso');
1029
-                break;
1030
-            case 'edit_price_type':
1031
-                $this->_admin_page_title = esc_html__('Edit Price Type', 'event_espresso');
1032
-                break;
1033
-            default:
1034
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
1035
-        }
1036
-        // add PRT_ID to title if editing
1037
-        $this->_admin_page_title = $PRT_ID ? $this->_admin_page_title . ' # ' . $PRT_ID : $this->_admin_page_title;
1038
-
1039
-        if ($PRT_ID) {
1040
-            $price_type = EEM_Price_Type::instance()->get_one_by_ID($PRT_ID);
1041
-            $additional_hidden_fields = array('PRT_ID' => array('type' => 'hidden', 'value' => $PRT_ID));
1042
-            $this->_set_add_edit_form_tags('update_price_type', $additional_hidden_fields);
1043
-        } else {
1044
-            $price_type = EEM_Price_Type::instance()->get_new_price_type();
1045
-            $this->_set_add_edit_form_tags('insert_price_type');
1046
-        }
1047
-
1048
-        $this->_template_args['PRT_ID'] = $PRT_ID;
1049
-        $this->_template_args['price_type'] = $price_type;
1050
-
1051
-
1052
-        $base_types = EEM_Price_Type::instance()->get_base_types();
1053
-        $select_values = array();
1054
-        foreach ($base_types as $ref => $text) {
1055
-            if ($ref == EEM_Price_Type::base_type_base_price) {
1056
-                // do not allow creation of base_type_base_prices because that's a system only base type.
1057
-                continue;
1058
-            }
1059
-            $values[] = array('id' => $ref, 'text' => $text);
1060
-        }
1061
-
1062
-
1063
-        $this->_template_args['base_type_select'] = EEH_Form_Fields::select_input(
1064
-            'base_type',
1065
-            $values,
1066
-            $price_type->base_type(),
1067
-            'id="price-type-base-type-slct"'
1068
-        );
1069
-        $this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
1070
-        $redirect_URL = add_query_arg(array('action' => 'price_types'), $this->_admin_base_url);
1071
-        $this->_set_publish_post_box_vars('id', $PRT_ID, false, $redirect_URL);
1072
-        // the details template wrapper
1073
-        $this->display_admin_page_with_sidebar();
1074
-    }
1075
-
1076
-
1077
-    /**
1078
-     *        declare price type details page metaboxes
1079
-     *
1080
-     * @access protected
1081
-     * @return void
1082
-     */
1083
-    protected function _price_type_details_meta_boxes()
1084
-    {
1085
-        add_meta_box(
1086
-            'edit-price-details-mbox',
1087
-            esc_html__('Price Type Details', 'event_espresso'),
1088
-            array($this, '_edit_price_type_details_meta_box'),
1089
-            $this->wp_page_slug,
1090
-            'normal',
1091
-            'high'
1092
-        );
1093
-    }
1094
-
1095
-
1096
-    /**
1097
-     *        _edit_price_type_details_meta_box
1098
-     *
1099
-     * @access public
1100
-     * @return void
1101
-     */
1102
-    public function _edit_price_type_details_meta_box()
1103
-    {
1104
-        echo EEH_Template::display_template(
1105
-            PRICING_TEMPLATE_PATH . 'pricing_type_details_main_meta_box.template.php',
1106
-            $this->_template_args,
1107
-            true
1108
-        );
1109
-    }
1110
-
1111
-
1112
-    /**
1113
-     *        set_price_type_column_values
1114
-     *
1115
-     * @access protected
1116
-     * @return void
1117
-     */
1118
-    protected function set_price_type_column_values()
1119
-    {
1120
-
1121
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1122
-
1123
-        $base_type = ! empty($this->_req_data['base_type']) ? $this->_req_data['base_type']
1124
-            : EEM_Price_Type::base_type_base_price;
1125
-
1126
-        switch ($base_type) {
1127
-            case EEM_Price_Type::base_type_base_price:
1128
-                $this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_base_price;
1129
-                $this->_req_data['PRT_is_percent'] = 0;
1130
-                $this->_req_data['PRT_order'] = 0;
1131
-                break;
1132
-
1133
-            case EEM_Price_Type::base_type_discount:
1134
-                $this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_discount;
1135
-                break;
1136
-
1137
-            case EEM_Price_Type::base_type_surcharge:
1138
-                $this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_surcharge;
1139
-                break;
1140
-
1141
-            case EEM_Price_Type::base_type_tax:
1142
-                $this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_tax;
1143
-                $this->_req_data['PRT_is_percent'] = 1;
1144
-                break;
1145
-        }/**/
1146
-
1147
-        $set_column_values = array(
1148
-            'PRT_name'       => $this->_req_data['PRT_name'],
1149
-            'PBT_ID'         => absint($this->_req_data['PBT_ID']),
1150
-            'PRT_is_percent' => absint($this->_req_data['PRT_is_percent']),
1151
-            'PRT_order'      => absint($this->_req_data['PRT_order']),
1152
-            'PRT_deleted'    => 0,
1153
-        );
1154
-
1155
-        return $set_column_values;
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     *        _insert_or_update_price_type
1161
-     *
1162
-     * @param boolean $new_price_type - whether to insert or update
1163
-     * @access protected
1164
-     * @return void
1165
-     */
1166
-    protected function _insert_or_update_price_type($new_price_type = false)
1167
-    {
1168
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1169
-
1170
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
1171
-        $PRT = EEM_Price_Type::instance();
1172
-
1173
-        // why be so pessimistic ???  : (
1174
-        $success = 0;
1175
-
1176
-        $set_column_values = $this->set_price_type_column_values();
1177
-        // is this a new Price ?
1178
-        if ($new_price_type) {
1179
-            // run the insert
1180
-            if ($PRT_ID = $PRT->insert($set_column_values)) {
1181
-                $success = 1;
1182
-            }
1183
-            $action_desc = 'created';
1184
-        } else {
1185
-            $PRT_ID = absint($this->_req_data['PRT_ID']);
1186
-            // run the update
1187
-            $where_cols_n_values = array('PRT_ID' => $PRT_ID);
1188
-            if ($PRT->update($set_column_values, array($where_cols_n_values))) {
1189
-                $success = 1;
1190
-            }
1191
-            $action_desc = 'updated';
1192
-        }
1193
-
1194
-        $query_args = array('action' => 'edit_price_type', 'id' => $PRT_ID);
1195
-        $this->_redirect_after_action($success, 'Price Type', $action_desc, $query_args);
1196
-    }
1197
-
1198
-
1199
-    /**
1200
-     *        _trash_or_restore_price_type
1201
-     *
1202
-     * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
1203
-     * @access protected
1204
-     * @return void
1205
-     */
1206
-    protected function _trash_or_restore_price_type($trash = true)
1207
-    {
1208
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1209
-
1210
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
1211
-        $PRT = EEM_Price_Type::instance();
1212
-
1213
-        $success = 1;
1214
-        $PRT_deleted = $trash ? true : false;
1215
-        // Checkboxes
1216
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1217
-            // if array has more than one element than success message should be plural
1218
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1219
-            $what = count($this->_req_data['checkbox']) > 1 ? 'Price Types' : 'Price Type';
1220
-            // cycle thru checkboxes
1221
-            while (list($PRT_ID, $value) = each($this->_req_data['checkbox'])) {
1222
-                if (! $PRT->update_by_ID(array('PRT_deleted' => $PRT_deleted), $PRT_ID)) {
1223
-                    $success = 0;
1224
-                }
1225
-            }
1226
-        } else {
1227
-            // grab single id and delete
1228
-            $PRT_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
1229
-            if (empty($PRT_ID) || ! $PRT->update_by_ID(array('PRT_deleted' => $PRT_deleted), $PRT_ID)) {
1230
-                $success = 0;
1231
-            }
1232
-            $what = 'Price Type';
1233
-        }
1234
-
1235
-        $query_args = array('action' => 'price_types');
1236
-        if ($success) {
1237
-            if ($trash) {
1238
-                $msg = $success > 1
1239
-                    ? esc_html__('The Price Types have been trashed.', 'event_espresso')
1240
-                    : esc_html__(
1241
-                        'The Price Type has been trashed.',
1242
-                        'event_espresso'
1243
-                    );
1244
-            } else {
1245
-                $msg = $success > 1
1246
-                    ? esc_html__('The Price Types have been restored.', 'event_espresso')
1247
-                    : esc_html__(
1248
-                        'The Price Type has been restored.',
1249
-                        'event_espresso'
1250
-                    );
1251
-            }
1252
-            EE_Error::add_success($msg);
1253
-        }
1254
-
1255
-        $this->_redirect_after_action(false, '', '', $query_args, true);
1256
-    }
1257
-
1258
-
1259
-    /**
1260
-     *        _delete_price_type
1261
-     *
1262
-     * @access protected
1263
-     * @return void
1264
-     */
1265
-    protected function _delete_price_type()
1266
-    {
1267
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1268
-
1269
-        $PRT = EEM_Price_Type::instance();
1270
-
1271
-        $success = 1;
1272
-        // Checkboxes
1273
-        if (! empty($this->_req_data['checkbox'])) {
1274
-            // if array has more than one element than success message should be plural
1275
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1276
-            $what = $PRT->item_name($success);
1277
-            // cycle thru bulk action checkboxes
1278
-            while (list($PRT_ID, $value) = each($this->_req_data['checkbox'])) {
1279
-                if (! $PRT->delete_permanently_by_ID($PRT_ID)) {
1280
-                    $success = 0;
1281
-                }
1282
-            }
1283
-        }
1284
-
1285
-
1286
-        $query_args = array('action' => 'price_types');
1287
-        $this->_redirect_after_action($success, $what, 'deleted', $query_args);
1288
-    }
1289
-
1290
-
1291
-    /**
1292
-     *        _learn_more_about_pricing_link
1293
-     *
1294
-     * @access protected
1295
-     * @return string
1296
-     */
1297
-    protected function _learn_more_about_pricing_link()
1298
-    {
1299
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . esc_html__(
1300
-            'learn more about how pricing works',
1301
-            'event_espresso'
1302
-        ) . '</a>';
1303
-    }
1304
-
1305
-
1306
-    protected function _tax_settings()
1307
-    {
1308
-        $this->_set_add_edit_form_tags('update_tax_settings');
1309
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
1310
-        $this->_template_args['admin_page_content'] = $this->tax_settings_form()->get_html();
1311
-        $this->display_admin_page_with_sidebar();
1312
-    }
1313
-
1314
-
1315
-    /**
1316
-     * @return \EE_Form_Section_Proper
1317
-     * @throws \EE_Error
1318
-     */
1319
-    protected function tax_settings_form()
1320
-    {
1321
-        return new EE_Form_Section_Proper(
1322
-            array(
1323
-                'name'            => 'tax_settings_form',
1324
-                'html_id'         => 'tax_settings_form',
1325
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1326
-                'subsections'     => apply_filters(
1327
-                    'FHEE__Pricing_Admin_Page__tax_settings_form__form_subsections',
1328
-                    array(
1329
-                        'tax_settings' => new EE_Form_Section_Proper(
1330
-                            array(
1331
-                                'name'            => 'tax_settings_tbl',
1332
-                                'html_id'         => 'tax_settings_tbl',
1333
-                                'html_class'      => 'form-table',
1334
-                                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1335
-                                'subsections'     => array(
1336
-                                    'prices_displayed_including_taxes' => new EE_Yes_No_Input(
1337
-                                        array(
1338
-                                            'html_label_text'         => esc_html__(
1339
-                                                "Show Prices With Taxes Included?",
1340
-                                                'event_espresso'
1341
-                                            ),
1342
-                                            'html_help_text'          => esc_html__(
1343
-                                                'Indicates whether or not to display prices with the taxes included',
1344
-                                                'event_espresso'
1345
-                                            ),
1346
-                                            'default'                 => isset(
1347
-                                                EE_Registry::instance()
1348
-                                                    ->CFG
1349
-                                                    ->tax_settings
1350
-                                                    ->prices_displayed_including_taxes
1351
-                                            )
1352
-                                                ? EE_Registry::instance()
1353
-                                                    ->CFG
1354
-                                                    ->tax_settings
1355
-                                                    ->prices_displayed_including_taxes
1356
-                                                : true,
1357
-                                            'display_html_label_text' => false,
1358
-                                        )
1359
-                                    ),
1360
-                                ),
1361
-                            )
1362
-                        ),
1363
-                    )
1364
-                ),
1365
-            )
1366
-        );
1367
-    }
1368
-
1369
-
1370
-    /**
1371
-     * _update_tax_settings
1372
-     *
1373
-     * @since 4.9.13
1374
-     * @return void
1375
-     */
1376
-    public function _update_tax_settings()
1377
-    {
1378
-        if (! isset(EE_Registry::instance()->CFG->tax_settings)) {
1379
-            EE_Registry::instance()->CFG->tax_settings = new EE_Tax_Config();
1380
-        }
1381
-        try {
1382
-            $tax_form = $this->tax_settings_form();
1383
-            // check for form submission
1384
-            if ($tax_form->was_submitted()) {
1385
-                // capture form data
1386
-                $tax_form->receive_form_submission();
1387
-                // validate form data
1388
-                if ($tax_form->is_valid()) {
1389
-                    // grab validated data from form
1390
-                    $valid_data = $tax_form->valid_data();
1391
-                    // set data on config
1392
-                    EE_Registry::instance()
1393
-                        ->CFG
1394
-                        ->tax_settings
1395
-                        ->prices_displayed_including_taxes
1396
-                        = $valid_data['tax_settings']['prices_displayed_including_taxes'];
1397
-                } else {
1398
-                    if ($tax_form->submission_error_message() !== '') {
1399
-                        EE_Error::add_error(
1400
-                            $tax_form->submission_error_message(),
1401
-                            __FILE__,
1402
-                            __FUNCTION__,
1403
-                            __LINE__
1404
-                        );
1405
-                    }
1406
-                }
1407
-            }
1408
-        } catch (EE_Error $e) {
1409
-            EE_Error::add_error($e->get_error(), __FILE__, __FUNCTION__, __LINE__);
1410
-        }
1411
-
1412
-        $what = 'Tax Settings';
1413
-        $success = $this->_update_espresso_configuration(
1414
-            $what,
1415
-            EE_Registry::instance()->CFG->tax_settings,
1416
-            __FILE__,
1417
-            __FUNCTION__,
1418
-            __LINE__
1419
-        );
1420
-        $this->_redirect_after_action($success, $what, 'updated', array('action' => 'tax_settings'));
1421
-    }
929
+	/**
930
+	 *        generates HTML for main Prices Admin page
931
+	 *
932
+	 * @access protected
933
+	 * @return void
934
+	 */
935
+	protected function _price_types_overview_list_table()
936
+	{
937
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
938
+			'add_new_price_type',
939
+			'add_type',
940
+			array(),
941
+			'add-new-h2'
942
+		);
943
+		$this->admin_page_title .= $this->_learn_more_about_pricing_link();
944
+		$this->_search_btn_label = esc_html__('Price Types', 'event_espresso');
945
+		$this->display_admin_list_table_page_with_no_sidebar();
946
+	}
947
+
948
+
949
+	/**
950
+	 *    retrieve data for Price Types List table
951
+	 *
952
+	 * @access public
953
+	 * @param  int     $per_page how many prices displayed per page
954
+	 * @param  boolean $count    return the count or objects
955
+	 * @param  boolean $trashed  whether the current view is of the trash can - eww yuck!
956
+	 * @return mixed (int|array)  int = count || array of price objects
957
+	 */
958
+	public function get_price_types_overview_data($per_page = 10, $count = false, $trashed = false)
959
+	{
960
+
961
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
962
+		// start with an empty array
963
+
964
+		require_once(PRICING_ADMIN . 'Price_Types_List_Table.class.php');
965
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
966
+
967
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? '' : $this->_req_data['orderby'];
968
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
969
+			: 'ASC';
970
+		switch ($this->_req_data['orderby']) {
971
+			case 'name':
972
+				$orderby = array('PRT_name' => $order);
973
+				break;
974
+			default:
975
+				$orderby = array('PRT_order' => $order);
976
+		}
977
+
978
+
979
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
980
+			? $this->_req_data['paged'] : 1;
981
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
982
+			? $this->_req_data['perpage'] : $per_page;
983
+
984
+		$offset = ($current_page - 1) * $per_page;
985
+		$limit = array($offset, $per_page);
986
+
987
+		$_where = array('PRT_deleted' => $trashed, 'PBT_ID' => array('!=', 1));
988
+
989
+		if (isset($this->_req_data['s'])) {
990
+			$sstr = '%' . $this->_req_data['s'] . '%';
991
+			$_where['OR'] = array(
992
+				'PRT_name' => array('LIKE', $sstr),
993
+			);
994
+		}
995
+		$query_params = array(
996
+			$_where,
997
+			'order_by' => $orderby,
998
+			'limit'    => $limit,
999
+		);
1000
+		if ($count) {
1001
+			return EEM_Price_Type::instance()->count_deleted_and_undeleted($query_params);
1002
+		} else {
1003
+			return EEM_Price_Type::instance()->get_all_deleted_and_undeleted($query_params);
1004
+		}
1005
+
1006
+		// EEH_Debug_Tools::printr( $price_types, '$price_types  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
1007
+	}
1008
+
1009
+
1010
+	/**
1011
+	 *        _edit_price_type_details
1012
+	 *
1013
+	 * @access protected
1014
+	 * @return void
1015
+	 */
1016
+	protected function _edit_price_type_details()
1017
+	{
1018
+
1019
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1020
+
1021
+
1022
+		// grab price type ID
1023
+		$PRT_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id'])
1024
+			: false;
1025
+		// change page title based on request action
1026
+		switch ($this->_req_action) {
1027
+			case 'add_new_price_type':
1028
+				$this->_admin_page_title = esc_html__('Add New Price Type', 'event_espresso');
1029
+				break;
1030
+			case 'edit_price_type':
1031
+				$this->_admin_page_title = esc_html__('Edit Price Type', 'event_espresso');
1032
+				break;
1033
+			default:
1034
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
1035
+		}
1036
+		// add PRT_ID to title if editing
1037
+		$this->_admin_page_title = $PRT_ID ? $this->_admin_page_title . ' # ' . $PRT_ID : $this->_admin_page_title;
1038
+
1039
+		if ($PRT_ID) {
1040
+			$price_type = EEM_Price_Type::instance()->get_one_by_ID($PRT_ID);
1041
+			$additional_hidden_fields = array('PRT_ID' => array('type' => 'hidden', 'value' => $PRT_ID));
1042
+			$this->_set_add_edit_form_tags('update_price_type', $additional_hidden_fields);
1043
+		} else {
1044
+			$price_type = EEM_Price_Type::instance()->get_new_price_type();
1045
+			$this->_set_add_edit_form_tags('insert_price_type');
1046
+		}
1047
+
1048
+		$this->_template_args['PRT_ID'] = $PRT_ID;
1049
+		$this->_template_args['price_type'] = $price_type;
1050
+
1051
+
1052
+		$base_types = EEM_Price_Type::instance()->get_base_types();
1053
+		$select_values = array();
1054
+		foreach ($base_types as $ref => $text) {
1055
+			if ($ref == EEM_Price_Type::base_type_base_price) {
1056
+				// do not allow creation of base_type_base_prices because that's a system only base type.
1057
+				continue;
1058
+			}
1059
+			$values[] = array('id' => $ref, 'text' => $text);
1060
+		}
1061
+
1062
+
1063
+		$this->_template_args['base_type_select'] = EEH_Form_Fields::select_input(
1064
+			'base_type',
1065
+			$values,
1066
+			$price_type->base_type(),
1067
+			'id="price-type-base-type-slct"'
1068
+		);
1069
+		$this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
1070
+		$redirect_URL = add_query_arg(array('action' => 'price_types'), $this->_admin_base_url);
1071
+		$this->_set_publish_post_box_vars('id', $PRT_ID, false, $redirect_URL);
1072
+		// the details template wrapper
1073
+		$this->display_admin_page_with_sidebar();
1074
+	}
1075
+
1076
+
1077
+	/**
1078
+	 *        declare price type details page metaboxes
1079
+	 *
1080
+	 * @access protected
1081
+	 * @return void
1082
+	 */
1083
+	protected function _price_type_details_meta_boxes()
1084
+	{
1085
+		add_meta_box(
1086
+			'edit-price-details-mbox',
1087
+			esc_html__('Price Type Details', 'event_espresso'),
1088
+			array($this, '_edit_price_type_details_meta_box'),
1089
+			$this->wp_page_slug,
1090
+			'normal',
1091
+			'high'
1092
+		);
1093
+	}
1094
+
1095
+
1096
+	/**
1097
+	 *        _edit_price_type_details_meta_box
1098
+	 *
1099
+	 * @access public
1100
+	 * @return void
1101
+	 */
1102
+	public function _edit_price_type_details_meta_box()
1103
+	{
1104
+		echo EEH_Template::display_template(
1105
+			PRICING_TEMPLATE_PATH . 'pricing_type_details_main_meta_box.template.php',
1106
+			$this->_template_args,
1107
+			true
1108
+		);
1109
+	}
1110
+
1111
+
1112
+	/**
1113
+	 *        set_price_type_column_values
1114
+	 *
1115
+	 * @access protected
1116
+	 * @return void
1117
+	 */
1118
+	protected function set_price_type_column_values()
1119
+	{
1120
+
1121
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1122
+
1123
+		$base_type = ! empty($this->_req_data['base_type']) ? $this->_req_data['base_type']
1124
+			: EEM_Price_Type::base_type_base_price;
1125
+
1126
+		switch ($base_type) {
1127
+			case EEM_Price_Type::base_type_base_price:
1128
+				$this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_base_price;
1129
+				$this->_req_data['PRT_is_percent'] = 0;
1130
+				$this->_req_data['PRT_order'] = 0;
1131
+				break;
1132
+
1133
+			case EEM_Price_Type::base_type_discount:
1134
+				$this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_discount;
1135
+				break;
1136
+
1137
+			case EEM_Price_Type::base_type_surcharge:
1138
+				$this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_surcharge;
1139
+				break;
1140
+
1141
+			case EEM_Price_Type::base_type_tax:
1142
+				$this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_tax;
1143
+				$this->_req_data['PRT_is_percent'] = 1;
1144
+				break;
1145
+		}/**/
1146
+
1147
+		$set_column_values = array(
1148
+			'PRT_name'       => $this->_req_data['PRT_name'],
1149
+			'PBT_ID'         => absint($this->_req_data['PBT_ID']),
1150
+			'PRT_is_percent' => absint($this->_req_data['PRT_is_percent']),
1151
+			'PRT_order'      => absint($this->_req_data['PRT_order']),
1152
+			'PRT_deleted'    => 0,
1153
+		);
1154
+
1155
+		return $set_column_values;
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 *        _insert_or_update_price_type
1161
+	 *
1162
+	 * @param boolean $new_price_type - whether to insert or update
1163
+	 * @access protected
1164
+	 * @return void
1165
+	 */
1166
+	protected function _insert_or_update_price_type($new_price_type = false)
1167
+	{
1168
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1169
+
1170
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
1171
+		$PRT = EEM_Price_Type::instance();
1172
+
1173
+		// why be so pessimistic ???  : (
1174
+		$success = 0;
1175
+
1176
+		$set_column_values = $this->set_price_type_column_values();
1177
+		// is this a new Price ?
1178
+		if ($new_price_type) {
1179
+			// run the insert
1180
+			if ($PRT_ID = $PRT->insert($set_column_values)) {
1181
+				$success = 1;
1182
+			}
1183
+			$action_desc = 'created';
1184
+		} else {
1185
+			$PRT_ID = absint($this->_req_data['PRT_ID']);
1186
+			// run the update
1187
+			$where_cols_n_values = array('PRT_ID' => $PRT_ID);
1188
+			if ($PRT->update($set_column_values, array($where_cols_n_values))) {
1189
+				$success = 1;
1190
+			}
1191
+			$action_desc = 'updated';
1192
+		}
1193
+
1194
+		$query_args = array('action' => 'edit_price_type', 'id' => $PRT_ID);
1195
+		$this->_redirect_after_action($success, 'Price Type', $action_desc, $query_args);
1196
+	}
1197
+
1198
+
1199
+	/**
1200
+	 *        _trash_or_restore_price_type
1201
+	 *
1202
+	 * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
1203
+	 * @access protected
1204
+	 * @return void
1205
+	 */
1206
+	protected function _trash_or_restore_price_type($trash = true)
1207
+	{
1208
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1209
+
1210
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
1211
+		$PRT = EEM_Price_Type::instance();
1212
+
1213
+		$success = 1;
1214
+		$PRT_deleted = $trash ? true : false;
1215
+		// Checkboxes
1216
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1217
+			// if array has more than one element than success message should be plural
1218
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1219
+			$what = count($this->_req_data['checkbox']) > 1 ? 'Price Types' : 'Price Type';
1220
+			// cycle thru checkboxes
1221
+			while (list($PRT_ID, $value) = each($this->_req_data['checkbox'])) {
1222
+				if (! $PRT->update_by_ID(array('PRT_deleted' => $PRT_deleted), $PRT_ID)) {
1223
+					$success = 0;
1224
+				}
1225
+			}
1226
+		} else {
1227
+			// grab single id and delete
1228
+			$PRT_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
1229
+			if (empty($PRT_ID) || ! $PRT->update_by_ID(array('PRT_deleted' => $PRT_deleted), $PRT_ID)) {
1230
+				$success = 0;
1231
+			}
1232
+			$what = 'Price Type';
1233
+		}
1234
+
1235
+		$query_args = array('action' => 'price_types');
1236
+		if ($success) {
1237
+			if ($trash) {
1238
+				$msg = $success > 1
1239
+					? esc_html__('The Price Types have been trashed.', 'event_espresso')
1240
+					: esc_html__(
1241
+						'The Price Type has been trashed.',
1242
+						'event_espresso'
1243
+					);
1244
+			} else {
1245
+				$msg = $success > 1
1246
+					? esc_html__('The Price Types have been restored.', 'event_espresso')
1247
+					: esc_html__(
1248
+						'The Price Type has been restored.',
1249
+						'event_espresso'
1250
+					);
1251
+			}
1252
+			EE_Error::add_success($msg);
1253
+		}
1254
+
1255
+		$this->_redirect_after_action(false, '', '', $query_args, true);
1256
+	}
1257
+
1258
+
1259
+	/**
1260
+	 *        _delete_price_type
1261
+	 *
1262
+	 * @access protected
1263
+	 * @return void
1264
+	 */
1265
+	protected function _delete_price_type()
1266
+	{
1267
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1268
+
1269
+		$PRT = EEM_Price_Type::instance();
1270
+
1271
+		$success = 1;
1272
+		// Checkboxes
1273
+		if (! empty($this->_req_data['checkbox'])) {
1274
+			// if array has more than one element than success message should be plural
1275
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1276
+			$what = $PRT->item_name($success);
1277
+			// cycle thru bulk action checkboxes
1278
+			while (list($PRT_ID, $value) = each($this->_req_data['checkbox'])) {
1279
+				if (! $PRT->delete_permanently_by_ID($PRT_ID)) {
1280
+					$success = 0;
1281
+				}
1282
+			}
1283
+		}
1284
+
1285
+
1286
+		$query_args = array('action' => 'price_types');
1287
+		$this->_redirect_after_action($success, $what, 'deleted', $query_args);
1288
+	}
1289
+
1290
+
1291
+	/**
1292
+	 *        _learn_more_about_pricing_link
1293
+	 *
1294
+	 * @access protected
1295
+	 * @return string
1296
+	 */
1297
+	protected function _learn_more_about_pricing_link()
1298
+	{
1299
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . esc_html__(
1300
+			'learn more about how pricing works',
1301
+			'event_espresso'
1302
+		) . '</a>';
1303
+	}
1304
+
1305
+
1306
+	protected function _tax_settings()
1307
+	{
1308
+		$this->_set_add_edit_form_tags('update_tax_settings');
1309
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
1310
+		$this->_template_args['admin_page_content'] = $this->tax_settings_form()->get_html();
1311
+		$this->display_admin_page_with_sidebar();
1312
+	}
1313
+
1314
+
1315
+	/**
1316
+	 * @return \EE_Form_Section_Proper
1317
+	 * @throws \EE_Error
1318
+	 */
1319
+	protected function tax_settings_form()
1320
+	{
1321
+		return new EE_Form_Section_Proper(
1322
+			array(
1323
+				'name'            => 'tax_settings_form',
1324
+				'html_id'         => 'tax_settings_form',
1325
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1326
+				'subsections'     => apply_filters(
1327
+					'FHEE__Pricing_Admin_Page__tax_settings_form__form_subsections',
1328
+					array(
1329
+						'tax_settings' => new EE_Form_Section_Proper(
1330
+							array(
1331
+								'name'            => 'tax_settings_tbl',
1332
+								'html_id'         => 'tax_settings_tbl',
1333
+								'html_class'      => 'form-table',
1334
+								'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1335
+								'subsections'     => array(
1336
+									'prices_displayed_including_taxes' => new EE_Yes_No_Input(
1337
+										array(
1338
+											'html_label_text'         => esc_html__(
1339
+												"Show Prices With Taxes Included?",
1340
+												'event_espresso'
1341
+											),
1342
+											'html_help_text'          => esc_html__(
1343
+												'Indicates whether or not to display prices with the taxes included',
1344
+												'event_espresso'
1345
+											),
1346
+											'default'                 => isset(
1347
+												EE_Registry::instance()
1348
+													->CFG
1349
+													->tax_settings
1350
+													->prices_displayed_including_taxes
1351
+											)
1352
+												? EE_Registry::instance()
1353
+													->CFG
1354
+													->tax_settings
1355
+													->prices_displayed_including_taxes
1356
+												: true,
1357
+											'display_html_label_text' => false,
1358
+										)
1359
+									),
1360
+								),
1361
+							)
1362
+						),
1363
+					)
1364
+				),
1365
+			)
1366
+		);
1367
+	}
1368
+
1369
+
1370
+	/**
1371
+	 * _update_tax_settings
1372
+	 *
1373
+	 * @since 4.9.13
1374
+	 * @return void
1375
+	 */
1376
+	public function _update_tax_settings()
1377
+	{
1378
+		if (! isset(EE_Registry::instance()->CFG->tax_settings)) {
1379
+			EE_Registry::instance()->CFG->tax_settings = new EE_Tax_Config();
1380
+		}
1381
+		try {
1382
+			$tax_form = $this->tax_settings_form();
1383
+			// check for form submission
1384
+			if ($tax_form->was_submitted()) {
1385
+				// capture form data
1386
+				$tax_form->receive_form_submission();
1387
+				// validate form data
1388
+				if ($tax_form->is_valid()) {
1389
+					// grab validated data from form
1390
+					$valid_data = $tax_form->valid_data();
1391
+					// set data on config
1392
+					EE_Registry::instance()
1393
+						->CFG
1394
+						->tax_settings
1395
+						->prices_displayed_including_taxes
1396
+						= $valid_data['tax_settings']['prices_displayed_including_taxes'];
1397
+				} else {
1398
+					if ($tax_form->submission_error_message() !== '') {
1399
+						EE_Error::add_error(
1400
+							$tax_form->submission_error_message(),
1401
+							__FILE__,
1402
+							__FUNCTION__,
1403
+							__LINE__
1404
+						);
1405
+					}
1406
+				}
1407
+			}
1408
+		} catch (EE_Error $e) {
1409
+			EE_Error::add_error($e->get_error(), __FILE__, __FUNCTION__, __LINE__);
1410
+		}
1411
+
1412
+		$what = 'Tax Settings';
1413
+		$success = $this->_update_espresso_configuration(
1414
+			$what,
1415
+			EE_Registry::instance()->CFG->tax_settings,
1416
+			__FILE__,
1417
+			__FUNCTION__,
1418
+			__LINE__
1419
+		);
1420
+		$this->_redirect_after_action($success, $what, 'updated', array('action' => 'tax_settings'));
1421
+	}
1422 1422
 }
Please login to merge, or discard this patch.
admin/new/pricing/help_tabs/pricing_default_pricing.help_tab.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -2,23 +2,23 @@
 block discarded – undo
2 2
     <strong><?php esc_html_e('Default Pricing', 'event_espresso'); ?></strong>
3 3
     <br />
4 4
     <?php esc_html_e(
5
-        'This page shows all default prices that have been created with Event Espresso. These default prices can be applied to all events that are created.',
6
-        'event_espresso'
7
-    ); ?>
5
+		'This page shows all default prices that have been created with Event Espresso. These default prices can be applied to all events that are created.',
6
+		'event_espresso'
7
+	); ?>
8 8
 </p>
9 9
 <p>
10 10
     <strong><?php esc_html_e('Recommendations', 'event_espresso'); ?></strong>
11 11
     <br />
12 12
     <?php esc_html_e(
13
-        'To learn more about the options on this page, take a look at the different tabs that appear on the left side of the page.',
14
-        'event_espresso'
15
-    ); ?>
13
+		'To learn more about the options on this page, take a look at the different tabs that appear on the left side of the page.',
14
+		'event_espresso'
15
+	); ?>
16 16
 </p>
17 17
 <p>
18 18
     <strong><?php esc_html_e('Screen Options', 'event_espresso'); ?></strong>
19 19
     <br />
20 20
     <?php esc_html_e(
21
-        'You can customize the information that is shown on this page by toggling the Screen Options tab. Then you can add or remove checkmarks to hide or show certain content and even adjust the pagination for default pricing.',
22
-        'event_espresso'
23
-    ); ?>
21
+		'You can customize the information that is shown on this page by toggling the Screen Options tab. Then you can add or remove checkmarks to hide or show certain content and even adjust the pagination for default pricing.',
22
+		'event_espresso'
23
+	); ?>
24 24
 </p>
25 25
\ No newline at end of file
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -38,103 +38,103 @@
 block discarded – undo
38 38
  * @since           4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.6.2');
65
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.6.2');
65
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
-        /**
98
-         * espresso_version
99
-         * Returns the plugin version
100
-         *
101
-         * @return string
102
-         */
103
-        function espresso_version()
104
-        {
105
-            return apply_filters('FHEE__espresso__espresso_version', '4.10.29.rc.010');
106
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
+		/**
98
+		 * espresso_version
99
+		 * Returns the plugin version
100
+		 *
101
+		 * @return string
102
+		 */
103
+		function espresso_version()
104
+		{
105
+			return apply_filters('FHEE__espresso__espresso_version', '4.10.29.rc.010');
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.
admin_pages/payments/Payments_Admin_Page.core.php 1 patch
Indentation   +1191 added lines, -1191 removed lines patch added patch discarded remove patch
@@ -15,1195 +15,1195 @@
 block discarded – undo
15 15
 class Payments_Admin_Page extends EE_Admin_Page
16 16
 {
17 17
 
18
-    /**
19
-     * Variables used for when we're re-sorting the logs results,
20
-     * in case we needed to do two queries, and we need to resort
21
-     *
22
-     * @var string
23
-     */
24
-    private $_sort_logs_again_direction;
25
-
26
-
27
-    /**
28
-     * @Constructor
29
-     * @access public
30
-     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
31
-     * @throws EE_Error
32
-     * @throws InvalidArgumentException
33
-     * @throws InvalidDataTypeException
34
-     * @throws InvalidInterfaceException
35
-     * @throws ReflectionException
36
-     */
37
-    public function __construct($routing = true)
38
-    {
39
-        parent::__construct($routing);
40
-    }
41
-
42
-
43
-    protected function _init_page_props()
44
-    {
45
-        $this->page_slug = EE_PAYMENTS_PG_SLUG;
46
-        $this->page_label = esc_html__('Payment Methods', 'event_espresso');
47
-        $this->_admin_base_url = EE_PAYMENTS_ADMIN_URL;
48
-        $this->_admin_base_path = EE_PAYMENTS_ADMIN;
49
-    }
50
-
51
-
52
-    protected function _ajax_hooks()
53
-    {
54
-        // todo: all hooks for ajax goes here.
55
-    }
56
-
57
-
58
-    protected function _define_page_props()
59
-    {
60
-        $this->_admin_page_title = $this->page_label;
61
-        $this->_labels = array(
62
-            'publishbox' => esc_html__('Update Settings', 'event_espresso'),
63
-        );
64
-    }
65
-
66
-
67
-    protected function _set_page_routes()
68
-    {
69
-        /**
70
-         * note that with payment method capabilities, although we've implemented
71
-         * capability mapping which will be used for accessing payment methods owned by
72
-         * other users.  This is not fully implemented yet in the payment method ui.
73
-         * Currently, only the "plural" caps are in active use.
74
-         * When cap mapping is implemented, some routes will need to use the singular form of
75
-         * capability method and also include the $id of the payment method for the route.
76
-         **/
77
-        $this->_page_routes = array(
78
-            'default'                   => array(
79
-                'func'       => '_payment_methods_list',
80
-                'capability' => 'ee_edit_payment_methods',
81
-            ),
82
-            'payment_settings'          => array(
83
-                'func'       => '_payment_settings',
84
-                'capability' => 'ee_manage_gateways',
85
-            ),
86
-            'activate_payment_method'   => array(
87
-                'func'       => '_activate_payment_method',
88
-                'noheader'   => true,
89
-                'capability' => 'ee_edit_payment_methods',
90
-            ),
91
-            'deactivate_payment_method' => array(
92
-                'func'       => '_deactivate_payment_method',
93
-                'noheader'   => true,
94
-                'capability' => 'ee_delete_payment_methods',
95
-            ),
96
-            'update_payment_method'     => array(
97
-                'func'               => '_update_payment_method',
98
-                'noheader'           => true,
99
-                'headers_sent_route' => 'default',
100
-                'capability'         => 'ee_edit_payment_methods',
101
-            ),
102
-            'update_payment_settings'   => array(
103
-                'func'       => '_update_payment_settings',
104
-                'noheader'   => true,
105
-                'capability' => 'ee_manage_gateways',
106
-            ),
107
-            'payment_log'               => array(
108
-                'func'       => '_payment_log_overview_list_table',
109
-                'capability' => 'ee_read_payment_methods',
110
-            ),
111
-            'payment_log_details'       => array(
112
-                'func'       => '_payment_log_details',
113
-                'capability' => 'ee_read_payment_methods',
114
-            ),
115
-        );
116
-    }
117
-
118
-
119
-    /**
120
-     * @throws EE_Error
121
-     * @throws ReflectionException
122
-     */
123
-    protected function _set_page_config()
124
-    {
125
-        $payment_method_list_config = array(
126
-            'nav'           => array(
127
-                'label' => esc_html__('Payment Methods', 'event_espresso'),
128
-                'order' => 10,
129
-            ),
130
-            'metaboxes'     => $this->_default_espresso_metaboxes,
131
-            'help_tabs'     => array_merge(
132
-                array(
133
-                    'payment_methods_overview_help_tab' => array(
134
-                        'title'    => esc_html__('Payment Methods Overview', 'event_espresso'),
135
-                        'filename' => 'payment_methods_overview',
136
-                    ),
137
-                ),
138
-                $this->_add_payment_method_help_tabs()
139
-            ),
140
-            'require_nonce' => false,
141
-        );
142
-        $this->_page_config = array(
143
-            'default'          => $payment_method_list_config,
144
-            'payment_settings' => array(
145
-                'nav'           => array(
146
-                    'label' => esc_html__('Settings', 'event_espresso'),
147
-                    'order' => 20,
148
-                ),
149
-                'help_tabs'     => array(
150
-                    'payment_methods_settings_help_tab' => array(
151
-                        'title'    => esc_html__('Payment Method Settings', 'event_espresso'),
152
-                        'filename' => 'payment_methods_settings',
153
-                    ),
154
-                ),
155
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
156
-                'require_nonce' => false,
157
-            ),
158
-            'payment_log'      => array(
159
-                'nav'           => array(
160
-                    'label' => esc_html__("Logs", 'event_espresso'),
161
-                    'order' => 30,
162
-                ),
163
-                'list_table'    => 'Payment_Log_Admin_List_Table',
164
-                'metaboxes'     => $this->_default_espresso_metaboxes,
165
-                'require_nonce' => false,
166
-            ),
167
-        );
168
-    }
169
-
170
-
171
-    /**
172
-     * @return array
173
-     * @throws DomainException
174
-     * @throws EE_Error
175
-     * @throws InvalidArgumentException
176
-     * @throws InvalidDataTypeException
177
-     * @throws InvalidInterfaceException
178
-     * @throws ReflectionException
179
-     */
180
-    protected function _add_payment_method_help_tabs()
181
-    {
182
-        EE_Registry::instance()->load_lib('Payment_Method_Manager');
183
-        $payment_method_types = EE_Payment_Method_Manager::instance()->payment_method_types();
184
-        $all_pmt_help_tabs_config = array();
185
-        foreach ($payment_method_types as $payment_method_type) {
186
-            if (
187
-                ! EE_Registry::instance()->CAP->current_user_can(
188
-                    $payment_method_type->cap_name(),
189
-                    'specific_payment_method_type_access'
190
-                )
191
-            ) {
192
-                continue;
193
-            }
194
-            foreach ($payment_method_type->help_tabs_config() as $help_tab_name => $config) {
195
-                $template_args = isset($config['template_args']) ? $config['template_args'] : array();
196
-                $template_args['admin_page_obj'] = $this;
197
-                $all_pmt_help_tabs_config[ $help_tab_name ] = array(
198
-                    'title'   => $config['title'],
199
-                    'content' => EEH_Template::display_template(
200
-                        $payment_method_type->file_folder() . 'help_tabs/' . $config['filename'] . '.help_tab.php',
201
-                        $template_args,
202
-                        true
203
-                    ),
204
-                );
205
-            }
206
-        }
207
-        return $all_pmt_help_tabs_config;
208
-    }
209
-
210
-
211
-    // none of the below group are currently used for Gateway Settings
212
-    protected function _add_screen_options()
213
-    {
214
-    }
215
-
216
-
217
-    protected function _add_feature_pointers()
218
-    {
219
-    }
220
-
221
-
222
-    public function admin_init()
223
-    {
224
-    }
225
-
226
-
227
-    public function admin_notices()
228
-    {
229
-    }
230
-
231
-
232
-    public function admin_footer_scripts()
233
-    {
234
-    }
235
-
236
-
237
-    public function load_scripts_styles()
238
-    {
239
-        // styles
240
-        wp_enqueue_style('espresso-ui-theme');
241
-        // scripts
242
-        wp_enqueue_script('ee_admin_js');
243
-        wp_enqueue_script('ee-text-links');
244
-        wp_enqueue_script(
245
-            'espresso_payments',
246
-            EE_PAYMENTS_ASSETS_URL . 'espresso_payments_admin.js',
247
-            array('ee-datepicker'),
248
-            EVENT_ESPRESSO_VERSION,
249
-            true
250
-        );
251
-    }
252
-
253
-
254
-    public function load_scripts_styles_default()
255
-    {
256
-        // styles
257
-        wp_register_style(
258
-            'espresso_payments',
259
-            EE_PAYMENTS_ASSETS_URL . 'ee-payments.css',
260
-            array(),
261
-            EVENT_ESPRESSO_VERSION
262
-        );
263
-        wp_enqueue_style('espresso_payments');
264
-        wp_enqueue_style('ee-text-links');
265
-        // scripts
266
-    }
267
-
268
-
269
-    /**
270
-     * @throws EE_Error
271
-     * @throws ReflectionException
272
-     */
273
-    protected function _payment_methods_list()
274
-    {
275
-        /**
276
-         * first let's ensure payment methods have been set up.
277
-         * We do this here because when people activate a payment method for the first time (as an addon),
278
-         * it may not set up its capabilities or get registered correctly due to the loading process.
279
-         * However, people MUST set up the details for the payment method,
280
-         * so it's safe to do a recheck here.
281
-         */
282
-        EE_Registry::instance()->load_lib('Payment_Method_Manager');
283
-        EEM_Payment_Method::instance()->verify_button_urls();
284
-        // set up tabs, one for each payment method type
285
-        $tabs = array();
286
-        $payment_methods = array();
287
-        foreach (EE_Payment_Method_Manager::instance()->payment_method_types() as $pmt_obj) {
288
-            // we don't want to show admin-only PMTs for now
289
-            if ($pmt_obj instanceof EE_PMT_Admin_Only) {
290
-                continue;
291
-            }
292
-            // check access
293
-            if (
294
-                ! EE_Registry::instance()->CAP->current_user_can(
295
-                    $pmt_obj->cap_name(),
296
-                    'specific_payment_method_type_access'
297
-                )
298
-            ) {
299
-                continue;
300
-            }
301
-            // check for any active pms of that type
302
-            $payment_method = EEM_Payment_Method::instance()->get_one_of_type($pmt_obj->system_name());
303
-            if (! $payment_method instanceof EE_Payment_Method) {
304
-                $payment_method = EE_Payment_Method::new_instance(
305
-                    array(
306
-                        'PMD_slug'       => sanitize_key($pmt_obj->system_name()),
307
-                        'PMD_type'       => $pmt_obj->system_name(),
308
-                        'PMD_name'       => $pmt_obj->pretty_name(),
309
-                        'PMD_admin_name' => $pmt_obj->pretty_name(),
310
-                    )
311
-                );
312
-            }
313
-            $payment_methods[ $payment_method->slug() ] = $payment_method;
314
-        }
315
-        $payment_methods = apply_filters(
316
-            'FHEE__Payments_Admin_Page___payment_methods_list__payment_methods',
317
-            $payment_methods
318
-        );
319
-        foreach ($payment_methods as $payment_method) {
320
-            if ($payment_method instanceof EE_Payment_Method) {
321
-                add_meta_box(
322
-                    // html id
323
-                    'espresso_' . $payment_method->slug() . '_payment_settings',
324
-                    // title
325
-                    sprintf(esc_html__('%s Settings', 'event_espresso'), $payment_method->admin_name()),
326
-                    // callback
327
-                    array($this, 'payment_method_settings_meta_box'),
328
-                    // post type
329
-                    null,
330
-                    // context
331
-                    'normal',
332
-                    // priority
333
-                    'default',
334
-                    // callback args
335
-                    array('payment_method' => $payment_method)
336
-                );
337
-                // setup for tabbed content
338
-                $tabs[ $payment_method->slug() ] = array(
339
-                    'label' => $payment_method->admin_name(),
340
-                    'class' => $payment_method->active() ? 'gateway-active' : '',
341
-                    'href'  => 'espresso_' . $payment_method->slug() . '_payment_settings',
342
-                    'title' => esc_html__('Modify this Payment Method', 'event_espresso'),
343
-                    'slug'  => $payment_method->slug(),
344
-                );
345
-            }
346
-        }
347
-        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
348
-            $tabs,
349
-            'payment_method_links',
350
-            '|',
351
-            $this->_get_active_payment_method_slug()
352
-        );
353
-        $this->display_admin_page_with_sidebar();
354
-    }
355
-
356
-
357
-    /**
358
-     *   _get_active_payment_method_slug
359
-     *
360
-     * @return string
361
-     * @throws EE_Error
362
-     */
363
-    protected function _get_active_payment_method_slug()
364
-    {
365
-        $payment_method_slug = false;
366
-        // decide which payment method tab to open first, as dictated by the request's 'payment_method'
367
-        if (isset($this->_req_data['payment_method'])) {
368
-            // if they provided the current payment method, use it
369
-            $payment_method_slug = sanitize_key($this->_req_data['payment_method']);
370
-        }
371
-        /** @var EE_Payment_Method $payment_method */
372
-        $payment_method = EEM_Payment_Method::instance()->get_one(array(array('PMD_slug' => $payment_method_slug)));
373
-        // if that didn't work or wasn't provided, find another way to select the current pm
374
-        if (! $this->_verify_payment_method($payment_method)) {
375
-            // like, looking for an active one
376
-            $payment_method = EEM_Payment_Method::instance()->get_one_active('CART');
377
-            // test that one as well
378
-            if ($this->_verify_payment_method($payment_method)) {
379
-                $payment_method_slug = $payment_method->slug();
380
-            } else {
381
-                $payment_method_slug = 'paypal_standard';
382
-            }
383
-        }
384
-        return $payment_method_slug;
385
-    }
386
-
387
-
388
-    /**
389
-     *    payment_method_settings_meta_box
390
-     *    returns TRUE if the passed payment method is properly constructed and the logged-in user has the correct
391
-     *    capabilities to access it
392
-     *
393
-     * @param EE_Payment_Method $payment_method
394
-     * @return boolean
395
-     * @throws EE_Error
396
-     */
397
-    protected function _verify_payment_method($payment_method)
398
-    {
399
-        if (
400
-            $payment_method instanceof EE_Payment_Method && $payment_method->type_obj() instanceof EE_PMT_Base
401
-            && EE_Registry::instance()->CAP->current_user_can(
402
-                $payment_method->type_obj()->cap_name(),
403
-                'specific_payment_method_type_access'
404
-            )
405
-        ) {
406
-            return true;
407
-        }
408
-        return false;
409
-    }
410
-
411
-
412
-    /**
413
-     *    payment_method_settings_meta_box
414
-     *
415
-     * @param NULL  $post_obj_which_is_null is an object containing the current post (as a $post object)
416
-     * @param array $metabox                is an array with metabox id, title, callback, and args elements. the value
417
-     *                                      at 'args' has key 'payment_method', as set within _payment_methods_list
418
-     * @return void
419
-     * @throws EE_Error
420
-     * @throws ReflectionException
421
-     */
422
-    public function payment_method_settings_meta_box($post_obj_which_is_null, $metabox)
423
-    {
424
-        $payment_method = isset($metabox['args'], $metabox['args']['payment_method'])
425
-            ? $metabox['args']['payment_method'] : null;
426
-        if (! $payment_method instanceof EE_Payment_Method) {
427
-            throw new EE_Error(
428
-                esc_html__(
429
-                    'Payment method metabox setup incorrectly. No Payment method object was supplied',
430
-                    'event_espresso'
431
-                )
432
-            );
433
-        }
434
-        $payment_method_scopes = $payment_method->active();
435
-        // if the payment method really exists show its form, otherwise the activation template
436
-        if ($payment_method->ID() && ! empty($payment_method_scopes)) {
437
-            $form = $this->_generate_payment_method_settings_form($payment_method);
438
-            if ($form->form_data_present_in($this->_req_data)) {
439
-                $form->receive_form_submission($this->_req_data);
440
-            }
441
-            echo $form->form_open() . $form->get_html_and_js() . $form->form_close(); // already escaped
442
-        } else {
443
-            echo $this->_activate_payment_method_button($payment_method)->get_html_and_js(); // already escaped
444
-        }
445
-    }
446
-
447
-
448
-    /**
449
-     * Gets the form for all the settings related to this payment method type
450
-     *
451
-     * @access protected
452
-     * @param EE_Payment_Method $payment_method
453
-     * @return EE_Form_Section_Proper
454
-     * @throws EE_Error
455
-     */
456
-    protected function _generate_payment_method_settings_form(EE_Payment_Method $payment_method = null)
457
-    {
458
-        if (! $payment_method instanceof EE_Payment_Method) {
459
-            return new EE_Form_Section_Proper();
460
-        }
461
-        return new EE_Form_Section_Proper(
462
-            array(
463
-                'name'            => $payment_method->slug() . '_settings_form',
464
-                'html_id'         => $payment_method->slug() . '_settings_form',
465
-                'action'          => EE_Admin_Page::add_query_args_and_nonce(
466
-                    array(
467
-                        'action'         => 'update_payment_method',
468
-                        'payment_method' => $payment_method->slug(),
469
-                    ),
470
-                    EE_PAYMENTS_ADMIN_URL
471
-                ),
472
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
473
-                'subsections'     => apply_filters(
474
-                    'FHEE__Payments_Admin_Page___generate_payment_method_settings_form__form_subsections',
475
-                    array(
476
-                        'pci_dss_compliance'      => $this->_pci_dss_compliance($payment_method),
477
-                        'currency_support'        => $this->_currency_support($payment_method),
478
-                        'payment_method_settings' => $this->_payment_method_settings($payment_method),
479
-                        'update'                  => $this->_update_payment_method_button($payment_method),
480
-                        'deactivate'              => $this->_deactivate_payment_method_button($payment_method),
481
-                        'fine_print'              => $this->_fine_print(),
482
-                    ),
483
-                    $payment_method
484
-                ),
485
-            )
486
-        );
487
-    }
488
-
489
-
490
-    /**
491
-     * _pci_dss_compliance
492
-     *
493
-     * @access protected
494
-     * @param EE_Payment_Method $payment_method
495
-     * @return EE_Form_Section_HTML
496
-     * @throws EE_Error
497
-     */
498
-    protected function _pci_dss_compliance(EE_Payment_Method $payment_method)
499
-    {
500
-        if ($payment_method->type_obj()->requires_https()) {
501
-            return new EE_Form_Section_HTML(
502
-                EEH_HTML::table(
503
-                    EEH_HTML::tr(
504
-                        EEH_HTML::th(
505
-                            EEH_HTML::label(
506
-                                EEH_HTML::strong(
507
-                                    esc_html__('IMPORTANT', 'event_espresso'),
508
-                                    '',
509
-                                    'important-notice'
510
-                                )
511
-                            )
512
-                        ) .
513
-                        EEH_HTML::td(
514
-                            EEH_HTML::strong(
515
-                                esc_html__(
516
-                                    'You are responsible for your own website security and Payment Card Industry Data Security Standards (PCI DSS) compliance.',
517
-                                    'event_espresso'
518
-                                )
519
-                            )
520
-                            .
521
-                            EEH_HTML::br()
522
-                            .
523
-                            esc_html__('Learn more about ', 'event_espresso')
524
-                            . EEH_HTML::link(
525
-                                'https://www.pcisecuritystandards.org/merchants/index.php',
526
-                                esc_html__('PCI DSS compliance', 'event_espresso')
527
-                            )
528
-                        )
529
-                    )
530
-                )
531
-            );
532
-        }
533
-        return new EE_Form_Section_HTML('');
534
-    }
535
-
536
-
537
-    /**
538
-     * _currency_support
539
-     *
540
-     * @access protected
541
-     * @param EE_Payment_Method $payment_method
542
-     * @return EE_Form_Section_HTML
543
-     * @throws EE_Error
544
-     */
545
-    protected function _currency_support(EE_Payment_Method $payment_method)
546
-    {
547
-        if (! $payment_method->usable_for_currency(EE_Config::instance()->currency->code)) {
548
-            return new EE_Form_Section_HTML(
549
-                EEH_HTML::table(
550
-                    EEH_HTML::tr(
551
-                        EEH_HTML::th(
552
-                            EEH_HTML::label(
553
-                                EEH_HTML::strong(
554
-                                    esc_html__('IMPORTANT', 'event_espresso'),
555
-                                    '',
556
-                                    'important-notice'
557
-                                )
558
-                            )
559
-                        ) .
560
-                        EEH_HTML::td(
561
-                            EEH_HTML::strong(
562
-                                sprintf(
563
-                                    esc_html__(
564
-                                        'This payment method does not support the currency set on your site (%1$s). Please activate a different payment method or change your site\'s country and associated currency.',
565
-                                        'event_espresso'
566
-                                    ),
567
-                                    EE_Config::instance()->currency->code
568
-                                )
569
-                            )
570
-                        )
571
-                    )
572
-                )
573
-            );
574
-        }
575
-        return new EE_Form_Section_HTML('');
576
-    }
577
-
578
-
579
-    /**
580
-     * _update_payment_method_button
581
-     *
582
-     * @access protected
583
-     * @param EE_Payment_Method $payment_method
584
-     * @return EE_Payment_Method_Form
585
-     * @throws EE_Error
586
-     */
587
-    protected function _payment_method_settings(EE_Payment_Method $payment_method)
588
-    {
589
-        // modify the form, so we only have/show fields that will be implemented for this version
590
-        return $this->_simplify_form($payment_method->type_obj()->settings_form(), $payment_method->name());
591
-    }
592
-
593
-
594
-    /**
595
-     * Simplifies the form to merely reproduce 4.1's gateway settings functionality
596
-     *
597
-     * @param EE_Form_Section_Proper $form_section
598
-     * @param string                 $payment_method_name
599
-     * @return EE_Payment_Method_Form
600
-     * @throws EE_Error
601
-     */
602
-    protected function _simplify_form($form_section, $payment_method_name = '')
603
-    {
604
-        if ($form_section instanceof EE_Payment_Method_Form) {
605
-            $form_section->exclude(
606
-                array(
607
-                    'PMD_type', // don't want them changing the type
608
-                    'PMD_slug', // or the slug (probably never)
609
-                    'PMD_wp_user', // or the user's ID
610
-                    'Currency' // or the currency, until the rest of EE supports simultaneous currencies
611
-                )
612
-            );
613
-            return $form_section;
614
-        } else {
615
-            throw new EE_Error(
616
-                sprintf(
617
-                    esc_html__(
618
-                        'The EE_Payment_Method_Form for the "%1$s" payment method is missing or invalid.',
619
-                        'event_espresso'
620
-                    ),
621
-                    $payment_method_name
622
-                )
623
-            );
624
-        }
625
-    }
626
-
627
-
628
-    /**
629
-     * _update_payment_method_button
630
-     *
631
-     * @access protected
632
-     * @param EE_Payment_Method $payment_method
633
-     * @return EE_Form_Section_HTML
634
-     * @throws EE_Error
635
-     */
636
-    protected function _update_payment_method_button(EE_Payment_Method $payment_method)
637
-    {
638
-        $update_button = new EE_Submit_Input(
639
-            array(
640
-                'name'       => 'submit',
641
-                'html_id'    => 'save_' . $payment_method->slug() . '_settings',
642
-                'default'    => sprintf(
643
-                    esc_html__('Update %s Payment Settings', 'event_espresso'),
644
-                    $payment_method->admin_name()
645
-                ),
646
-                'html_label' => EEH_HTML::nbsp(),
647
-            )
648
-        );
649
-        return new EE_Form_Section_HTML(
650
-            EEH_HTML::table(
651
-                EEH_HTML::no_row(EEH_HTML::br(2)) .
652
-                EEH_HTML::tr(
653
-                    EEH_HTML::th(esc_html__('Update Settings', 'event_espresso')) .
654
-                    EEH_HTML::td(
655
-                        $update_button->get_html_for_input()
656
-                    )
657
-                )
658
-            )
659
-        );
660
-    }
661
-
662
-
663
-    /**
664
-     * _deactivate_payment_method_button
665
-     *
666
-     * @access protected
667
-     * @param EE_Payment_Method $payment_method
668
-     * @return EE_Form_Section_HTML
669
-     */
670
-    protected function _deactivate_payment_method_button(EE_Payment_Method $payment_method)
671
-    {
672
-        $link_text_and_title = sprintf(
673
-            esc_html__('Deactivate %1$s Payments?', 'event_espresso'),
674
-            $payment_method->admin_name()
675
-        );
676
-        return new EE_Form_Section_HTML(
677
-            EEH_HTML::table(
678
-                EEH_HTML::tr(
679
-                    EEH_HTML::th(esc_html__('Deactivate Payment Method', 'event_espresso')) .
680
-                    EEH_HTML::td(
681
-                        EEH_HTML::link(
682
-                            EE_Admin_Page::add_query_args_and_nonce(
683
-                                array(
684
-                                    'action'         => 'deactivate_payment_method',
685
-                                    'payment_method' => $payment_method->slug(),
686
-                                ),
687
-                                EE_PAYMENTS_ADMIN_URL
688
-                            ),
689
-                            $link_text_and_title,
690
-                            $link_text_and_title,
691
-                            'deactivate_' . $payment_method->slug(),
692
-                            'espresso-button button-secondary'
693
-                        )
694
-                    )
695
-                )
696
-            )
697
-        );
698
-    }
699
-
700
-
701
-    /**
702
-     * _activate_payment_method_button
703
-     *
704
-     * @access protected
705
-     * @param EE_Payment_Method $payment_method
706
-     * @return EE_Form_Section_Proper
707
-     * @throws EE_Error
708
-     */
709
-    protected function _activate_payment_method_button(EE_Payment_Method $payment_method)
710
-    {
711
-        $link_text_and_title = sprintf(
712
-            esc_html__('Activate %1$s Payment Method?', 'event_espresso'),
713
-            $payment_method->admin_name()
714
-        );
715
-        return new EE_Form_Section_Proper(
716
-            array(
717
-                'name'            => 'activate_' . $payment_method->slug() . '_settings_form',
718
-                'html_id'         => 'activate_' . $payment_method->slug() . '_settings_form',
719
-                'action'          => '#',
720
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
721
-                'subsections'     => apply_filters(
722
-                    'FHEE__Payments_Admin_Page___activate_payment_method_button__form_subsections',
723
-                    array(
724
-                        new EE_Form_Section_HTML(
725
-                            EEH_HTML::table(
726
-                                EEH_HTML::tr(
727
-                                    EEH_HTML::td(
728
-                                        $payment_method->type_obj()->introductory_html(),
729
-                                        '',
730
-                                        '',
731
-                                        '',
732
-                                        'colspan="2"'
733
-                                    )
734
-                                ) .
735
-                                EEH_HTML::tr(
736
-                                    EEH_HTML::th(
737
-                                        EEH_HTML::label(esc_html__('Click to Activate ', 'event_espresso'))
738
-                                    ) .
739
-                                    EEH_HTML::td(
740
-                                        EEH_HTML::link(
741
-                                            EE_Admin_Page::add_query_args_and_nonce(
742
-                                                array(
743
-                                                    'action'              => 'activate_payment_method',
744
-                                                    'payment_method_type' => $payment_method->type(),
745
-                                                ),
746
-                                                EE_PAYMENTS_ADMIN_URL
747
-                                            ),
748
-                                            $link_text_and_title,
749
-                                            $link_text_and_title,
750
-                                            'activate_' . $payment_method->slug(),
751
-                                            'espresso-button-green button-primary'
752
-                                        )
753
-                                    )
754
-                                )
755
-                            )
756
-                        ),
757
-                    ),
758
-                    $payment_method
759
-                ),
760
-            )
761
-        );
762
-    }
763
-
764
-
765
-    /**
766
-     * _fine_print
767
-     *
768
-     * @access protected
769
-     * @return EE_Form_Section_HTML
770
-     */
771
-    protected function _fine_print()
772
-    {
773
-        return new EE_Form_Section_HTML(
774
-            EEH_HTML::table(
775
-                EEH_HTML::tr(
776
-                    EEH_HTML::th() .
777
-                    EEH_HTML::td(
778
-                        EEH_HTML::p(esc_html__('All fields marked with a * are required fields', 'event_espresso'), '', 'grey-text')
779
-                    )
780
-                )
781
-            )
782
-        );
783
-    }
784
-
785
-
786
-    /**
787
-     * Activates a payment method of that type. Mostly assuming there is only 1 of that type (or none so far)
788
-     *
789
-     * @throws EE_Error
790
-     * @throws ReflectionException
791
-     * @global WP_User $current_user
792
-     */
793
-    protected function _activate_payment_method()
794
-    {
795
-        if (isset($this->_req_data['payment_method_type'])) {
796
-            $payment_method_type = sanitize_text_field($this->_req_data['payment_method_type']);
797
-            // see if one exists
798
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
799
-            $payment_method = EE_Payment_Method_Manager::instance()
800
-                                                       ->activate_a_payment_method_of_type($payment_method_type);
801
-            $this->_redirect_after_action(
802
-                1,
803
-                'Payment Method',
804
-                'activated',
805
-                array('action' => 'default', 'payment_method' => $payment_method->slug())
806
-            );
807
-        } else {
808
-            $this->_redirect_after_action(false, 'Payment Method', 'activated', array('action' => 'default'));
809
-        }
810
-    }
811
-
812
-
813
-    /**
814
-     * @throws EE_Error
815
-     * @throws ReflectionException
816
-     */
817
-    protected function _deactivate_payment_method()
818
-    {
819
-        if (isset($this->_req_data['payment_method'])) {
820
-            $payment_method_slug = sanitize_key($this->_req_data['payment_method']);
821
-            // deactivate it
822
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
823
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method($payment_method_slug);
824
-            $this->_redirect_after_action(
825
-                $count_updated,
826
-                'Payment Method',
827
-                'deactivated',
828
-                array('action' => 'default', 'payment_method' => $payment_method_slug)
829
-            );
830
-        } else {
831
-            $this->_redirect_after_action(false, 'Payment Method', 'deactivated', array('action' => 'default'));
832
-        }
833
-    }
834
-
835
-
836
-    /**
837
-     * Processes the payment method form that was submitted. This is slightly trickier than usual form
838
-     * processing because we first need to identify WHICH form was processed and which payment method
839
-     * it corresponds to. Once we have done that, we see if the form is valid. If it is, the
840
-     * form's data is saved, and we redirect to the default payment methods page, setting the updated payment method
841
-     * as the currently-selected one. If it DOESN'T validate, we render the page with the form's errors (in the
842
-     * subsequently called 'headers_sent_func' which is _payment_methods_list)
843
-     *
844
-     * @return void
845
-     * @throws EE_Error
846
-     * @throws ReflectionException
847
-     */
848
-    protected function _update_payment_method()
849
-    {
850
-        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
851
-            // ok let's find which gateway form to use based on the form input
852
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
853
-            /** @var $correct_pmt_form_to_use EE_Payment_Method_Form */
854
-            $correct_pmt_form_to_use = null;
855
-            $payment_method = null;
856
-            foreach (EEM_Payment_Method::instance()->get_all() as $payment_method) {
857
-                if ($payment_method instanceof EE_Payment_Method) {
858
-                    // get the form and simplify it, like what we do when we display it
859
-                    $pmt_form = $this->_generate_payment_method_settings_form($payment_method);
860
-                    if ($pmt_form->form_data_present_in($this->_req_data)) {
861
-                        $correct_pmt_form_to_use = $pmt_form;
862
-                        break;
863
-                    }
864
-                }
865
-            }
866
-            // if we couldn't find the correct payment method type...
867
-            if (! $correct_pmt_form_to_use) {
868
-                EE_Error::add_error(
869
-                    esc_html__(
870
-                        "We could not find which payment method type your form submission related to. Please contact support",
871
-                        'event_espresso'
872
-                    ),
873
-                    __FILE__,
874
-                    __FUNCTION__,
875
-                    __LINE__
876
-                );
877
-                $this->_redirect_after_action(false, 'Payment Method', 'activated', array('action' => 'default'));
878
-            }
879
-            $correct_pmt_form_to_use->receive_form_submission($this->_req_data);
880
-            if ($correct_pmt_form_to_use->is_valid()) {
881
-                $payment_settings_subform = $correct_pmt_form_to_use->get_subsection('payment_method_settings');
882
-                if (! $payment_settings_subform instanceof EE_Payment_Method_Form) {
883
-                    throw new EE_Error(
884
-                        sprintf(
885
-                            esc_html__(
886
-                                'The payment method could not be saved because the form sections were misnamed. We expected to find %1$s, but did not.',
887
-                                'event_espresso'
888
-                            ),
889
-                            'payment_method_settings'
890
-                        )
891
-                    );
892
-                }
893
-                $payment_settings_subform->save();
894
-                /** @var $pm EE_Payment_Method */
895
-                $this->_redirect_after_action(
896
-                    true,
897
-                    'Payment Method',
898
-                    'updated',
899
-                    array('action' => 'default', 'payment_method' => $payment_method->slug())
900
-                );
901
-            } else {
902
-                EE_Error::add_error(
903
-                    sprintf(
904
-                        esc_html__(
905
-                            'Payment method of type %s was not saved because there were validation errors. They have been marked in the form',
906
-                            'event_espresso'
907
-                        ),
908
-                        $payment_method instanceof EE_Payment_Method ? $payment_method->type_obj()->pretty_name()
909
-                            : esc_html__('"(unknown)"', 'event_espresso')
910
-                    ),
911
-                    __FILE__,
912
-                    __FUNCTION__,
913
-                    __LINE__
914
-                );
915
-            }
916
-        }
917
-    }
918
-
919
-
920
-    /**
921
-     * Displays payment settings (not payment METHOD settings, that's _payment_method_settings)
922
-     * @throws DomainException
923
-     * @throws EE_Error
924
-     * @throws InvalidArgumentException
925
-     * @throws InvalidDataTypeException
926
-     * @throws InvalidInterfaceException
927
-     */
928
-    protected function _payment_settings()
929
-    {
930
-        $form = $this->getPaymentSettingsForm();
931
-        $this->_set_add_edit_form_tags('update_payment_settings');
932
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
933
-        $this->_template_args['admin_page_content'] =  $form->get_html_and_js();
934
-        $this->display_admin_page_with_sidebar();
935
-    }
936
-
937
-
938
-    /**
939
-     *        _update_payment_settings
940
-     *
941
-     * @access protected
942
-     * @return void
943
-     * @throws EE_Error
944
-     * @throws InvalidArgumentException
945
-     * @throws InvalidDataTypeException
946
-     * @throws InvalidInterfaceException
947
-     */
948
-    protected function _update_payment_settings()
949
-    {
950
-        $form = $this->getPaymentSettingsForm();
951
-        if ($form->was_submitted($this->_req_data)) {
952
-            $form->receive_form_submission($this->_req_data);
953
-            if ($form->is_valid()) {
954
-                /**
955
-                 * @var $reg_config EE_Registration_Config
956
-                 */
957
-                $loader = LoaderFactory::getLoader();
958
-                $reg_config = $loader->getShared('EE_Registration_Config');
959
-                $valid_data = $form->valid_data();
960
-                $reg_config->show_pending_payment_options = $valid_data['show_pending_payment_options'];
961
-                $reg_config->gateway_log_lifespan = $valid_data['gateway_log_lifespan'];
962
-            }
963
-        }
964
-        EE_Registry::instance()->CFG = apply_filters(
965
-            'FHEE__Payments_Admin_Page___update_payment_settings__CFG',
966
-            EE_Registry::instance()->CFG
967
-        );
968
-
969
-        $what = esc_html__('Payment Settings', 'event_espresso');
970
-        $success = $this->_update_espresso_configuration(
971
-            $what,
972
-            EE_Registry::instance()->CFG,
973
-            __FILE__,
974
-            __FUNCTION__,
975
-            __LINE__
976
-        );
977
-        $this->_redirect_after_action(
978
-            $success,
979
-            $what,
980
-            esc_html__('updated', 'event_espresso'),
981
-            array('action' => 'payment_settings')
982
-        );
983
-    }
984
-
985
-
986
-    /**
987
-     * Gets the form used for updating payment settings
988
-     *
989
-     * @return EE_Form_Section_Proper
990
-     * @throws EE_Error
991
-     * @throws InvalidArgumentException
992
-     * @throws InvalidDataTypeException
993
-     * @throws InvalidInterfaceException
994
-     */
995
-    protected function getPaymentSettingsForm()
996
-    {
997
-        /**
998
-         * @var $reg_config EE_Registration_Config
999
-         */
1000
-        $reg_config = LoaderFactory::getLoader()->getShared('EE_Registration_Config');
1001
-        return new EE_Form_Section_Proper(
1002
-            array(
1003
-                'name' => 'payment-settings',
1004
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1005
-                'subsections' => array(
1006
-                    'show_pending_payment_options' => new EE_Yes_No_Input(
1007
-                        array(
1008
-                            'html_name' => 'show_pending_payment_options',
1009
-                            'default' => $reg_config->show_pending_payment_options,
1010
-                            'html_help_text' => esc_html__(
1011
-                                "If a payment is marked as 'Pending Payment', or if payment is deferred (ie, an offline gateway like Check, Bank, or Invoice is used), then give registrants the option to retry payment. ",
1012
-                                'event_espresso'
1013
-                            )
1014
-                        )
1015
-                    ),
1016
-                    'gateway_log_lifespan' => new EE_Select_Input(
1017
-                        $reg_config->gatewayLogLifespanOptions(),
1018
-                        array(
1019
-                            'html_label_text' => esc_html__('Gateway Logs Lifespan', 'event_espresso'),
1020
-                            'html_help_text' => esc_html__('If issues arise with payments being made through a payment gateway, it\'s helpful to log non-sensitive communications with the payment gateway. But it\'s a security responsibility, so it\'s a good idea to not keep them for any longer than necessary.', 'event_espresso'),
1021
-                            'default' => $reg_config->gateway_log_lifespan,
1022
-                        )
1023
-                    )
1024
-                )
1025
-            )
1026
-        );
1027
-    }
1028
-
1029
-
1030
-    /**
1031
-     * @throws EE_Error
1032
-     */
1033
-    protected function _payment_log_overview_list_table()
1034
-    {
1035
-        $this->display_admin_list_table_page_with_sidebar();
1036
-    }
1037
-
1038
-
1039
-    protected function _set_list_table_views_payment_log()
1040
-    {
1041
-        $this->_views = array(
1042
-            'all' => array(
1043
-                'slug'  => 'all',
1044
-                'label' => esc_html__('View All Logs', 'event_espresso'),
1045
-                'count' => 0,
1046
-            ),
1047
-        );
1048
-    }
1049
-
1050
-
1051
-    /**
1052
-     * @param int  $per_page
1053
-     * @param int  $current_page
1054
-     * @param bool $count
1055
-     * @return array|int
1056
-     * @throws EE_Error
1057
-     * @throws ReflectionException
1058
-     */
1059
-    public function get_payment_logs($per_page = 50, $current_page = 0, $count = false)
1060
-    {
1061
-        EE_Registry::instance()->load_model('Change_Log');
1062
-        // we may need to do multiple queries (joining differently), so we actually want an array of query params
1063
-        $query_params = array(array('LOG_type' => EEM_Change_Log::type_gateway));
1064
-        // check if they've selected a specific payment method
1065
-        if (isset($this->_req_data['_payment_method']) && $this->_req_data['_payment_method'] !== 'all') {
1066
-            $query_params[0]['OR*pm_or_pay_pm'] = array(
1067
-                'Payment.Payment_Method.PMD_ID' => $this->_req_data['_payment_method'],
1068
-                'Payment_Method.PMD_ID'         => $this->_req_data['_payment_method'],
1069
-            );
1070
-        }
1071
-        // take into account search
1072
-        if (isset($this->_req_data['s']) && $this->_req_data['s']) {
1073
-            $similarity_string = array('LIKE', '%' . str_replace("", "%", $this->_req_data['s']) . '%');
1074
-            $query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_fname'] = $similarity_string;
1075
-            $query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_lname'] = $similarity_string;
1076
-            $query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_email'] = $similarity_string;
1077
-            $query_params[0]['OR*s']['Payment.Payment_Method.PMD_name'] = $similarity_string;
1078
-            $query_params[0]['OR*s']['Payment.Payment_Method.PMD_admin_name'] = $similarity_string;
1079
-            $query_params[0]['OR*s']['Payment.Payment_Method.PMD_type'] = $similarity_string;
1080
-            $query_params[0]['OR*s']['LOG_message'] = $similarity_string;
1081
-            $query_params[0]['OR*s']['Payment_Method.PMD_name'] = $similarity_string;
1082
-            $query_params[0]['OR*s']['Payment_Method.PMD_admin_name'] = $similarity_string;
1083
-            $query_params[0]['OR*s']['Payment_Method.PMD_type'] = $similarity_string;
1084
-            $query_params[0]['OR*s']['LOG_message'] = $similarity_string;
1085
-        }
1086
-        if (
1087
-            isset($this->_req_data['payment-filter-start-date'])
1088
-            && isset($this->_req_data['payment-filter-end-date'])
1089
-        ) {
1090
-            // add date
1091
-            $start_date = wp_strip_all_tags($this->_req_data['payment-filter-start-date']);
1092
-            $end_date = wp_strip_all_tags($this->_req_data['payment-filter-end-date']);
1093
-            // make sure our timestamps start and end right at the boundaries for each day
1094
-            $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
1095
-            $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
1096
-            // convert to timestamps
1097
-            $start_date = strtotime($start_date);
1098
-            $end_date = strtotime($end_date);
1099
-            // makes sure start date is the lowest value and vice versa
1100
-            $start_date = min($start_date, $end_date);
1101
-            $end_date = max($start_date, $end_date);
1102
-            // convert for query
1103
-            $start_date = EEM_Change_Log::instance()->convert_datetime_for_query(
1104
-                'LOG_time',
1105
-                date('Y-m-d H:i:s', $start_date),
1106
-                'Y-m-d H:i:s'
1107
-            );
1108
-            $end_date   = EEM_Change_Log::instance()->convert_datetime_for_query(
1109
-                'LOG_time',
1110
-                date('Y-m-d H:i:s', $end_date),
1111
-                'Y-m-d H:i:s'
1112
-            );
1113
-            $query_params[0]['LOG_time'] = array('BETWEEN', array($start_date, $end_date));
1114
-        }
1115
-        if ($count) {
1116
-            return EEM_Change_Log::instance()->count($query_params);
1117
-        }
1118
-        if (isset($this->_req_data['order'])) {
1119
-            $sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1120
-                ? $this->_req_data['order']
1121
-                : 'DESC';
1122
-            $query_params['order_by'] = array('LOG_time' => $sort);
1123
-        } else {
1124
-            $query_params['order_by'] = array('LOG_time' => 'DESC');
1125
-        }
1126
-        $offset = ($current_page - 1) * $per_page;
1127
-        if (! isset($this->_req_data['download_results'])) {
1128
-            $query_params['limit'] = array($offset, $per_page);
1129
-        }
1130
-        // now they've requested to instead just download the file instead of viewing it.
1131
-        if (isset($this->_req_data['download_results'])) {
1132
-            $wpdb_results = EEM_Change_Log::instance()->get_all_efficiently($query_params);
1133
-            header('Content-Disposition: attachment');
1134
-            header("Content-Disposition: attachment; filename=ee_payment_logs_for_" . sanitize_key(site_url()));
1135
-            echo '<h1> '
1136
-                . sprintf(
1137
-                    esc_html__('Payment Logs for %1$s', 'event_espresso'),
1138
-                    esc_url_raw(site_url())
1139
-                )
1140
-                . '</h1 >';
1141
-            echo '<h3>' . esc_html__('Query:', 'event_espresso') . '</h3>';
1142
-            echo esc_html(var_export($query_params, true));
1143
-            echo '<h3>' . esc_html__('Results:', 'event_espresso') . '</h3>';
1144
-            echo esc_html(var_export($wpdb_results, true));
1145
-            die;
1146
-        }
1147
-        return EEM_Change_Log::instance()->get_all($query_params);
1148
-    }
1149
-
1150
-
1151
-    /**
1152
-     * Used by usort to RE-sort log query results, because we lose the ordering
1153
-     * because we're possibly combining the results from two queries
1154
-     *
1155
-     * @param EE_Change_Log $logA
1156
-     * @param EE_Change_Log $logB
1157
-     * @return int
1158
-     * @throws EE_Error
1159
-     * @throws ReflectionException
1160
-     */
1161
-    protected function _sort_logs_again($logA, $logB)
1162
-    {
1163
-        $timeA = $logA->get_raw('LOG_time');
1164
-        $timeB = $logB->get_raw('LOG_time');
1165
-        if ($timeA == $timeB) {
1166
-            return 0;
1167
-        }
1168
-        $comparison = $timeA < $timeB ? -1 : 1;
1169
-        if (strtoupper($this->_sort_logs_again_direction) == 'DESC') {
1170
-            return $comparison * -1;
1171
-        }
1172
-        return $comparison;
1173
-    }
1174
-
1175
-
1176
-    /**
1177
-     * @throws EE_Error
1178
-     * @throws ReflectionException
1179
-     */
1180
-    protected function _payment_log_details()
1181
-    {
1182
-        EE_Registry::instance()->load_model('Change_Log');
1183
-        /** @var $payment_log EE_Change_Log */
1184
-        $payment_log = EEM_Change_Log::instance()->get_one_by_ID($this->_req_data['ID']);
1185
-        $payment_method = null;
1186
-        $transaction = null;
1187
-        if ($payment_log instanceof EE_Change_Log) {
1188
-            if ($payment_log->object() instanceof EE_Payment) {
1189
-                $payment_method = $payment_log->object()->payment_method();
1190
-                $transaction = $payment_log->object()->transaction();
1191
-            } elseif ($payment_log->object() instanceof EE_Payment_Method) {
1192
-                $payment_method = $payment_log->object();
1193
-            } elseif ($payment_log->object() instanceof EE_Transaction) {
1194
-                $transaction = $payment_log->object();
1195
-                $payment_method = $transaction->payment_method();
1196
-            }
1197
-        }
1198
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1199
-            EE_PAYMENTS_TEMPLATE_PATH . 'payment_log_details.template.php',
1200
-            array(
1201
-                'payment_log'    => $payment_log,
1202
-                'payment_method' => $payment_method,
1203
-                'transaction'    => $transaction,
1204
-            ),
1205
-            true
1206
-        );
1207
-        $this->display_admin_page_with_sidebar();
1208
-    }
18
+	/**
19
+	 * Variables used for when we're re-sorting the logs results,
20
+	 * in case we needed to do two queries, and we need to resort
21
+	 *
22
+	 * @var string
23
+	 */
24
+	private $_sort_logs_again_direction;
25
+
26
+
27
+	/**
28
+	 * @Constructor
29
+	 * @access public
30
+	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
31
+	 * @throws EE_Error
32
+	 * @throws InvalidArgumentException
33
+	 * @throws InvalidDataTypeException
34
+	 * @throws InvalidInterfaceException
35
+	 * @throws ReflectionException
36
+	 */
37
+	public function __construct($routing = true)
38
+	{
39
+		parent::__construct($routing);
40
+	}
41
+
42
+
43
+	protected function _init_page_props()
44
+	{
45
+		$this->page_slug = EE_PAYMENTS_PG_SLUG;
46
+		$this->page_label = esc_html__('Payment Methods', 'event_espresso');
47
+		$this->_admin_base_url = EE_PAYMENTS_ADMIN_URL;
48
+		$this->_admin_base_path = EE_PAYMENTS_ADMIN;
49
+	}
50
+
51
+
52
+	protected function _ajax_hooks()
53
+	{
54
+		// todo: all hooks for ajax goes here.
55
+	}
56
+
57
+
58
+	protected function _define_page_props()
59
+	{
60
+		$this->_admin_page_title = $this->page_label;
61
+		$this->_labels = array(
62
+			'publishbox' => esc_html__('Update Settings', 'event_espresso'),
63
+		);
64
+	}
65
+
66
+
67
+	protected function _set_page_routes()
68
+	{
69
+		/**
70
+		 * note that with payment method capabilities, although we've implemented
71
+		 * capability mapping which will be used for accessing payment methods owned by
72
+		 * other users.  This is not fully implemented yet in the payment method ui.
73
+		 * Currently, only the "plural" caps are in active use.
74
+		 * When cap mapping is implemented, some routes will need to use the singular form of
75
+		 * capability method and also include the $id of the payment method for the route.
76
+		 **/
77
+		$this->_page_routes = array(
78
+			'default'                   => array(
79
+				'func'       => '_payment_methods_list',
80
+				'capability' => 'ee_edit_payment_methods',
81
+			),
82
+			'payment_settings'          => array(
83
+				'func'       => '_payment_settings',
84
+				'capability' => 'ee_manage_gateways',
85
+			),
86
+			'activate_payment_method'   => array(
87
+				'func'       => '_activate_payment_method',
88
+				'noheader'   => true,
89
+				'capability' => 'ee_edit_payment_methods',
90
+			),
91
+			'deactivate_payment_method' => array(
92
+				'func'       => '_deactivate_payment_method',
93
+				'noheader'   => true,
94
+				'capability' => 'ee_delete_payment_methods',
95
+			),
96
+			'update_payment_method'     => array(
97
+				'func'               => '_update_payment_method',
98
+				'noheader'           => true,
99
+				'headers_sent_route' => 'default',
100
+				'capability'         => 'ee_edit_payment_methods',
101
+			),
102
+			'update_payment_settings'   => array(
103
+				'func'       => '_update_payment_settings',
104
+				'noheader'   => true,
105
+				'capability' => 'ee_manage_gateways',
106
+			),
107
+			'payment_log'               => array(
108
+				'func'       => '_payment_log_overview_list_table',
109
+				'capability' => 'ee_read_payment_methods',
110
+			),
111
+			'payment_log_details'       => array(
112
+				'func'       => '_payment_log_details',
113
+				'capability' => 'ee_read_payment_methods',
114
+			),
115
+		);
116
+	}
117
+
118
+
119
+	/**
120
+	 * @throws EE_Error
121
+	 * @throws ReflectionException
122
+	 */
123
+	protected function _set_page_config()
124
+	{
125
+		$payment_method_list_config = array(
126
+			'nav'           => array(
127
+				'label' => esc_html__('Payment Methods', 'event_espresso'),
128
+				'order' => 10,
129
+			),
130
+			'metaboxes'     => $this->_default_espresso_metaboxes,
131
+			'help_tabs'     => array_merge(
132
+				array(
133
+					'payment_methods_overview_help_tab' => array(
134
+						'title'    => esc_html__('Payment Methods Overview', 'event_espresso'),
135
+						'filename' => 'payment_methods_overview',
136
+					),
137
+				),
138
+				$this->_add_payment_method_help_tabs()
139
+			),
140
+			'require_nonce' => false,
141
+		);
142
+		$this->_page_config = array(
143
+			'default'          => $payment_method_list_config,
144
+			'payment_settings' => array(
145
+				'nav'           => array(
146
+					'label' => esc_html__('Settings', 'event_espresso'),
147
+					'order' => 20,
148
+				),
149
+				'help_tabs'     => array(
150
+					'payment_methods_settings_help_tab' => array(
151
+						'title'    => esc_html__('Payment Method Settings', 'event_espresso'),
152
+						'filename' => 'payment_methods_settings',
153
+					),
154
+				),
155
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
156
+				'require_nonce' => false,
157
+			),
158
+			'payment_log'      => array(
159
+				'nav'           => array(
160
+					'label' => esc_html__("Logs", 'event_espresso'),
161
+					'order' => 30,
162
+				),
163
+				'list_table'    => 'Payment_Log_Admin_List_Table',
164
+				'metaboxes'     => $this->_default_espresso_metaboxes,
165
+				'require_nonce' => false,
166
+			),
167
+		);
168
+	}
169
+
170
+
171
+	/**
172
+	 * @return array
173
+	 * @throws DomainException
174
+	 * @throws EE_Error
175
+	 * @throws InvalidArgumentException
176
+	 * @throws InvalidDataTypeException
177
+	 * @throws InvalidInterfaceException
178
+	 * @throws ReflectionException
179
+	 */
180
+	protected function _add_payment_method_help_tabs()
181
+	{
182
+		EE_Registry::instance()->load_lib('Payment_Method_Manager');
183
+		$payment_method_types = EE_Payment_Method_Manager::instance()->payment_method_types();
184
+		$all_pmt_help_tabs_config = array();
185
+		foreach ($payment_method_types as $payment_method_type) {
186
+			if (
187
+				! EE_Registry::instance()->CAP->current_user_can(
188
+					$payment_method_type->cap_name(),
189
+					'specific_payment_method_type_access'
190
+				)
191
+			) {
192
+				continue;
193
+			}
194
+			foreach ($payment_method_type->help_tabs_config() as $help_tab_name => $config) {
195
+				$template_args = isset($config['template_args']) ? $config['template_args'] : array();
196
+				$template_args['admin_page_obj'] = $this;
197
+				$all_pmt_help_tabs_config[ $help_tab_name ] = array(
198
+					'title'   => $config['title'],
199
+					'content' => EEH_Template::display_template(
200
+						$payment_method_type->file_folder() . 'help_tabs/' . $config['filename'] . '.help_tab.php',
201
+						$template_args,
202
+						true
203
+					),
204
+				);
205
+			}
206
+		}
207
+		return $all_pmt_help_tabs_config;
208
+	}
209
+
210
+
211
+	// none of the below group are currently used for Gateway Settings
212
+	protected function _add_screen_options()
213
+	{
214
+	}
215
+
216
+
217
+	protected function _add_feature_pointers()
218
+	{
219
+	}
220
+
221
+
222
+	public function admin_init()
223
+	{
224
+	}
225
+
226
+
227
+	public function admin_notices()
228
+	{
229
+	}
230
+
231
+
232
+	public function admin_footer_scripts()
233
+	{
234
+	}
235
+
236
+
237
+	public function load_scripts_styles()
238
+	{
239
+		// styles
240
+		wp_enqueue_style('espresso-ui-theme');
241
+		// scripts
242
+		wp_enqueue_script('ee_admin_js');
243
+		wp_enqueue_script('ee-text-links');
244
+		wp_enqueue_script(
245
+			'espresso_payments',
246
+			EE_PAYMENTS_ASSETS_URL . 'espresso_payments_admin.js',
247
+			array('ee-datepicker'),
248
+			EVENT_ESPRESSO_VERSION,
249
+			true
250
+		);
251
+	}
252
+
253
+
254
+	public function load_scripts_styles_default()
255
+	{
256
+		// styles
257
+		wp_register_style(
258
+			'espresso_payments',
259
+			EE_PAYMENTS_ASSETS_URL . 'ee-payments.css',
260
+			array(),
261
+			EVENT_ESPRESSO_VERSION
262
+		);
263
+		wp_enqueue_style('espresso_payments');
264
+		wp_enqueue_style('ee-text-links');
265
+		// scripts
266
+	}
267
+
268
+
269
+	/**
270
+	 * @throws EE_Error
271
+	 * @throws ReflectionException
272
+	 */
273
+	protected function _payment_methods_list()
274
+	{
275
+		/**
276
+		 * first let's ensure payment methods have been set up.
277
+		 * We do this here because when people activate a payment method for the first time (as an addon),
278
+		 * it may not set up its capabilities or get registered correctly due to the loading process.
279
+		 * However, people MUST set up the details for the payment method,
280
+		 * so it's safe to do a recheck here.
281
+		 */
282
+		EE_Registry::instance()->load_lib('Payment_Method_Manager');
283
+		EEM_Payment_Method::instance()->verify_button_urls();
284
+		// set up tabs, one for each payment method type
285
+		$tabs = array();
286
+		$payment_methods = array();
287
+		foreach (EE_Payment_Method_Manager::instance()->payment_method_types() as $pmt_obj) {
288
+			// we don't want to show admin-only PMTs for now
289
+			if ($pmt_obj instanceof EE_PMT_Admin_Only) {
290
+				continue;
291
+			}
292
+			// check access
293
+			if (
294
+				! EE_Registry::instance()->CAP->current_user_can(
295
+					$pmt_obj->cap_name(),
296
+					'specific_payment_method_type_access'
297
+				)
298
+			) {
299
+				continue;
300
+			}
301
+			// check for any active pms of that type
302
+			$payment_method = EEM_Payment_Method::instance()->get_one_of_type($pmt_obj->system_name());
303
+			if (! $payment_method instanceof EE_Payment_Method) {
304
+				$payment_method = EE_Payment_Method::new_instance(
305
+					array(
306
+						'PMD_slug'       => sanitize_key($pmt_obj->system_name()),
307
+						'PMD_type'       => $pmt_obj->system_name(),
308
+						'PMD_name'       => $pmt_obj->pretty_name(),
309
+						'PMD_admin_name' => $pmt_obj->pretty_name(),
310
+					)
311
+				);
312
+			}
313
+			$payment_methods[ $payment_method->slug() ] = $payment_method;
314
+		}
315
+		$payment_methods = apply_filters(
316
+			'FHEE__Payments_Admin_Page___payment_methods_list__payment_methods',
317
+			$payment_methods
318
+		);
319
+		foreach ($payment_methods as $payment_method) {
320
+			if ($payment_method instanceof EE_Payment_Method) {
321
+				add_meta_box(
322
+					// html id
323
+					'espresso_' . $payment_method->slug() . '_payment_settings',
324
+					// title
325
+					sprintf(esc_html__('%s Settings', 'event_espresso'), $payment_method->admin_name()),
326
+					// callback
327
+					array($this, 'payment_method_settings_meta_box'),
328
+					// post type
329
+					null,
330
+					// context
331
+					'normal',
332
+					// priority
333
+					'default',
334
+					// callback args
335
+					array('payment_method' => $payment_method)
336
+				);
337
+				// setup for tabbed content
338
+				$tabs[ $payment_method->slug() ] = array(
339
+					'label' => $payment_method->admin_name(),
340
+					'class' => $payment_method->active() ? 'gateway-active' : '',
341
+					'href'  => 'espresso_' . $payment_method->slug() . '_payment_settings',
342
+					'title' => esc_html__('Modify this Payment Method', 'event_espresso'),
343
+					'slug'  => $payment_method->slug(),
344
+				);
345
+			}
346
+		}
347
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
348
+			$tabs,
349
+			'payment_method_links',
350
+			'|',
351
+			$this->_get_active_payment_method_slug()
352
+		);
353
+		$this->display_admin_page_with_sidebar();
354
+	}
355
+
356
+
357
+	/**
358
+	 *   _get_active_payment_method_slug
359
+	 *
360
+	 * @return string
361
+	 * @throws EE_Error
362
+	 */
363
+	protected function _get_active_payment_method_slug()
364
+	{
365
+		$payment_method_slug = false;
366
+		// decide which payment method tab to open first, as dictated by the request's 'payment_method'
367
+		if (isset($this->_req_data['payment_method'])) {
368
+			// if they provided the current payment method, use it
369
+			$payment_method_slug = sanitize_key($this->_req_data['payment_method']);
370
+		}
371
+		/** @var EE_Payment_Method $payment_method */
372
+		$payment_method = EEM_Payment_Method::instance()->get_one(array(array('PMD_slug' => $payment_method_slug)));
373
+		// if that didn't work or wasn't provided, find another way to select the current pm
374
+		if (! $this->_verify_payment_method($payment_method)) {
375
+			// like, looking for an active one
376
+			$payment_method = EEM_Payment_Method::instance()->get_one_active('CART');
377
+			// test that one as well
378
+			if ($this->_verify_payment_method($payment_method)) {
379
+				$payment_method_slug = $payment_method->slug();
380
+			} else {
381
+				$payment_method_slug = 'paypal_standard';
382
+			}
383
+		}
384
+		return $payment_method_slug;
385
+	}
386
+
387
+
388
+	/**
389
+	 *    payment_method_settings_meta_box
390
+	 *    returns TRUE if the passed payment method is properly constructed and the logged-in user has the correct
391
+	 *    capabilities to access it
392
+	 *
393
+	 * @param EE_Payment_Method $payment_method
394
+	 * @return boolean
395
+	 * @throws EE_Error
396
+	 */
397
+	protected function _verify_payment_method($payment_method)
398
+	{
399
+		if (
400
+			$payment_method instanceof EE_Payment_Method && $payment_method->type_obj() instanceof EE_PMT_Base
401
+			&& EE_Registry::instance()->CAP->current_user_can(
402
+				$payment_method->type_obj()->cap_name(),
403
+				'specific_payment_method_type_access'
404
+			)
405
+		) {
406
+			return true;
407
+		}
408
+		return false;
409
+	}
410
+
411
+
412
+	/**
413
+	 *    payment_method_settings_meta_box
414
+	 *
415
+	 * @param NULL  $post_obj_which_is_null is an object containing the current post (as a $post object)
416
+	 * @param array $metabox                is an array with metabox id, title, callback, and args elements. the value
417
+	 *                                      at 'args' has key 'payment_method', as set within _payment_methods_list
418
+	 * @return void
419
+	 * @throws EE_Error
420
+	 * @throws ReflectionException
421
+	 */
422
+	public function payment_method_settings_meta_box($post_obj_which_is_null, $metabox)
423
+	{
424
+		$payment_method = isset($metabox['args'], $metabox['args']['payment_method'])
425
+			? $metabox['args']['payment_method'] : null;
426
+		if (! $payment_method instanceof EE_Payment_Method) {
427
+			throw new EE_Error(
428
+				esc_html__(
429
+					'Payment method metabox setup incorrectly. No Payment method object was supplied',
430
+					'event_espresso'
431
+				)
432
+			);
433
+		}
434
+		$payment_method_scopes = $payment_method->active();
435
+		// if the payment method really exists show its form, otherwise the activation template
436
+		if ($payment_method->ID() && ! empty($payment_method_scopes)) {
437
+			$form = $this->_generate_payment_method_settings_form($payment_method);
438
+			if ($form->form_data_present_in($this->_req_data)) {
439
+				$form->receive_form_submission($this->_req_data);
440
+			}
441
+			echo $form->form_open() . $form->get_html_and_js() . $form->form_close(); // already escaped
442
+		} else {
443
+			echo $this->_activate_payment_method_button($payment_method)->get_html_and_js(); // already escaped
444
+		}
445
+	}
446
+
447
+
448
+	/**
449
+	 * Gets the form for all the settings related to this payment method type
450
+	 *
451
+	 * @access protected
452
+	 * @param EE_Payment_Method $payment_method
453
+	 * @return EE_Form_Section_Proper
454
+	 * @throws EE_Error
455
+	 */
456
+	protected function _generate_payment_method_settings_form(EE_Payment_Method $payment_method = null)
457
+	{
458
+		if (! $payment_method instanceof EE_Payment_Method) {
459
+			return new EE_Form_Section_Proper();
460
+		}
461
+		return new EE_Form_Section_Proper(
462
+			array(
463
+				'name'            => $payment_method->slug() . '_settings_form',
464
+				'html_id'         => $payment_method->slug() . '_settings_form',
465
+				'action'          => EE_Admin_Page::add_query_args_and_nonce(
466
+					array(
467
+						'action'         => 'update_payment_method',
468
+						'payment_method' => $payment_method->slug(),
469
+					),
470
+					EE_PAYMENTS_ADMIN_URL
471
+				),
472
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
473
+				'subsections'     => apply_filters(
474
+					'FHEE__Payments_Admin_Page___generate_payment_method_settings_form__form_subsections',
475
+					array(
476
+						'pci_dss_compliance'      => $this->_pci_dss_compliance($payment_method),
477
+						'currency_support'        => $this->_currency_support($payment_method),
478
+						'payment_method_settings' => $this->_payment_method_settings($payment_method),
479
+						'update'                  => $this->_update_payment_method_button($payment_method),
480
+						'deactivate'              => $this->_deactivate_payment_method_button($payment_method),
481
+						'fine_print'              => $this->_fine_print(),
482
+					),
483
+					$payment_method
484
+				),
485
+			)
486
+		);
487
+	}
488
+
489
+
490
+	/**
491
+	 * _pci_dss_compliance
492
+	 *
493
+	 * @access protected
494
+	 * @param EE_Payment_Method $payment_method
495
+	 * @return EE_Form_Section_HTML
496
+	 * @throws EE_Error
497
+	 */
498
+	protected function _pci_dss_compliance(EE_Payment_Method $payment_method)
499
+	{
500
+		if ($payment_method->type_obj()->requires_https()) {
501
+			return new EE_Form_Section_HTML(
502
+				EEH_HTML::table(
503
+					EEH_HTML::tr(
504
+						EEH_HTML::th(
505
+							EEH_HTML::label(
506
+								EEH_HTML::strong(
507
+									esc_html__('IMPORTANT', 'event_espresso'),
508
+									'',
509
+									'important-notice'
510
+								)
511
+							)
512
+						) .
513
+						EEH_HTML::td(
514
+							EEH_HTML::strong(
515
+								esc_html__(
516
+									'You are responsible for your own website security and Payment Card Industry Data Security Standards (PCI DSS) compliance.',
517
+									'event_espresso'
518
+								)
519
+							)
520
+							.
521
+							EEH_HTML::br()
522
+							.
523
+							esc_html__('Learn more about ', 'event_espresso')
524
+							. EEH_HTML::link(
525
+								'https://www.pcisecuritystandards.org/merchants/index.php',
526
+								esc_html__('PCI DSS compliance', 'event_espresso')
527
+							)
528
+						)
529
+					)
530
+				)
531
+			);
532
+		}
533
+		return new EE_Form_Section_HTML('');
534
+	}
535
+
536
+
537
+	/**
538
+	 * _currency_support
539
+	 *
540
+	 * @access protected
541
+	 * @param EE_Payment_Method $payment_method
542
+	 * @return EE_Form_Section_HTML
543
+	 * @throws EE_Error
544
+	 */
545
+	protected function _currency_support(EE_Payment_Method $payment_method)
546
+	{
547
+		if (! $payment_method->usable_for_currency(EE_Config::instance()->currency->code)) {
548
+			return new EE_Form_Section_HTML(
549
+				EEH_HTML::table(
550
+					EEH_HTML::tr(
551
+						EEH_HTML::th(
552
+							EEH_HTML::label(
553
+								EEH_HTML::strong(
554
+									esc_html__('IMPORTANT', 'event_espresso'),
555
+									'',
556
+									'important-notice'
557
+								)
558
+							)
559
+						) .
560
+						EEH_HTML::td(
561
+							EEH_HTML::strong(
562
+								sprintf(
563
+									esc_html__(
564
+										'This payment method does not support the currency set on your site (%1$s). Please activate a different payment method or change your site\'s country and associated currency.',
565
+										'event_espresso'
566
+									),
567
+									EE_Config::instance()->currency->code
568
+								)
569
+							)
570
+						)
571
+					)
572
+				)
573
+			);
574
+		}
575
+		return new EE_Form_Section_HTML('');
576
+	}
577
+
578
+
579
+	/**
580
+	 * _update_payment_method_button
581
+	 *
582
+	 * @access protected
583
+	 * @param EE_Payment_Method $payment_method
584
+	 * @return EE_Payment_Method_Form
585
+	 * @throws EE_Error
586
+	 */
587
+	protected function _payment_method_settings(EE_Payment_Method $payment_method)
588
+	{
589
+		// modify the form, so we only have/show fields that will be implemented for this version
590
+		return $this->_simplify_form($payment_method->type_obj()->settings_form(), $payment_method->name());
591
+	}
592
+
593
+
594
+	/**
595
+	 * Simplifies the form to merely reproduce 4.1's gateway settings functionality
596
+	 *
597
+	 * @param EE_Form_Section_Proper $form_section
598
+	 * @param string                 $payment_method_name
599
+	 * @return EE_Payment_Method_Form
600
+	 * @throws EE_Error
601
+	 */
602
+	protected function _simplify_form($form_section, $payment_method_name = '')
603
+	{
604
+		if ($form_section instanceof EE_Payment_Method_Form) {
605
+			$form_section->exclude(
606
+				array(
607
+					'PMD_type', // don't want them changing the type
608
+					'PMD_slug', // or the slug (probably never)
609
+					'PMD_wp_user', // or the user's ID
610
+					'Currency' // or the currency, until the rest of EE supports simultaneous currencies
611
+				)
612
+			);
613
+			return $form_section;
614
+		} else {
615
+			throw new EE_Error(
616
+				sprintf(
617
+					esc_html__(
618
+						'The EE_Payment_Method_Form for the "%1$s" payment method is missing or invalid.',
619
+						'event_espresso'
620
+					),
621
+					$payment_method_name
622
+				)
623
+			);
624
+		}
625
+	}
626
+
627
+
628
+	/**
629
+	 * _update_payment_method_button
630
+	 *
631
+	 * @access protected
632
+	 * @param EE_Payment_Method $payment_method
633
+	 * @return EE_Form_Section_HTML
634
+	 * @throws EE_Error
635
+	 */
636
+	protected function _update_payment_method_button(EE_Payment_Method $payment_method)
637
+	{
638
+		$update_button = new EE_Submit_Input(
639
+			array(
640
+				'name'       => 'submit',
641
+				'html_id'    => 'save_' . $payment_method->slug() . '_settings',
642
+				'default'    => sprintf(
643
+					esc_html__('Update %s Payment Settings', 'event_espresso'),
644
+					$payment_method->admin_name()
645
+				),
646
+				'html_label' => EEH_HTML::nbsp(),
647
+			)
648
+		);
649
+		return new EE_Form_Section_HTML(
650
+			EEH_HTML::table(
651
+				EEH_HTML::no_row(EEH_HTML::br(2)) .
652
+				EEH_HTML::tr(
653
+					EEH_HTML::th(esc_html__('Update Settings', 'event_espresso')) .
654
+					EEH_HTML::td(
655
+						$update_button->get_html_for_input()
656
+					)
657
+				)
658
+			)
659
+		);
660
+	}
661
+
662
+
663
+	/**
664
+	 * _deactivate_payment_method_button
665
+	 *
666
+	 * @access protected
667
+	 * @param EE_Payment_Method $payment_method
668
+	 * @return EE_Form_Section_HTML
669
+	 */
670
+	protected function _deactivate_payment_method_button(EE_Payment_Method $payment_method)
671
+	{
672
+		$link_text_and_title = sprintf(
673
+			esc_html__('Deactivate %1$s Payments?', 'event_espresso'),
674
+			$payment_method->admin_name()
675
+		);
676
+		return new EE_Form_Section_HTML(
677
+			EEH_HTML::table(
678
+				EEH_HTML::tr(
679
+					EEH_HTML::th(esc_html__('Deactivate Payment Method', 'event_espresso')) .
680
+					EEH_HTML::td(
681
+						EEH_HTML::link(
682
+							EE_Admin_Page::add_query_args_and_nonce(
683
+								array(
684
+									'action'         => 'deactivate_payment_method',
685
+									'payment_method' => $payment_method->slug(),
686
+								),
687
+								EE_PAYMENTS_ADMIN_URL
688
+							),
689
+							$link_text_and_title,
690
+							$link_text_and_title,
691
+							'deactivate_' . $payment_method->slug(),
692
+							'espresso-button button-secondary'
693
+						)
694
+					)
695
+				)
696
+			)
697
+		);
698
+	}
699
+
700
+
701
+	/**
702
+	 * _activate_payment_method_button
703
+	 *
704
+	 * @access protected
705
+	 * @param EE_Payment_Method $payment_method
706
+	 * @return EE_Form_Section_Proper
707
+	 * @throws EE_Error
708
+	 */
709
+	protected function _activate_payment_method_button(EE_Payment_Method $payment_method)
710
+	{
711
+		$link_text_and_title = sprintf(
712
+			esc_html__('Activate %1$s Payment Method?', 'event_espresso'),
713
+			$payment_method->admin_name()
714
+		);
715
+		return new EE_Form_Section_Proper(
716
+			array(
717
+				'name'            => 'activate_' . $payment_method->slug() . '_settings_form',
718
+				'html_id'         => 'activate_' . $payment_method->slug() . '_settings_form',
719
+				'action'          => '#',
720
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
721
+				'subsections'     => apply_filters(
722
+					'FHEE__Payments_Admin_Page___activate_payment_method_button__form_subsections',
723
+					array(
724
+						new EE_Form_Section_HTML(
725
+							EEH_HTML::table(
726
+								EEH_HTML::tr(
727
+									EEH_HTML::td(
728
+										$payment_method->type_obj()->introductory_html(),
729
+										'',
730
+										'',
731
+										'',
732
+										'colspan="2"'
733
+									)
734
+								) .
735
+								EEH_HTML::tr(
736
+									EEH_HTML::th(
737
+										EEH_HTML::label(esc_html__('Click to Activate ', 'event_espresso'))
738
+									) .
739
+									EEH_HTML::td(
740
+										EEH_HTML::link(
741
+											EE_Admin_Page::add_query_args_and_nonce(
742
+												array(
743
+													'action'              => 'activate_payment_method',
744
+													'payment_method_type' => $payment_method->type(),
745
+												),
746
+												EE_PAYMENTS_ADMIN_URL
747
+											),
748
+											$link_text_and_title,
749
+											$link_text_and_title,
750
+											'activate_' . $payment_method->slug(),
751
+											'espresso-button-green button-primary'
752
+										)
753
+									)
754
+								)
755
+							)
756
+						),
757
+					),
758
+					$payment_method
759
+				),
760
+			)
761
+		);
762
+	}
763
+
764
+
765
+	/**
766
+	 * _fine_print
767
+	 *
768
+	 * @access protected
769
+	 * @return EE_Form_Section_HTML
770
+	 */
771
+	protected function _fine_print()
772
+	{
773
+		return new EE_Form_Section_HTML(
774
+			EEH_HTML::table(
775
+				EEH_HTML::tr(
776
+					EEH_HTML::th() .
777
+					EEH_HTML::td(
778
+						EEH_HTML::p(esc_html__('All fields marked with a * are required fields', 'event_espresso'), '', 'grey-text')
779
+					)
780
+				)
781
+			)
782
+		);
783
+	}
784
+
785
+
786
+	/**
787
+	 * Activates a payment method of that type. Mostly assuming there is only 1 of that type (or none so far)
788
+	 *
789
+	 * @throws EE_Error
790
+	 * @throws ReflectionException
791
+	 * @global WP_User $current_user
792
+	 */
793
+	protected function _activate_payment_method()
794
+	{
795
+		if (isset($this->_req_data['payment_method_type'])) {
796
+			$payment_method_type = sanitize_text_field($this->_req_data['payment_method_type']);
797
+			// see if one exists
798
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
799
+			$payment_method = EE_Payment_Method_Manager::instance()
800
+													   ->activate_a_payment_method_of_type($payment_method_type);
801
+			$this->_redirect_after_action(
802
+				1,
803
+				'Payment Method',
804
+				'activated',
805
+				array('action' => 'default', 'payment_method' => $payment_method->slug())
806
+			);
807
+		} else {
808
+			$this->_redirect_after_action(false, 'Payment Method', 'activated', array('action' => 'default'));
809
+		}
810
+	}
811
+
812
+
813
+	/**
814
+	 * @throws EE_Error
815
+	 * @throws ReflectionException
816
+	 */
817
+	protected function _deactivate_payment_method()
818
+	{
819
+		if (isset($this->_req_data['payment_method'])) {
820
+			$payment_method_slug = sanitize_key($this->_req_data['payment_method']);
821
+			// deactivate it
822
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
823
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method($payment_method_slug);
824
+			$this->_redirect_after_action(
825
+				$count_updated,
826
+				'Payment Method',
827
+				'deactivated',
828
+				array('action' => 'default', 'payment_method' => $payment_method_slug)
829
+			);
830
+		} else {
831
+			$this->_redirect_after_action(false, 'Payment Method', 'deactivated', array('action' => 'default'));
832
+		}
833
+	}
834
+
835
+
836
+	/**
837
+	 * Processes the payment method form that was submitted. This is slightly trickier than usual form
838
+	 * processing because we first need to identify WHICH form was processed and which payment method
839
+	 * it corresponds to. Once we have done that, we see if the form is valid. If it is, the
840
+	 * form's data is saved, and we redirect to the default payment methods page, setting the updated payment method
841
+	 * as the currently-selected one. If it DOESN'T validate, we render the page with the form's errors (in the
842
+	 * subsequently called 'headers_sent_func' which is _payment_methods_list)
843
+	 *
844
+	 * @return void
845
+	 * @throws EE_Error
846
+	 * @throws ReflectionException
847
+	 */
848
+	protected function _update_payment_method()
849
+	{
850
+		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
851
+			// ok let's find which gateway form to use based on the form input
852
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
853
+			/** @var $correct_pmt_form_to_use EE_Payment_Method_Form */
854
+			$correct_pmt_form_to_use = null;
855
+			$payment_method = null;
856
+			foreach (EEM_Payment_Method::instance()->get_all() as $payment_method) {
857
+				if ($payment_method instanceof EE_Payment_Method) {
858
+					// get the form and simplify it, like what we do when we display it
859
+					$pmt_form = $this->_generate_payment_method_settings_form($payment_method);
860
+					if ($pmt_form->form_data_present_in($this->_req_data)) {
861
+						$correct_pmt_form_to_use = $pmt_form;
862
+						break;
863
+					}
864
+				}
865
+			}
866
+			// if we couldn't find the correct payment method type...
867
+			if (! $correct_pmt_form_to_use) {
868
+				EE_Error::add_error(
869
+					esc_html__(
870
+						"We could not find which payment method type your form submission related to. Please contact support",
871
+						'event_espresso'
872
+					),
873
+					__FILE__,
874
+					__FUNCTION__,
875
+					__LINE__
876
+				);
877
+				$this->_redirect_after_action(false, 'Payment Method', 'activated', array('action' => 'default'));
878
+			}
879
+			$correct_pmt_form_to_use->receive_form_submission($this->_req_data);
880
+			if ($correct_pmt_form_to_use->is_valid()) {
881
+				$payment_settings_subform = $correct_pmt_form_to_use->get_subsection('payment_method_settings');
882
+				if (! $payment_settings_subform instanceof EE_Payment_Method_Form) {
883
+					throw new EE_Error(
884
+						sprintf(
885
+							esc_html__(
886
+								'The payment method could not be saved because the form sections were misnamed. We expected to find %1$s, but did not.',
887
+								'event_espresso'
888
+							),
889
+							'payment_method_settings'
890
+						)
891
+					);
892
+				}
893
+				$payment_settings_subform->save();
894
+				/** @var $pm EE_Payment_Method */
895
+				$this->_redirect_after_action(
896
+					true,
897
+					'Payment Method',
898
+					'updated',
899
+					array('action' => 'default', 'payment_method' => $payment_method->slug())
900
+				);
901
+			} else {
902
+				EE_Error::add_error(
903
+					sprintf(
904
+						esc_html__(
905
+							'Payment method of type %s was not saved because there were validation errors. They have been marked in the form',
906
+							'event_espresso'
907
+						),
908
+						$payment_method instanceof EE_Payment_Method ? $payment_method->type_obj()->pretty_name()
909
+							: esc_html__('"(unknown)"', 'event_espresso')
910
+					),
911
+					__FILE__,
912
+					__FUNCTION__,
913
+					__LINE__
914
+				);
915
+			}
916
+		}
917
+	}
918
+
919
+
920
+	/**
921
+	 * Displays payment settings (not payment METHOD settings, that's _payment_method_settings)
922
+	 * @throws DomainException
923
+	 * @throws EE_Error
924
+	 * @throws InvalidArgumentException
925
+	 * @throws InvalidDataTypeException
926
+	 * @throws InvalidInterfaceException
927
+	 */
928
+	protected function _payment_settings()
929
+	{
930
+		$form = $this->getPaymentSettingsForm();
931
+		$this->_set_add_edit_form_tags('update_payment_settings');
932
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
933
+		$this->_template_args['admin_page_content'] =  $form->get_html_and_js();
934
+		$this->display_admin_page_with_sidebar();
935
+	}
936
+
937
+
938
+	/**
939
+	 *        _update_payment_settings
940
+	 *
941
+	 * @access protected
942
+	 * @return void
943
+	 * @throws EE_Error
944
+	 * @throws InvalidArgumentException
945
+	 * @throws InvalidDataTypeException
946
+	 * @throws InvalidInterfaceException
947
+	 */
948
+	protected function _update_payment_settings()
949
+	{
950
+		$form = $this->getPaymentSettingsForm();
951
+		if ($form->was_submitted($this->_req_data)) {
952
+			$form->receive_form_submission($this->_req_data);
953
+			if ($form->is_valid()) {
954
+				/**
955
+				 * @var $reg_config EE_Registration_Config
956
+				 */
957
+				$loader = LoaderFactory::getLoader();
958
+				$reg_config = $loader->getShared('EE_Registration_Config');
959
+				$valid_data = $form->valid_data();
960
+				$reg_config->show_pending_payment_options = $valid_data['show_pending_payment_options'];
961
+				$reg_config->gateway_log_lifespan = $valid_data['gateway_log_lifespan'];
962
+			}
963
+		}
964
+		EE_Registry::instance()->CFG = apply_filters(
965
+			'FHEE__Payments_Admin_Page___update_payment_settings__CFG',
966
+			EE_Registry::instance()->CFG
967
+		);
968
+
969
+		$what = esc_html__('Payment Settings', 'event_espresso');
970
+		$success = $this->_update_espresso_configuration(
971
+			$what,
972
+			EE_Registry::instance()->CFG,
973
+			__FILE__,
974
+			__FUNCTION__,
975
+			__LINE__
976
+		);
977
+		$this->_redirect_after_action(
978
+			$success,
979
+			$what,
980
+			esc_html__('updated', 'event_espresso'),
981
+			array('action' => 'payment_settings')
982
+		);
983
+	}
984
+
985
+
986
+	/**
987
+	 * Gets the form used for updating payment settings
988
+	 *
989
+	 * @return EE_Form_Section_Proper
990
+	 * @throws EE_Error
991
+	 * @throws InvalidArgumentException
992
+	 * @throws InvalidDataTypeException
993
+	 * @throws InvalidInterfaceException
994
+	 */
995
+	protected function getPaymentSettingsForm()
996
+	{
997
+		/**
998
+		 * @var $reg_config EE_Registration_Config
999
+		 */
1000
+		$reg_config = LoaderFactory::getLoader()->getShared('EE_Registration_Config');
1001
+		return new EE_Form_Section_Proper(
1002
+			array(
1003
+				'name' => 'payment-settings',
1004
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1005
+				'subsections' => array(
1006
+					'show_pending_payment_options' => new EE_Yes_No_Input(
1007
+						array(
1008
+							'html_name' => 'show_pending_payment_options',
1009
+							'default' => $reg_config->show_pending_payment_options,
1010
+							'html_help_text' => esc_html__(
1011
+								"If a payment is marked as 'Pending Payment', or if payment is deferred (ie, an offline gateway like Check, Bank, or Invoice is used), then give registrants the option to retry payment. ",
1012
+								'event_espresso'
1013
+							)
1014
+						)
1015
+					),
1016
+					'gateway_log_lifespan' => new EE_Select_Input(
1017
+						$reg_config->gatewayLogLifespanOptions(),
1018
+						array(
1019
+							'html_label_text' => esc_html__('Gateway Logs Lifespan', 'event_espresso'),
1020
+							'html_help_text' => esc_html__('If issues arise with payments being made through a payment gateway, it\'s helpful to log non-sensitive communications with the payment gateway. But it\'s a security responsibility, so it\'s a good idea to not keep them for any longer than necessary.', 'event_espresso'),
1021
+							'default' => $reg_config->gateway_log_lifespan,
1022
+						)
1023
+					)
1024
+				)
1025
+			)
1026
+		);
1027
+	}
1028
+
1029
+
1030
+	/**
1031
+	 * @throws EE_Error
1032
+	 */
1033
+	protected function _payment_log_overview_list_table()
1034
+	{
1035
+		$this->display_admin_list_table_page_with_sidebar();
1036
+	}
1037
+
1038
+
1039
+	protected function _set_list_table_views_payment_log()
1040
+	{
1041
+		$this->_views = array(
1042
+			'all' => array(
1043
+				'slug'  => 'all',
1044
+				'label' => esc_html__('View All Logs', 'event_espresso'),
1045
+				'count' => 0,
1046
+			),
1047
+		);
1048
+	}
1049
+
1050
+
1051
+	/**
1052
+	 * @param int  $per_page
1053
+	 * @param int  $current_page
1054
+	 * @param bool $count
1055
+	 * @return array|int
1056
+	 * @throws EE_Error
1057
+	 * @throws ReflectionException
1058
+	 */
1059
+	public function get_payment_logs($per_page = 50, $current_page = 0, $count = false)
1060
+	{
1061
+		EE_Registry::instance()->load_model('Change_Log');
1062
+		// we may need to do multiple queries (joining differently), so we actually want an array of query params
1063
+		$query_params = array(array('LOG_type' => EEM_Change_Log::type_gateway));
1064
+		// check if they've selected a specific payment method
1065
+		if (isset($this->_req_data['_payment_method']) && $this->_req_data['_payment_method'] !== 'all') {
1066
+			$query_params[0]['OR*pm_or_pay_pm'] = array(
1067
+				'Payment.Payment_Method.PMD_ID' => $this->_req_data['_payment_method'],
1068
+				'Payment_Method.PMD_ID'         => $this->_req_data['_payment_method'],
1069
+			);
1070
+		}
1071
+		// take into account search
1072
+		if (isset($this->_req_data['s']) && $this->_req_data['s']) {
1073
+			$similarity_string = array('LIKE', '%' . str_replace("", "%", $this->_req_data['s']) . '%');
1074
+			$query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_fname'] = $similarity_string;
1075
+			$query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_lname'] = $similarity_string;
1076
+			$query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_email'] = $similarity_string;
1077
+			$query_params[0]['OR*s']['Payment.Payment_Method.PMD_name'] = $similarity_string;
1078
+			$query_params[0]['OR*s']['Payment.Payment_Method.PMD_admin_name'] = $similarity_string;
1079
+			$query_params[0]['OR*s']['Payment.Payment_Method.PMD_type'] = $similarity_string;
1080
+			$query_params[0]['OR*s']['LOG_message'] = $similarity_string;
1081
+			$query_params[0]['OR*s']['Payment_Method.PMD_name'] = $similarity_string;
1082
+			$query_params[0]['OR*s']['Payment_Method.PMD_admin_name'] = $similarity_string;
1083
+			$query_params[0]['OR*s']['Payment_Method.PMD_type'] = $similarity_string;
1084
+			$query_params[0]['OR*s']['LOG_message'] = $similarity_string;
1085
+		}
1086
+		if (
1087
+			isset($this->_req_data['payment-filter-start-date'])
1088
+			&& isset($this->_req_data['payment-filter-end-date'])
1089
+		) {
1090
+			// add date
1091
+			$start_date = wp_strip_all_tags($this->_req_data['payment-filter-start-date']);
1092
+			$end_date = wp_strip_all_tags($this->_req_data['payment-filter-end-date']);
1093
+			// make sure our timestamps start and end right at the boundaries for each day
1094
+			$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
1095
+			$end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
1096
+			// convert to timestamps
1097
+			$start_date = strtotime($start_date);
1098
+			$end_date = strtotime($end_date);
1099
+			// makes sure start date is the lowest value and vice versa
1100
+			$start_date = min($start_date, $end_date);
1101
+			$end_date = max($start_date, $end_date);
1102
+			// convert for query
1103
+			$start_date = EEM_Change_Log::instance()->convert_datetime_for_query(
1104
+				'LOG_time',
1105
+				date('Y-m-d H:i:s', $start_date),
1106
+				'Y-m-d H:i:s'
1107
+			);
1108
+			$end_date   = EEM_Change_Log::instance()->convert_datetime_for_query(
1109
+				'LOG_time',
1110
+				date('Y-m-d H:i:s', $end_date),
1111
+				'Y-m-d H:i:s'
1112
+			);
1113
+			$query_params[0]['LOG_time'] = array('BETWEEN', array($start_date, $end_date));
1114
+		}
1115
+		if ($count) {
1116
+			return EEM_Change_Log::instance()->count($query_params);
1117
+		}
1118
+		if (isset($this->_req_data['order'])) {
1119
+			$sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1120
+				? $this->_req_data['order']
1121
+				: 'DESC';
1122
+			$query_params['order_by'] = array('LOG_time' => $sort);
1123
+		} else {
1124
+			$query_params['order_by'] = array('LOG_time' => 'DESC');
1125
+		}
1126
+		$offset = ($current_page - 1) * $per_page;
1127
+		if (! isset($this->_req_data['download_results'])) {
1128
+			$query_params['limit'] = array($offset, $per_page);
1129
+		}
1130
+		// now they've requested to instead just download the file instead of viewing it.
1131
+		if (isset($this->_req_data['download_results'])) {
1132
+			$wpdb_results = EEM_Change_Log::instance()->get_all_efficiently($query_params);
1133
+			header('Content-Disposition: attachment');
1134
+			header("Content-Disposition: attachment; filename=ee_payment_logs_for_" . sanitize_key(site_url()));
1135
+			echo '<h1> '
1136
+				. sprintf(
1137
+					esc_html__('Payment Logs for %1$s', 'event_espresso'),
1138
+					esc_url_raw(site_url())
1139
+				)
1140
+				. '</h1 >';
1141
+			echo '<h3>' . esc_html__('Query:', 'event_espresso') . '</h3>';
1142
+			echo esc_html(var_export($query_params, true));
1143
+			echo '<h3>' . esc_html__('Results:', 'event_espresso') . '</h3>';
1144
+			echo esc_html(var_export($wpdb_results, true));
1145
+			die;
1146
+		}
1147
+		return EEM_Change_Log::instance()->get_all($query_params);
1148
+	}
1149
+
1150
+
1151
+	/**
1152
+	 * Used by usort to RE-sort log query results, because we lose the ordering
1153
+	 * because we're possibly combining the results from two queries
1154
+	 *
1155
+	 * @param EE_Change_Log $logA
1156
+	 * @param EE_Change_Log $logB
1157
+	 * @return int
1158
+	 * @throws EE_Error
1159
+	 * @throws ReflectionException
1160
+	 */
1161
+	protected function _sort_logs_again($logA, $logB)
1162
+	{
1163
+		$timeA = $logA->get_raw('LOG_time');
1164
+		$timeB = $logB->get_raw('LOG_time');
1165
+		if ($timeA == $timeB) {
1166
+			return 0;
1167
+		}
1168
+		$comparison = $timeA < $timeB ? -1 : 1;
1169
+		if (strtoupper($this->_sort_logs_again_direction) == 'DESC') {
1170
+			return $comparison * -1;
1171
+		}
1172
+		return $comparison;
1173
+	}
1174
+
1175
+
1176
+	/**
1177
+	 * @throws EE_Error
1178
+	 * @throws ReflectionException
1179
+	 */
1180
+	protected function _payment_log_details()
1181
+	{
1182
+		EE_Registry::instance()->load_model('Change_Log');
1183
+		/** @var $payment_log EE_Change_Log */
1184
+		$payment_log = EEM_Change_Log::instance()->get_one_by_ID($this->_req_data['ID']);
1185
+		$payment_method = null;
1186
+		$transaction = null;
1187
+		if ($payment_log instanceof EE_Change_Log) {
1188
+			if ($payment_log->object() instanceof EE_Payment) {
1189
+				$payment_method = $payment_log->object()->payment_method();
1190
+				$transaction = $payment_log->object()->transaction();
1191
+			} elseif ($payment_log->object() instanceof EE_Payment_Method) {
1192
+				$payment_method = $payment_log->object();
1193
+			} elseif ($payment_log->object() instanceof EE_Transaction) {
1194
+				$transaction = $payment_log->object();
1195
+				$payment_method = $transaction->payment_method();
1196
+			}
1197
+		}
1198
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1199
+			EE_PAYMENTS_TEMPLATE_PATH . 'payment_log_details.template.php',
1200
+			array(
1201
+				'payment_log'    => $payment_log,
1202
+				'payment_method' => $payment_method,
1203
+				'transaction'    => $transaction,
1204
+			),
1205
+			true
1206
+		);
1207
+		$this->display_admin_page_with_sidebar();
1208
+	}
1209 1209
 }
Please login to merge, or discard this patch.