Completed
Branch gql-search-support (da87e5)
by
unknown
65:32 queued 56:59
created
core/EE_Load_Espresso_Core.core.php 2 patches
Unused Use Statements   -5 removed lines patch added patch discarded remove patch
@@ -1,12 +1,7 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-use EventEspresso\core\domain\DomainFactory;
4
-use EventEspresso\core\domain\values\FilePath;
5
-use EventEspresso\core\domain\values\FullyQualifiedName;
6
-use EventEspresso\core\domain\values\Version;
7 3
 use EventEspresso\core\exceptions\InvalidDataTypeException;
8 4
 use EventEspresso\core\exceptions\InvalidInterfaceException;
9
-use EventEspresso\core\services\loaders\LoaderFactory;
10 5
 use EventEspresso\core\services\request\RequestDecoratorInterface;
11 6
 use EventEspresso\core\services\request\RequestInterface;
12 7
 use EventEspresso\core\services\request\RequestStackCoreAppInterface;
Please login to merge, or discard this patch.
Indentation   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -27,114 +27,114 @@
 block discarded – undo
27 27
 class EE_Load_Espresso_Core implements RequestDecoratorInterface, RequestStackCoreAppInterface
28 28
 {
29 29
 
30
-    /**
31
-     * @var RequestInterface $request
32
-     */
33
-    protected $request;
34
-
35
-    /**
36
-     * @var ResponseInterface $response
37
-     */
38
-    protected $response;
39
-
40
-    /**
41
-     * @var EE_Dependency_Map $dependency_map
42
-     */
43
-    protected $dependency_map;
44
-
45
-    /**
46
-     * @var EE_Registry $registry
47
-     */
48
-    protected $registry;
49
-
50
-
51
-    /**
52
-     * EE_Load_Espresso_Core constructor
53
-     *
54
-     * @param EE_Registry       $registry
55
-     * @param EE_Dependency_Map $dependency_map
56
-     * @throws EE_Error
57
-     */
58
-    public function __construct(EE_Registry $registry, EE_Dependency_Map $dependency_map)
59
-    {
60
-        EE_Error::doing_it_wrong(
61
-            __METHOD__,
62
-            sprintf(
63
-                esc_html__(
64
-                    'This class is deprecated. Please use %1$s instead. All Event Espresso request stack classes have been moved to %2$s and are now under the %3$s namespace',
65
-                    'event_espresso'
66
-                ),
67
-                'EventEspresso\core\services\request\RequestStackCoreApp',
68
-                '\core\services\request',
69
-                'EventEspresso\core\services\request'
70
-            ),
71
-            '4.9.53'
72
-        );
73
-    }
74
-
75
-
76
-    /**
77
-     * handle
78
-     * sets hooks for running rest of system
79
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
80
-     * starting EE Addons from any other point may lead to problems
81
-     *
82
-     * @param RequestInterface  $request
83
-     * @param ResponseInterface $response
84
-     * @return ResponseInterface
85
-     * @throws EE_Error
86
-     * @throws InvalidDataTypeException
87
-     * @throws InvalidInterfaceException
88
-     * @throws InvalidArgumentException
89
-     * @throws DomainException
90
-     */
91
-    public function handleRequest(RequestInterface $request, ResponseInterface $response)
92
-    {
93
-    }
94
-
95
-
96
-    /**
97
-     * @return RequestInterface
98
-     */
99
-    public function request()
100
-    {
101
-    }
102
-
103
-
104
-    /**
105
-     * @return ResponseInterface
106
-     */
107
-    public function response()
108
-    {
109
-    }
110
-
111
-
112
-    /**
113
-     * @return EE_Dependency_Map
114
-     * @throws EE_Error
115
-     */
116
-    public function dependency_map()
117
-    {
118
-    }
119
-
120
-
121
-    /**
122
-     * @return EE_Registry
123
-     * @throws EE_Error
124
-     */
125
-    public function registry()
126
-    {
127
-    }
128
-
129
-
130
-    /**
131
-     * called after the request stack has been fully processed
132
-     * if any of the middleware apps has requested the plugin be deactivated, then we do that now
133
-     *
134
-     * @param RequestInterface  $request
135
-     * @param ResponseInterface $response
136
-     */
137
-    public function handleResponse(RequestInterface $request, ResponseInterface $response)
138
-    {
139
-    }
30
+	/**
31
+	 * @var RequestInterface $request
32
+	 */
33
+	protected $request;
34
+
35
+	/**
36
+	 * @var ResponseInterface $response
37
+	 */
38
+	protected $response;
39
+
40
+	/**
41
+	 * @var EE_Dependency_Map $dependency_map
42
+	 */
43
+	protected $dependency_map;
44
+
45
+	/**
46
+	 * @var EE_Registry $registry
47
+	 */
48
+	protected $registry;
49
+
50
+
51
+	/**
52
+	 * EE_Load_Espresso_Core constructor
53
+	 *
54
+	 * @param EE_Registry       $registry
55
+	 * @param EE_Dependency_Map $dependency_map
56
+	 * @throws EE_Error
57
+	 */
58
+	public function __construct(EE_Registry $registry, EE_Dependency_Map $dependency_map)
59
+	{
60
+		EE_Error::doing_it_wrong(
61
+			__METHOD__,
62
+			sprintf(
63
+				esc_html__(
64
+					'This class is deprecated. Please use %1$s instead. All Event Espresso request stack classes have been moved to %2$s and are now under the %3$s namespace',
65
+					'event_espresso'
66
+				),
67
+				'EventEspresso\core\services\request\RequestStackCoreApp',
68
+				'\core\services\request',
69
+				'EventEspresso\core\services\request'
70
+			),
71
+			'4.9.53'
72
+		);
73
+	}
74
+
75
+
76
+	/**
77
+	 * handle
78
+	 * sets hooks for running rest of system
79
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
80
+	 * starting EE Addons from any other point may lead to problems
81
+	 *
82
+	 * @param RequestInterface  $request
83
+	 * @param ResponseInterface $response
84
+	 * @return ResponseInterface
85
+	 * @throws EE_Error
86
+	 * @throws InvalidDataTypeException
87
+	 * @throws InvalidInterfaceException
88
+	 * @throws InvalidArgumentException
89
+	 * @throws DomainException
90
+	 */
91
+	public function handleRequest(RequestInterface $request, ResponseInterface $response)
92
+	{
93
+	}
94
+
95
+
96
+	/**
97
+	 * @return RequestInterface
98
+	 */
99
+	public function request()
100
+	{
101
+	}
102
+
103
+
104
+	/**
105
+	 * @return ResponseInterface
106
+	 */
107
+	public function response()
108
+	{
109
+	}
110
+
111
+
112
+	/**
113
+	 * @return EE_Dependency_Map
114
+	 * @throws EE_Error
115
+	 */
116
+	public function dependency_map()
117
+	{
118
+	}
119
+
120
+
121
+	/**
122
+	 * @return EE_Registry
123
+	 * @throws EE_Error
124
+	 */
125
+	public function registry()
126
+	{
127
+	}
128
+
129
+
130
+	/**
131
+	 * called after the request stack has been fully processed
132
+	 * if any of the middleware apps has requested the plugin be deactivated, then we do that now
133
+	 *
134
+	 * @param RequestInterface  $request
135
+	 * @param ResponseInterface $response
136
+	 */
137
+	public function handleResponse(RequestInterface $request, ResponseInterface $response)
138
+	{
139
+	}
140 140
 }
Please login to merge, or discard this patch.
admin_pages/messages/Messages_Admin_Page.core.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -2597,7 +2597,7 @@  discard block
 block discarded – undo
2597 2597
      *
2598 2598
      * @param int $index This helps us know which template field to select from the request array.
2599 2599
      *
2600
-     * @return array
2600
+     * @return string
2601 2601
      */
2602 2602
     protected function _set_message_template_column_values($index)
2603 2603
     {
@@ -3088,7 +3088,7 @@  discard block
 block discarded – undo
3088 3088
      *
3089 3089
      * @param  int  $GRP_ID        The group being deleted
3090 3090
      * @param  bool $include_group whether to delete the Message Template Group as well.
3091
-     * @return bool boolean to indicate the success of the deletes or not.
3091
+     * @return integer boolean to indicate the success of the deletes or not.
3092 3092
      * @throws EE_Error
3093 3093
      * @throws InvalidArgumentException
3094 3094
      * @throws InvalidDataTypeException
Please login to merge, or discard this patch.
Indentation   +4537 added lines, -4537 removed lines patch added patch discarded remove patch
@@ -19,2638 +19,2638 @@  discard block
 block discarded – undo
19 19
 class Messages_Admin_Page extends EE_Admin_Page
20 20
 {
21 21
 
22
-    /**
23
-     * @type EE_Message_Resource_Manager $_message_resource_manager
24
-     */
25
-    protected $_message_resource_manager;
26
-
27
-    /**
28
-     * @type string $_active_message_type_name
29
-     */
30
-    protected $_active_message_type_name = '';
31
-
32
-    /**
33
-     * @type EE_messenger $_active_messenger
34
-     */
35
-    protected $_active_messenger;
36
-    protected $_activate_state;
37
-    protected $_activate_meta_box_type;
38
-    protected $_current_message_meta_box;
39
-    protected $_current_message_meta_box_object;
40
-    protected $_context_switcher;
41
-    protected $_shortcodes = array();
42
-    protected $_active_messengers = array();
43
-    protected $_active_message_types = array();
44
-
45
-    /**
46
-     * @var EE_Message_Template_Group $_message_template_group
47
-     */
48
-    protected $_message_template_group;
49
-    protected $_m_mt_settings = array();
50
-
51
-
52
-    /**
53
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
-     * IF there is no group then it gets automatically set to the Default template pack.
55
-     *
56
-     * @since 4.5.0
57
-     *
58
-     * @var EE_Messages_Template_Pack
59
-     */
60
-    protected $_template_pack;
61
-
62
-
63
-    /**
64
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
-     * group is.  If there is no group then it automatically gets set to default.
66
-     *
67
-     * @since 4.5.0
68
-     *
69
-     * @var string
70
-     */
71
-    protected $_variation;
72
-
73
-
74
-    /**
75
-     * @param bool $routing
76
-     * @throws EE_Error
77
-     */
78
-    public function __construct($routing = true)
79
-    {
80
-        // make sure messages autoloader is running
81
-        EED_Messages::set_autoloaders();
82
-        parent::__construct($routing);
83
-    }
84
-
85
-
86
-    protected function _init_page_props()
87
-    {
88
-        $this->page_slug = EE_MSG_PG_SLUG;
89
-        $this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
-        $this->_admin_base_url = EE_MSG_ADMIN_URL;
91
-        $this->_admin_base_path = EE_MSG_ADMIN;
92
-
93
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
-            : array();
95
-
96
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
-        $this->_load_message_resource_manager();
98
-    }
99
-
100
-
101
-    /**
102
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
-     *
104
-     * @throws EE_Error
105
-     * @throws InvalidDataTypeException
106
-     * @throws InvalidInterfaceException
107
-     * @throws InvalidArgumentException
108
-     * @throws ReflectionException
109
-     */
110
-    protected function _load_message_resource_manager()
111
-    {
112
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
-    }
114
-
115
-
116
-    /**
117
-     * @deprecated 4.9.9.rc.014
118
-     * @return array
119
-     * @throws EE_Error
120
-     * @throws InvalidArgumentException
121
-     * @throws InvalidDataTypeException
122
-     * @throws InvalidInterfaceException
123
-     */
124
-    public function get_messengers_for_list_table()
125
-    {
126
-        EE_Error::doing_it_wrong(
127
-            __METHOD__,
128
-            sprintf(
129
-                esc_html__(
130
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
-                    'event_espresso'
132
-                ),
133
-                'Messages_Admin_Page::get_messengers_select_input()'
134
-            ),
135
-            '4.9.9.rc.014'
136
-        );
137
-
138
-        $m_values = array();
139
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
-        // setup messengers for selects
141
-        $i = 1;
142
-        foreach ($active_messengers as $active_messenger) {
143
-            if ($active_messenger instanceof EE_Message) {
144
-                $m_values[ $i ]['id'] = $active_messenger->messenger();
145
-                $m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
-                $i++;
147
-            }
148
-        }
149
-
150
-        return $m_values;
151
-    }
152
-
153
-
154
-    /**
155
-     * @deprecated 4.9.9.rc.014
156
-     * @return array
157
-     * @throws EE_Error
158
-     * @throws InvalidArgumentException
159
-     * @throws InvalidDataTypeException
160
-     * @throws InvalidInterfaceException
161
-     */
162
-    public function get_message_types_for_list_table()
163
-    {
164
-        EE_Error::doing_it_wrong(
165
-            __METHOD__,
166
-            sprintf(
167
-                esc_html__(
168
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
-                    'event_espresso'
170
-                ),
171
-                'Messages_Admin_Page::get_message_types_select_input()'
172
-            ),
173
-            '4.9.9.rc.014'
174
-        );
175
-
176
-        $mt_values = array();
177
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
-        $i = 1;
179
-        foreach ($active_messages as $active_message) {
180
-            if ($active_message instanceof EE_Message) {
181
-                $mt_values[ $i ]['id'] = $active_message->message_type();
182
-                $mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
-                $i++;
184
-            }
185
-        }
186
-
187
-        return $mt_values;
188
-    }
189
-
190
-
191
-    /**
192
-     * @deprecated 4.9.9.rc.014
193
-     * @return array
194
-     * @throws EE_Error
195
-     * @throws InvalidArgumentException
196
-     * @throws InvalidDataTypeException
197
-     * @throws InvalidInterfaceException
198
-     */
199
-    public function get_contexts_for_message_types_for_list_table()
200
-    {
201
-        EE_Error::doing_it_wrong(
202
-            __METHOD__,
203
-            sprintf(
204
-                esc_html__(
205
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
-                    'event_espresso'
207
-                ),
208
-                'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
-            ),
210
-            '4.9.9.rc.014'
211
-        );
212
-
213
-        $contexts = array();
214
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
-        foreach ($active_message_contexts as $active_message) {
216
-            if ($active_message instanceof EE_Message) {
217
-                $message_type = $active_message->message_type_object();
218
-                if ($message_type instanceof EE_message_type) {
219
-                    $message_type_contexts = $message_type->get_contexts();
220
-                    foreach ($message_type_contexts as $context => $context_details) {
221
-                        $contexts[ $context ] = $context_details['label'];
222
-                    }
223
-                }
224
-            }
225
-        }
226
-
227
-        return $contexts;
228
-    }
229
-
230
-
231
-    /**
232
-     * Generate select input with provided messenger options array.
233
-     *
234
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
-     *                                 labels.
236
-     * @return string
237
-     * @throws EE_Error
238
-     */
239
-    public function get_messengers_select_input($messenger_options)
240
-    {
241
-        // if empty or just one value then just return an empty string
242
-        if (empty($messenger_options)
243
-            || ! is_array($messenger_options)
244
-            || count($messenger_options) === 1
245
-        ) {
246
-            return '';
247
-        }
248
-        // merge in default
249
-        $messenger_options = array_merge(
250
-            array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
-            $messenger_options
252
-        );
253
-        $input = new EE_Select_Input(
254
-            $messenger_options,
255
-            array(
256
-                'html_name'  => 'ee_messenger_filter_by',
257
-                'html_id'    => 'ee_messenger_filter_by',
258
-                'html_class' => 'wide',
259
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
-                    : 'none_selected',
262
-            )
263
-        );
264
-
265
-        return $input->get_html_for_input();
266
-    }
267
-
268
-
269
-    /**
270
-     * Generate select input with provided message type options array.
271
-     *
272
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
-     *                                    message type labels
274
-     * @return string
275
-     * @throws EE_Error
276
-     */
277
-    public function get_message_types_select_input($message_type_options)
278
-    {
279
-        // if empty or count of options is 1 then just return an empty string
280
-        if (empty($message_type_options)
281
-            || ! is_array($message_type_options)
282
-            || count($message_type_options) === 1
283
-        ) {
284
-            return '';
285
-        }
286
-        // merge in default
287
-        $message_type_options = array_merge(
288
-            array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
-            $message_type_options
290
-        );
291
-        $input = new EE_Select_Input(
292
-            $message_type_options,
293
-            array(
294
-                'html_name'  => 'ee_message_type_filter_by',
295
-                'html_id'    => 'ee_message_type_filter_by',
296
-                'html_class' => 'wide',
297
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
-                    : 'none_selected',
300
-            )
301
-        );
302
-
303
-        return $input->get_html_for_input();
304
-    }
305
-
306
-
307
-    /**
308
-     * Generate select input with provide message type contexts array.
309
-     *
310
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
-     *                               context label.
312
-     * @return string
313
-     * @throws EE_Error
314
-     */
315
-    public function get_contexts_for_message_types_select_input($context_options)
316
-    {
317
-        // if empty or count of options is one then just return empty string
318
-        if (empty($context_options)
319
-            || ! is_array($context_options)
320
-            || count($context_options) === 1
321
-        ) {
322
-            return '';
323
-        }
324
-        // merge in default
325
-        $context_options = array_merge(
326
-            array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
-            $context_options
328
-        );
329
-        $input = new EE_Select_Input(
330
-            $context_options,
331
-            array(
332
-                'html_name'  => 'ee_context_filter_by',
333
-                'html_id'    => 'ee_context_filter_by',
334
-                'html_class' => 'wide',
335
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
336
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
337
-                    : 'none_selected',
338
-            )
339
-        );
340
-
341
-        return $input->get_html_for_input();
342
-    }
343
-
344
-
345
-    protected function _ajax_hooks()
346
-    {
347
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
-        add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
-    }
354
-
355
-
356
-    protected function _define_page_props()
357
-    {
358
-        $this->_admin_page_title = $this->page_label;
359
-        $this->_labels = array(
360
-            'buttons'    => array(
361
-                'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
-                'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
-                'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
-            ),
365
-            'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
-        );
367
-    }
368
-
369
-
370
-    /**
371
-     *        an array for storing key => value pairs of request actions and their corresponding methods
372
-     *
373
-     * @access protected
374
-     * @return void
375
-     */
376
-    protected function _set_page_routes()
377
-    {
378
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
-            ? $this->_req_data['GRP_ID']
380
-            : 0;
381
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
-            ? $this->_req_data['id']
383
-            : $grp_id;
384
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
-            ? $this->_req_data['MSG_ID']
386
-            : 0;
387
-
388
-        $this->_page_routes = array(
389
-            'default'                          => array(
390
-                'func'       => '_message_queue_list_table',
391
-                'capability' => 'ee_read_global_messages',
392
-            ),
393
-            'global_mtps'                      => array(
394
-                'func'       => '_ee_default_messages_overview_list_table',
395
-                'capability' => 'ee_read_global_messages',
396
-            ),
397
-            'custom_mtps'                      => array(
398
-                'func'       => '_custom_mtps_preview',
399
-                'capability' => 'ee_read_messages',
400
-            ),
401
-            'add_new_message_template'         => array(
402
-                'func'       => '_add_message_template',
403
-                'capability' => 'ee_edit_messages',
404
-                'noheader'   => true,
405
-            ),
406
-            'edit_message_template'            => array(
407
-                'func'       => '_edit_message_template',
408
-                'capability' => 'ee_edit_message',
409
-                'obj_id'     => $grp_id,
410
-            ),
411
-            'preview_message'                  => array(
412
-                'func'               => '_preview_message',
413
-                'capability'         => 'ee_read_message',
414
-                'obj_id'             => $grp_id,
415
-                'noheader'           => true,
416
-                'headers_sent_route' => 'display_preview_message',
417
-            ),
418
-            'display_preview_message'          => array(
419
-                'func'       => '_display_preview_message',
420
-                'capability' => 'ee_read_message',
421
-                'obj_id'     => $grp_id,
422
-            ),
423
-            'insert_message_template'          => array(
424
-                'func'       => '_insert_or_update_message_template',
425
-                'capability' => 'ee_edit_messages',
426
-                'args'       => array('new_template' => true),
427
-                'noheader'   => true,
428
-            ),
429
-            'update_message_template'          => array(
430
-                'func'       => '_insert_or_update_message_template',
431
-                'capability' => 'ee_edit_message',
432
-                'obj_id'     => $grp_id,
433
-                'args'       => array('new_template' => false),
434
-                'noheader'   => true,
435
-            ),
436
-            'trash_message_template'           => array(
437
-                'func'       => '_trash_or_restore_message_template',
438
-                'capability' => 'ee_delete_message',
439
-                'obj_id'     => $grp_id,
440
-                'args'       => array('trash' => true, 'all' => true),
441
-                'noheader'   => true,
442
-            ),
443
-            'trash_message_template_context'   => array(
444
-                'func'       => '_trash_or_restore_message_template',
445
-                'capability' => 'ee_delete_message',
446
-                'obj_id'     => $grp_id,
447
-                'args'       => array('trash' => true),
448
-                'noheader'   => true,
449
-            ),
450
-            'restore_message_template'         => array(
451
-                'func'       => '_trash_or_restore_message_template',
452
-                'capability' => 'ee_delete_message',
453
-                'obj_id'     => $grp_id,
454
-                'args'       => array('trash' => false, 'all' => true),
455
-                'noheader'   => true,
456
-            ),
457
-            'restore_message_template_context' => array(
458
-                'func'       => '_trash_or_restore_message_template',
459
-                'capability' => 'ee_delete_message',
460
-                'obj_id'     => $grp_id,
461
-                'args'       => array('trash' => false),
462
-                'noheader'   => true,
463
-            ),
464
-            'delete_message_template'          => array(
465
-                'func'       => '_delete_message_template',
466
-                'capability' => 'ee_delete_message',
467
-                'obj_id'     => $grp_id,
468
-                'noheader'   => true,
469
-            ),
470
-            'reset_to_default'                 => array(
471
-                'func'       => '_reset_to_default_template',
472
-                'capability' => 'ee_edit_message',
473
-                'obj_id'     => $grp_id,
474
-                'noheader'   => true,
475
-            ),
476
-            'settings'                         => array(
477
-                'func'       => '_settings',
478
-                'capability' => 'manage_options',
479
-            ),
480
-            'update_global_settings'           => array(
481
-                'func'       => '_update_global_settings',
482
-                'capability' => 'manage_options',
483
-                'noheader'   => true,
484
-            ),
485
-            'generate_now'                     => array(
486
-                'func'       => '_generate_now',
487
-                'capability' => 'ee_send_message',
488
-                'noheader'   => true,
489
-            ),
490
-            'generate_and_send_now'            => array(
491
-                'func'       => '_generate_and_send_now',
492
-                'capability' => 'ee_send_message',
493
-                'noheader'   => true,
494
-            ),
495
-            'queue_for_resending'              => array(
496
-                'func'       => '_queue_for_resending',
497
-                'capability' => 'ee_send_message',
498
-                'noheader'   => true,
499
-            ),
500
-            'send_now'                         => array(
501
-                'func'       => '_send_now',
502
-                'capability' => 'ee_send_message',
503
-                'noheader'   => true,
504
-            ),
505
-            'delete_ee_message'                => array(
506
-                'func'       => '_delete_ee_messages',
507
-                'capability' => 'ee_delete_messages',
508
-                'noheader'   => true,
509
-            ),
510
-            'delete_ee_messages'               => array(
511
-                'func'       => '_delete_ee_messages',
512
-                'capability' => 'ee_delete_messages',
513
-                'noheader'   => true,
514
-                'obj_id'     => $msg_id,
515
-            ),
516
-        );
517
-    }
518
-
519
-
520
-    protected function _set_page_config()
521
-    {
522
-        $this->_page_config = array(
523
-            'default'                  => array(
524
-                'nav'           => array(
525
-                    'label' => esc_html__('Message Activity', 'event_espresso'),
526
-                    'order' => 10,
527
-                ),
528
-                'list_table'    => 'EE_Message_List_Table',
529
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
-                'require_nonce' => false,
531
-            ),
532
-            'global_mtps'              => array(
533
-                'nav'           => array(
534
-                    'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
-                    'order' => 20,
536
-                ),
537
-                'list_table'    => 'Messages_Template_List_Table',
538
-                'help_tabs'     => array(
539
-                    'messages_overview_help_tab'                                => array(
540
-                        'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
-                        'filename' => 'messages_overview',
542
-                    ),
543
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
544
-                        'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
-                        'filename' => 'messages_overview_table_column_headings',
546
-                    ),
547
-                    'messages_overview_messages_filters_help_tab'               => array(
548
-                        'title'    => esc_html__('Message Filters', 'event_espresso'),
549
-                        'filename' => 'messages_overview_filters',
550
-                    ),
551
-                    'messages_overview_messages_views_help_tab'                 => array(
552
-                        'title'    => esc_html__('Message Views', 'event_espresso'),
553
-                        'filename' => 'messages_overview_views',
554
-                    ),
555
-                    'message_overview_message_types_help_tab'                   => array(
556
-                        'title'    => esc_html__('Message Types', 'event_espresso'),
557
-                        'filename' => 'messages_overview_types',
558
-                    ),
559
-                    'messages_overview_messengers_help_tab'                     => array(
560
-                        'title'    => esc_html__('Messengers', 'event_espresso'),
561
-                        'filename' => 'messages_overview_messengers',
562
-                    ),
563
-                ),
564
-                'help_tour'     => array('Messages_Overview_Help_Tour'),
565
-                'require_nonce' => false,
566
-            ),
567
-            'custom_mtps'              => array(
568
-                'nav'           => array(
569
-                    'label' => esc_html__('Custom Message Templates', 'event_espresso'),
570
-                    'order' => 30,
571
-                ),
572
-                'help_tabs'     => array(),
573
-                'help_tour'     => array(),
574
-                'require_nonce' => false,
575
-            ),
576
-            'add_new_message_template' => array(
577
-                'nav'           => array(
578
-                    'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
579
-                    'order'      => 5,
580
-                    'persistent' => false,
581
-                ),
582
-                'require_nonce' => false,
583
-            ),
584
-            'edit_message_template'    => array(
585
-                'labels'        => array(
586
-                    'buttons'    => array(
587
-                        'reset' => esc_html__('Reset Templates', 'event_espresso'),
588
-                    ),
589
-                    'publishbox' => esc_html__('Update Actions', 'event_espresso'),
590
-                ),
591
-                'nav'           => array(
592
-                    'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
593
-                    'order'      => 5,
594
-                    'persistent' => false,
595
-                    'url'        => '',
596
-                ),
597
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
598
-                'has_metaboxes' => true,
599
-                'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
600
-                'help_tabs'     => array(
601
-                    'edit_message_template'            => array(
602
-                        'title'    => esc_html__('Message Template Editor', 'event_espresso'),
603
-                        'callback' => 'edit_message_template_help_tab',
604
-                    ),
605
-                    'message_templates_help_tab'       => array(
606
-                        'title'    => esc_html__('Message Templates', 'event_espresso'),
607
-                        'filename' => 'messages_templates',
608
-                    ),
609
-                    'message_template_shortcodes'      => array(
610
-                        'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
611
-                        'callback' => 'message_template_shortcodes_help_tab',
612
-                    ),
613
-                    'message_preview_help_tab'         => array(
614
-                        'title'    => esc_html__('Message Preview', 'event_espresso'),
615
-                        'filename' => 'messages_preview',
616
-                    ),
617
-                    'messages_overview_other_help_tab' => array(
618
-                        'title'    => esc_html__('Messages Other', 'event_espresso'),
619
-                        'filename' => 'messages_overview_other',
620
-                    ),
621
-                ),
622
-                'require_nonce' => false,
623
-            ),
624
-            'display_preview_message'  => array(
625
-                'nav'           => array(
626
-                    'label'      => esc_html__('Message Preview', 'event_espresso'),
627
-                    'order'      => 5,
628
-                    'url'        => '',
629
-                    'persistent' => false,
630
-                ),
631
-                'help_tabs'     => array(
632
-                    'preview_message' => array(
633
-                        'title'    => esc_html__('About Previews', 'event_espresso'),
634
-                        'callback' => 'preview_message_help_tab',
635
-                    ),
636
-                ),
637
-                'require_nonce' => false,
638
-            ),
639
-            'settings'                 => array(
640
-                'nav'           => array(
641
-                    'label' => esc_html__('Settings', 'event_espresso'),
642
-                    'order' => 40,
643
-                ),
644
-                'metaboxes'     => array('_messages_settings_metaboxes'),
645
-                'help_tabs'     => array(
646
-                    'messages_settings_help_tab'               => array(
647
-                        'title'    => esc_html__('Messages Settings', 'event_espresso'),
648
-                        'filename' => 'messages_settings',
649
-                    ),
650
-                    'messages_settings_message_types_help_tab' => array(
651
-                        'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
652
-                        'filename' => 'messages_settings_message_types',
653
-                    ),
654
-                    'messages_settings_messengers_help_tab'    => array(
655
-                        'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
656
-                        'filename' => 'messages_settings_messengers',
657
-                    ),
658
-                ),
659
-                'help_tour'     => array('Messages_Settings_Help_Tour'),
660
-                'require_nonce' => false,
661
-            ),
662
-        );
663
-    }
664
-
665
-
666
-    protected function _add_screen_options()
667
-    {
668
-        // todo
669
-    }
670
-
671
-
672
-    protected function _add_screen_options_global_mtps()
673
-    {
674
-        /**
675
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
676
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
677
-         */
678
-        $page_title = $this->_admin_page_title;
679
-        $this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
680
-        $this->_per_page_screen_option();
681
-        $this->_admin_page_title = $page_title;
682
-    }
683
-
684
-
685
-    protected function _add_screen_options_default()
686
-    {
687
-        $this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
688
-        $this->_per_page_screen_option();
689
-    }
690
-
691
-
692
-    // none of the below group are currently used for Messages
693
-    protected function _add_feature_pointers()
694
-    {
695
-    }
696
-
697
-    public function admin_init()
698
-    {
699
-    }
700
-
701
-    public function admin_notices()
702
-    {
703
-    }
704
-
705
-    public function admin_footer_scripts()
706
-    {
707
-    }
708
-
709
-
710
-    public function messages_help_tab()
711
-    {
712
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
713
-    }
714
-
715
-
716
-    public function messengers_help_tab()
717
-    {
718
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
719
-    }
720
-
721
-
722
-    public function message_types_help_tab()
723
-    {
724
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
725
-    }
726
-
727
-
728
-    public function messages_overview_help_tab()
729
-    {
730
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
731
-    }
732
-
733
-
734
-    public function message_templates_help_tab()
735
-    {
736
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
737
-    }
738
-
739
-
740
-    public function edit_message_template_help_tab()
741
-    {
742
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
743
-                        . esc_attr__('Editor Title', 'event_espresso')
744
-                        . '" />';
745
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
746
-                        . esc_attr__('Context Switcher and Preview', 'event_espresso')
747
-                        . '" />';
748
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
749
-                        . esc_attr__('Message Template Form Fields', 'event_espresso')
750
-                        . '" />';
751
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
752
-                        . esc_attr__('Shortcodes Metabox', 'event_espresso')
753
-                        . '" />';
754
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
755
-                        . esc_attr__('Publish Metabox', 'event_espresso')
756
-                        . '" />';
757
-        EEH_Template::display_template(
758
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
759
-            $args
760
-        );
761
-    }
762
-
763
-
764
-    public function message_template_shortcodes_help_tab()
765
-    {
766
-        $this->_set_shortcodes();
767
-        $args['shortcodes'] = $this->_shortcodes;
768
-        EEH_Template::display_template(
769
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
770
-            $args
771
-        );
772
-    }
773
-
774
-
775
-    public function preview_message_help_tab()
776
-    {
777
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
778
-    }
779
-
780
-
781
-    public function settings_help_tab()
782
-    {
783
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
784
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
785
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
786
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
787
-        $args['img3'] = '<div class="switch">'
788
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
789
-                        . ' type="checkbox" checked="checked">'
790
-                        . '<label for="ee-on-off-toggle-on"></label>'
791
-                        . '</div>';
792
-        $args['img4'] = '<div class="switch">'
793
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
794
-                        . ' type="checkbox">'
795
-                        . '<label for="ee-on-off-toggle-on"></label>'
796
-                        . '</div>';
797
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
798
-    }
799
-
800
-
801
-    public function load_scripts_styles()
802
-    {
803
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
804
-        wp_enqueue_style('espresso_ee_msg');
805
-
806
-        wp_register_script(
807
-            'ee-messages-settings',
808
-            EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
-            array('jquery-ui-droppable', 'ee-serialize-full-array'),
810
-            EVENT_ESPRESSO_VERSION,
811
-            true
812
-        );
813
-        wp_register_script(
814
-            'ee-msg-list-table-js',
815
-            EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
816
-            array('ee-dialog'),
817
-            EVENT_ESPRESSO_VERSION
818
-        );
819
-    }
820
-
821
-
822
-    public function load_scripts_styles_default()
823
-    {
824
-        wp_enqueue_script('ee-msg-list-table-js');
825
-    }
826
-
827
-
828
-    public function wp_editor_css($mce_css)
829
-    {
830
-        // if we're on the edit_message_template route
831
-        if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
832
-            $message_type_name = $this->_active_message_type_name;
833
-
834
-            // we're going to REPLACE the existing mce css
835
-            // we need to get the css file location from the active messenger
836
-            $mce_css = $this->_active_messenger->get_variation(
837
-                $this->_template_pack,
838
-                $message_type_name,
839
-                true,
840
-                'wpeditor',
841
-                $this->_variation
842
-            );
843
-        }
844
-
845
-        return $mce_css;
846
-    }
847
-
848
-
849
-    public function load_scripts_styles_edit_message_template()
850
-    {
851
-
852
-        $this->_set_shortcodes();
853
-
854
-        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
855
-            esc_html__(
856
-                'Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
857
-                'event_espresso'
858
-            ),
859
-            $this->_message_template_group->messenger_obj()->label['singular'],
860
-            $this->_message_template_group->message_type_obj()->label['singular']
861
-        );
862
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
863
-            'Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
864
-            'event_espresso'
865
-        );
866
-        EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
867
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
868
-            'event_espresso'
869
-        );
870
-
871
-        wp_register_script(
872
-            'ee_msgs_edit_js',
873
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
874
-            array('jquery'),
875
-            EVENT_ESPRESSO_VERSION
876
-        );
877
-
878
-        wp_enqueue_script('ee_admin_js');
879
-        wp_enqueue_script('ee_msgs_edit_js');
880
-
881
-        // add in special css for tiny_mce
882
-        add_filter('mce_css', array($this, 'wp_editor_css'));
883
-    }
884
-
885
-
886
-    public function load_scripts_styles_display_preview_message()
887
-    {
888
-
889
-        $this->_set_message_template_group();
890
-
891
-        if (isset($this->_req_data['messenger'])) {
892
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
893
-                $this->_req_data['messenger']
894
-            );
895
-        }
896
-
897
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
898
-
899
-
900
-        wp_enqueue_style(
901
-            'espresso_preview_css',
902
-            $this->_active_messenger->get_variation(
903
-                $this->_template_pack,
904
-                $message_type_name,
905
-                true,
906
-                'preview',
907
-                $this->_variation
908
-            )
909
-        );
910
-    }
911
-
912
-
913
-    public function load_scripts_styles_settings()
914
-    {
915
-        wp_register_style(
916
-            'ee-message-settings',
917
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
918
-            array(),
919
-            EVENT_ESPRESSO_VERSION
920
-        );
921
-        wp_enqueue_style('ee-text-links');
922
-        wp_enqueue_style('ee-message-settings');
923
-        wp_enqueue_script('ee-messages-settings');
924
-    }
925
-
926
-
927
-    /**
928
-     * set views array for List Table
929
-     */
930
-    public function _set_list_table_views_global_mtps()
931
-    {
932
-        $this->_views = array(
933
-            'in_use' => array(
934
-                'slug'  => 'in_use',
935
-                'label' => esc_html__('In Use', 'event_espresso'),
936
-                'count' => 0,
937
-            ),
938
-        );
939
-    }
940
-
941
-
942
-    /**
943
-     * Set views array for the Custom Template List Table
944
-     */
945
-    public function _set_list_table_views_custom_mtps()
946
-    {
947
-        $this->_set_list_table_views_global_mtps();
948
-        $this->_views['in_use']['bulk_action'] = array(
949
-            'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
950
-        );
951
-    }
952
-
953
-
954
-    /**
955
-     * set views array for message queue list table
956
-     *
957
-     * @throws InvalidDataTypeException
958
-     * @throws InvalidInterfaceException
959
-     * @throws InvalidArgumentException
960
-     * @throws EE_Error
961
-     * @throws ReflectionException
962
-     */
963
-    public function _set_list_table_views_default()
964
-    {
965
-        EE_Registry::instance()->load_helper('Template');
966
-
967
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
968
-            'ee_send_message',
969
-            'message_list_table_bulk_actions'
970
-        )
971
-            ? array(
972
-                'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
973
-                'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
974
-                'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
975
-                'send_now'              => esc_html__('Send Now', 'event_espresso'),
976
-            )
977
-            : array();
978
-
979
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
980
-            'ee_delete_messages',
981
-            'message_list_table_bulk_actions'
982
-        )
983
-            ? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
984
-            : array();
985
-
986
-
987
-        $this->_views = array(
988
-            'all' => array(
989
-                'slug'        => 'all',
990
-                'label'       => esc_html__('All', 'event_espresso'),
991
-                'count'       => 0,
992
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
993
-            ),
994
-        );
995
-
996
-
997
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
998
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
999
-                continue;
1000
-            }
1001
-            $status_bulk_actions = $common_bulk_actions;
1002
-            // unset bulk actions not applying to status
1003
-            if (! empty($status_bulk_actions)) {
1004
-                switch ($status) {
1005
-                    case EEM_Message::status_idle:
1006
-                    case EEM_Message::status_resend:
1007
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1008
-                        break;
1009
-
1010
-                    case EEM_Message::status_failed:
1011
-                    case EEM_Message::status_debug_only:
1012
-                    case EEM_Message::status_messenger_executing:
1013
-                        $status_bulk_actions = array();
1014
-                        break;
1015
-
1016
-                    case EEM_Message::status_incomplete:
1017
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1018
-                        break;
1019
-
1020
-                    case EEM_Message::status_retry:
1021
-                    case EEM_Message::status_sent:
1022
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1023
-                        break;
1024
-                }
1025
-            }
1026
-
1027
-            // skip adding messenger executing status to views because it will be included with the Failed view.
1028
-            if ($status === EEM_Message::status_messenger_executing) {
1029
-                continue;
1030
-            }
1031
-
1032
-            $this->_views[ strtolower($status) ] = array(
1033
-                'slug'        => strtolower($status),
1034
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1035
-                'count'       => 0,
1036
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1037
-            );
1038
-        }
1039
-    }
1040
-
1041
-
1042
-    protected function _ee_default_messages_overview_list_table()
1043
-    {
1044
-        $this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1045
-        $this->display_admin_list_table_page_with_no_sidebar();
1046
-    }
1047
-
1048
-
1049
-    protected function _message_queue_list_table()
1050
-    {
1051
-        $this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1052
-        $this->_template_args['per_column'] = 6;
1053
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1054
-        $this->_template_args['before_list_table'] = '<h3>'
1055
-                                                     . EEM_Message::instance()->get_pretty_label_for_results()
1056
-                                                     . '</h3>';
1057
-        $this->display_admin_list_table_page_with_no_sidebar();
1058
-    }
1059
-
1060
-
1061
-    protected function _message_legend_items()
1062
-    {
1063
-
1064
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
1065
-        $action_items = array();
1066
-
1067
-        foreach ($action_css_classes as $action_item => $action_details) {
1068
-            if ($action_item === 'see_notifications_for') {
1069
-                continue;
1070
-            }
1071
-            $action_items[ $action_item ] = array(
1072
-                'class' => $action_details['css_class'],
1073
-                'desc'  => $action_details['label'],
1074
-            );
1075
-        }
1076
-
1077
-        /** @type array $status_items status legend setup */
1078
-        $status_items = array(
1079
-            'incomplete_status'          => array(
1080
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1081
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1082
-            ),
1083
-            'idle_status'                => array(
1084
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1085
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1086
-            ),
1087
-            'resend_status'              => array(
1088
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1089
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1090
-            ),
1091
-            'messenger_executing_status' => array(
1092
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1093
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1094
-            ),
1095
-            'sent_status'                => array(
1096
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1097
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1098
-            ),
1099
-            'retry_status'               => array(
1100
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1101
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1102
-            ),
1103
-            'failed_status'              => array(
1104
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1105
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1106
-            ),
1107
-        );
1108
-        if (EEM_Message::debug()) {
1109
-            $status_items['debug_only_status'] = array(
1110
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1111
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1112
-            );
1113
-        }
1114
-
1115
-        return array_merge($action_items, $status_items);
1116
-    }
1117
-
1118
-
1119
-    protected function _custom_mtps_preview()
1120
-    {
1121
-        $this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1122
-        $this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1123
-                                               . ' alt="' . esc_attr__(
1124
-                                                   'Preview Custom Message Templates screenshot',
1125
-                                                   'event_espresso'
1126
-                                               ) . '" />';
1127
-        $this->_template_args['preview_text'] = '<strong>'
1128
-                                                . esc_html__(
1129
-                                                    'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1130
-                                                    'event_espresso'
1131
-                                                )
1132
-                                                . '</strong>';
1133
-
1134
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1135
-    }
1136
-
1137
-
1138
-    /**
1139
-     * get_message_templates
1140
-     * This gets all the message templates for listing on the overview list.
1141
-     *
1142
-     * @access public
1143
-     * @param int    $perpage the amount of templates groups to show per page
1144
-     * @param string $type    the current _view we're getting templates for
1145
-     * @param bool   $count   return count?
1146
-     * @param bool   $all     disregard any paging info (get all data);
1147
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1148
-     * @return array
1149
-     * @throws EE_Error
1150
-     * @throws InvalidArgumentException
1151
-     * @throws InvalidDataTypeException
1152
-     * @throws InvalidInterfaceException
1153
-     */
1154
-    public function get_message_templates(
1155
-        $perpage = 10,
1156
-        $type = 'in_use',
1157
-        $count = false,
1158
-        $all = false,
1159
-        $global = true
1160
-    ) {
1161
-
1162
-        $MTP = EEM_Message_Template_Group::instance();
1163
-
1164
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1165
-        $orderby = $this->_req_data['orderby'];
1166
-
1167
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1168
-            ? $this->_req_data['order']
1169
-            : 'ASC';
1170
-
1171
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1172
-            ? $this->_req_data['paged']
1173
-            : 1;
1174
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1175
-            ? $this->_req_data['perpage']
1176
-            : $perpage;
1177
-
1178
-        $offset = ($current_page - 1) * $per_page;
1179
-        $limit = $all ? null : array($offset, $per_page);
1180
-
1181
-
1182
-        // options will match what is in the _views array property
1183
-        switch ($type) {
1184
-            case 'in_use':
1185
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1186
-                break;
1187
-            default:
1188
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1189
-        }
1190
-
1191
-        return $templates;
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * filters etc might need a list of installed message_types
1197
-     *
1198
-     * @return array an array of message type objects
1199
-     */
1200
-    public function get_installed_message_types()
1201
-    {
1202
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1203
-        $installed = array();
1204
-
1205
-        foreach ($installed_message_types as $message_type) {
1206
-            $installed[ $message_type->name ] = $message_type;
1207
-        }
1208
-
1209
-        return $installed;
1210
-    }
1211
-
1212
-
1213
-    /**
1214
-     * _add_message_template
1215
-     *
1216
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1217
-     *
1218
-     * @param string $message_type
1219
-     * @param string $messenger
1220
-     * @param string $GRP_ID
1221
-     *
1222
-     * @throws EE_error
1223
-     */
1224
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1225
-    {
1226
-        // set values override any request data
1227
-        $message_type = ! empty($message_type) ? $message_type : '';
1228
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1229
-            ? $this->_req_data['message_type']
1230
-            : $message_type;
1231
-
1232
-        $messenger = ! empty($messenger) ? $messenger : '';
1233
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1234
-            ? $this->_req_data['messenger']
1235
-            : $messenger;
1236
-
1237
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1238
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1239
-
1240
-        // we need messenger and message type.  They should be coming from the event editor. If not here then return error
1241
-        if (empty($message_type) || empty($messenger)) {
1242
-            throw new EE_Error(
1243
-                esc_html__(
1244
-                    'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1245
-                    'event_espresso'
1246
-                )
1247
-            );
1248
-        }
1249
-
1250
-        // we need the GRP_ID for the template being used as the base for the new template
1251
-        if (empty($GRP_ID)) {
1252
-            throw new EE_Error(
1253
-                esc_html__(
1254
-                    'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1255
-                    'event_espresso'
1256
-                )
1257
-            );
1258
-        }
1259
-
1260
-        // let's just make sure the template gets generated!
1261
-
1262
-        // we need to reassign some variables for what the insert is expecting
1263
-        $this->_req_data['MTP_messenger'] = $messenger;
1264
-        $this->_req_data['MTP_message_type'] = $message_type;
1265
-        $this->_req_data['GRP_ID'] = $GRP_ID;
1266
-        $this->_insert_or_update_message_template(true);
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * public wrapper for the _add_message_template method
1272
-     *
1273
-     * @param string $message_type     message type slug
1274
-     * @param string $messenger        messenger slug
1275
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1276
-     *                                 off of.
1277
-     * @throws EE_error
1278
-     */
1279
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1280
-    {
1281
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1282
-    }
1283
-
1284
-
1285
-    /**
1286
-     * _edit_message_template
1287
-     *
1288
-     * @access protected
1289
-     * @return void
1290
-     * @throws InvalidIdentifierException
1291
-     * @throws DomainException
1292
-     * @throws EE_Error
1293
-     * @throws InvalidArgumentException
1294
-     * @throws ReflectionException
1295
-     * @throws InvalidDataTypeException
1296
-     * @throws InvalidInterfaceException
1297
-     */
1298
-    protected function _edit_message_template()
1299
-    {
1300
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1301
-        $template_fields = '';
1302
-        $sidebar_fields = '';
1303
-        // we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1304
-        // valid html in the templates.
1305
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1306
-
1307
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1308
-            ? absint($this->_req_data['id'])
1309
-            : false;
1310
-
1311
-        $EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
1312
-        ? absint($this->_req_data['evt_id'])
1313
-        : false;
1314
-
1315
-        $this->_set_shortcodes(); // this also sets the _message_template property.
1316
-        $message_template_group = $this->_message_template_group;
1317
-        $c_label = $message_template_group->context_label();
1318
-        $c_config = $message_template_group->contexts_config();
1319
-
1320
-        reset($c_config);
1321
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1322
-            ? strtolower($this->_req_data['context'])
1323
-            : key($c_config);
1324
-
1325
-
1326
-        if (empty($GRP_ID)) {
1327
-            $action = 'insert_message_template';
1328
-            $edit_message_template_form_url = add_query_arg(
1329
-                array('action' => $action, 'noheader' => true),
1330
-                EE_MSG_ADMIN_URL
1331
-            );
1332
-        } else {
1333
-            $action = 'update_message_template';
1334
-            $edit_message_template_form_url = add_query_arg(
1335
-                array('action' => $action, 'noheader' => true),
1336
-                EE_MSG_ADMIN_URL
1337
-            );
1338
-        }
1339
-
1340
-        // set active messenger for this view
1341
-        $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1342
-            $message_template_group->messenger()
1343
-        );
1344
-        $this->_active_message_type_name = $message_template_group->message_type();
1345
-
1346
-
1347
-        // Do we have any validation errors?
1348
-        $validators = $this->_get_transient();
1349
-        $v_fields = ! empty($validators) ? array_keys($validators) : array();
1350
-
1351
-
1352
-        // we need to assemble the title from Various details
1353
-        $context_label = sprintf(
1354
-            esc_html__('(%s %s)', 'event_espresso'),
1355
-            $c_config[ $context ]['label'],
1356
-            ucwords($c_label['label'])
1357
-        );
1358
-
1359
-        $title = sprintf(
1360
-            esc_html__(' %s %s Template %s', 'event_espresso'),
1361
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1362
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1363
-            $context_label
1364
-        );
1365
-
1366
-        $this->_template_args['GRP_ID'] = $GRP_ID;
1367
-        $this->_template_args['message_template'] = $message_template_group;
1368
-        $this->_template_args['is_extra_fields'] = false;
1369
-
1370
-
1371
-        // let's get EEH_MSG_Template so we can get template form fields
1372
-        $template_field_structure = EEH_MSG_Template::get_fields(
1373
-            $message_template_group->messenger(),
1374
-            $message_template_group->message_type()
1375
-        );
1376
-
1377
-        if (! $template_field_structure) {
1378
-            $template_field_structure = false;
1379
-            $template_fields = esc_html__(
1380
-                'There was an error in assembling the fields for this display (you should see an error message)',
1381
-                'event_espresso'
1382
-            );
1383
-        }
1384
-
1385
-
1386
-        $message_templates = $message_template_group->context_templates();
1387
-
1388
-
1389
-        // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1390
-        // will get handled in the "extra" array.
1391
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1392
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1393
-                unset($template_field_structure[ $context ][ $reference_field ]);
1394
-            }
1395
-        }
1396
-
1397
-        // let's loop through the template_field_structure and actually assemble the input fields!
1398
-        if (! empty($template_field_structure)) {
1399
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1400
-                // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1401
-                // the extra array and reset them.
1402
-                if ($template_field === 'extra') {
1403
-                    $this->_template_args['is_extra_fields'] = true;
1404
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1405
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1406
-                        $content = $message_template instanceof EE_Message_Template
1407
-                            ? $message_template->get('MTP_content')
1408
-                            : '';
1409
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1410
-                            // let's verify if we need this extra field via the shortcodes parameter.
1411
-                            $continue = false;
1412
-                            if (isset($extra_array['shortcodes_required'])) {
1413
-                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1414
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1415
-                                        $continue = true;
1416
-                                    }
1417
-                                }
1418
-                                if ($continue) {
1419
-                                    continue;
1420
-                                }
1421
-                            }
1422
-
1423
-                            $field_id = $reference_field
1424
-                                        . '-'
1425
-                                        . $extra_field
1426
-                                        . '-content';
1427
-                            $template_form_fields[ $field_id ] = $extra_array;
1428
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1429
-                                                                         . $reference_field
1430
-                                                                         . '][content]['
1431
-                                                                         . $extra_field . ']';
1432
-                            $css_class = isset($extra_array['css_class'])
1433
-                                ? $extra_array['css_class']
1434
-                                : '';
1435
-
1436
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1437
-                                                                              && in_array($extra_field, $v_fields, true)
1438
-                                                                              &&
1439
-                                                                              (
1440
-                                                                                  is_array($validators[ $extra_field ])
1441
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1442
-                                                                              )
1443
-                                ? 'validate-error ' . $css_class
1444
-                                : $css_class;
1445
-
1446
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1447
-                                                                          && isset($content[ $extra_field ])
1448
-                                ? $content[ $extra_field ]
1449
-                                : '';
1450
-
1451
-                            // do we have a validation error?  if we do then let's use that value instead
1452
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1453
-                                ? $validators[ $extra_field ]['value']
1454
-                                : $template_form_fields[ $field_id ]['value'];
1455
-
1456
-
1457
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1458
-
1459
-                            // shortcode selector
1460
-                            $field_name_to_use = $extra_field === 'main'
1461
-                                ? 'content'
1462
-                                : $extra_field;
1463
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1464
-                                $field_name_to_use,
1465
-                                $field_id
1466
-                            );
1467
-
1468
-                            if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1469
-                                // we want to decode the entities
1470
-                                $template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1471
-                            }/**/
1472
-                        }
1473
-                        $templatefield_MTP_id = $reference_field . '-MTP_ID';
1474
-                        $templatefield_templatename_id = $reference_field . '-name';
1475
-
1476
-                        $template_form_fields[ $templatefield_MTP_id ] = array(
1477
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1478
-                            'label'      => null,
1479
-                            'input'      => 'hidden',
1480
-                            'type'       => 'int',
1481
-                            'required'   => false,
1482
-                            'validation' => false,
1483
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1484
-                            'css_class'  => '',
1485
-                            'format'     => '%d',
1486
-                            'db-col'     => 'MTP_ID',
1487
-                        );
1488
-
1489
-                        $template_form_fields[ $templatefield_templatename_id ] = array(
1490
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1491
-                            'label'      => null,
1492
-                            'input'      => 'hidden',
1493
-                            'type'       => 'string',
1494
-                            'required'   => false,
1495
-                            'validation' => true,
1496
-                            'value'      => $reference_field,
1497
-                            'css_class'  => '',
1498
-                            'format'     => '%s',
1499
-                            'db-col'     => 'MTP_template_field',
1500
-                        );
1501
-                    }
1502
-                    continue; // skip the next stuff, we got the necessary fields here for this dataset.
1503
-                } else {
1504
-                    $field_id = $template_field . '-content';
1505
-                    $template_form_fields[ $field_id ] = $field_setup_array;
1506
-                    $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1507
-                    $message_template = isset($message_templates[ $context ][ $template_field ])
1508
-                        ? $message_templates[ $context ][ $template_field ]
1509
-                        : null;
1510
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1511
-                                                                  && is_array($message_templates[ $context ])
1512
-                                                                  && $message_template instanceof EE_Message_Template
1513
-                        ? $message_template->get('MTP_content')
1514
-                        : '';
1515
-
1516
-                    // do we have a validator error for this field?  if we do then we'll use that value instead
1517
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1518
-                        ? $validators[ $template_field ]['value']
1519
-                        : $template_form_fields[ $field_id ]['value'];
1520
-
1521
-
1522
-                    $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1523
-                    $css_class = isset($field_setup_array['css_class'])
1524
-                        ? $field_setup_array['css_class']
1525
-                        : '';
1526
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1527
-                                                                      && in_array($template_field, $v_fields, true)
1528
-                                                                      && isset($validators[ $template_field ]['msg'])
1529
-                        ? 'validate-error ' . $css_class
1530
-                        : $css_class;
1531
-
1532
-                    // shortcode selector
1533
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1534
-                        $template_field,
1535
-                        $field_id
1536
-                    );
1537
-                }
1538
-
1539
-                // k took care of content field(s) now let's take care of others.
1540
-
1541
-                $templatefield_MTP_id = $template_field . '-MTP_ID';
1542
-                $templatefield_field_templatename_id = $template_field . '-name';
1543
-
1544
-                // foreach template field there are actually two form fields created
1545
-                $template_form_fields[ $templatefield_MTP_id ] = array(
1546
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1547
-                    'label'      => null,
1548
-                    'input'      => 'hidden',
1549
-                    'type'       => 'int',
1550
-                    'required'   => false,
1551
-                    'validation' => true,
1552
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1553
-                    'css_class'  => '',
1554
-                    'format'     => '%d',
1555
-                    'db-col'     => 'MTP_ID',
1556
-                );
1557
-
1558
-                $template_form_fields[ $templatefield_field_templatename_id ] = array(
1559
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1560
-                    'label'      => null,
1561
-                    'input'      => 'hidden',
1562
-                    'type'       => 'string',
1563
-                    'required'   => false,
1564
-                    'validation' => true,
1565
-                    'value'      => $template_field,
1566
-                    'css_class'  => '',
1567
-                    'format'     => '%s',
1568
-                    'db-col'     => 'MTP_template_field',
1569
-                );
1570
-            }
1571
-
1572
-            // add other fields
1573
-            $template_form_fields['ee-msg-current-context'] = array(
1574
-                'name'       => 'MTP_context',
1575
-                'label'      => null,
1576
-                'input'      => 'hidden',
1577
-                'type'       => 'string',
1578
-                'required'   => false,
1579
-                'validation' => true,
1580
-                'value'      => $context,
1581
-                'css_class'  => '',
1582
-                'format'     => '%s',
1583
-                'db-col'     => 'MTP_context',
1584
-            );
1585
-
1586
-            $template_form_fields['ee-msg-grp-id'] = array(
1587
-                'name'       => 'GRP_ID',
1588
-                'label'      => null,
1589
-                'input'      => 'hidden',
1590
-                'type'       => 'int',
1591
-                'required'   => false,
1592
-                'validation' => true,
1593
-                'value'      => $GRP_ID,
1594
-                'css_class'  => '',
1595
-                'format'     => '%d',
1596
-                'db-col'     => 'GRP_ID',
1597
-            );
1598
-
1599
-            $template_form_fields['ee-msg-messenger'] = array(
1600
-                'name'       => 'MTP_messenger',
1601
-                'label'      => null,
1602
-                'input'      => 'hidden',
1603
-                'type'       => 'string',
1604
-                'required'   => false,
1605
-                'validation' => true,
1606
-                'value'      => $message_template_group->messenger(),
1607
-                'css_class'  => '',
1608
-                'format'     => '%s',
1609
-                'db-col'     => 'MTP_messenger',
1610
-            );
1611
-
1612
-            $template_form_fields['ee-msg-message-type'] = array(
1613
-                'name'       => 'MTP_message_type',
1614
-                'label'      => null,
1615
-                'input'      => 'hidden',
1616
-                'type'       => 'string',
1617
-                'required'   => false,
1618
-                'validation' => true,
1619
-                'value'      => $message_template_group->message_type(),
1620
-                'css_class'  => '',
1621
-                'format'     => '%s',
1622
-                'db-col'     => 'MTP_message_type',
1623
-            );
1624
-
1625
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1626
-                'name'       => 'MTP_is_global',
1627
-                'label'      => esc_html__('Global Template', 'event_espresso'),
1628
-                'input'      => 'hidden',
1629
-                'type'       => 'int',
1630
-                'required'   => false,
1631
-                'validation' => true,
1632
-                'value'      => $message_template_group->get('MTP_is_global'),
1633
-                'css_class'  => '',
1634
-                'format'     => '%d',
1635
-                'db-col'     => 'MTP_is_global',
1636
-            );
1637
-
1638
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1639
-                'name'       => 'MTP_is_override',
1640
-                'label'      => esc_html__('Override all custom', 'event_espresso'),
1641
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1642
-                'type'       => 'int',
1643
-                'required'   => false,
1644
-                'validation' => true,
1645
-                'value'      => $message_template_group->get('MTP_is_override'),
1646
-                'css_class'  => '',
1647
-                'format'     => '%d',
1648
-                'db-col'     => 'MTP_is_override',
1649
-            );
1650
-
1651
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1652
-                'name'       => 'MTP_is_active',
1653
-                'label'      => esc_html__('Active Template', 'event_espresso'),
1654
-                'input'      => 'hidden',
1655
-                'type'       => 'int',
1656
-                'required'   => false,
1657
-                'validation' => true,
1658
-                'value'      => $message_template_group->is_active(),
1659
-                'css_class'  => '',
1660
-                'format'     => '%d',
1661
-                'db-col'     => 'MTP_is_active',
1662
-            );
1663
-
1664
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1665
-                'name'       => 'MTP_deleted',
1666
-                'label'      => null,
1667
-                'input'      => 'hidden',
1668
-                'type'       => 'int',
1669
-                'required'   => false,
1670
-                'validation' => true,
1671
-                'value'      => $message_template_group->get('MTP_deleted'),
1672
-                'css_class'  => '',
1673
-                'format'     => '%d',
1674
-                'db-col'     => 'MTP_deleted',
1675
-            );
1676
-            $sidebar_form_fields['ee-msg-author'] = array(
1677
-                'name'       => 'MTP_user_id',
1678
-                'label'      => esc_html__('Author', 'event_espresso'),
1679
-                'input'      => 'hidden',
1680
-                'type'       => 'int',
1681
-                'required'   => false,
1682
-                'validation' => false,
1683
-                'value'      => $message_template_group->user(),
1684
-                'format'     => '%d',
1685
-                'db-col'     => 'MTP_user_id',
1686
-            );
1687
-
1688
-            $sidebar_form_fields['ee-msg-route'] = array(
1689
-                'name'  => 'action',
1690
-                'input' => 'hidden',
1691
-                'type'  => 'string',
1692
-                'value' => $action,
1693
-            );
1694
-
1695
-            $sidebar_form_fields['ee-msg-id'] = array(
1696
-                'name'  => 'id',
1697
-                'input' => 'hidden',
1698
-                'type'  => 'int',
1699
-                'value' => $GRP_ID,
1700
-            );
1701
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1702
-                'name'  => $action . '_nonce',
1703
-                'input' => 'hidden',
1704
-                'type'  => 'string',
1705
-                'value' => wp_create_nonce($action . '_nonce'),
1706
-            );
1707
-
1708
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1709
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1710
-                    'name'  => 'template_switch',
1711
-                    'input' => 'hidden',
1712
-                    'type'  => 'int',
1713
-                    'value' => 1,
1714
-                );
1715
-            }
1716
-
1717
-
1718
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1719
-            $sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1720
-        } //end if ( !empty($template_field_structure) )
1721
-
1722
-        // set extra content for publish box
1723
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1724
-        $this->_set_publish_post_box_vars(
1725
-            'id',
1726
-            $GRP_ID,
1727
-            false,
1728
-            add_query_arg(
1729
-                array('action' => 'global_mtps'),
1730
-                $this->_admin_base_url
1731
-            )
1732
-        );
1733
-
1734
-        // add preview button
1735
-        $preview_url = parent::add_query_args_and_nonce(
1736
-            array(
1737
-                'message_type' => $message_template_group->message_type(),
1738
-                'messenger'    => $message_template_group->messenger(),
1739
-                'context'      => $context,
1740
-                'GRP_ID'       => $GRP_ID,
1741
-                'evt_id'       => $EVT_ID,
1742
-                'action'       => 'preview_message',
1743
-            ),
1744
-            $this->_admin_base_url
1745
-        );
1746
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1747
-                          . esc_html__('Preview', 'event_espresso')
1748
-                          . '</a>';
1749
-
1750
-
1751
-        // setup context switcher
1752
-        $context_switcher_args = array(
1753
-            'page'    => 'espresso_messages',
1754
-            'action'  => 'edit_message_template',
1755
-            'id'      => $GRP_ID,
1756
-            'evt_id'  => $EVT_ID,
1757
-            'context' => $context,
1758
-            'extra'   => $preview_button,
1759
-        );
1760
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1761
-
1762
-
1763
-        // main box
1764
-        $this->_template_args['template_fields'] = $template_fields;
1765
-        $this->_template_args['sidebar_box_id'] = 'details';
1766
-        $this->_template_args['action'] = $action;
1767
-        $this->_template_args['context'] = $context;
1768
-        $this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1769
-        $this->_template_args['learn_more_about_message_templates_link'] =
1770
-            $this->_learn_more_about_message_templates_link();
1771
-
1772
-
1773
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1774
-        $this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1775
-            $message_template_group,
1776
-            $context,
1777
-            $context_label
1778
-        );
1779
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1780
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1781
-
1782
-        $this->_template_path = $this->_template_args['GRP_ID']
1783
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1784
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1785
-
1786
-        // send along EE_Message_Template_Group object for further template use.
1787
-        $this->_template_args['MTP'] = $message_template_group;
1788
-
1789
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1790
-            $this->_template_path,
1791
-            $this->_template_args,
1792
-            true
1793
-        );
1794
-
1795
-
1796
-        // finally, let's set the admin_page title
1797
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1798
-
1799
-
1800
-        // we need to take care of setting the shortcodes property for use elsewhere.
1801
-        $this->_set_shortcodes();
1802
-
1803
-
1804
-        // final template wrapper
1805
-        $this->display_admin_page_with_sidebar();
1806
-    }
1807
-
1808
-
1809
-    public function filter_tinymce_init($mceInit, $editor_id)
1810
-    {
1811
-        return $mceInit;
1812
-    }
1813
-
1814
-
1815
-    public function add_context_switcher()
1816
-    {
1817
-        return $this->_context_switcher;
1818
-    }
1819
-
1820
-
1821
-    /**
1822
-     * Adds the activation/deactivation toggle for the message template context.
1823
-     *
1824
-     * @param EE_Message_Template_Group $message_template_group
1825
-     * @param string                    $context
1826
-     * @param string                    $context_label
1827
-     * @return string
1828
-     * @throws DomainException
1829
-     * @throws EE_Error
1830
-     * @throws InvalidIdentifierException
1831
-     */
1832
-    protected function add_active_context_element(
1833
-        EE_Message_Template_Group $message_template_group,
1834
-        $context,
1835
-        $context_label
1836
-    ) {
1837
-        $template_args = array(
1838
-            'context'                   => $context,
1839
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1840
-            'is_active'                 => $message_template_group->is_context_active($context),
1841
-            'on_off_action'             => $message_template_group->is_context_active($context)
1842
-                ? 'context-off'
1843
-                : 'context-on',
1844
-            'context_label'             => str_replace(array('(', ')'), '', $context_label),
1845
-            'message_template_group_id' => $message_template_group->ID(),
1846
-        );
1847
-        return EEH_Template::display_template(
1848
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1849
-            $template_args,
1850
-            true
1851
-        );
1852
-    }
1853
-
1854
-
1855
-    /**
1856
-     * Ajax callback for `toggle_context_template` ajax action.
1857
-     * Handles toggling the message context on or off.
1858
-     *
1859
-     * @throws EE_Error
1860
-     * @throws InvalidArgumentException
1861
-     * @throws InvalidDataTypeException
1862
-     * @throws InvalidIdentifierException
1863
-     * @throws InvalidInterfaceException
1864
-     */
1865
-    public function toggle_context_template()
1866
-    {
1867
-        $success = true;
1868
-        // check for required data
1869
-        if (! isset(
1870
-            $this->_req_data['message_template_group_id'],
1871
-            $this->_req_data['context'],
1872
-            $this->_req_data['status']
1873
-        )) {
1874
-            EE_Error::add_error(
1875
-                esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1876
-                __FILE__,
1877
-                __FUNCTION__,
1878
-                __LINE__
1879
-            );
1880
-            $success = false;
1881
-        }
1882
-
1883
-        $nonce = isset($this->_req_data['toggle_context_nonce'])
1884
-            ? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1885
-            : '';
1886
-        $nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1887
-        $this->_verify_nonce($nonce, $nonce_ref);
1888
-        $status = $this->_req_data['status'];
1889
-        if ($status !== 'off' && $status !== 'on') {
1890
-            EE_Error::add_error(
1891
-                sprintf(
1892
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1893
-                    $this->_req_data['status']
1894
-                ),
1895
-                __FILE__,
1896
-                __FUNCTION__,
1897
-                __LINE__
1898
-            );
1899
-            $success = false;
1900
-        }
1901
-        $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1902
-            $this->_req_data['message_template_group_id']
1903
-        );
1904
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1905
-            EE_Error::add_error(
1906
-                sprintf(
1907
-                    esc_html__(
1908
-                        'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1909
-                        'event_espresso'
1910
-                    ),
1911
-                    $this->_req_data['message_template_group_id'],
1912
-                    'EE_Message_Template_Group'
1913
-                ),
1914
-                __FILE__,
1915
-                __FUNCTION__,
1916
-                __LINE__
1917
-            );
1918
-            $success = false;
1919
-        }
1920
-        if ($success) {
1921
-            $success = $status === 'off'
1922
-                ? $message_template_group->deactivate_context($this->_req_data['context'])
1923
-                : $message_template_group->activate_context($this->_req_data['context']);
1924
-        }
1925
-        $this->_template_args['success'] = $success;
1926
-        $this->_return_json();
1927
-    }
1928
-
1929
-
1930
-    public function _add_form_element_before()
1931
-    {
1932
-        return '<form method="post" action="'
1933
-               . $this->_template_args["edit_message_template_form_url"]
1934
-               . '" id="ee-msg-edit-frm">';
1935
-    }
1936
-
1937
-    public function _add_form_element_after()
1938
-    {
1939
-        return '</form>';
1940
-    }
1941
-
1942
-
1943
-    /**
1944
-     * This executes switching the template pack for a message template.
1945
-     *
1946
-     * @since 4.5.0
1947
-     * @throws EE_Error
1948
-     * @throws InvalidDataTypeException
1949
-     * @throws InvalidInterfaceException
1950
-     * @throws InvalidArgumentException
1951
-     * @throws ReflectionException
1952
-     */
1953
-    public function switch_template_pack()
1954
-    {
1955
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1956
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1957
-
1958
-        // verify we have needed values.
1959
-        if (empty($GRP_ID) || empty($template_pack)) {
1960
-            $this->_template_args['error'] = true;
1961
-            EE_Error::add_error(
1962
-                esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1963
-                __FILE__,
1964
-                __FUNCTION__,
1965
-                __LINE__
1966
-            );
1967
-        } else {
1968
-            // get template, set the new template_pack and then reset to default
1969
-            /** @type EE_Message_Template_Group $message_template_group */
1970
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1971
-
1972
-            $message_template_group->set_template_pack_name($template_pack);
1973
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1974
-            $this->_req_data['mt'] = $message_template_group->message_type();
1975
-
1976
-            $query_args = $this->_reset_to_default_template();
1977
-
1978
-            if (empty($query_args['id'])) {
1979
-                EE_Error::add_error(
1980
-                    esc_html__(
1981
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1982
-                        'event_espresso'
1983
-                    ),
1984
-                    __FILE__,
1985
-                    __FUNCTION__,
1986
-                    __LINE__
1987
-                );
1988
-                $this->_template_args['error'] = true;
1989
-            } else {
1990
-                $template_label = $message_template_group->get_template_pack()->label;
1991
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1992
-                EE_Error::add_success(
1993
-                    sprintf(
1994
-                        esc_html__(
1995
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1996
-                            'event_espresso'
1997
-                        ),
1998
-                        $template_label,
1999
-                        $template_pack_labels->template_pack
2000
-                    )
2001
-                );
2002
-                // generate the redirect url for js.
2003
-                $url = self::add_query_args_and_nonce(
2004
-                    $query_args,
2005
-                    $this->_admin_base_url
2006
-                );
2007
-                $this->_template_args['data']['redirect_url'] = $url;
2008
-                $this->_template_args['success'] = true;
2009
-            }
2010
-
2011
-            $this->_return_json();
2012
-        }
2013
-    }
2014
-
2015
-
2016
-    /**
2017
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2018
-     * they want.
2019
-     *
2020
-     * @access protected
2021
-     * @return array|null
2022
-     * @throws EE_Error
2023
-     * @throws InvalidArgumentException
2024
-     * @throws InvalidDataTypeException
2025
-     * @throws InvalidInterfaceException
2026
-     */
2027
-    protected function _reset_to_default_template()
2028
-    {
2029
-
2030
-        $templates = array();
2031
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2032
-        // we need to make sure we've got the info we need.
2033
-        if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2034
-            EE_Error::add_error(
2035
-                esc_html__(
2036
-                    'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
2037
-                    'event_espresso'
2038
-                ),
2039
-                __FILE__,
2040
-                __FUNCTION__,
2041
-                __LINE__
2042
-            );
2043
-        }
2044
-
2045
-        // all templates will be reset to whatever the defaults are
2046
-        // for the global template matching the messenger and message type.
2047
-        $success = ! empty($GRP_ID) ? true : false;
2048
-
2049
-        if ($success) {
2050
-            // let's first determine if the incoming template is a global template,
2051
-            // if it isn't then we need to get the global template matching messenger and message type.
2052
-            // $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2053
-
2054
-
2055
-            // note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2056
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
2057
-
2058
-            if ($success) {
2059
-                // if successfully deleted, lets generate the new ones.
2060
-                // Note. We set GLOBAL to true, because resets on ANY template
2061
-                // will use the related global template defaults for regeneration.
2062
-                // This means that if a custom template is reset it resets to whatever the related global template is.
2063
-                // HOWEVER, we DO keep the template pack and template variation set
2064
-                // for the current custom template when resetting.
2065
-                $templates = $this->_generate_new_templates(
2066
-                    $this->_req_data['msgr'],
2067
-                    $this->_req_data['mt'],
2068
-                    $GRP_ID,
2069
-                    true
2070
-                );
2071
-            }
2072
-        }
2073
-
2074
-        // any error messages?
2075
-        if (! $success) {
2076
-            EE_Error::add_error(
2077
-                esc_html__(
2078
-                    'Something went wrong with deleting existing templates. Unable to reset to default',
2079
-                    'event_espresso'
2080
-                ),
2081
-                __FILE__,
2082
-                __FUNCTION__,
2083
-                __LINE__
2084
-            );
2085
-        }
2086
-
2087
-        // all good, let's add a success message!
2088
-        if ($success && ! empty($templates)) {
2089
-            // the info for the template we generated is the first element in the returned array
2090
-            // $templates = $templates[0];
2091
-            EE_Error::overwrite_success();
2092
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2093
-        }
2094
-
2095
-
2096
-        $query_args = array(
2097
-            'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2098
-            'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2099
-            'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2100
-        );
2101
-
2102
-        // if called via ajax then we return query args otherwise redirect
2103
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2104
-            return $query_args;
2105
-        } else {
2106
-            $this->_redirect_after_action(false, '', '', $query_args, true);
2107
-
2108
-            return null;
2109
-        }
2110
-    }
2111
-
2112
-
2113
-    /**
2114
-     * Retrieve and set the message preview for display.
2115
-     *
2116
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2117
-     * @return string
2118
-     * @throws ReflectionException
2119
-     * @throws EE_Error
2120
-     * @throws InvalidArgumentException
2121
-     * @throws InvalidDataTypeException
2122
-     * @throws InvalidInterfaceException
2123
-     */
2124
-    public function _preview_message($send = false)
2125
-    {
2126
-        // first make sure we've got the necessary parameters
2127
-        if (! isset(
2128
-            $this->_req_data['message_type'],
2129
-            $this->_req_data['messenger'],
2130
-            $this->_req_data['messenger'],
2131
-            $this->_req_data['GRP_ID']
2132
-        )) {
2133
-            EE_Error::add_error(
2134
-                esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2135
-                __FILE__,
2136
-                __FUNCTION__,
2137
-                __LINE__
2138
-            );
2139
-        }
2140
-
2141
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
22
+	/**
23
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
24
+	 */
25
+	protected $_message_resource_manager;
26
+
27
+	/**
28
+	 * @type string $_active_message_type_name
29
+	 */
30
+	protected $_active_message_type_name = '';
31
+
32
+	/**
33
+	 * @type EE_messenger $_active_messenger
34
+	 */
35
+	protected $_active_messenger;
36
+	protected $_activate_state;
37
+	protected $_activate_meta_box_type;
38
+	protected $_current_message_meta_box;
39
+	protected $_current_message_meta_box_object;
40
+	protected $_context_switcher;
41
+	protected $_shortcodes = array();
42
+	protected $_active_messengers = array();
43
+	protected $_active_message_types = array();
44
+
45
+	/**
46
+	 * @var EE_Message_Template_Group $_message_template_group
47
+	 */
48
+	protected $_message_template_group;
49
+	protected $_m_mt_settings = array();
50
+
51
+
52
+	/**
53
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
+	 * IF there is no group then it gets automatically set to the Default template pack.
55
+	 *
56
+	 * @since 4.5.0
57
+	 *
58
+	 * @var EE_Messages_Template_Pack
59
+	 */
60
+	protected $_template_pack;
61
+
62
+
63
+	/**
64
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
+	 * group is.  If there is no group then it automatically gets set to default.
66
+	 *
67
+	 * @since 4.5.0
68
+	 *
69
+	 * @var string
70
+	 */
71
+	protected $_variation;
72
+
73
+
74
+	/**
75
+	 * @param bool $routing
76
+	 * @throws EE_Error
77
+	 */
78
+	public function __construct($routing = true)
79
+	{
80
+		// make sure messages autoloader is running
81
+		EED_Messages::set_autoloaders();
82
+		parent::__construct($routing);
83
+	}
84
+
85
+
86
+	protected function _init_page_props()
87
+	{
88
+		$this->page_slug = EE_MSG_PG_SLUG;
89
+		$this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
+		$this->_admin_base_url = EE_MSG_ADMIN_URL;
91
+		$this->_admin_base_path = EE_MSG_ADMIN;
92
+
93
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
+			: array();
95
+
96
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
+		$this->_load_message_resource_manager();
98
+	}
99
+
100
+
101
+	/**
102
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
+	 *
104
+	 * @throws EE_Error
105
+	 * @throws InvalidDataTypeException
106
+	 * @throws InvalidInterfaceException
107
+	 * @throws InvalidArgumentException
108
+	 * @throws ReflectionException
109
+	 */
110
+	protected function _load_message_resource_manager()
111
+	{
112
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
+	}
114
+
115
+
116
+	/**
117
+	 * @deprecated 4.9.9.rc.014
118
+	 * @return array
119
+	 * @throws EE_Error
120
+	 * @throws InvalidArgumentException
121
+	 * @throws InvalidDataTypeException
122
+	 * @throws InvalidInterfaceException
123
+	 */
124
+	public function get_messengers_for_list_table()
125
+	{
126
+		EE_Error::doing_it_wrong(
127
+			__METHOD__,
128
+			sprintf(
129
+				esc_html__(
130
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
+					'event_espresso'
132
+				),
133
+				'Messages_Admin_Page::get_messengers_select_input()'
134
+			),
135
+			'4.9.9.rc.014'
136
+		);
137
+
138
+		$m_values = array();
139
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
+		// setup messengers for selects
141
+		$i = 1;
142
+		foreach ($active_messengers as $active_messenger) {
143
+			if ($active_messenger instanceof EE_Message) {
144
+				$m_values[ $i ]['id'] = $active_messenger->messenger();
145
+				$m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
+				$i++;
147
+			}
148
+		}
149
+
150
+		return $m_values;
151
+	}
152
+
153
+
154
+	/**
155
+	 * @deprecated 4.9.9.rc.014
156
+	 * @return array
157
+	 * @throws EE_Error
158
+	 * @throws InvalidArgumentException
159
+	 * @throws InvalidDataTypeException
160
+	 * @throws InvalidInterfaceException
161
+	 */
162
+	public function get_message_types_for_list_table()
163
+	{
164
+		EE_Error::doing_it_wrong(
165
+			__METHOD__,
166
+			sprintf(
167
+				esc_html__(
168
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
+					'event_espresso'
170
+				),
171
+				'Messages_Admin_Page::get_message_types_select_input()'
172
+			),
173
+			'4.9.9.rc.014'
174
+		);
175
+
176
+		$mt_values = array();
177
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
+		$i = 1;
179
+		foreach ($active_messages as $active_message) {
180
+			if ($active_message instanceof EE_Message) {
181
+				$mt_values[ $i ]['id'] = $active_message->message_type();
182
+				$mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
+				$i++;
184
+			}
185
+		}
186
+
187
+		return $mt_values;
188
+	}
189
+
190
+
191
+	/**
192
+	 * @deprecated 4.9.9.rc.014
193
+	 * @return array
194
+	 * @throws EE_Error
195
+	 * @throws InvalidArgumentException
196
+	 * @throws InvalidDataTypeException
197
+	 * @throws InvalidInterfaceException
198
+	 */
199
+	public function get_contexts_for_message_types_for_list_table()
200
+	{
201
+		EE_Error::doing_it_wrong(
202
+			__METHOD__,
203
+			sprintf(
204
+				esc_html__(
205
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
+					'event_espresso'
207
+				),
208
+				'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
+			),
210
+			'4.9.9.rc.014'
211
+		);
212
+
213
+		$contexts = array();
214
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
+		foreach ($active_message_contexts as $active_message) {
216
+			if ($active_message instanceof EE_Message) {
217
+				$message_type = $active_message->message_type_object();
218
+				if ($message_type instanceof EE_message_type) {
219
+					$message_type_contexts = $message_type->get_contexts();
220
+					foreach ($message_type_contexts as $context => $context_details) {
221
+						$contexts[ $context ] = $context_details['label'];
222
+					}
223
+				}
224
+			}
225
+		}
226
+
227
+		return $contexts;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Generate select input with provided messenger options array.
233
+	 *
234
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
+	 *                                 labels.
236
+	 * @return string
237
+	 * @throws EE_Error
238
+	 */
239
+	public function get_messengers_select_input($messenger_options)
240
+	{
241
+		// if empty or just one value then just return an empty string
242
+		if (empty($messenger_options)
243
+			|| ! is_array($messenger_options)
244
+			|| count($messenger_options) === 1
245
+		) {
246
+			return '';
247
+		}
248
+		// merge in default
249
+		$messenger_options = array_merge(
250
+			array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
+			$messenger_options
252
+		);
253
+		$input = new EE_Select_Input(
254
+			$messenger_options,
255
+			array(
256
+				'html_name'  => 'ee_messenger_filter_by',
257
+				'html_id'    => 'ee_messenger_filter_by',
258
+				'html_class' => 'wide',
259
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
+					: 'none_selected',
262
+			)
263
+		);
264
+
265
+		return $input->get_html_for_input();
266
+	}
267
+
268
+
269
+	/**
270
+	 * Generate select input with provided message type options array.
271
+	 *
272
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
+	 *                                    message type labels
274
+	 * @return string
275
+	 * @throws EE_Error
276
+	 */
277
+	public function get_message_types_select_input($message_type_options)
278
+	{
279
+		// if empty or count of options is 1 then just return an empty string
280
+		if (empty($message_type_options)
281
+			|| ! is_array($message_type_options)
282
+			|| count($message_type_options) === 1
283
+		) {
284
+			return '';
285
+		}
286
+		// merge in default
287
+		$message_type_options = array_merge(
288
+			array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
+			$message_type_options
290
+		);
291
+		$input = new EE_Select_Input(
292
+			$message_type_options,
293
+			array(
294
+				'html_name'  => 'ee_message_type_filter_by',
295
+				'html_id'    => 'ee_message_type_filter_by',
296
+				'html_class' => 'wide',
297
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
+					: 'none_selected',
300
+			)
301
+		);
302
+
303
+		return $input->get_html_for_input();
304
+	}
305
+
306
+
307
+	/**
308
+	 * Generate select input with provide message type contexts array.
309
+	 *
310
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
+	 *                               context label.
312
+	 * @return string
313
+	 * @throws EE_Error
314
+	 */
315
+	public function get_contexts_for_message_types_select_input($context_options)
316
+	{
317
+		// if empty or count of options is one then just return empty string
318
+		if (empty($context_options)
319
+			|| ! is_array($context_options)
320
+			|| count($context_options) === 1
321
+		) {
322
+			return '';
323
+		}
324
+		// merge in default
325
+		$context_options = array_merge(
326
+			array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
+			$context_options
328
+		);
329
+		$input = new EE_Select_Input(
330
+			$context_options,
331
+			array(
332
+				'html_name'  => 'ee_context_filter_by',
333
+				'html_id'    => 'ee_context_filter_by',
334
+				'html_class' => 'wide',
335
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
336
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
337
+					: 'none_selected',
338
+			)
339
+		);
340
+
341
+		return $input->get_html_for_input();
342
+	}
343
+
344
+
345
+	protected function _ajax_hooks()
346
+	{
347
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
+		add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
+	}
354
+
355
+
356
+	protected function _define_page_props()
357
+	{
358
+		$this->_admin_page_title = $this->page_label;
359
+		$this->_labels = array(
360
+			'buttons'    => array(
361
+				'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
+				'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
+				'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
+			),
365
+			'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
+		);
367
+	}
368
+
369
+
370
+	/**
371
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
372
+	 *
373
+	 * @access protected
374
+	 * @return void
375
+	 */
376
+	protected function _set_page_routes()
377
+	{
378
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
+			? $this->_req_data['GRP_ID']
380
+			: 0;
381
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
+			? $this->_req_data['id']
383
+			: $grp_id;
384
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
+			? $this->_req_data['MSG_ID']
386
+			: 0;
387
+
388
+		$this->_page_routes = array(
389
+			'default'                          => array(
390
+				'func'       => '_message_queue_list_table',
391
+				'capability' => 'ee_read_global_messages',
392
+			),
393
+			'global_mtps'                      => array(
394
+				'func'       => '_ee_default_messages_overview_list_table',
395
+				'capability' => 'ee_read_global_messages',
396
+			),
397
+			'custom_mtps'                      => array(
398
+				'func'       => '_custom_mtps_preview',
399
+				'capability' => 'ee_read_messages',
400
+			),
401
+			'add_new_message_template'         => array(
402
+				'func'       => '_add_message_template',
403
+				'capability' => 'ee_edit_messages',
404
+				'noheader'   => true,
405
+			),
406
+			'edit_message_template'            => array(
407
+				'func'       => '_edit_message_template',
408
+				'capability' => 'ee_edit_message',
409
+				'obj_id'     => $grp_id,
410
+			),
411
+			'preview_message'                  => array(
412
+				'func'               => '_preview_message',
413
+				'capability'         => 'ee_read_message',
414
+				'obj_id'             => $grp_id,
415
+				'noheader'           => true,
416
+				'headers_sent_route' => 'display_preview_message',
417
+			),
418
+			'display_preview_message'          => array(
419
+				'func'       => '_display_preview_message',
420
+				'capability' => 'ee_read_message',
421
+				'obj_id'     => $grp_id,
422
+			),
423
+			'insert_message_template'          => array(
424
+				'func'       => '_insert_or_update_message_template',
425
+				'capability' => 'ee_edit_messages',
426
+				'args'       => array('new_template' => true),
427
+				'noheader'   => true,
428
+			),
429
+			'update_message_template'          => array(
430
+				'func'       => '_insert_or_update_message_template',
431
+				'capability' => 'ee_edit_message',
432
+				'obj_id'     => $grp_id,
433
+				'args'       => array('new_template' => false),
434
+				'noheader'   => true,
435
+			),
436
+			'trash_message_template'           => array(
437
+				'func'       => '_trash_or_restore_message_template',
438
+				'capability' => 'ee_delete_message',
439
+				'obj_id'     => $grp_id,
440
+				'args'       => array('trash' => true, 'all' => true),
441
+				'noheader'   => true,
442
+			),
443
+			'trash_message_template_context'   => array(
444
+				'func'       => '_trash_or_restore_message_template',
445
+				'capability' => 'ee_delete_message',
446
+				'obj_id'     => $grp_id,
447
+				'args'       => array('trash' => true),
448
+				'noheader'   => true,
449
+			),
450
+			'restore_message_template'         => array(
451
+				'func'       => '_trash_or_restore_message_template',
452
+				'capability' => 'ee_delete_message',
453
+				'obj_id'     => $grp_id,
454
+				'args'       => array('trash' => false, 'all' => true),
455
+				'noheader'   => true,
456
+			),
457
+			'restore_message_template_context' => array(
458
+				'func'       => '_trash_or_restore_message_template',
459
+				'capability' => 'ee_delete_message',
460
+				'obj_id'     => $grp_id,
461
+				'args'       => array('trash' => false),
462
+				'noheader'   => true,
463
+			),
464
+			'delete_message_template'          => array(
465
+				'func'       => '_delete_message_template',
466
+				'capability' => 'ee_delete_message',
467
+				'obj_id'     => $grp_id,
468
+				'noheader'   => true,
469
+			),
470
+			'reset_to_default'                 => array(
471
+				'func'       => '_reset_to_default_template',
472
+				'capability' => 'ee_edit_message',
473
+				'obj_id'     => $grp_id,
474
+				'noheader'   => true,
475
+			),
476
+			'settings'                         => array(
477
+				'func'       => '_settings',
478
+				'capability' => 'manage_options',
479
+			),
480
+			'update_global_settings'           => array(
481
+				'func'       => '_update_global_settings',
482
+				'capability' => 'manage_options',
483
+				'noheader'   => true,
484
+			),
485
+			'generate_now'                     => array(
486
+				'func'       => '_generate_now',
487
+				'capability' => 'ee_send_message',
488
+				'noheader'   => true,
489
+			),
490
+			'generate_and_send_now'            => array(
491
+				'func'       => '_generate_and_send_now',
492
+				'capability' => 'ee_send_message',
493
+				'noheader'   => true,
494
+			),
495
+			'queue_for_resending'              => array(
496
+				'func'       => '_queue_for_resending',
497
+				'capability' => 'ee_send_message',
498
+				'noheader'   => true,
499
+			),
500
+			'send_now'                         => array(
501
+				'func'       => '_send_now',
502
+				'capability' => 'ee_send_message',
503
+				'noheader'   => true,
504
+			),
505
+			'delete_ee_message'                => array(
506
+				'func'       => '_delete_ee_messages',
507
+				'capability' => 'ee_delete_messages',
508
+				'noheader'   => true,
509
+			),
510
+			'delete_ee_messages'               => array(
511
+				'func'       => '_delete_ee_messages',
512
+				'capability' => 'ee_delete_messages',
513
+				'noheader'   => true,
514
+				'obj_id'     => $msg_id,
515
+			),
516
+		);
517
+	}
518
+
519
+
520
+	protected function _set_page_config()
521
+	{
522
+		$this->_page_config = array(
523
+			'default'                  => array(
524
+				'nav'           => array(
525
+					'label' => esc_html__('Message Activity', 'event_espresso'),
526
+					'order' => 10,
527
+				),
528
+				'list_table'    => 'EE_Message_List_Table',
529
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
+				'require_nonce' => false,
531
+			),
532
+			'global_mtps'              => array(
533
+				'nav'           => array(
534
+					'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
+					'order' => 20,
536
+				),
537
+				'list_table'    => 'Messages_Template_List_Table',
538
+				'help_tabs'     => array(
539
+					'messages_overview_help_tab'                                => array(
540
+						'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
+						'filename' => 'messages_overview',
542
+					),
543
+					'messages_overview_messages_table_column_headings_help_tab' => array(
544
+						'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
+						'filename' => 'messages_overview_table_column_headings',
546
+					),
547
+					'messages_overview_messages_filters_help_tab'               => array(
548
+						'title'    => esc_html__('Message Filters', 'event_espresso'),
549
+						'filename' => 'messages_overview_filters',
550
+					),
551
+					'messages_overview_messages_views_help_tab'                 => array(
552
+						'title'    => esc_html__('Message Views', 'event_espresso'),
553
+						'filename' => 'messages_overview_views',
554
+					),
555
+					'message_overview_message_types_help_tab'                   => array(
556
+						'title'    => esc_html__('Message Types', 'event_espresso'),
557
+						'filename' => 'messages_overview_types',
558
+					),
559
+					'messages_overview_messengers_help_tab'                     => array(
560
+						'title'    => esc_html__('Messengers', 'event_espresso'),
561
+						'filename' => 'messages_overview_messengers',
562
+					),
563
+				),
564
+				'help_tour'     => array('Messages_Overview_Help_Tour'),
565
+				'require_nonce' => false,
566
+			),
567
+			'custom_mtps'              => array(
568
+				'nav'           => array(
569
+					'label' => esc_html__('Custom Message Templates', 'event_espresso'),
570
+					'order' => 30,
571
+				),
572
+				'help_tabs'     => array(),
573
+				'help_tour'     => array(),
574
+				'require_nonce' => false,
575
+			),
576
+			'add_new_message_template' => array(
577
+				'nav'           => array(
578
+					'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
579
+					'order'      => 5,
580
+					'persistent' => false,
581
+				),
582
+				'require_nonce' => false,
583
+			),
584
+			'edit_message_template'    => array(
585
+				'labels'        => array(
586
+					'buttons'    => array(
587
+						'reset' => esc_html__('Reset Templates', 'event_espresso'),
588
+					),
589
+					'publishbox' => esc_html__('Update Actions', 'event_espresso'),
590
+				),
591
+				'nav'           => array(
592
+					'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
593
+					'order'      => 5,
594
+					'persistent' => false,
595
+					'url'        => '',
596
+				),
597
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
598
+				'has_metaboxes' => true,
599
+				'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
600
+				'help_tabs'     => array(
601
+					'edit_message_template'            => array(
602
+						'title'    => esc_html__('Message Template Editor', 'event_espresso'),
603
+						'callback' => 'edit_message_template_help_tab',
604
+					),
605
+					'message_templates_help_tab'       => array(
606
+						'title'    => esc_html__('Message Templates', 'event_espresso'),
607
+						'filename' => 'messages_templates',
608
+					),
609
+					'message_template_shortcodes'      => array(
610
+						'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
611
+						'callback' => 'message_template_shortcodes_help_tab',
612
+					),
613
+					'message_preview_help_tab'         => array(
614
+						'title'    => esc_html__('Message Preview', 'event_espresso'),
615
+						'filename' => 'messages_preview',
616
+					),
617
+					'messages_overview_other_help_tab' => array(
618
+						'title'    => esc_html__('Messages Other', 'event_espresso'),
619
+						'filename' => 'messages_overview_other',
620
+					),
621
+				),
622
+				'require_nonce' => false,
623
+			),
624
+			'display_preview_message'  => array(
625
+				'nav'           => array(
626
+					'label'      => esc_html__('Message Preview', 'event_espresso'),
627
+					'order'      => 5,
628
+					'url'        => '',
629
+					'persistent' => false,
630
+				),
631
+				'help_tabs'     => array(
632
+					'preview_message' => array(
633
+						'title'    => esc_html__('About Previews', 'event_espresso'),
634
+						'callback' => 'preview_message_help_tab',
635
+					),
636
+				),
637
+				'require_nonce' => false,
638
+			),
639
+			'settings'                 => array(
640
+				'nav'           => array(
641
+					'label' => esc_html__('Settings', 'event_espresso'),
642
+					'order' => 40,
643
+				),
644
+				'metaboxes'     => array('_messages_settings_metaboxes'),
645
+				'help_tabs'     => array(
646
+					'messages_settings_help_tab'               => array(
647
+						'title'    => esc_html__('Messages Settings', 'event_espresso'),
648
+						'filename' => 'messages_settings',
649
+					),
650
+					'messages_settings_message_types_help_tab' => array(
651
+						'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
652
+						'filename' => 'messages_settings_message_types',
653
+					),
654
+					'messages_settings_messengers_help_tab'    => array(
655
+						'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
656
+						'filename' => 'messages_settings_messengers',
657
+					),
658
+				),
659
+				'help_tour'     => array('Messages_Settings_Help_Tour'),
660
+				'require_nonce' => false,
661
+			),
662
+		);
663
+	}
664
+
665
+
666
+	protected function _add_screen_options()
667
+	{
668
+		// todo
669
+	}
670
+
671
+
672
+	protected function _add_screen_options_global_mtps()
673
+	{
674
+		/**
675
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
676
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
677
+		 */
678
+		$page_title = $this->_admin_page_title;
679
+		$this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
680
+		$this->_per_page_screen_option();
681
+		$this->_admin_page_title = $page_title;
682
+	}
683
+
684
+
685
+	protected function _add_screen_options_default()
686
+	{
687
+		$this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
688
+		$this->_per_page_screen_option();
689
+	}
690
+
691
+
692
+	// none of the below group are currently used for Messages
693
+	protected function _add_feature_pointers()
694
+	{
695
+	}
696
+
697
+	public function admin_init()
698
+	{
699
+	}
700
+
701
+	public function admin_notices()
702
+	{
703
+	}
704
+
705
+	public function admin_footer_scripts()
706
+	{
707
+	}
708
+
709
+
710
+	public function messages_help_tab()
711
+	{
712
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
713
+	}
714
+
715
+
716
+	public function messengers_help_tab()
717
+	{
718
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
719
+	}
720
+
721
+
722
+	public function message_types_help_tab()
723
+	{
724
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
725
+	}
726
+
727
+
728
+	public function messages_overview_help_tab()
729
+	{
730
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
731
+	}
732
+
733
+
734
+	public function message_templates_help_tab()
735
+	{
736
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
737
+	}
738
+
739
+
740
+	public function edit_message_template_help_tab()
741
+	{
742
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
743
+						. esc_attr__('Editor Title', 'event_espresso')
744
+						. '" />';
745
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
746
+						. esc_attr__('Context Switcher and Preview', 'event_espresso')
747
+						. '" />';
748
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
749
+						. esc_attr__('Message Template Form Fields', 'event_espresso')
750
+						. '" />';
751
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
752
+						. esc_attr__('Shortcodes Metabox', 'event_espresso')
753
+						. '" />';
754
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
755
+						. esc_attr__('Publish Metabox', 'event_espresso')
756
+						. '" />';
757
+		EEH_Template::display_template(
758
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
759
+			$args
760
+		);
761
+	}
762
+
763
+
764
+	public function message_template_shortcodes_help_tab()
765
+	{
766
+		$this->_set_shortcodes();
767
+		$args['shortcodes'] = $this->_shortcodes;
768
+		EEH_Template::display_template(
769
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
770
+			$args
771
+		);
772
+	}
773
+
774
+
775
+	public function preview_message_help_tab()
776
+	{
777
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
778
+	}
779
+
780
+
781
+	public function settings_help_tab()
782
+	{
783
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
784
+						. '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
785
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
786
+						. '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
787
+		$args['img3'] = '<div class="switch">'
788
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
789
+						. ' type="checkbox" checked="checked">'
790
+						. '<label for="ee-on-off-toggle-on"></label>'
791
+						. '</div>';
792
+		$args['img4'] = '<div class="switch">'
793
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
794
+						. ' type="checkbox">'
795
+						. '<label for="ee-on-off-toggle-on"></label>'
796
+						. '</div>';
797
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
798
+	}
799
+
800
+
801
+	public function load_scripts_styles()
802
+	{
803
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
804
+		wp_enqueue_style('espresso_ee_msg');
805
+
806
+		wp_register_script(
807
+			'ee-messages-settings',
808
+			EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
+			array('jquery-ui-droppable', 'ee-serialize-full-array'),
810
+			EVENT_ESPRESSO_VERSION,
811
+			true
812
+		);
813
+		wp_register_script(
814
+			'ee-msg-list-table-js',
815
+			EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
816
+			array('ee-dialog'),
817
+			EVENT_ESPRESSO_VERSION
818
+		);
819
+	}
820
+
821
+
822
+	public function load_scripts_styles_default()
823
+	{
824
+		wp_enqueue_script('ee-msg-list-table-js');
825
+	}
826
+
827
+
828
+	public function wp_editor_css($mce_css)
829
+	{
830
+		// if we're on the edit_message_template route
831
+		if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
832
+			$message_type_name = $this->_active_message_type_name;
833
+
834
+			// we're going to REPLACE the existing mce css
835
+			// we need to get the css file location from the active messenger
836
+			$mce_css = $this->_active_messenger->get_variation(
837
+				$this->_template_pack,
838
+				$message_type_name,
839
+				true,
840
+				'wpeditor',
841
+				$this->_variation
842
+			);
843
+		}
844
+
845
+		return $mce_css;
846
+	}
847
+
848
+
849
+	public function load_scripts_styles_edit_message_template()
850
+	{
851
+
852
+		$this->_set_shortcodes();
853
+
854
+		EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
855
+			esc_html__(
856
+				'Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
857
+				'event_espresso'
858
+			),
859
+			$this->_message_template_group->messenger_obj()->label['singular'],
860
+			$this->_message_template_group->message_type_obj()->label['singular']
861
+		);
862
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
863
+			'Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
864
+			'event_espresso'
865
+		);
866
+		EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
867
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
868
+			'event_espresso'
869
+		);
870
+
871
+		wp_register_script(
872
+			'ee_msgs_edit_js',
873
+			EE_MSG_ASSETS_URL . 'ee_message_editor.js',
874
+			array('jquery'),
875
+			EVENT_ESPRESSO_VERSION
876
+		);
877
+
878
+		wp_enqueue_script('ee_admin_js');
879
+		wp_enqueue_script('ee_msgs_edit_js');
880
+
881
+		// add in special css for tiny_mce
882
+		add_filter('mce_css', array($this, 'wp_editor_css'));
883
+	}
884
+
885
+
886
+	public function load_scripts_styles_display_preview_message()
887
+	{
888
+
889
+		$this->_set_message_template_group();
890
+
891
+		if (isset($this->_req_data['messenger'])) {
892
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
893
+				$this->_req_data['messenger']
894
+			);
895
+		}
896
+
897
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
898
+
899
+
900
+		wp_enqueue_style(
901
+			'espresso_preview_css',
902
+			$this->_active_messenger->get_variation(
903
+				$this->_template_pack,
904
+				$message_type_name,
905
+				true,
906
+				'preview',
907
+				$this->_variation
908
+			)
909
+		);
910
+	}
911
+
912
+
913
+	public function load_scripts_styles_settings()
914
+	{
915
+		wp_register_style(
916
+			'ee-message-settings',
917
+			EE_MSG_ASSETS_URL . 'ee_message_settings.css',
918
+			array(),
919
+			EVENT_ESPRESSO_VERSION
920
+		);
921
+		wp_enqueue_style('ee-text-links');
922
+		wp_enqueue_style('ee-message-settings');
923
+		wp_enqueue_script('ee-messages-settings');
924
+	}
925
+
926
+
927
+	/**
928
+	 * set views array for List Table
929
+	 */
930
+	public function _set_list_table_views_global_mtps()
931
+	{
932
+		$this->_views = array(
933
+			'in_use' => array(
934
+				'slug'  => 'in_use',
935
+				'label' => esc_html__('In Use', 'event_espresso'),
936
+				'count' => 0,
937
+			),
938
+		);
939
+	}
940
+
941
+
942
+	/**
943
+	 * Set views array for the Custom Template List Table
944
+	 */
945
+	public function _set_list_table_views_custom_mtps()
946
+	{
947
+		$this->_set_list_table_views_global_mtps();
948
+		$this->_views['in_use']['bulk_action'] = array(
949
+			'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
950
+		);
951
+	}
952
+
953
+
954
+	/**
955
+	 * set views array for message queue list table
956
+	 *
957
+	 * @throws InvalidDataTypeException
958
+	 * @throws InvalidInterfaceException
959
+	 * @throws InvalidArgumentException
960
+	 * @throws EE_Error
961
+	 * @throws ReflectionException
962
+	 */
963
+	public function _set_list_table_views_default()
964
+	{
965
+		EE_Registry::instance()->load_helper('Template');
966
+
967
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
968
+			'ee_send_message',
969
+			'message_list_table_bulk_actions'
970
+		)
971
+			? array(
972
+				'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
973
+				'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
974
+				'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
975
+				'send_now'              => esc_html__('Send Now', 'event_espresso'),
976
+			)
977
+			: array();
978
+
979
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
980
+			'ee_delete_messages',
981
+			'message_list_table_bulk_actions'
982
+		)
983
+			? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
984
+			: array();
985
+
986
+
987
+		$this->_views = array(
988
+			'all' => array(
989
+				'slug'        => 'all',
990
+				'label'       => esc_html__('All', 'event_espresso'),
991
+				'count'       => 0,
992
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
993
+			),
994
+		);
995
+
996
+
997
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
998
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
999
+				continue;
1000
+			}
1001
+			$status_bulk_actions = $common_bulk_actions;
1002
+			// unset bulk actions not applying to status
1003
+			if (! empty($status_bulk_actions)) {
1004
+				switch ($status) {
1005
+					case EEM_Message::status_idle:
1006
+					case EEM_Message::status_resend:
1007
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1008
+						break;
1009
+
1010
+					case EEM_Message::status_failed:
1011
+					case EEM_Message::status_debug_only:
1012
+					case EEM_Message::status_messenger_executing:
1013
+						$status_bulk_actions = array();
1014
+						break;
1015
+
1016
+					case EEM_Message::status_incomplete:
1017
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1018
+						break;
1019
+
1020
+					case EEM_Message::status_retry:
1021
+					case EEM_Message::status_sent:
1022
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1023
+						break;
1024
+				}
1025
+			}
1026
+
1027
+			// skip adding messenger executing status to views because it will be included with the Failed view.
1028
+			if ($status === EEM_Message::status_messenger_executing) {
1029
+				continue;
1030
+			}
1031
+
1032
+			$this->_views[ strtolower($status) ] = array(
1033
+				'slug'        => strtolower($status),
1034
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1035
+				'count'       => 0,
1036
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1037
+			);
1038
+		}
1039
+	}
1040
+
1041
+
1042
+	protected function _ee_default_messages_overview_list_table()
1043
+	{
1044
+		$this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1045
+		$this->display_admin_list_table_page_with_no_sidebar();
1046
+	}
1047
+
1048
+
1049
+	protected function _message_queue_list_table()
1050
+	{
1051
+		$this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1052
+		$this->_template_args['per_column'] = 6;
1053
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1054
+		$this->_template_args['before_list_table'] = '<h3>'
1055
+													 . EEM_Message::instance()->get_pretty_label_for_results()
1056
+													 . '</h3>';
1057
+		$this->display_admin_list_table_page_with_no_sidebar();
1058
+	}
1059
+
1060
+
1061
+	protected function _message_legend_items()
1062
+	{
1063
+
1064
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
1065
+		$action_items = array();
1066
+
1067
+		foreach ($action_css_classes as $action_item => $action_details) {
1068
+			if ($action_item === 'see_notifications_for') {
1069
+				continue;
1070
+			}
1071
+			$action_items[ $action_item ] = array(
1072
+				'class' => $action_details['css_class'],
1073
+				'desc'  => $action_details['label'],
1074
+			);
1075
+		}
1076
+
1077
+		/** @type array $status_items status legend setup */
1078
+		$status_items = array(
1079
+			'incomplete_status'          => array(
1080
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1081
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1082
+			),
1083
+			'idle_status'                => array(
1084
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1085
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1086
+			),
1087
+			'resend_status'              => array(
1088
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1089
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1090
+			),
1091
+			'messenger_executing_status' => array(
1092
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1093
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1094
+			),
1095
+			'sent_status'                => array(
1096
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1097
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1098
+			),
1099
+			'retry_status'               => array(
1100
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1101
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1102
+			),
1103
+			'failed_status'              => array(
1104
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1105
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1106
+			),
1107
+		);
1108
+		if (EEM_Message::debug()) {
1109
+			$status_items['debug_only_status'] = array(
1110
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1111
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1112
+			);
1113
+		}
1114
+
1115
+		return array_merge($action_items, $status_items);
1116
+	}
1117
+
1118
+
1119
+	protected function _custom_mtps_preview()
1120
+	{
1121
+		$this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1122
+		$this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1123
+											   . ' alt="' . esc_attr__(
1124
+												   'Preview Custom Message Templates screenshot',
1125
+												   'event_espresso'
1126
+											   ) . '" />';
1127
+		$this->_template_args['preview_text'] = '<strong>'
1128
+												. esc_html__(
1129
+													'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1130
+													'event_espresso'
1131
+												)
1132
+												. '</strong>';
1133
+
1134
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1135
+	}
1136
+
1137
+
1138
+	/**
1139
+	 * get_message_templates
1140
+	 * This gets all the message templates for listing on the overview list.
1141
+	 *
1142
+	 * @access public
1143
+	 * @param int    $perpage the amount of templates groups to show per page
1144
+	 * @param string $type    the current _view we're getting templates for
1145
+	 * @param bool   $count   return count?
1146
+	 * @param bool   $all     disregard any paging info (get all data);
1147
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1148
+	 * @return array
1149
+	 * @throws EE_Error
1150
+	 * @throws InvalidArgumentException
1151
+	 * @throws InvalidDataTypeException
1152
+	 * @throws InvalidInterfaceException
1153
+	 */
1154
+	public function get_message_templates(
1155
+		$perpage = 10,
1156
+		$type = 'in_use',
1157
+		$count = false,
1158
+		$all = false,
1159
+		$global = true
1160
+	) {
1161
+
1162
+		$MTP = EEM_Message_Template_Group::instance();
1163
+
1164
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1165
+		$orderby = $this->_req_data['orderby'];
1166
+
1167
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1168
+			? $this->_req_data['order']
1169
+			: 'ASC';
1170
+
1171
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1172
+			? $this->_req_data['paged']
1173
+			: 1;
1174
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1175
+			? $this->_req_data['perpage']
1176
+			: $perpage;
1177
+
1178
+		$offset = ($current_page - 1) * $per_page;
1179
+		$limit = $all ? null : array($offset, $per_page);
1180
+
1181
+
1182
+		// options will match what is in the _views array property
1183
+		switch ($type) {
1184
+			case 'in_use':
1185
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1186
+				break;
1187
+			default:
1188
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1189
+		}
1190
+
1191
+		return $templates;
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * filters etc might need a list of installed message_types
1197
+	 *
1198
+	 * @return array an array of message type objects
1199
+	 */
1200
+	public function get_installed_message_types()
1201
+	{
1202
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1203
+		$installed = array();
1204
+
1205
+		foreach ($installed_message_types as $message_type) {
1206
+			$installed[ $message_type->name ] = $message_type;
1207
+		}
1208
+
1209
+		return $installed;
1210
+	}
1211
+
1212
+
1213
+	/**
1214
+	 * _add_message_template
1215
+	 *
1216
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1217
+	 *
1218
+	 * @param string $message_type
1219
+	 * @param string $messenger
1220
+	 * @param string $GRP_ID
1221
+	 *
1222
+	 * @throws EE_error
1223
+	 */
1224
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1225
+	{
1226
+		// set values override any request data
1227
+		$message_type = ! empty($message_type) ? $message_type : '';
1228
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1229
+			? $this->_req_data['message_type']
1230
+			: $message_type;
1231
+
1232
+		$messenger = ! empty($messenger) ? $messenger : '';
1233
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1234
+			? $this->_req_data['messenger']
1235
+			: $messenger;
1236
+
1237
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1238
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1239
+
1240
+		// we need messenger and message type.  They should be coming from the event editor. If not here then return error
1241
+		if (empty($message_type) || empty($messenger)) {
1242
+			throw new EE_Error(
1243
+				esc_html__(
1244
+					'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1245
+					'event_espresso'
1246
+				)
1247
+			);
1248
+		}
1249
+
1250
+		// we need the GRP_ID for the template being used as the base for the new template
1251
+		if (empty($GRP_ID)) {
1252
+			throw new EE_Error(
1253
+				esc_html__(
1254
+					'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1255
+					'event_espresso'
1256
+				)
1257
+			);
1258
+		}
1259
+
1260
+		// let's just make sure the template gets generated!
1261
+
1262
+		// we need to reassign some variables for what the insert is expecting
1263
+		$this->_req_data['MTP_messenger'] = $messenger;
1264
+		$this->_req_data['MTP_message_type'] = $message_type;
1265
+		$this->_req_data['GRP_ID'] = $GRP_ID;
1266
+		$this->_insert_or_update_message_template(true);
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * public wrapper for the _add_message_template method
1272
+	 *
1273
+	 * @param string $message_type     message type slug
1274
+	 * @param string $messenger        messenger slug
1275
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1276
+	 *                                 off of.
1277
+	 * @throws EE_error
1278
+	 */
1279
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1280
+	{
1281
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1282
+	}
1283
+
1284
+
1285
+	/**
1286
+	 * _edit_message_template
1287
+	 *
1288
+	 * @access protected
1289
+	 * @return void
1290
+	 * @throws InvalidIdentifierException
1291
+	 * @throws DomainException
1292
+	 * @throws EE_Error
1293
+	 * @throws InvalidArgumentException
1294
+	 * @throws ReflectionException
1295
+	 * @throws InvalidDataTypeException
1296
+	 * @throws InvalidInterfaceException
1297
+	 */
1298
+	protected function _edit_message_template()
1299
+	{
1300
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1301
+		$template_fields = '';
1302
+		$sidebar_fields = '';
1303
+		// we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1304
+		// valid html in the templates.
1305
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1306
+
1307
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1308
+			? absint($this->_req_data['id'])
1309
+			: false;
1310
+
1311
+		$EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
1312
+		? absint($this->_req_data['evt_id'])
1313
+		: false;
1314
+
1315
+		$this->_set_shortcodes(); // this also sets the _message_template property.
1316
+		$message_template_group = $this->_message_template_group;
1317
+		$c_label = $message_template_group->context_label();
1318
+		$c_config = $message_template_group->contexts_config();
1319
+
1320
+		reset($c_config);
1321
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1322
+			? strtolower($this->_req_data['context'])
1323
+			: key($c_config);
1324
+
1325
+
1326
+		if (empty($GRP_ID)) {
1327
+			$action = 'insert_message_template';
1328
+			$edit_message_template_form_url = add_query_arg(
1329
+				array('action' => $action, 'noheader' => true),
1330
+				EE_MSG_ADMIN_URL
1331
+			);
1332
+		} else {
1333
+			$action = 'update_message_template';
1334
+			$edit_message_template_form_url = add_query_arg(
1335
+				array('action' => $action, 'noheader' => true),
1336
+				EE_MSG_ADMIN_URL
1337
+			);
1338
+		}
1339
+
1340
+		// set active messenger for this view
1341
+		$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1342
+			$message_template_group->messenger()
1343
+		);
1344
+		$this->_active_message_type_name = $message_template_group->message_type();
1345
+
1346
+
1347
+		// Do we have any validation errors?
1348
+		$validators = $this->_get_transient();
1349
+		$v_fields = ! empty($validators) ? array_keys($validators) : array();
1350
+
1351
+
1352
+		// we need to assemble the title from Various details
1353
+		$context_label = sprintf(
1354
+			esc_html__('(%s %s)', 'event_espresso'),
1355
+			$c_config[ $context ]['label'],
1356
+			ucwords($c_label['label'])
1357
+		);
1358
+
1359
+		$title = sprintf(
1360
+			esc_html__(' %s %s Template %s', 'event_espresso'),
1361
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1362
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1363
+			$context_label
1364
+		);
1365
+
1366
+		$this->_template_args['GRP_ID'] = $GRP_ID;
1367
+		$this->_template_args['message_template'] = $message_template_group;
1368
+		$this->_template_args['is_extra_fields'] = false;
1369
+
1370
+
1371
+		// let's get EEH_MSG_Template so we can get template form fields
1372
+		$template_field_structure = EEH_MSG_Template::get_fields(
1373
+			$message_template_group->messenger(),
1374
+			$message_template_group->message_type()
1375
+		);
1376
+
1377
+		if (! $template_field_structure) {
1378
+			$template_field_structure = false;
1379
+			$template_fields = esc_html__(
1380
+				'There was an error in assembling the fields for this display (you should see an error message)',
1381
+				'event_espresso'
1382
+			);
1383
+		}
1384
+
1385
+
1386
+		$message_templates = $message_template_group->context_templates();
1387
+
1388
+
1389
+		// if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1390
+		// will get handled in the "extra" array.
1391
+		if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1392
+			foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1393
+				unset($template_field_structure[ $context ][ $reference_field ]);
1394
+			}
1395
+		}
1396
+
1397
+		// let's loop through the template_field_structure and actually assemble the input fields!
1398
+		if (! empty($template_field_structure)) {
1399
+			foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1400
+				// if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1401
+				// the extra array and reset them.
1402
+				if ($template_field === 'extra') {
1403
+					$this->_template_args['is_extra_fields'] = true;
1404
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1405
+						$message_template = $message_templates[ $context ][ $reference_field ];
1406
+						$content = $message_template instanceof EE_Message_Template
1407
+							? $message_template->get('MTP_content')
1408
+							: '';
1409
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1410
+							// let's verify if we need this extra field via the shortcodes parameter.
1411
+							$continue = false;
1412
+							if (isset($extra_array['shortcodes_required'])) {
1413
+								foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1414
+									if (! array_key_exists($shortcode, $this->_shortcodes)) {
1415
+										$continue = true;
1416
+									}
1417
+								}
1418
+								if ($continue) {
1419
+									continue;
1420
+								}
1421
+							}
1422
+
1423
+							$field_id = $reference_field
1424
+										. '-'
1425
+										. $extra_field
1426
+										. '-content';
1427
+							$template_form_fields[ $field_id ] = $extra_array;
1428
+							$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1429
+																		 . $reference_field
1430
+																		 . '][content]['
1431
+																		 . $extra_field . ']';
1432
+							$css_class = isset($extra_array['css_class'])
1433
+								? $extra_array['css_class']
1434
+								: '';
1435
+
1436
+							$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1437
+																			  && in_array($extra_field, $v_fields, true)
1438
+																			  &&
1439
+																			  (
1440
+																				  is_array($validators[ $extra_field ])
1441
+																				  && isset($validators[ $extra_field ]['msg'])
1442
+																			  )
1443
+								? 'validate-error ' . $css_class
1444
+								: $css_class;
1445
+
1446
+							$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1447
+																		  && isset($content[ $extra_field ])
1448
+								? $content[ $extra_field ]
1449
+								: '';
1450
+
1451
+							// do we have a validation error?  if we do then let's use that value instead
1452
+							$template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1453
+								? $validators[ $extra_field ]['value']
1454
+								: $template_form_fields[ $field_id ]['value'];
1455
+
1456
+
1457
+							$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1458
+
1459
+							// shortcode selector
1460
+							$field_name_to_use = $extra_field === 'main'
1461
+								? 'content'
1462
+								: $extra_field;
1463
+							$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1464
+								$field_name_to_use,
1465
+								$field_id
1466
+							);
1467
+
1468
+							if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1469
+								// we want to decode the entities
1470
+								$template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1471
+							}/**/
1472
+						}
1473
+						$templatefield_MTP_id = $reference_field . '-MTP_ID';
1474
+						$templatefield_templatename_id = $reference_field . '-name';
1475
+
1476
+						$template_form_fields[ $templatefield_MTP_id ] = array(
1477
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1478
+							'label'      => null,
1479
+							'input'      => 'hidden',
1480
+							'type'       => 'int',
1481
+							'required'   => false,
1482
+							'validation' => false,
1483
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1484
+							'css_class'  => '',
1485
+							'format'     => '%d',
1486
+							'db-col'     => 'MTP_ID',
1487
+						);
1488
+
1489
+						$template_form_fields[ $templatefield_templatename_id ] = array(
1490
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1491
+							'label'      => null,
1492
+							'input'      => 'hidden',
1493
+							'type'       => 'string',
1494
+							'required'   => false,
1495
+							'validation' => true,
1496
+							'value'      => $reference_field,
1497
+							'css_class'  => '',
1498
+							'format'     => '%s',
1499
+							'db-col'     => 'MTP_template_field',
1500
+						);
1501
+					}
1502
+					continue; // skip the next stuff, we got the necessary fields here for this dataset.
1503
+				} else {
1504
+					$field_id = $template_field . '-content';
1505
+					$template_form_fields[ $field_id ] = $field_setup_array;
1506
+					$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1507
+					$message_template = isset($message_templates[ $context ][ $template_field ])
1508
+						? $message_templates[ $context ][ $template_field ]
1509
+						: null;
1510
+					$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1511
+																  && is_array($message_templates[ $context ])
1512
+																  && $message_template instanceof EE_Message_Template
1513
+						? $message_template->get('MTP_content')
1514
+						: '';
1515
+
1516
+					// do we have a validator error for this field?  if we do then we'll use that value instead
1517
+					$template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1518
+						? $validators[ $template_field ]['value']
1519
+						: $template_form_fields[ $field_id ]['value'];
1520
+
1521
+
1522
+					$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1523
+					$css_class = isset($field_setup_array['css_class'])
1524
+						? $field_setup_array['css_class']
1525
+						: '';
1526
+					$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1527
+																	  && in_array($template_field, $v_fields, true)
1528
+																	  && isset($validators[ $template_field ]['msg'])
1529
+						? 'validate-error ' . $css_class
1530
+						: $css_class;
1531
+
1532
+					// shortcode selector
1533
+					$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1534
+						$template_field,
1535
+						$field_id
1536
+					);
1537
+				}
1538
+
1539
+				// k took care of content field(s) now let's take care of others.
1540
+
1541
+				$templatefield_MTP_id = $template_field . '-MTP_ID';
1542
+				$templatefield_field_templatename_id = $template_field . '-name';
1543
+
1544
+				// foreach template field there are actually two form fields created
1545
+				$template_form_fields[ $templatefield_MTP_id ] = array(
1546
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1547
+					'label'      => null,
1548
+					'input'      => 'hidden',
1549
+					'type'       => 'int',
1550
+					'required'   => false,
1551
+					'validation' => true,
1552
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1553
+					'css_class'  => '',
1554
+					'format'     => '%d',
1555
+					'db-col'     => 'MTP_ID',
1556
+				);
1557
+
1558
+				$template_form_fields[ $templatefield_field_templatename_id ] = array(
1559
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1560
+					'label'      => null,
1561
+					'input'      => 'hidden',
1562
+					'type'       => 'string',
1563
+					'required'   => false,
1564
+					'validation' => true,
1565
+					'value'      => $template_field,
1566
+					'css_class'  => '',
1567
+					'format'     => '%s',
1568
+					'db-col'     => 'MTP_template_field',
1569
+				);
1570
+			}
1571
+
1572
+			// add other fields
1573
+			$template_form_fields['ee-msg-current-context'] = array(
1574
+				'name'       => 'MTP_context',
1575
+				'label'      => null,
1576
+				'input'      => 'hidden',
1577
+				'type'       => 'string',
1578
+				'required'   => false,
1579
+				'validation' => true,
1580
+				'value'      => $context,
1581
+				'css_class'  => '',
1582
+				'format'     => '%s',
1583
+				'db-col'     => 'MTP_context',
1584
+			);
1585
+
1586
+			$template_form_fields['ee-msg-grp-id'] = array(
1587
+				'name'       => 'GRP_ID',
1588
+				'label'      => null,
1589
+				'input'      => 'hidden',
1590
+				'type'       => 'int',
1591
+				'required'   => false,
1592
+				'validation' => true,
1593
+				'value'      => $GRP_ID,
1594
+				'css_class'  => '',
1595
+				'format'     => '%d',
1596
+				'db-col'     => 'GRP_ID',
1597
+			);
1598
+
1599
+			$template_form_fields['ee-msg-messenger'] = array(
1600
+				'name'       => 'MTP_messenger',
1601
+				'label'      => null,
1602
+				'input'      => 'hidden',
1603
+				'type'       => 'string',
1604
+				'required'   => false,
1605
+				'validation' => true,
1606
+				'value'      => $message_template_group->messenger(),
1607
+				'css_class'  => '',
1608
+				'format'     => '%s',
1609
+				'db-col'     => 'MTP_messenger',
1610
+			);
1611
+
1612
+			$template_form_fields['ee-msg-message-type'] = array(
1613
+				'name'       => 'MTP_message_type',
1614
+				'label'      => null,
1615
+				'input'      => 'hidden',
1616
+				'type'       => 'string',
1617
+				'required'   => false,
1618
+				'validation' => true,
1619
+				'value'      => $message_template_group->message_type(),
1620
+				'css_class'  => '',
1621
+				'format'     => '%s',
1622
+				'db-col'     => 'MTP_message_type',
1623
+			);
1624
+
1625
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1626
+				'name'       => 'MTP_is_global',
1627
+				'label'      => esc_html__('Global Template', 'event_espresso'),
1628
+				'input'      => 'hidden',
1629
+				'type'       => 'int',
1630
+				'required'   => false,
1631
+				'validation' => true,
1632
+				'value'      => $message_template_group->get('MTP_is_global'),
1633
+				'css_class'  => '',
1634
+				'format'     => '%d',
1635
+				'db-col'     => 'MTP_is_global',
1636
+			);
1637
+
1638
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1639
+				'name'       => 'MTP_is_override',
1640
+				'label'      => esc_html__('Override all custom', 'event_espresso'),
1641
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1642
+				'type'       => 'int',
1643
+				'required'   => false,
1644
+				'validation' => true,
1645
+				'value'      => $message_template_group->get('MTP_is_override'),
1646
+				'css_class'  => '',
1647
+				'format'     => '%d',
1648
+				'db-col'     => 'MTP_is_override',
1649
+			);
1650
+
1651
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1652
+				'name'       => 'MTP_is_active',
1653
+				'label'      => esc_html__('Active Template', 'event_espresso'),
1654
+				'input'      => 'hidden',
1655
+				'type'       => 'int',
1656
+				'required'   => false,
1657
+				'validation' => true,
1658
+				'value'      => $message_template_group->is_active(),
1659
+				'css_class'  => '',
1660
+				'format'     => '%d',
1661
+				'db-col'     => 'MTP_is_active',
1662
+			);
1663
+
1664
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1665
+				'name'       => 'MTP_deleted',
1666
+				'label'      => null,
1667
+				'input'      => 'hidden',
1668
+				'type'       => 'int',
1669
+				'required'   => false,
1670
+				'validation' => true,
1671
+				'value'      => $message_template_group->get('MTP_deleted'),
1672
+				'css_class'  => '',
1673
+				'format'     => '%d',
1674
+				'db-col'     => 'MTP_deleted',
1675
+			);
1676
+			$sidebar_form_fields['ee-msg-author'] = array(
1677
+				'name'       => 'MTP_user_id',
1678
+				'label'      => esc_html__('Author', 'event_espresso'),
1679
+				'input'      => 'hidden',
1680
+				'type'       => 'int',
1681
+				'required'   => false,
1682
+				'validation' => false,
1683
+				'value'      => $message_template_group->user(),
1684
+				'format'     => '%d',
1685
+				'db-col'     => 'MTP_user_id',
1686
+			);
1687
+
1688
+			$sidebar_form_fields['ee-msg-route'] = array(
1689
+				'name'  => 'action',
1690
+				'input' => 'hidden',
1691
+				'type'  => 'string',
1692
+				'value' => $action,
1693
+			);
1694
+
1695
+			$sidebar_form_fields['ee-msg-id'] = array(
1696
+				'name'  => 'id',
1697
+				'input' => 'hidden',
1698
+				'type'  => 'int',
1699
+				'value' => $GRP_ID,
1700
+			);
1701
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1702
+				'name'  => $action . '_nonce',
1703
+				'input' => 'hidden',
1704
+				'type'  => 'string',
1705
+				'value' => wp_create_nonce($action . '_nonce'),
1706
+			);
1707
+
1708
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1709
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1710
+					'name'  => 'template_switch',
1711
+					'input' => 'hidden',
1712
+					'type'  => 'int',
1713
+					'value' => 1,
1714
+				);
1715
+			}
1716
+
1717
+
1718
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1719
+			$sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1720
+		} //end if ( !empty($template_field_structure) )
1721
+
1722
+		// set extra content for publish box
1723
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1724
+		$this->_set_publish_post_box_vars(
1725
+			'id',
1726
+			$GRP_ID,
1727
+			false,
1728
+			add_query_arg(
1729
+				array('action' => 'global_mtps'),
1730
+				$this->_admin_base_url
1731
+			)
1732
+		);
1733
+
1734
+		// add preview button
1735
+		$preview_url = parent::add_query_args_and_nonce(
1736
+			array(
1737
+				'message_type' => $message_template_group->message_type(),
1738
+				'messenger'    => $message_template_group->messenger(),
1739
+				'context'      => $context,
1740
+				'GRP_ID'       => $GRP_ID,
1741
+				'evt_id'       => $EVT_ID,
1742
+				'action'       => 'preview_message',
1743
+			),
1744
+			$this->_admin_base_url
1745
+		);
1746
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1747
+						  . esc_html__('Preview', 'event_espresso')
1748
+						  . '</a>';
1749
+
1750
+
1751
+		// setup context switcher
1752
+		$context_switcher_args = array(
1753
+			'page'    => 'espresso_messages',
1754
+			'action'  => 'edit_message_template',
1755
+			'id'      => $GRP_ID,
1756
+			'evt_id'  => $EVT_ID,
1757
+			'context' => $context,
1758
+			'extra'   => $preview_button,
1759
+		);
1760
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1761
+
1762
+
1763
+		// main box
1764
+		$this->_template_args['template_fields'] = $template_fields;
1765
+		$this->_template_args['sidebar_box_id'] = 'details';
1766
+		$this->_template_args['action'] = $action;
1767
+		$this->_template_args['context'] = $context;
1768
+		$this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1769
+		$this->_template_args['learn_more_about_message_templates_link'] =
1770
+			$this->_learn_more_about_message_templates_link();
1771
+
1772
+
1773
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1774
+		$this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1775
+			$message_template_group,
1776
+			$context,
1777
+			$context_label
1778
+		);
1779
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1780
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1781
+
1782
+		$this->_template_path = $this->_template_args['GRP_ID']
1783
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1784
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1785
+
1786
+		// send along EE_Message_Template_Group object for further template use.
1787
+		$this->_template_args['MTP'] = $message_template_group;
1788
+
1789
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1790
+			$this->_template_path,
1791
+			$this->_template_args,
1792
+			true
1793
+		);
1794
+
1795
+
1796
+		// finally, let's set the admin_page title
1797
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1798
+
1799
+
1800
+		// we need to take care of setting the shortcodes property for use elsewhere.
1801
+		$this->_set_shortcodes();
1802
+
1803
+
1804
+		// final template wrapper
1805
+		$this->display_admin_page_with_sidebar();
1806
+	}
1807
+
1808
+
1809
+	public function filter_tinymce_init($mceInit, $editor_id)
1810
+	{
1811
+		return $mceInit;
1812
+	}
1813
+
1814
+
1815
+	public function add_context_switcher()
1816
+	{
1817
+		return $this->_context_switcher;
1818
+	}
1819
+
1820
+
1821
+	/**
1822
+	 * Adds the activation/deactivation toggle for the message template context.
1823
+	 *
1824
+	 * @param EE_Message_Template_Group $message_template_group
1825
+	 * @param string                    $context
1826
+	 * @param string                    $context_label
1827
+	 * @return string
1828
+	 * @throws DomainException
1829
+	 * @throws EE_Error
1830
+	 * @throws InvalidIdentifierException
1831
+	 */
1832
+	protected function add_active_context_element(
1833
+		EE_Message_Template_Group $message_template_group,
1834
+		$context,
1835
+		$context_label
1836
+	) {
1837
+		$template_args = array(
1838
+			'context'                   => $context,
1839
+			'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1840
+			'is_active'                 => $message_template_group->is_context_active($context),
1841
+			'on_off_action'             => $message_template_group->is_context_active($context)
1842
+				? 'context-off'
1843
+				: 'context-on',
1844
+			'context_label'             => str_replace(array('(', ')'), '', $context_label),
1845
+			'message_template_group_id' => $message_template_group->ID(),
1846
+		);
1847
+		return EEH_Template::display_template(
1848
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1849
+			$template_args,
1850
+			true
1851
+		);
1852
+	}
1853
+
1854
+
1855
+	/**
1856
+	 * Ajax callback for `toggle_context_template` ajax action.
1857
+	 * Handles toggling the message context on or off.
1858
+	 *
1859
+	 * @throws EE_Error
1860
+	 * @throws InvalidArgumentException
1861
+	 * @throws InvalidDataTypeException
1862
+	 * @throws InvalidIdentifierException
1863
+	 * @throws InvalidInterfaceException
1864
+	 */
1865
+	public function toggle_context_template()
1866
+	{
1867
+		$success = true;
1868
+		// check for required data
1869
+		if (! isset(
1870
+			$this->_req_data['message_template_group_id'],
1871
+			$this->_req_data['context'],
1872
+			$this->_req_data['status']
1873
+		)) {
1874
+			EE_Error::add_error(
1875
+				esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1876
+				__FILE__,
1877
+				__FUNCTION__,
1878
+				__LINE__
1879
+			);
1880
+			$success = false;
1881
+		}
1882
+
1883
+		$nonce = isset($this->_req_data['toggle_context_nonce'])
1884
+			? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1885
+			: '';
1886
+		$nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1887
+		$this->_verify_nonce($nonce, $nonce_ref);
1888
+		$status = $this->_req_data['status'];
1889
+		if ($status !== 'off' && $status !== 'on') {
1890
+			EE_Error::add_error(
1891
+				sprintf(
1892
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1893
+					$this->_req_data['status']
1894
+				),
1895
+				__FILE__,
1896
+				__FUNCTION__,
1897
+				__LINE__
1898
+			);
1899
+			$success = false;
1900
+		}
1901
+		$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1902
+			$this->_req_data['message_template_group_id']
1903
+		);
1904
+		if (! $message_template_group instanceof EE_Message_Template_Group) {
1905
+			EE_Error::add_error(
1906
+				sprintf(
1907
+					esc_html__(
1908
+						'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1909
+						'event_espresso'
1910
+					),
1911
+					$this->_req_data['message_template_group_id'],
1912
+					'EE_Message_Template_Group'
1913
+				),
1914
+				__FILE__,
1915
+				__FUNCTION__,
1916
+				__LINE__
1917
+			);
1918
+			$success = false;
1919
+		}
1920
+		if ($success) {
1921
+			$success = $status === 'off'
1922
+				? $message_template_group->deactivate_context($this->_req_data['context'])
1923
+				: $message_template_group->activate_context($this->_req_data['context']);
1924
+		}
1925
+		$this->_template_args['success'] = $success;
1926
+		$this->_return_json();
1927
+	}
1928
+
1929
+
1930
+	public function _add_form_element_before()
1931
+	{
1932
+		return '<form method="post" action="'
1933
+			   . $this->_template_args["edit_message_template_form_url"]
1934
+			   . '" id="ee-msg-edit-frm">';
1935
+	}
1936
+
1937
+	public function _add_form_element_after()
1938
+	{
1939
+		return '</form>';
1940
+	}
1941
+
1942
+
1943
+	/**
1944
+	 * This executes switching the template pack for a message template.
1945
+	 *
1946
+	 * @since 4.5.0
1947
+	 * @throws EE_Error
1948
+	 * @throws InvalidDataTypeException
1949
+	 * @throws InvalidInterfaceException
1950
+	 * @throws InvalidArgumentException
1951
+	 * @throws ReflectionException
1952
+	 */
1953
+	public function switch_template_pack()
1954
+	{
1955
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1956
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1957
+
1958
+		// verify we have needed values.
1959
+		if (empty($GRP_ID) || empty($template_pack)) {
1960
+			$this->_template_args['error'] = true;
1961
+			EE_Error::add_error(
1962
+				esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1963
+				__FILE__,
1964
+				__FUNCTION__,
1965
+				__LINE__
1966
+			);
1967
+		} else {
1968
+			// get template, set the new template_pack and then reset to default
1969
+			/** @type EE_Message_Template_Group $message_template_group */
1970
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1971
+
1972
+			$message_template_group->set_template_pack_name($template_pack);
1973
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1974
+			$this->_req_data['mt'] = $message_template_group->message_type();
1975
+
1976
+			$query_args = $this->_reset_to_default_template();
1977
+
1978
+			if (empty($query_args['id'])) {
1979
+				EE_Error::add_error(
1980
+					esc_html__(
1981
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1982
+						'event_espresso'
1983
+					),
1984
+					__FILE__,
1985
+					__FUNCTION__,
1986
+					__LINE__
1987
+				);
1988
+				$this->_template_args['error'] = true;
1989
+			} else {
1990
+				$template_label = $message_template_group->get_template_pack()->label;
1991
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1992
+				EE_Error::add_success(
1993
+					sprintf(
1994
+						esc_html__(
1995
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1996
+							'event_espresso'
1997
+						),
1998
+						$template_label,
1999
+						$template_pack_labels->template_pack
2000
+					)
2001
+				);
2002
+				// generate the redirect url for js.
2003
+				$url = self::add_query_args_and_nonce(
2004
+					$query_args,
2005
+					$this->_admin_base_url
2006
+				);
2007
+				$this->_template_args['data']['redirect_url'] = $url;
2008
+				$this->_template_args['success'] = true;
2009
+			}
2010
+
2011
+			$this->_return_json();
2012
+		}
2013
+	}
2014
+
2015
+
2016
+	/**
2017
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2018
+	 * they want.
2019
+	 *
2020
+	 * @access protected
2021
+	 * @return array|null
2022
+	 * @throws EE_Error
2023
+	 * @throws InvalidArgumentException
2024
+	 * @throws InvalidDataTypeException
2025
+	 * @throws InvalidInterfaceException
2026
+	 */
2027
+	protected function _reset_to_default_template()
2028
+	{
2029
+
2030
+		$templates = array();
2031
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2032
+		// we need to make sure we've got the info we need.
2033
+		if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2034
+			EE_Error::add_error(
2035
+				esc_html__(
2036
+					'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
2037
+					'event_espresso'
2038
+				),
2039
+				__FILE__,
2040
+				__FUNCTION__,
2041
+				__LINE__
2042
+			);
2043
+		}
2044
+
2045
+		// all templates will be reset to whatever the defaults are
2046
+		// for the global template matching the messenger and message type.
2047
+		$success = ! empty($GRP_ID) ? true : false;
2048
+
2049
+		if ($success) {
2050
+			// let's first determine if the incoming template is a global template,
2051
+			// if it isn't then we need to get the global template matching messenger and message type.
2052
+			// $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2053
+
2054
+
2055
+			// note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2056
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
2057
+
2058
+			if ($success) {
2059
+				// if successfully deleted, lets generate the new ones.
2060
+				// Note. We set GLOBAL to true, because resets on ANY template
2061
+				// will use the related global template defaults for regeneration.
2062
+				// This means that if a custom template is reset it resets to whatever the related global template is.
2063
+				// HOWEVER, we DO keep the template pack and template variation set
2064
+				// for the current custom template when resetting.
2065
+				$templates = $this->_generate_new_templates(
2066
+					$this->_req_data['msgr'],
2067
+					$this->_req_data['mt'],
2068
+					$GRP_ID,
2069
+					true
2070
+				);
2071
+			}
2072
+		}
2073
+
2074
+		// any error messages?
2075
+		if (! $success) {
2076
+			EE_Error::add_error(
2077
+				esc_html__(
2078
+					'Something went wrong with deleting existing templates. Unable to reset to default',
2079
+					'event_espresso'
2080
+				),
2081
+				__FILE__,
2082
+				__FUNCTION__,
2083
+				__LINE__
2084
+			);
2085
+		}
2086
+
2087
+		// all good, let's add a success message!
2088
+		if ($success && ! empty($templates)) {
2089
+			// the info for the template we generated is the first element in the returned array
2090
+			// $templates = $templates[0];
2091
+			EE_Error::overwrite_success();
2092
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2093
+		}
2094
+
2095
+
2096
+		$query_args = array(
2097
+			'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2098
+			'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2099
+			'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2100
+		);
2101
+
2102
+		// if called via ajax then we return query args otherwise redirect
2103
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2104
+			return $query_args;
2105
+		} else {
2106
+			$this->_redirect_after_action(false, '', '', $query_args, true);
2107
+
2108
+			return null;
2109
+		}
2110
+	}
2111
+
2112
+
2113
+	/**
2114
+	 * Retrieve and set the message preview for display.
2115
+	 *
2116
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2117
+	 * @return string
2118
+	 * @throws ReflectionException
2119
+	 * @throws EE_Error
2120
+	 * @throws InvalidArgumentException
2121
+	 * @throws InvalidDataTypeException
2122
+	 * @throws InvalidInterfaceException
2123
+	 */
2124
+	public function _preview_message($send = false)
2125
+	{
2126
+		// first make sure we've got the necessary parameters
2127
+		if (! isset(
2128
+			$this->_req_data['message_type'],
2129
+			$this->_req_data['messenger'],
2130
+			$this->_req_data['messenger'],
2131
+			$this->_req_data['GRP_ID']
2132
+		)) {
2133
+			EE_Error::add_error(
2134
+				esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2135
+				__FILE__,
2136
+				__FUNCTION__,
2137
+				__LINE__
2138
+			);
2139
+		}
2140
+
2141
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2142 2142
         
2143
-        // if we have an evt_id set on the request, use it.
2144
-        $EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
2145
-        ? absint($this->_req_data['evt_id'])
2146
-        : false;
2147
-
2148
-
2149
-        // get the preview!
2150
-        $preview = EED_Messages::preview_message(
2151
-            $this->_req_data['message_type'],
2152
-            $this->_req_data['context'],
2153
-            $this->_req_data['messenger'],
2154
-            $send
2155
-        );
2156
-
2157
-        if ($send) {
2158
-            return $preview;
2159
-        }
2160
-
2161
-        // let's add a button to go back to the edit view
2162
-        $query_args = array(
2163
-            'id'      => $this->_req_data['GRP_ID'],
2164
-            'evt_id'  => $EVT_ID,
2165
-            'context' => $this->_req_data['context'],
2166
-            'action'  => 'edit_message_template',
2167
-        );
2168
-        $go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2169
-        $preview_button = '<a href="'
2170
-                          . $go_back_url
2171
-                          . '" class="button-secondary messages-preview-go-back-button">'
2172
-                          . esc_html__('Go Back to Edit', 'event_espresso')
2173
-                          . '</a>';
2174
-        $message_types = $this->get_installed_message_types();
2175
-        $active_messenger = $this->_message_resource_manager->get_active_messenger(
2176
-            $this->_req_data['messenger']
2177
-        );
2178
-        $active_messenger_label = $active_messenger instanceof EE_messenger
2179
-            ? ucwords($active_messenger->label['singular'])
2180
-            : esc_html__('Unknown Messenger', 'event_espresso');
2181
-        // let's provide a helpful title for context
2182
-        $preview_title = sprintf(
2183
-            esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2184
-            $active_messenger_label,
2185
-            ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2186
-        );
2187
-        if (empty($preview)) {
2188
-            $this->noEventsErrorMessage();
2189
-        }
2190
-        // setup display of preview.
2191
-        $this->_admin_page_title = $preview_title;
2192
-        $this->_template_args['admin_page_title'] = $preview_title;
2193
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2194
-        $this->_template_args['data']['force_json'] = true;
2195
-
2196
-        return '';
2197
-    }
2198
-
2199
-
2200
-    /**
2201
-     * Used to set an error if there are no events available for generating a preview/test send.
2202
-     *
2203
-     * @param bool $test_send  Whether the error should be generated for the context of a test send.
2204
-     */
2205
-    protected function noEventsErrorMessage($test_send = false)
2206
-    {
2207
-        $events_url = parent::add_query_args_and_nonce(
2208
-            array(
2209
-                'action' => 'default',
2210
-                'page'   => 'espresso_events',
2211
-            ),
2212
-            admin_url('admin.php')
2213
-        );
2214
-        $message = $test_send
2215
-            ? __(
2216
-                '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!',
2217
-                'event_espresso'
2218
-            )
2219
-            : __(
2220
-                '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!',
2221
-                'event_espresso'
2222
-            );
2223
-
2224
-        EE_Error::add_attention(
2225
-            sprintf(
2226
-                $message,
2227
-                "<a href='{$events_url}'>",
2228
-                '</a>'
2229
-            )
2230
-        );
2231
-    }
2232
-
2233
-
2234
-    /**
2235
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2236
-     * gets called automatically.
2237
-     *
2238
-     * @since 4.5.0
2239
-     *
2240
-     * @return string
2241
-     */
2242
-    protected function _display_preview_message()
2243
-    {
2244
-        $this->display_admin_page_with_no_sidebar();
2245
-    }
2246
-
2247
-
2248
-    /**
2249
-     * registers metaboxes that should show up on the "edit_message_template" page
2250
-     *
2251
-     * @access protected
2252
-     * @return void
2253
-     */
2254
-    protected function _register_edit_meta_boxes()
2255
-    {
2256
-        add_meta_box(
2257
-            'mtp_valid_shortcodes',
2258
-            esc_html__('Valid Shortcodes', 'event_espresso'),
2259
-            array($this, 'shortcode_meta_box'),
2260
-            $this->_current_screen->id,
2261
-            'side',
2262
-            'default'
2263
-        );
2264
-        add_meta_box(
2265
-            'mtp_extra_actions',
2266
-            esc_html__('Extra Actions', 'event_espresso'),
2267
-            array($this, 'extra_actions_meta_box'),
2268
-            $this->_current_screen->id,
2269
-            'side',
2270
-            'high'
2271
-        );
2272
-        add_meta_box(
2273
-            'mtp_templates',
2274
-            esc_html__('Template Styles', 'event_espresso'),
2275
-            array($this, 'template_pack_meta_box'),
2276
-            $this->_current_screen->id,
2277
-            'side',
2278
-            'high'
2279
-        );
2280
-    }
2281
-
2282
-
2283
-    /**
2284
-     * metabox content for all template pack and variation selection.
2285
-     *
2286
-     * @since 4.5.0
2287
-     * @return string
2288
-     * @throws DomainException
2289
-     * @throws EE_Error
2290
-     * @throws InvalidArgumentException
2291
-     * @throws ReflectionException
2292
-     * @throws InvalidDataTypeException
2293
-     * @throws InvalidInterfaceException
2294
-     */
2295
-    public function template_pack_meta_box()
2296
-    {
2297
-        $this->_set_message_template_group();
2298
-
2299
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
2300
-
2301
-        $tp_select_values = array();
2302
-
2303
-        foreach ($tp_collection as $tp) {
2304
-            // only include template packs that support this messenger and message type!
2305
-            $supports = $tp->get_supports();
2306
-            if (! isset($supports[ $this->_message_template_group->messenger() ])
2307
-                || ! in_array(
2308
-                    $this->_message_template_group->message_type(),
2309
-                    $supports[ $this->_message_template_group->messenger() ],
2310
-                    true
2311
-                )
2312
-            ) {
2313
-                // not supported
2314
-                continue;
2315
-            }
2316
-
2317
-            $tp_select_values[] = array(
2318
-                'text' => $tp->label,
2319
-                'id'   => $tp->dbref,
2320
-            );
2321
-        }
2322
-
2323
-        // if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2324
-        // the default template pack.  This still allows for the odd template pack to override.
2325
-        if (empty($tp_select_values)) {
2326
-            $tp_select_values[] = array(
2327
-                'text' => esc_html__('Default', 'event_espresso'),
2328
-                'id'   => 'default',
2329
-            );
2330
-        }
2331
-
2332
-        // setup variation select values for the currently selected template.
2333
-        $variations = $this->_message_template_group->get_template_pack()->get_variations(
2334
-            $this->_message_template_group->messenger(),
2335
-            $this->_message_template_group->message_type()
2336
-        );
2337
-        $variations_select_values = array();
2338
-        foreach ($variations as $variation => $label) {
2339
-            $variations_select_values[] = array(
2340
-                'text' => $label,
2341
-                'id'   => $variation,
2342
-            );
2343
-        }
2344
-
2345
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2346
-
2347
-        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2348
-            'MTP_template_pack',
2349
-            $tp_select_values,
2350
-            $this->_message_template_group->get_template_pack_name()
2351
-        );
2352
-        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
2353
-            'MTP_template_variation',
2354
-            $variations_select_values,
2355
-            $this->_message_template_group->get_template_pack_variation()
2356
-        );
2357
-        $template_args['template_pack_label'] = $template_pack_labels->template_pack;
2358
-        $template_args['template_variation_label'] = $template_pack_labels->template_variation;
2359
-        $template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2360
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2361
-
2362
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2363
-
2364
-        EEH_Template::display_template($template, $template_args);
2365
-    }
2366
-
2367
-
2368
-    /**
2369
-     * This meta box holds any extra actions related to Message Templates
2370
-     * For now, this includes Resetting templates to defaults and sending a test email.
2371
-     *
2372
-     * @access  public
2373
-     * @return void
2374
-     * @throws EE_Error
2375
-     */
2376
-    public function extra_actions_meta_box()
2377
-    {
2378
-        $template_form_fields = array();
2379
-
2380
-        $extra_args = array(
2381
-            'msgr'   => $this->_message_template_group->messenger(),
2382
-            'mt'     => $this->_message_template_group->message_type(),
2383
-            'GRP_ID' => $this->_message_template_group->GRP_ID(),
2384
-        );
2385
-        // first we need to see if there are any fields
2386
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2387
-
2388
-        if (! empty($fields)) {
2389
-            // yup there be fields
2390
-            foreach ($fields as $field => $config) {
2391
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2392
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2393
-                $default = isset($config['default']) ? $config['default'] : '';
2394
-                $default = isset($config['value']) ? $config['value'] : $default;
2395
-
2396
-                // if type is hidden and the value is empty
2397
-                // something may have gone wrong so let's correct with the defaults
2398
-                $fix = $config['input'] === 'hidden'
2399
-                       && isset($existing[ $field ])
2400
-                       && empty($existing[ $field ])
2401
-                    ? $default
2402
-                    : '';
2403
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2404
-                    ? $existing[ $field ]
2405
-                    : $fix;
2406
-
2407
-                $template_form_fields[ $field_id ] = array(
2408
-                    'name'       => 'test_settings_fld[' . $field . ']',
2409
-                    'label'      => $config['label'],
2410
-                    'input'      => $config['input'],
2411
-                    'type'       => $config['type'],
2412
-                    'required'   => $config['required'],
2413
-                    'validation' => $config['validation'],
2414
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2415
-                    'css_class'  => $config['css_class'],
2416
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2417
-                    'default'    => $default,
2418
-                    'format'     => $config['format'],
2419
-                );
2420
-            }
2421
-        }
2422
-
2423
-        $test_settings_fields = ! empty($template_form_fields)
2424
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2425
-            : '';
2426
-
2427
-        $test_settings_html = '';
2428
-        // print out $test_settings_fields
2429
-        if (! empty($test_settings_fields)) {
2430
-            echo $test_settings_fields;
2431
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2432
-            $test_settings_html .= 'name="test_button" value="';
2433
-            $test_settings_html .= esc_html__('Test Send', 'event_espresso');
2434
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2435
-        }
2436
-
2437
-        // and button
2438
-        $test_settings_html .= '<p>'
2439
-                               . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2440
-                               . '</p>';
2441
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2442
-        $test_settings_html .= $this->get_action_link_or_button(
2443
-            'reset_to_default',
2444
-            'reset',
2445
-            $extra_args,
2446
-            'button-primary reset-default-button'
2447
-        );
2448
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2449
-        echo $test_settings_html;
2450
-    }
2451
-
2452
-
2453
-    /**
2454
-     * This returns the shortcode selector skeleton for a given context and field.
2455
-     *
2456
-     * @since 4.9.rc.000
2457
-     * @param string $field           The name of the field retrieving shortcodes for.
2458
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2459
-     * @return string
2460
-     * @throws DomainException
2461
-     * @throws EE_Error
2462
-     * @throws InvalidArgumentException
2463
-     * @throws ReflectionException
2464
-     * @throws InvalidDataTypeException
2465
-     * @throws InvalidInterfaceException
2466
-     */
2467
-    protected function _get_shortcode_selector($field, $linked_input_id)
2468
-    {
2469
-        $template_args = array(
2470
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2471
-            'fieldname'       => $field,
2472
-            'linked_input_id' => $linked_input_id,
2473
-        );
2474
-
2475
-        return EEH_Template::display_template(
2476
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2477
-            $template_args,
2478
-            true
2479
-        );
2480
-    }
2481
-
2482
-
2483
-    /**
2484
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2485
-     * page)
2486
-     *
2487
-     * @access public
2488
-     * @return void
2489
-     * @throws EE_Error
2490
-     * @throws InvalidArgumentException
2491
-     * @throws ReflectionException
2492
-     * @throws InvalidDataTypeException
2493
-     * @throws InvalidInterfaceException
2494
-     */
2495
-    public function shortcode_meta_box()
2496
-    {
2497
-        $shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2498
-        // $messenger = $this->_message_template_group->messenger_obj();
2499
-        // now let's set the content depending on the status of the shortcodes array
2500
-        if (empty($shortcodes)) {
2501
-            $content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2502
-            echo $content;
2503
-        } else {
2504
-            // $alt = 0;
2505
-            ?>
2143
+		// if we have an evt_id set on the request, use it.
2144
+		$EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
2145
+		? absint($this->_req_data['evt_id'])
2146
+		: false;
2147
+
2148
+
2149
+		// get the preview!
2150
+		$preview = EED_Messages::preview_message(
2151
+			$this->_req_data['message_type'],
2152
+			$this->_req_data['context'],
2153
+			$this->_req_data['messenger'],
2154
+			$send
2155
+		);
2156
+
2157
+		if ($send) {
2158
+			return $preview;
2159
+		}
2160
+
2161
+		// let's add a button to go back to the edit view
2162
+		$query_args = array(
2163
+			'id'      => $this->_req_data['GRP_ID'],
2164
+			'evt_id'  => $EVT_ID,
2165
+			'context' => $this->_req_data['context'],
2166
+			'action'  => 'edit_message_template',
2167
+		);
2168
+		$go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2169
+		$preview_button = '<a href="'
2170
+						  . $go_back_url
2171
+						  . '" class="button-secondary messages-preview-go-back-button">'
2172
+						  . esc_html__('Go Back to Edit', 'event_espresso')
2173
+						  . '</a>';
2174
+		$message_types = $this->get_installed_message_types();
2175
+		$active_messenger = $this->_message_resource_manager->get_active_messenger(
2176
+			$this->_req_data['messenger']
2177
+		);
2178
+		$active_messenger_label = $active_messenger instanceof EE_messenger
2179
+			? ucwords($active_messenger->label['singular'])
2180
+			: esc_html__('Unknown Messenger', 'event_espresso');
2181
+		// let's provide a helpful title for context
2182
+		$preview_title = sprintf(
2183
+			esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2184
+			$active_messenger_label,
2185
+			ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2186
+		);
2187
+		if (empty($preview)) {
2188
+			$this->noEventsErrorMessage();
2189
+		}
2190
+		// setup display of preview.
2191
+		$this->_admin_page_title = $preview_title;
2192
+		$this->_template_args['admin_page_title'] = $preview_title;
2193
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2194
+		$this->_template_args['data']['force_json'] = true;
2195
+
2196
+		return '';
2197
+	}
2198
+
2199
+
2200
+	/**
2201
+	 * Used to set an error if there are no events available for generating a preview/test send.
2202
+	 *
2203
+	 * @param bool $test_send  Whether the error should be generated for the context of a test send.
2204
+	 */
2205
+	protected function noEventsErrorMessage($test_send = false)
2206
+	{
2207
+		$events_url = parent::add_query_args_and_nonce(
2208
+			array(
2209
+				'action' => 'default',
2210
+				'page'   => 'espresso_events',
2211
+			),
2212
+			admin_url('admin.php')
2213
+		);
2214
+		$message = $test_send
2215
+			? __(
2216
+				'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!',
2217
+				'event_espresso'
2218
+			)
2219
+			: __(
2220
+				'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!',
2221
+				'event_espresso'
2222
+			);
2223
+
2224
+		EE_Error::add_attention(
2225
+			sprintf(
2226
+				$message,
2227
+				"<a href='{$events_url}'>",
2228
+				'</a>'
2229
+			)
2230
+		);
2231
+	}
2232
+
2233
+
2234
+	/**
2235
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2236
+	 * gets called automatically.
2237
+	 *
2238
+	 * @since 4.5.0
2239
+	 *
2240
+	 * @return string
2241
+	 */
2242
+	protected function _display_preview_message()
2243
+	{
2244
+		$this->display_admin_page_with_no_sidebar();
2245
+	}
2246
+
2247
+
2248
+	/**
2249
+	 * registers metaboxes that should show up on the "edit_message_template" page
2250
+	 *
2251
+	 * @access protected
2252
+	 * @return void
2253
+	 */
2254
+	protected function _register_edit_meta_boxes()
2255
+	{
2256
+		add_meta_box(
2257
+			'mtp_valid_shortcodes',
2258
+			esc_html__('Valid Shortcodes', 'event_espresso'),
2259
+			array($this, 'shortcode_meta_box'),
2260
+			$this->_current_screen->id,
2261
+			'side',
2262
+			'default'
2263
+		);
2264
+		add_meta_box(
2265
+			'mtp_extra_actions',
2266
+			esc_html__('Extra Actions', 'event_espresso'),
2267
+			array($this, 'extra_actions_meta_box'),
2268
+			$this->_current_screen->id,
2269
+			'side',
2270
+			'high'
2271
+		);
2272
+		add_meta_box(
2273
+			'mtp_templates',
2274
+			esc_html__('Template Styles', 'event_espresso'),
2275
+			array($this, 'template_pack_meta_box'),
2276
+			$this->_current_screen->id,
2277
+			'side',
2278
+			'high'
2279
+		);
2280
+	}
2281
+
2282
+
2283
+	/**
2284
+	 * metabox content for all template pack and variation selection.
2285
+	 *
2286
+	 * @since 4.5.0
2287
+	 * @return string
2288
+	 * @throws DomainException
2289
+	 * @throws EE_Error
2290
+	 * @throws InvalidArgumentException
2291
+	 * @throws ReflectionException
2292
+	 * @throws InvalidDataTypeException
2293
+	 * @throws InvalidInterfaceException
2294
+	 */
2295
+	public function template_pack_meta_box()
2296
+	{
2297
+		$this->_set_message_template_group();
2298
+
2299
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
2300
+
2301
+		$tp_select_values = array();
2302
+
2303
+		foreach ($tp_collection as $tp) {
2304
+			// only include template packs that support this messenger and message type!
2305
+			$supports = $tp->get_supports();
2306
+			if (! isset($supports[ $this->_message_template_group->messenger() ])
2307
+				|| ! in_array(
2308
+					$this->_message_template_group->message_type(),
2309
+					$supports[ $this->_message_template_group->messenger() ],
2310
+					true
2311
+				)
2312
+			) {
2313
+				// not supported
2314
+				continue;
2315
+			}
2316
+
2317
+			$tp_select_values[] = array(
2318
+				'text' => $tp->label,
2319
+				'id'   => $tp->dbref,
2320
+			);
2321
+		}
2322
+
2323
+		// if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2324
+		// the default template pack.  This still allows for the odd template pack to override.
2325
+		if (empty($tp_select_values)) {
2326
+			$tp_select_values[] = array(
2327
+				'text' => esc_html__('Default', 'event_espresso'),
2328
+				'id'   => 'default',
2329
+			);
2330
+		}
2331
+
2332
+		// setup variation select values for the currently selected template.
2333
+		$variations = $this->_message_template_group->get_template_pack()->get_variations(
2334
+			$this->_message_template_group->messenger(),
2335
+			$this->_message_template_group->message_type()
2336
+		);
2337
+		$variations_select_values = array();
2338
+		foreach ($variations as $variation => $label) {
2339
+			$variations_select_values[] = array(
2340
+				'text' => $label,
2341
+				'id'   => $variation,
2342
+			);
2343
+		}
2344
+
2345
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2346
+
2347
+		$template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2348
+			'MTP_template_pack',
2349
+			$tp_select_values,
2350
+			$this->_message_template_group->get_template_pack_name()
2351
+		);
2352
+		$template_args['variations_selector'] = EEH_Form_Fields::select_input(
2353
+			'MTP_template_variation',
2354
+			$variations_select_values,
2355
+			$this->_message_template_group->get_template_pack_variation()
2356
+		);
2357
+		$template_args['template_pack_label'] = $template_pack_labels->template_pack;
2358
+		$template_args['template_variation_label'] = $template_pack_labels->template_variation;
2359
+		$template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2360
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2361
+
2362
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2363
+
2364
+		EEH_Template::display_template($template, $template_args);
2365
+	}
2366
+
2367
+
2368
+	/**
2369
+	 * This meta box holds any extra actions related to Message Templates
2370
+	 * For now, this includes Resetting templates to defaults and sending a test email.
2371
+	 *
2372
+	 * @access  public
2373
+	 * @return void
2374
+	 * @throws EE_Error
2375
+	 */
2376
+	public function extra_actions_meta_box()
2377
+	{
2378
+		$template_form_fields = array();
2379
+
2380
+		$extra_args = array(
2381
+			'msgr'   => $this->_message_template_group->messenger(),
2382
+			'mt'     => $this->_message_template_group->message_type(),
2383
+			'GRP_ID' => $this->_message_template_group->GRP_ID(),
2384
+		);
2385
+		// first we need to see if there are any fields
2386
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2387
+
2388
+		if (! empty($fields)) {
2389
+			// yup there be fields
2390
+			foreach ($fields as $field => $config) {
2391
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2392
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2393
+				$default = isset($config['default']) ? $config['default'] : '';
2394
+				$default = isset($config['value']) ? $config['value'] : $default;
2395
+
2396
+				// if type is hidden and the value is empty
2397
+				// something may have gone wrong so let's correct with the defaults
2398
+				$fix = $config['input'] === 'hidden'
2399
+					   && isset($existing[ $field ])
2400
+					   && empty($existing[ $field ])
2401
+					? $default
2402
+					: '';
2403
+				$existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2404
+					? $existing[ $field ]
2405
+					: $fix;
2406
+
2407
+				$template_form_fields[ $field_id ] = array(
2408
+					'name'       => 'test_settings_fld[' . $field . ']',
2409
+					'label'      => $config['label'],
2410
+					'input'      => $config['input'],
2411
+					'type'       => $config['type'],
2412
+					'required'   => $config['required'],
2413
+					'validation' => $config['validation'],
2414
+					'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2415
+					'css_class'  => $config['css_class'],
2416
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2417
+					'default'    => $default,
2418
+					'format'     => $config['format'],
2419
+				);
2420
+			}
2421
+		}
2422
+
2423
+		$test_settings_fields = ! empty($template_form_fields)
2424
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2425
+			: '';
2426
+
2427
+		$test_settings_html = '';
2428
+		// print out $test_settings_fields
2429
+		if (! empty($test_settings_fields)) {
2430
+			echo $test_settings_fields;
2431
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2432
+			$test_settings_html .= 'name="test_button" value="';
2433
+			$test_settings_html .= esc_html__('Test Send', 'event_espresso');
2434
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2435
+		}
2436
+
2437
+		// and button
2438
+		$test_settings_html .= '<p>'
2439
+							   . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2440
+							   . '</p>';
2441
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2442
+		$test_settings_html .= $this->get_action_link_or_button(
2443
+			'reset_to_default',
2444
+			'reset',
2445
+			$extra_args,
2446
+			'button-primary reset-default-button'
2447
+		);
2448
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2449
+		echo $test_settings_html;
2450
+	}
2451
+
2452
+
2453
+	/**
2454
+	 * This returns the shortcode selector skeleton for a given context and field.
2455
+	 *
2456
+	 * @since 4.9.rc.000
2457
+	 * @param string $field           The name of the field retrieving shortcodes for.
2458
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2459
+	 * @return string
2460
+	 * @throws DomainException
2461
+	 * @throws EE_Error
2462
+	 * @throws InvalidArgumentException
2463
+	 * @throws ReflectionException
2464
+	 * @throws InvalidDataTypeException
2465
+	 * @throws InvalidInterfaceException
2466
+	 */
2467
+	protected function _get_shortcode_selector($field, $linked_input_id)
2468
+	{
2469
+		$template_args = array(
2470
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2471
+			'fieldname'       => $field,
2472
+			'linked_input_id' => $linked_input_id,
2473
+		);
2474
+
2475
+		return EEH_Template::display_template(
2476
+			EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2477
+			$template_args,
2478
+			true
2479
+		);
2480
+	}
2481
+
2482
+
2483
+	/**
2484
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2485
+	 * page)
2486
+	 *
2487
+	 * @access public
2488
+	 * @return void
2489
+	 * @throws EE_Error
2490
+	 * @throws InvalidArgumentException
2491
+	 * @throws ReflectionException
2492
+	 * @throws InvalidDataTypeException
2493
+	 * @throws InvalidInterfaceException
2494
+	 */
2495
+	public function shortcode_meta_box()
2496
+	{
2497
+		$shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2498
+		// $messenger = $this->_message_template_group->messenger_obj();
2499
+		// now let's set the content depending on the status of the shortcodes array
2500
+		if (empty($shortcodes)) {
2501
+			$content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2502
+			echo $content;
2503
+		} else {
2504
+			// $alt = 0;
2505
+			?>
2506 2506
             <div style="float:right; margin-top:10px"><?php
2507
-                            echo $this->_get_help_tab_link('message_template_shortcodes');
2508
-                            ?></div>
2507
+							echo $this->_get_help_tab_link('message_template_shortcodes');
2508
+							?></div>
2509 2509
             <p class="small-text"><?php
2510
-                                  printf(
2511
-                                      esc_html__(
2512
-                                          'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2513
-                                          'event_espresso'
2514
-                                      ),
2515
-                                      '<span class="dashicons dashicons-menu"></span>'
2516
-                                  );
2517
-                                ?>
2510
+								  printf(
2511
+									  esc_html__(
2512
+										  'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2513
+										  'event_espresso'
2514
+									  ),
2515
+									  '<span class="dashicons dashicons-menu"></span>'
2516
+								  );
2517
+								?>
2518 2518
             </p>
2519 2519
             <?php
2520
-        }
2521
-    }
2522
-
2523
-
2524
-    /**
2525
-     * used to set the $_shortcodes property for when its needed elsewhere.
2526
-     *
2527
-     * @access protected
2528
-     * @return void
2529
-     * @throws EE_Error
2530
-     * @throws InvalidArgumentException
2531
-     * @throws ReflectionException
2532
-     * @throws InvalidDataTypeException
2533
-     * @throws InvalidInterfaceException
2534
-     */
2535
-    protected function _set_shortcodes()
2536
-    {
2537
-
2538
-        // no need to run this if the property is already set
2539
-        if (! empty($this->_shortcodes)) {
2540
-            return;
2541
-        }
2542
-
2543
-        $this->_shortcodes = $this->_get_shortcodes();
2544
-    }
2545
-
2546
-
2547
-    /**
2548
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2549
-     * property)
2550
-     *
2551
-     * @access  protected
2552
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2553
-     *                         for. Defaults to all (for the given context)
2554
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2555
-     * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2556
-     *                         true just an array of shortcode/label pairs.
2557
-     * @throws EE_Error
2558
-     * @throws InvalidArgumentException
2559
-     * @throws ReflectionException
2560
-     * @throws InvalidDataTypeException
2561
-     * @throws InvalidInterfaceException
2562
-     */
2563
-    protected function _get_shortcodes($fields = array(), $merged = true)
2564
-    {
2565
-        $this->_set_message_template_group();
2566
-
2567
-        // we need the messenger and message template to retrieve the valid shortcodes array.
2568
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2569
-            ? absint($this->_req_data['id'])
2570
-            : false;
2571
-        $context = isset($this->_req_data['context'])
2572
-            ? $this->_req_data['context']
2573
-            : key($this->_message_template_group->contexts_config());
2574
-
2575
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2576
-    }
2577
-
2578
-
2579
-    /**
2580
-     * This sets the _message_template property (containing the called message_template object)
2581
-     *
2582
-     * @access protected
2583
-     * @return void
2584
-     * @throws EE_Error
2585
-     * @throws InvalidArgumentException
2586
-     * @throws ReflectionException
2587
-     * @throws InvalidDataTypeException
2588
-     * @throws InvalidInterfaceException
2589
-     */
2590
-    protected function _set_message_template_group()
2591
-    {
2592
-
2593
-        if (! empty($this->_message_template_group)) {
2594
-            return;
2595
-        } //get out if this is already set.
2596
-
2597
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2598
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2599
-
2600
-        // let's get the message templates
2601
-        $MTP = EEM_Message_Template_Group::instance();
2602
-
2603
-        if (empty($GRP_ID)) {
2604
-            $this->_message_template_group = $MTP->create_default_object();
2605
-        } else {
2606
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2607
-        }
2608
-
2609
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2610
-        $this->_variation = $this->_message_template_group->get_template_pack_variation();
2611
-    }
2612
-
2613
-
2614
-    /**
2615
-     * sets up a context switcher for edit forms
2616
-     *
2617
-     * @access  protected
2618
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2619
-     * @param array                      $args                  various things the context switcher needs.
2620
-     * @throws EE_Error
2621
-     */
2622
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2623
-    {
2624
-        $context_details = $template_group_object->contexts_config();
2625
-        $context_label = $template_group_object->context_label();
2626
-        ob_start();
2627
-        ?>
2520
+		}
2521
+	}
2522
+
2523
+
2524
+	/**
2525
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2526
+	 *
2527
+	 * @access protected
2528
+	 * @return void
2529
+	 * @throws EE_Error
2530
+	 * @throws InvalidArgumentException
2531
+	 * @throws ReflectionException
2532
+	 * @throws InvalidDataTypeException
2533
+	 * @throws InvalidInterfaceException
2534
+	 */
2535
+	protected function _set_shortcodes()
2536
+	{
2537
+
2538
+		// no need to run this if the property is already set
2539
+		if (! empty($this->_shortcodes)) {
2540
+			return;
2541
+		}
2542
+
2543
+		$this->_shortcodes = $this->_get_shortcodes();
2544
+	}
2545
+
2546
+
2547
+	/**
2548
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2549
+	 * property)
2550
+	 *
2551
+	 * @access  protected
2552
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2553
+	 *                         for. Defaults to all (for the given context)
2554
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2555
+	 * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2556
+	 *                         true just an array of shortcode/label pairs.
2557
+	 * @throws EE_Error
2558
+	 * @throws InvalidArgumentException
2559
+	 * @throws ReflectionException
2560
+	 * @throws InvalidDataTypeException
2561
+	 * @throws InvalidInterfaceException
2562
+	 */
2563
+	protected function _get_shortcodes($fields = array(), $merged = true)
2564
+	{
2565
+		$this->_set_message_template_group();
2566
+
2567
+		// we need the messenger and message template to retrieve the valid shortcodes array.
2568
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2569
+			? absint($this->_req_data['id'])
2570
+			: false;
2571
+		$context = isset($this->_req_data['context'])
2572
+			? $this->_req_data['context']
2573
+			: key($this->_message_template_group->contexts_config());
2574
+
2575
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2576
+	}
2577
+
2578
+
2579
+	/**
2580
+	 * This sets the _message_template property (containing the called message_template object)
2581
+	 *
2582
+	 * @access protected
2583
+	 * @return void
2584
+	 * @throws EE_Error
2585
+	 * @throws InvalidArgumentException
2586
+	 * @throws ReflectionException
2587
+	 * @throws InvalidDataTypeException
2588
+	 * @throws InvalidInterfaceException
2589
+	 */
2590
+	protected function _set_message_template_group()
2591
+	{
2592
+
2593
+		if (! empty($this->_message_template_group)) {
2594
+			return;
2595
+		} //get out if this is already set.
2596
+
2597
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2598
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2599
+
2600
+		// let's get the message templates
2601
+		$MTP = EEM_Message_Template_Group::instance();
2602
+
2603
+		if (empty($GRP_ID)) {
2604
+			$this->_message_template_group = $MTP->create_default_object();
2605
+		} else {
2606
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2607
+		}
2608
+
2609
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2610
+		$this->_variation = $this->_message_template_group->get_template_pack_variation();
2611
+	}
2612
+
2613
+
2614
+	/**
2615
+	 * sets up a context switcher for edit forms
2616
+	 *
2617
+	 * @access  protected
2618
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2619
+	 * @param array                      $args                  various things the context switcher needs.
2620
+	 * @throws EE_Error
2621
+	 */
2622
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2623
+	{
2624
+		$context_details = $template_group_object->contexts_config();
2625
+		$context_label = $template_group_object->context_label();
2626
+		ob_start();
2627
+		?>
2628 2628
         <div class="ee-msg-switcher-container">
2629 2629
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2630 2630
                 <?php
2631
-                foreach ($args as $name => $value) {
2632
-                    if ($name === 'context' || empty($value) || $name === 'extra') {
2633
-                        continue;
2634
-                    }
2635
-                    ?>
2631
+				foreach ($args as $name => $value) {
2632
+					if ($name === 'context' || empty($value) || $name === 'extra') {
2633
+						continue;
2634
+					}
2635
+					?>
2636 2636
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2637 2637
                     <?php
2638
-                }
2639
-                // setup nonce_url
2640
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2641
-                ?>
2638
+				}
2639
+				// setup nonce_url
2640
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2641
+				?>
2642 2642
                 <select name="context">
2643 2643
                     <?php
2644
-                    $context_templates = $template_group_object->context_templates();
2645
-                    if (is_array($context_templates)) :
2646
-                        foreach ($context_templates as $context => $template_fields) :
2647
-                            $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2648
-                            ?>
2644
+					$context_templates = $template_group_object->context_templates();
2645
+					if (is_array($context_templates)) :
2646
+						foreach ($context_templates as $context => $template_fields) :
2647
+							$checked = ($context === $args['context']) ? 'selected="selected"' : '';
2648
+							?>
2649 2649
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2650 2650
                                 <?php echo $context_details[ $context ]['label']; ?>
2651 2651
                             </option>
2652 2652
                         <?php endforeach;
2653
-                    endif; ?>
2653
+					endif; ?>
2654 2654
                 </select>
2655 2655
                 <?php $button_text = sprintf(__('Switch %s', 'event_espresso'), ucwords($context_label['label'])); ?>
2656 2656
                 <input id="submit-msg-context-switcher-sbmt" class="button-secondary" type="submit"
@@ -2659,1925 +2659,1925 @@  discard block
 block discarded – undo
2659 2659
             <?php echo $args['extra']; ?>
2660 2660
         </div> <!-- end .ee-msg-switcher-container -->
2661 2661
         <?php
2662
-        $output = ob_get_contents();
2663
-        ob_clean();
2664
-        $this->_context_switcher = $output;
2665
-    }
2666
-
2667
-
2668
-    /**
2669
-     * utility for sanitizing new values coming in.
2670
-     * Note: this is only used when updating a context.
2671
-     *
2672
-     * @access protected
2673
-     *
2674
-     * @param int $index This helps us know which template field to select from the request array.
2675
-     *
2676
-     * @return array
2677
-     */
2678
-    protected function _set_message_template_column_values($index)
2679
-    {
2680
-        if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2681
-            foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2682
-                $this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2683
-            }
2684
-        }
2685
-
2686
-
2687
-        $set_column_values = array(
2688
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2689
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2690
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2691
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2692
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2693
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2694
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2695
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2696
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2697
-                ? absint($this->_req_data['MTP_is_global'])
2698
-                : 0,
2699
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2700
-                ? absint($this->_req_data['MTP_is_override'])
2701
-                : 0,
2702
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2703
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2704
-        );
2705
-
2706
-
2707
-        return $set_column_values;
2708
-    }
2709
-
2710
-
2711
-    protected function _insert_or_update_message_template($new = false)
2712
-    {
2713
-
2714
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2715
-        $success = 0;
2716
-        $override = false;
2717
-
2718
-        // setup notices description
2719
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2720
-
2721
-        // need the message type and messenger objects to be able to use the labels for the notices
2722
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2723
-        $messenger_label = $messenger_object instanceof EE_messenger
2724
-            ? ucwords($messenger_object->label['singular'])
2725
-            : '';
2726
-
2727
-        $message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2728
-            ? $this->_req_data['MTP_message_type']
2729
-            : '';
2730
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2731
-
2732
-        $message_type_label = $message_type_object instanceof EE_message_type
2733
-            ? ucwords($message_type_object->label['singular'])
2734
-            : '';
2735
-
2736
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2737
-            ? $this->_req_data['MTP_context']
2738
-            : '';
2739
-        $context = ucwords(str_replace('_', ' ', $context_slug));
2740
-
2741
-        $item_desc = $messenger_label && $message_type_label
2742
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2743
-            : '';
2744
-        $item_desc .= 'Message Template';
2745
-        $query_args = array();
2746
-        $edit_array = array();
2747
-        $action_desc = '';
2748
-
2749
-        // if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2750
-        // user to edit.
2751
-        if ($new) {
2752
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2753
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2754
-                if (empty($edit_array)) {
2755
-                    $success = 0;
2756
-                } else {
2757
-                    $success = 1;
2758
-                    $edit_array = $edit_array[0];
2759
-                    $query_args = array(
2760
-                        'id'      => $edit_array['GRP_ID'],
2761
-                        'context' => $edit_array['MTP_context'],
2762
-                        'action'  => 'edit_message_template',
2763
-                    );
2764
-                }
2765
-            }
2766
-            $action_desc = 'created';
2767
-        } else {
2768
-            $MTPG = EEM_Message_Template_Group::instance();
2769
-            $MTP = EEM_Message_Template::instance();
2770
-
2771
-
2772
-            // run update for each template field in displayed context
2773
-            if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2774
-                EE_Error::add_error(
2775
-                    esc_html__(
2776
-                        'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2777
-                        'event_espresso'
2778
-                    ),
2779
-                    __FILE__,
2780
-                    __FUNCTION__,
2781
-                    __LINE__
2782
-                );
2783
-                $success = 0;
2784
-            } else {
2785
-                // first validate all fields!
2786
-                // this filter allows client code to add its own validation to the template fields as well.
2787
-                // returning an empty array means everything passed validation.
2788
-                // errors in validation should be represented in an array with the following shape:
2789
-                // array(
2790
-                //   'fieldname' => array(
2791
-                //          'msg' => 'error message'
2792
-                //          'value' => 'value for field producing error'
2793
-                // )
2794
-                $custom_validation = (array) apply_filters(
2795
-                    'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2796
-                    array(),
2797
-                    $this->_req_data['MTP_template_fields'],
2798
-                    $context_slug,
2799
-                    $messenger_slug,
2800
-                    $message_type_slug
2801
-                );
2802
-
2803
-                $system_validation = $MTPG->validate(
2804
-                    $this->_req_data['MTP_template_fields'],
2805
-                    $context_slug,
2806
-                    $messenger_slug,
2807
-                    $message_type_slug
2808
-                );
2809
-
2810
-                $system_validation = ! is_array($system_validation) && $system_validation ? array()
2811
-                    : $system_validation;
2812
-                $validates = array_merge($custom_validation, $system_validation);
2813
-
2814
-                // if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2815
-                // appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2816
-                //  WE need to make sure there is no actual error messages in validates.
2817
-                if (is_array($validates) && ! empty($validates)) {
2818
-                    // add the transient so when the form loads we know which fields to highlight
2819
-                    $this->_add_transient('edit_message_template', $validates);
2820
-
2821
-                    $success = 0;
2822
-
2823
-                    // setup notices
2824
-                    foreach ($validates as $field => $error) {
2825
-                        if (isset($error['msg'])) {
2826
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2827
-                        }
2828
-                    }
2829
-                } else {
2830
-                    $set_column_values = array();
2831
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2832
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2833
-
2834
-                        $where_cols_n_values = array(
2835
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2836
-                        );
2837
-                        // if they aren't allowed to use all JS, restrict them to just posty-y tags
2838
-                        if (! current_user_can('unfiltered_html')) {
2839
-                            if (is_array($set_column_values['MTP_content'])) {
2840
-                                foreach ($set_column_values['MTP_content'] as $key => $value) {
2841
-                                    // remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2842
-                                    // only removes slashes from double-quotes, so attributes using single quotes always
2843
-                                    // appear invalid.) But currently the models expect slashed data, so after wp_kses
2844
-                                    // runs we need to re-slash the data. Sheesh. See
2845
-                                    // https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2846
-                                    $set_column_values['MTP_content'][ $key ] = addslashes(
2847
-                                        wp_kses(
2848
-                                            stripslashes($value),
2849
-                                            wp_kses_allowed_html('post')
2850
-                                        )
2851
-                                    );
2852
-                                }
2853
-                            } else {
2854
-                                $set_column_values['MTP_content'] = wp_kses(
2855
-                                    $set_column_values['MTP_content'],
2856
-                                    wp_kses_allowed_html('post')
2857
-                                );
2858
-                            }
2859
-                        }
2860
-                        $message_template_fields = array(
2861
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2862
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2863
-                            'MTP_context'        => $set_column_values['MTP_context'],
2864
-                            'MTP_content'        => $set_column_values['MTP_content'],
2865
-                        );
2866
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2867
-                            if ($updated === false) {
2868
-                                EE_Error::add_error(
2869
-                                    sprintf(
2870
-                                        esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2871
-                                        $template_field
2872
-                                    ),
2873
-                                    __FILE__,
2874
-                                    __FUNCTION__,
2875
-                                    __LINE__
2876
-                                );
2877
-                            } else {
2878
-                                $success = 1;
2879
-                            }
2880
-                        } else {
2881
-                            // only do this logic if we don't have a MTP_ID for this field
2882
-                            if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2883
-                                // this has already been through the template field validator and sanitized, so it will be
2884
-                                // safe to insert this field.  Why insert?  This typically happens when we introduce a new
2885
-                                // message template field in a messenger/message type and existing users don't have the
2886
-                                // default setup for it.
2887
-                                // @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2888
-                                $updated = $MTP->insert($message_template_fields);
2889
-                                if (! $updated || is_wp_error($updated)) {
2890
-                                    EE_Error::add_error(
2891
-                                        sprintf(
2892
-                                            esc_html__('%s field could not be updated.', 'event_espresso'),
2893
-                                            $template_field
2894
-                                        ),
2895
-                                        __FILE__,
2896
-                                        __FUNCTION__,
2897
-                                        __LINE__
2898
-                                    );
2899
-                                    $success = 0;
2900
-                                } else {
2901
-                                    $success = 1;
2902
-                                }
2903
-                            }
2904
-                        }
2905
-                        $action_desc = 'updated';
2906
-                    }
2907
-
2908
-                    // we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2909
-                    $mtpg_fields = array(
2910
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2911
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2912
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2913
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2914
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2915
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2916
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2917
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2918
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2919
-                            : '',
2920
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2921
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2922
-                            : '',
2923
-                    );
2924
-
2925
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2926
-                    $updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2927
-
2928
-                    if ($updated === false) {
2929
-                        EE_Error::add_error(
2930
-                            sprintf(
2931
-                                esc_html__(
2932
-                                    'The Message Template Group (%d) was NOT updated for some reason',
2933
-                                    'event_espresso'
2934
-                                ),
2935
-                                $set_column_values['GRP_ID']
2936
-                            ),
2937
-                            __FILE__,
2938
-                            __FUNCTION__,
2939
-                            __LINE__
2940
-                        );
2941
-                    } else {
2942
-                        // k now we need to ensure the template_pack and template_variation fields are set.
2943
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2944
-                            ? $this->_req_data['MTP_template_pack']
2945
-                            : 'default';
2946
-
2947
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2948
-                            ? $this->_req_data['MTP_template_variation']
2949
-                            : 'default';
2950
-
2951
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2952
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2953
-                            $mtpg_obj->set_template_pack_name($template_pack);
2954
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2955
-                        }
2956
-                        $success = 1;
2957
-                    }
2958
-                }
2959
-            }
2960
-        }
2961
-
2962
-        // we return things differently if doing ajax
2963
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2964
-            $this->_template_args['success'] = $success;
2965
-            $this->_template_args['error'] = ! $success ? true : false;
2966
-            $this->_template_args['content'] = '';
2967
-            $this->_template_args['data'] = array(
2968
-                'grpID'        => $edit_array['GRP_ID'],
2969
-                'templateName' => $edit_array['template_name'],
2970
-            );
2971
-            if ($success) {
2972
-                EE_Error::overwrite_success();
2973
-                EE_Error::add_success(
2974
-                    esc_html__(
2975
-                        '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.',
2976
-                        'event_espresso'
2977
-                    )
2978
-                );
2979
-            }
2980
-
2981
-            $this->_return_json();
2982
-        }
2983
-
2984
-
2985
-        // was a test send triggered?
2986
-        if (isset($this->_req_data['test_button'])) {
2987
-            EE_Error::overwrite_success();
2988
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2989
-            $override = true;
2990
-        }
2991
-
2992
-        if (empty($query_args)) {
2993
-            $query_args = array(
2994
-                'id'      => $this->_req_data['GRP_ID'],
2995
-                'context' => $context_slug,
2996
-                'action'  => 'edit_message_template',
2997
-            );
2998
-        }
2999
-
3000
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
3001
-    }
3002
-
3003
-
3004
-    /**
3005
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
3006
-     *
3007
-     * @param  string $context      what context being tested
3008
-     * @param  string $messenger    messenger being tested
3009
-     * @param  string $message_type message type being tested
3010
-     * @throws EE_Error
3011
-     * @throws InvalidArgumentException
3012
-     * @throws InvalidDataTypeException
3013
-     * @throws InvalidInterfaceException
3014
-     */
3015
-    protected function _do_test_send($context, $messenger, $message_type)
3016
-    {
3017
-        // set things up for preview
3018
-        $this->_req_data['messenger'] = $messenger;
3019
-        $this->_req_data['message_type'] = $message_type;
3020
-        $this->_req_data['context'] = $context;
3021
-        $this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
3022
-        $active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
3023
-
3024
-        // let's save any existing fields that might be required by the messenger
3025
-        if (isset($this->_req_data['test_settings_fld'])
3026
-            && $active_messenger instanceof EE_messenger
3027
-            && apply_filters(
3028
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3029
-                true,
3030
-                $this->_req_data['test_settings_fld'],
3031
-                $active_messenger
3032
-            )
3033
-        ) {
3034
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
3035
-        }
3036
-
3037
-        /**
3038
-         * Use filter to add additional controls on whether message can send or not
3039
-         */
3040
-        if (apply_filters(
3041
-            'FHEE__Messages_Admin_Page__do_test_send__can_send',
3042
-            true,
3043
-            $context,
3044
-            $this->_req_data,
3045
-            $messenger,
3046
-            $message_type
3047
-        )) {
3048
-            if (EEM_Event::instance()->count() > 0) {
3049
-                $success = $this->_preview_message(true);
3050
-                if ($success) {
3051
-                    EE_Error::add_success(__('Test message sent', 'event_espresso'));
3052
-                } else {
3053
-                    EE_Error::add_error(
3054
-                        esc_html__('The test message was not sent', 'event_espresso'),
3055
-                        __FILE__,
3056
-                        __FUNCTION__,
3057
-                        __LINE__
3058
-                    );
3059
-                }
3060
-            } else {
3061
-                $this->noEventsErrorMessage(true);
3062
-            }
3063
-        }
3064
-    }
3065
-
3066
-
3067
-    /**
3068
-     * _generate_new_templates
3069
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3070
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3071
-     * for the event.
3072
-     *
3073
-     *
3074
-     * @param  string $messenger     the messenger we are generating templates for
3075
-     * @param array   $message_types array of message types that the templates are generated for.
3076
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3077
-     *                               indicate the message_template_group being used as the base.
3078
-     *
3079
-     * @param bool    $global
3080
-     *
3081
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
3082
-     *                               encountering problems.
3083
-     * @throws EE_Error
3084
-     */
3085
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3086
-    {
3087
-
3088
-        // if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3089
-        // just don't generate any templates.
3090
-        if (empty($message_types)) {
3091
-            return true;
3092
-        }
3093
-
3094
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3095
-    }
3096
-
3097
-
3098
-    /**
3099
-     * [_trash_or_restore_message_template]
3100
-     *
3101
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3102
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3103
-     *                        an individual context (FALSE).
3104
-     * @return void
3105
-     * @throws EE_Error
3106
-     * @throws InvalidArgumentException
3107
-     * @throws InvalidDataTypeException
3108
-     * @throws InvalidInterfaceException
3109
-     */
3110
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
3111
-    {
3112
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3113
-        $MTP = EEM_Message_Template_Group::instance();
3114
-
3115
-        $success = 1;
3116
-
3117
-        // incoming GRP_IDs
3118
-        if ($all) {
3119
-            // Checkboxes
3120
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3121
-                // if array has more than one element then success message should be plural.
3122
-                // todo: what about nonce?
3123
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3124
-
3125
-                // cycle through checkboxes
3126
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3127
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3128
-                    if (! $trashed_or_restored) {
3129
-                        $success = 0;
3130
-                    }
3131
-                }
3132
-            } else {
3133
-                // grab single GRP_ID and handle
3134
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3135
-                if (! empty($GRP_ID)) {
3136
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3137
-                    if (! $trashed_or_restored) {
3138
-                        $success = 0;
3139
-                    }
3140
-                } else {
3141
-                    $success = 0;
3142
-                }
3143
-            }
3144
-        }
3145
-
3146
-        $action_desc = $trash
3147
-            ? esc_html__('moved to the trash', 'event_espresso')
3148
-            : esc_html__('restored', 'event_espresso');
3149
-
3150
-        $action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3151
-
3152
-        $item_desc = $all ? _n(
3153
-            'Message Template Group',
3154
-            'Message Template Groups',
3155
-            $success,
3156
-            'event_espresso'
3157
-        ) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3158
-
3159
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3160
-            'template',
3161
-            'templates',
3162
-            $success,
3163
-            'event_espresso'
3164
-        ) : $item_desc;
3165
-
3166
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
3167
-    }
3168
-
3169
-
3170
-    /**
3171
-     * [_delete_message_template]
3172
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3173
-     *
3174
-     * @return void
3175
-     * @throws EE_Error
3176
-     * @throws InvalidArgumentException
3177
-     * @throws InvalidDataTypeException
3178
-     * @throws InvalidInterfaceException
3179
-     */
3180
-    protected function _delete_message_template()
3181
-    {
3182
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3183
-
3184
-        // checkboxes
3185
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3186
-            // if array has more than one element then success message should be plural
3187
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3188
-
3189
-            // cycle through bulk action checkboxes
3190
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3191
-                $success = $this->_delete_mtp_permanently($GRP_ID);
3192
-            }
3193
-        } else {
3194
-            // grab single grp_id and delete
3195
-            $GRP_ID = absint($this->_req_data['id']);
3196
-            $success = $this->_delete_mtp_permanently($GRP_ID);
3197
-        }
3198
-
3199
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3200
-    }
3201
-
3202
-
3203
-    /**
3204
-     * helper for permanently deleting a mtP group and all related message_templates
3205
-     *
3206
-     * @param  int  $GRP_ID        The group being deleted
3207
-     * @param  bool $include_group whether to delete the Message Template Group as well.
3208
-     * @return bool boolean to indicate the success of the deletes or not.
3209
-     * @throws EE_Error
3210
-     * @throws InvalidArgumentException
3211
-     * @throws InvalidDataTypeException
3212
-     * @throws InvalidInterfaceException
3213
-     */
3214
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3215
-    {
3216
-        $success = 1;
3217
-        $MTPG = EEM_Message_Template_Group::instance();
3218
-        // first let's GET this group
3219
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
3220
-        // then delete permanently all the related Message Templates
3221
-        $deleted = $MTG->delete_related_permanently('Message_Template');
3222
-
3223
-        if ($deleted === 0) {
3224
-            $success = 0;
3225
-        }
3226
-
3227
-        // now delete permanently this particular group
3228
-
3229
-        if ($include_group && ! $MTG->delete_permanently()) {
3230
-            $success = 0;
3231
-        }
3232
-
3233
-        return $success;
3234
-    }
3235
-
3236
-
3237
-    /**
3238
-     *    _learn_more_about_message_templates_link
3239
-     *
3240
-     * @access protected
3241
-     * @return string
3242
-     */
3243
-    protected function _learn_more_about_message_templates_link()
3244
-    {
3245
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3246
-               . esc_html__('learn more about how message templates works', 'event_espresso')
3247
-               . '</a>';
3248
-    }
3249
-
3250
-
3251
-    /**
3252
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3253
-     * ajax and other routes.
3254
-     *
3255
-     * @return void
3256
-     * @throws DomainException
3257
-     */
3258
-    protected function _settings()
3259
-    {
3260
-
3261
-
3262
-        $this->_set_m_mt_settings();
3263
-
3264
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3265
-            ? $this->_req_data['selected_messenger']
3266
-            : 'email';
3267
-
3268
-        // let's setup the messenger tabs
3269
-        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3270
-            $this->_m_mt_settings['messenger_tabs'],
3271
-            'messenger_links',
3272
-            '|',
3273
-            $selected_messenger
3274
-        );
3275
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3276
-        $this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3277
-
3278
-        $this->display_admin_page_with_sidebar();
3279
-    }
3280
-
3281
-
3282
-    /**
3283
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3284
-     *
3285
-     * @access protected
3286
-     * @return void
3287
-     * @throws DomainException
3288
-     */
3289
-    protected function _set_m_mt_settings()
3290
-    {
3291
-        // first if this is already set then lets get out no need to regenerate data.
3292
-        if (! empty($this->_m_mt_settings)) {
3293
-            return;
3294
-        }
3295
-
3296
-        // get all installed messengers and message_types
3297
-        /** @type EE_messenger[] $messengers */
3298
-        $messengers = $this->_message_resource_manager->installed_messengers();
3299
-        /** @type EE_message_type[] $message_types */
3300
-        $message_types = $this->_message_resource_manager->installed_message_types();
3301
-
3302
-
3303
-        // assemble the array for the _tab_text_links helper
3304
-
3305
-        foreach ($messengers as $messenger) {
3306
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3307
-                'label' => ucwords($messenger->label['singular']),
3308
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3309
-                    ? 'messenger-active'
3310
-                    : '',
3311
-                'href'  => $messenger->name,
3312
-                'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3313
-                'slug'  => $messenger->name,
3314
-                'obj'   => $messenger,
3315
-            );
3316
-
3317
-
3318
-            $message_types_for_messenger = $messenger->get_valid_message_types();
3319
-
3320
-            foreach ($message_types as $message_type) {
3321
-                // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3322
-                // it shouldn't show in either the inactive OR active metabox.
3323
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3324
-                    continue;
3325
-                }
3326
-
3327
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3328
-                    $messenger->name,
3329
-                    $message_type->name
3330
-                )
3331
-                    ? 'active'
3332
-                    : 'inactive';
3333
-
3334
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3335
-                    'label'    => ucwords($message_type->label['singular']),
3336
-                    'class'    => 'message-type-' . $a_or_i,
3337
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3338
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3339
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3340
-                    'title'    => $a_or_i === 'active'
3341
-                        ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3342
-                        : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3343
-                    'content'  => $a_or_i === 'active'
3344
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
3345
-                        : $this->_message_type_settings_content($message_type, $messenger),
3346
-                    'slug'     => $message_type->name,
3347
-                    'active'   => $a_or_i === 'active',
3348
-                    'obj'      => $message_type,
3349
-                );
3350
-            }
3351
-        }
3352
-    }
3353
-
3354
-
3355
-    /**
3356
-     * This just prepares the content for the message type settings
3357
-     *
3358
-     * @param  EE_message_type $message_type The message type object
3359
-     * @param  EE_messenger    $messenger    The messenger object
3360
-     * @param  boolean         $active       Whether the message type is active or not
3361
-     * @return string html output for the content
3362
-     * @throws DomainException
3363
-     */
3364
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
3365
-    {
3366
-        // get message type fields
3367
-        $fields = $message_type->get_admin_settings_fields();
3368
-        $settings_template_args['template_form_fields'] = '';
3369
-
3370
-        if (! empty($fields) && $active) {
3371
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3372
-            foreach ($fields as $fldname => $fldprops) {
3373
-                $field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3374
-                $template_form_field[ $field_id ] = array(
3375
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3376
-                    'label'      => $fldprops['label'],
3377
-                    'input'      => $fldprops['field_type'],
3378
-                    'type'       => $fldprops['value_type'],
3379
-                    'required'   => $fldprops['required'],
3380
-                    'validation' => $fldprops['validation'],
3381
-                    'value'      => isset($existing_settings[ $fldname ])
3382
-                        ? $existing_settings[ $fldname ]
3383
-                        : $fldprops['default'],
3384
-                    'options'    => isset($fldprops['options'])
3385
-                        ? $fldprops['options']
3386
-                        : array(),
3387
-                    'default'    => isset($existing_settings[ $fldname ])
3388
-                        ? $existing_settings[ $fldname ]
3389
-                        : $fldprops['default'],
3390
-                    'css_class'  => 'no-drag',
3391
-                    'format'     => $fldprops['format'],
3392
-                );
3393
-            }
3394
-
3395
-
3396
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3397
-                ? $this->_generate_admin_form_fields(
3398
-                    $template_form_field,
3399
-                    'string',
3400
-                    'ee_mt_activate_form'
3401
-                )
3402
-                : '';
3403
-        }
3404
-
3405
-        $settings_template_args['description'] = $message_type->description;
3406
-        // we also need some hidden fields
3407
-        $settings_template_args['hidden_fields'] = array(
3408
-            'message_type_settings[messenger]'    => array(
3409
-                'type'  => 'hidden',
3410
-                'value' => $messenger->name,
3411
-            ),
3412
-            'message_type_settings[message_type]' => array(
3413
-                'type'  => 'hidden',
3414
-                'value' => $message_type->name,
3415
-            ),
3416
-            'type'                                => array(
3417
-                'type'  => 'hidden',
3418
-                'value' => 'message_type',
3419
-            ),
3420
-        );
3421
-
3422
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3423
-            $settings_template_args['hidden_fields'],
3424
-            'array'
3425
-        );
3426
-        $settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3427
-            ? ' hidden'
3428
-            : '';
3429
-
3430
-
3431
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3432
-        $content = EEH_Template::display_template($template, $settings_template_args, true);
3433
-
3434
-        return $content;
3435
-    }
3436
-
3437
-
3438
-    /**
3439
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
3440
-     *
3441
-     * @access protected
3442
-     * @return void
3443
-     * @throws DomainException
3444
-     */
3445
-    protected function _messages_settings_metaboxes()
3446
-    {
3447
-        $this->_set_m_mt_settings();
3448
-        $m_boxes = $mt_boxes = array();
3449
-        $m_template_args = $mt_template_args = array();
3450
-
3451
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3452
-            ? $this->_req_data['selected_messenger']
3453
-            : 'email';
3454
-
3455
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
3456
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3457
-                $hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3458
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3459
-                // messenger meta boxes
3460
-                $active = $selected_messenger === $messenger;
3461
-                $active_mt_tabs = isset(
3462
-                    $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3463
-                )
3464
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3465
-                    : '';
3466
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3467
-                    esc_html__('%s Settings', 'event_espresso'),
3468
-                    $tab_array['label']
3469
-                );
3470
-                $m_template_args[ $messenger . '_a_box' ] = array(
3471
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3472
-                    'inactive_message_types' => isset(
3473
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3474
-                    )
3475
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3476
-                        : '',
3477
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3478
-                    'hidden'                 => $active ? '' : ' hidden',
3479
-                    'hide_on_message'        => $hide_on_message,
3480
-                    'messenger'              => $messenger,
3481
-                    'active'                 => $active,
3482
-                );
3483
-                // message type meta boxes
3484
-                // (which is really just the inactive container for each messenger
3485
-                // showing inactive message types for that messenger)
3486
-                $mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3487
-                $mt_template_args[ $messenger . '_i_box' ] = array(
3488
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3489
-                    'inactive_message_types' => isset(
3490
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3491
-                    )
3492
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3493
-                        : '',
3494
-                    'hidden'                 => $active ? '' : ' hidden',
3495
-                    'hide_on_message'        => $hide_on_message,
3496
-                    'hide_off_message'       => $hide_off_message,
3497
-                    'messenger'              => $messenger,
3498
-                    'active'                 => $active,
3499
-                );
3500
-            }
3501
-        }
3502
-
3503
-
3504
-        // register messenger metaboxes
3505
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3506
-        foreach ($m_boxes as $box => $label) {
3507
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3508
-            $msgr = str_replace('_a_box', '', $box);
3509
-            add_meta_box(
3510
-                'espresso_' . $msgr . '_settings',
3511
-                $label,
3512
-                function ($post, $metabox) {
3513
-                    echo EEH_Template::display_template(
3514
-                        $metabox["args"]["template_path"],
3515
-                        $metabox["args"]["template_args"],
3516
-                        true
3517
-                    );
3518
-                },
3519
-                $this->_current_screen->id,
3520
-                'normal',
3521
-                'high',
3522
-                $callback_args
3523
-            );
3524
-        }
3525
-
3526
-        // register message type metaboxes
3527
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3528
-        foreach ($mt_boxes as $box => $label) {
3529
-            $callback_args = array(
3530
-                'template_path' => $mt_template_path,
3531
-                'template_args' => $mt_template_args[ $box ],
3532
-            );
3533
-            $mt = str_replace('_i_box', '', $box);
3534
-            add_meta_box(
3535
-                'espresso_' . $mt . '_inactive_mts',
3536
-                $label,
3537
-                function ($post, $metabox) {
3538
-                    echo EEH_Template::display_template(
3539
-                        $metabox["args"]["template_path"],
3540
-                        $metabox["args"]["template_args"],
3541
-                        true
3542
-                    );
3543
-                },
3544
-                $this->_current_screen->id,
3545
-                'side',
3546
-                'high',
3547
-                $callback_args
3548
-            );
3549
-        }
3550
-
3551
-        // register metabox for global messages settings but only when on the main site.  On single site installs this
3552
-        // will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3553
-        if (is_main_site()) {
3554
-            add_meta_box(
3555
-                'espresso_global_message_settings',
3556
-                esc_html__('Global Message Settings', 'event_espresso'),
3557
-                array($this, 'global_messages_settings_metabox_content'),
3558
-                $this->_current_screen->id,
3559
-                'normal',
3560
-                'low',
3561
-                array()
3562
-            );
3563
-        }
3564
-    }
3565
-
3566
-
3567
-    /**
3568
-     *  This generates the content for the global messages settings metabox.
3569
-     *
3570
-     * @return string
3571
-     * @throws EE_Error
3572
-     * @throws InvalidArgumentException
3573
-     * @throws ReflectionException
3574
-     * @throws InvalidDataTypeException
3575
-     * @throws InvalidInterfaceException
3576
-     */
3577
-    public function global_messages_settings_metabox_content()
3578
-    {
3579
-        $form = $this->_generate_global_settings_form();
3580
-        echo $form->form_open(
3581
-            $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3582
-            'POST'
3583
-        )
3584
-             . $form->get_html()
3585
-             . $form->form_close();
3586
-    }
3587
-
3588
-
3589
-    /**
3590
-     * This generates and returns the form object for the global messages settings.
3591
-     *
3592
-     * @return EE_Form_Section_Proper
3593
-     * @throws EE_Error
3594
-     * @throws InvalidArgumentException
3595
-     * @throws ReflectionException
3596
-     * @throws InvalidDataTypeException
3597
-     * @throws InvalidInterfaceException
3598
-     */
3599
-    protected function _generate_global_settings_form()
3600
-    {
3601
-        EE_Registry::instance()->load_helper('HTML');
3602
-        /** @var EE_Network_Core_Config $network_config */
3603
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3604
-
3605
-        return new EE_Form_Section_Proper(
3606
-            array(
3607
-                'name'            => 'global_messages_settings',
3608
-                'html_id'         => 'global_messages_settings',
3609
-                'html_class'      => 'form-table',
3610
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3611
-                'subsections'     => apply_filters(
3612
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3613
-                    array(
3614
-                        'do_messages_on_same_request' => new EE_Select_Input(
3615
-                            array(
3616
-                                true  => esc_html__("On the same request", "event_espresso"),
3617
-                                false => esc_html__("On a separate request", "event_espresso"),
3618
-                            ),
3619
-                            array(
3620
-                                'default'         => $network_config->do_messages_on_same_request,
3621
-                                'html_label_text' => esc_html__(
3622
-                                    'Generate and send all messages:',
3623
-                                    'event_espresso'
3624
-                                ),
3625
-                                'html_help_text'  => esc_html__(
3626
-                                    '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.',
3627
-                                    'event_espresso'
3628
-                                ),
3629
-                            )
3630
-                        ),
3631
-                        'delete_threshold'            => new EE_Select_Input(
3632
-                            array(
3633
-                                0  => esc_html__('Forever', 'event_espresso'),
3634
-                                3  => esc_html__('3 Months', 'event_espresso'),
3635
-                                6  => esc_html__('6 Months', 'event_espresso'),
3636
-                                9  => esc_html__('9 Months', 'event_espresso'),
3637
-                                12 => esc_html__('12 Months', 'event_espresso'),
3638
-                                24 => esc_html__('24 Months', 'event_espresso'),
3639
-                                36 => esc_html__('36 Months', 'event_espresso'),
3640
-                            ),
3641
-                            array(
3642
-                                'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3643
-                                'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3644
-                                'html_help_text'  => esc_html__(
3645
-                                    'You can control how long a record of processed messages is kept via this option.',
3646
-                                    'event_espresso'
3647
-                                ),
3648
-                            )
3649
-                        ),
3650
-                        'update_settings'             => new EE_Submit_Input(
3651
-                            array(
3652
-                                'default'         => esc_html__('Update', 'event_espresso'),
3653
-                                'html_label_text' => '&nbsp',
3654
-                            )
3655
-                        ),
3656
-                    )
3657
-                ),
3658
-            )
3659
-        );
3660
-    }
3661
-
3662
-
3663
-    /**
3664
-     * This handles updating the global settings set on the admin page.
3665
-     *
3666
-     * @throws EE_Error
3667
-     * @throws InvalidDataTypeException
3668
-     * @throws InvalidInterfaceException
3669
-     * @throws InvalidArgumentException
3670
-     * @throws ReflectionException
3671
-     */
3672
-    protected function _update_global_settings()
3673
-    {
3674
-        /** @var EE_Network_Core_Config $network_config */
3675
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3676
-        $messages_config = EE_Registry::instance()->CFG->messages;
3677
-        $form = $this->_generate_global_settings_form();
3678
-        if ($form->was_submitted()) {
3679
-            $form->receive_form_submission();
3680
-            if ($form->is_valid()) {
3681
-                $valid_data = $form->valid_data();
3682
-                foreach ($valid_data as $property => $value) {
3683
-                    $setter = 'set_' . $property;
3684
-                    if (method_exists($network_config, $setter)) {
3685
-                        $network_config->{$setter}($value);
3686
-                    } elseif (property_exists($network_config, $property)
3687
-                        && $network_config->{$property} !== $value
3688
-                    ) {
3689
-                        $network_config->{$property} = $value;
3690
-                    } elseif (property_exists($messages_config, $property)
3691
-                        && $messages_config->{$property} !== $value
3692
-                    ) {
3693
-                        $messages_config->{$property} = $value;
3694
-                    }
3695
-                }
3696
-                // only update if the form submission was valid!
3697
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3698
-                EE_Registry::instance()->CFG->update_espresso_config();
3699
-                EE_Error::overwrite_success();
3700
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3701
-            }
3702
-        }
3703
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3704
-    }
3705
-
3706
-
3707
-    /**
3708
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3709
-     *
3710
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3711
-     * @return string html formatted tabs
3712
-     * @throws DomainException
3713
-     */
3714
-    protected function _get_mt_tabs($tab_array)
3715
-    {
3716
-        $tab_array = (array) $tab_array;
3717
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3718
-        $tabs = '';
3719
-
3720
-        foreach ($tab_array as $tab) {
3721
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3722
-        }
3723
-
3724
-        return $tabs;
3725
-    }
3726
-
3727
-
3728
-    /**
3729
-     * This prepares the content of the messenger meta box admin settings
3730
-     *
3731
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3732
-     * @return string html formatted content
3733
-     * @throws DomainException
3734
-     */
3735
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3736
-    {
3737
-
3738
-        $fields = $messenger->get_admin_settings_fields();
3739
-        $settings_template_args['template_form_fields'] = '';
3740
-
3741
-        // is $messenger active?
3742
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3743
-
3744
-
3745
-        if (! empty($fields)) {
3746
-            $existing_settings = $messenger->get_existing_admin_settings();
3747
-
3748
-            foreach ($fields as $fldname => $fldprops) {
3749
-                $field_id = $messenger->name . '-' . $fldname;
3750
-                $template_form_field[ $field_id ] = array(
3751
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3752
-                    'label'      => $fldprops['label'],
3753
-                    'input'      => $fldprops['field_type'],
3754
-                    'type'       => $fldprops['value_type'],
3755
-                    'required'   => $fldprops['required'],
3756
-                    'validation' => $fldprops['validation'],
3757
-                    'value'      => isset($existing_settings[ $field_id ])
3758
-                        ? $existing_settings[ $field_id ]
3759
-                        : $fldprops['default'],
3760
-                    'css_class'  => '',
3761
-                    'format'     => $fldprops['format'],
3762
-                );
3763
-            }
3764
-
3765
-
3766
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3767
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3768
-                : '';
3769
-        }
3770
-
3771
-        // we also need some hidden fields
3772
-        $settings_template_args['hidden_fields'] = array(
3773
-            'messenger_settings[messenger]' => array(
3774
-                'type'  => 'hidden',
3775
-                'value' => $messenger->name,
3776
-            ),
3777
-            'type'                          => array(
3778
-                'type'  => 'hidden',
3779
-                'value' => 'messenger',
3780
-            ),
3781
-        );
3782
-
3783
-        // make sure any active message types that are existing are included in the hidden fields
3784
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3785
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3786
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3787
-                    'type'  => 'hidden',
3788
-                    'value' => $mt,
3789
-                );
3790
-            }
3791
-        }
3792
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3793
-            $settings_template_args['hidden_fields'],
3794
-            'array'
3795
-        );
3796
-        $active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3797
-
3798
-        $settings_template_args['messenger'] = $messenger->name;
3799
-        $settings_template_args['description'] = $messenger->description;
3800
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3801
-
3802
-
3803
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3804
-            $messenger->name
3805
-        )
3806
-            ? $settings_template_args['show_hide_edit_form']
3807
-            : ' hidden';
3808
-
3809
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3810
-            ? ' hidden'
3811
-            : $settings_template_args['show_hide_edit_form'];
3812
-
3813
-
3814
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3815
-        $settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3816
-        $settings_template_args['on_off_status'] = $active ? true : false;
3817
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3818
-        $content = EEH_Template::display_template(
3819
-            $template,
3820
-            $settings_template_args,
3821
-            true
3822
-        );
3823
-
3824
-        return $content;
3825
-    }
3826
-
3827
-
3828
-    /**
3829
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3830
-     *
3831
-     * @throws DomainException
3832
-     * @throws EE_Error
3833
-     * @throws InvalidDataTypeException
3834
-     * @throws InvalidInterfaceException
3835
-     * @throws InvalidArgumentException
3836
-     * @throws ReflectionException
3837
-     */
3838
-    public function activate_messenger_toggle()
3839
-    {
3840
-        $success = true;
3841
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3842
-        // let's check that we have required data
3843
-        if (! isset($this->_req_data['messenger'])) {
3844
-            EE_Error::add_error(
3845
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3846
-                __FILE__,
3847
-                __FUNCTION__,
3848
-                __LINE__
3849
-            );
3850
-            $success = false;
3851
-        }
3852
-
3853
-        // do a nonce check here since we're not arriving via a normal route
3854
-        $nonce = isset($this->_req_data['activate_nonce'])
3855
-            ? sanitize_text_field($this->_req_data['activate_nonce'])
3856
-            : '';
3857
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3858
-
3859
-        $this->_verify_nonce($nonce, $nonce_ref);
3860
-
3861
-
3862
-        if (! isset($this->_req_data['status'])) {
3863
-            EE_Error::add_error(
3864
-                esc_html__(
3865
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3866
-                    'event_espresso'
3867
-                ),
3868
-                __FILE__,
3869
-                __FUNCTION__,
3870
-                __LINE__
3871
-            );
3872
-            $success = false;
3873
-        }
3874
-
3875
-        // do check to verify we have a valid status.
3876
-        $status = $this->_req_data['status'];
3877
-
3878
-        if ($status !== 'off' && $status !== 'on') {
3879
-            EE_Error::add_error(
3880
-                sprintf(
3881
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3882
-                    $this->_req_data['status']
3883
-                ),
3884
-                __FILE__,
3885
-                __FUNCTION__,
3886
-                __LINE__
3887
-            );
3888
-            $success = false;
3889
-        }
3890
-
3891
-        if ($success) {
3892
-            // made it here?  Stop dawdling then!!
3893
-            $success = $status === 'off'
3894
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3895
-                : $this->_activate_messenger($this->_req_data['messenger']);
3896
-        }
3897
-
3898
-        $this->_template_args['success'] = $success;
3899
-
3900
-        // no special instructions so let's just do the json return (which should automatically do all the special stuff).
3901
-        $this->_return_json();
3902
-    }
3903
-
3904
-
3905
-    /**
3906
-     * used by ajax from the messages settings page to activate|deactivate a message type
3907
-     *
3908
-     * @throws DomainException
3909
-     * @throws EE_Error
3910
-     * @throws ReflectionException
3911
-     * @throws InvalidDataTypeException
3912
-     * @throws InvalidInterfaceException
3913
-     * @throws InvalidArgumentException
3914
-     */
3915
-    public function activate_mt_toggle()
3916
-    {
3917
-        $success = true;
3918
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3919
-
3920
-        // let's make sure we have the necessary data
3921
-        if (! isset($this->_req_data['message_type'])) {
3922
-            EE_Error::add_error(
3923
-                esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3924
-                __FILE__,
3925
-                __FUNCTION__,
3926
-                __LINE__
3927
-            );
3928
-            $success = false;
3929
-        }
3930
-
3931
-        if (! isset($this->_req_data['messenger'])) {
3932
-            EE_Error::add_error(
3933
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3934
-                __FILE__,
3935
-                __FUNCTION__,
3936
-                __LINE__
3937
-            );
3938
-            $success = false;
3939
-        }
3940
-
3941
-        if (! isset($this->_req_data['status'])) {
3942
-            EE_Error::add_error(
3943
-                esc_html__(
3944
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3945
-                    'event_espresso'
3946
-                ),
3947
-                __FILE__,
3948
-                __FUNCTION__,
3949
-                __LINE__
3950
-            );
3951
-            $success = false;
3952
-        }
3953
-
3954
-
3955
-        // do check to verify we have a valid status.
3956
-        $status = $this->_req_data['status'];
3957
-
3958
-        if ($status !== 'activate' && $status !== 'deactivate') {
3959
-            EE_Error::add_error(
3960
-                sprintf(
3961
-                    esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3962
-                    $this->_req_data['status']
3963
-                ),
3964
-                __FILE__,
3965
-                __FUNCTION__,
3966
-                __LINE__
3967
-            );
3968
-            $success = false;
3969
-        }
3970
-
3971
-
3972
-        // do a nonce check here since we're not arriving via a normal route
3973
-        $nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3974
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3975
-
3976
-        $this->_verify_nonce($nonce, $nonce_ref);
3977
-
3978
-        if ($success) {
3979
-            // made it here? um, what are you waiting for then?
3980
-            $success = $status === 'deactivate'
3981
-                ? $this->_deactivate_message_type_for_messenger(
3982
-                    $this->_req_data['messenger'],
3983
-                    $this->_req_data['message_type']
3984
-                )
3985
-                : $this->_activate_message_type_for_messenger(
3986
-                    $this->_req_data['messenger'],
3987
-                    $this->_req_data['message_type']
3988
-                );
3989
-        }
3990
-
3991
-        $this->_template_args['success'] = $success;
3992
-        $this->_return_json();
3993
-    }
3994
-
3995
-
3996
-    /**
3997
-     * Takes care of processing activating a messenger and preparing the appropriate response.
3998
-     *
3999
-     * @param string $messenger_name The name of the messenger being activated
4000
-     * @return bool
4001
-     * @throws DomainException
4002
-     * @throws EE_Error
4003
-     * @throws InvalidArgumentException
4004
-     * @throws ReflectionException
4005
-     * @throws InvalidDataTypeException
4006
-     * @throws InvalidInterfaceException
4007
-     */
4008
-    protected function _activate_messenger($messenger_name)
4009
-    {
4010
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4011
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4012
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger
4013
-            ? $active_messenger->get_default_message_types()
4014
-            : array();
4015
-
4016
-        // ensure is active
4017
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
4018
-
4019
-        // set response_data for reload
4020
-        foreach ($message_types_to_activate as $message_type_name) {
4021
-            /** @var EE_message_type $message_type */
4022
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4023
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4024
-                $messenger_name,
4025
-                $message_type_name
4026
-            )
4027
-                && $message_type instanceof EE_message_type
4028
-            ) {
4029
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
4030
-                if ($message_type->get_admin_settings_fields()) {
4031
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
4032
-                }
4033
-            }
4034
-        }
4035
-
4036
-        // add success message for activating messenger
4037
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4038
-    }
4039
-
4040
-
4041
-    /**
4042
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
4043
-     *
4044
-     * @param string $messenger_name The name of the messenger being activated
4045
-     * @return bool
4046
-     * @throws DomainException
4047
-     * @throws EE_Error
4048
-     * @throws InvalidArgumentException
4049
-     * @throws ReflectionException
4050
-     * @throws InvalidDataTypeException
4051
-     * @throws InvalidInterfaceException
4052
-     */
4053
-    protected function _deactivate_messenger($messenger_name)
4054
-    {
4055
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4056
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4057
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
4058
-
4059
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4060
-    }
4061
-
4062
-
4063
-    /**
4064
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4065
-     *
4066
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
4067
-     * @param string $message_type_name The name of the message type being activated for the messenger
4068
-     * @return bool
4069
-     * @throws DomainException
4070
-     * @throws EE_Error
4071
-     * @throws InvalidArgumentException
4072
-     * @throws ReflectionException
4073
-     * @throws InvalidDataTypeException
4074
-     * @throws InvalidInterfaceException
4075
-     */
4076
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4077
-    {
4078
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4079
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4080
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4081
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4082
-
4083
-        // ensure is active
4084
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
4085
-
4086
-        // set response for load
4087
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4088
-            $messenger_name,
4089
-            $message_type_name
4090
-        )
4091
-        ) {
4092
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
4093
-            if ($message_type_to_activate->get_admin_settings_fields()) {
4094
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
4095
-            }
4096
-        }
4097
-
4098
-        return $this->_setup_response_message_for_activating_messenger_with_message_types(
4099
-            $active_messenger,
4100
-            $message_type_to_activate
4101
-        );
4102
-    }
4103
-
4104
-
4105
-    /**
4106
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4107
-     *
4108
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4109
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
4110
-     * @return bool
4111
-     * @throws DomainException
4112
-     * @throws EE_Error
4113
-     * @throws InvalidArgumentException
4114
-     * @throws ReflectionException
4115
-     * @throws InvalidDataTypeException
4116
-     * @throws InvalidInterfaceException
4117
-     */
4118
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4119
-    {
4120
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4121
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4122
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4123
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4124
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4125
-
4126
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4127
-            $active_messenger,
4128
-            $message_type_to_deactivate
4129
-        );
4130
-    }
4131
-
4132
-
4133
-    /**
4134
-     * This just initializes the defaults for activating messenger and message type responses.
4135
-     */
4136
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
4137
-    {
4138
-        $this->_template_args['data']['active_mts'] = array();
4139
-        $this->_template_args['data']['mt_reload'] = array();
4140
-    }
4141
-
4142
-
4143
-    /**
4144
-     * Setup appropriate response for activating a messenger and/or message types
4145
-     *
4146
-     * @param EE_messenger         $messenger
4147
-     * @param EE_message_type|null $message_type
4148
-     * @return bool
4149
-     * @throws DomainException
4150
-     * @throws EE_Error
4151
-     * @throws InvalidArgumentException
4152
-     * @throws ReflectionException
4153
-     * @throws InvalidDataTypeException
4154
-     * @throws InvalidInterfaceException
4155
-     */
4156
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
4157
-        $messenger,
4158
-        EE_Message_Type $message_type = null
4159
-    ) {
4160
-        // if $messenger isn't a valid messenger object then get out.
4161
-        if (! $messenger instanceof EE_Messenger) {
4162
-            EE_Error::add_error(
4163
-                esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4164
-                __FILE__,
4165
-                __FUNCTION__,
4166
-                __LINE__
4167
-            );
4168
-
4169
-            return false;
4170
-        }
4171
-        // activated
4172
-        if ($this->_template_args['data']['active_mts']) {
4173
-            EE_Error::overwrite_success();
4174
-            // activated a message type with the messenger
4175
-            if ($message_type instanceof EE_message_type) {
4176
-                EE_Error::add_success(
4177
-                    sprintf(
4178
-                        esc_html__(
4179
-                            '%s message type has been successfully activated with the %s messenger',
4180
-                            'event_espresso'
4181
-                        ),
4182
-                        ucwords($message_type->label['singular']),
4183
-                        ucwords($messenger->label['singular'])
4184
-                    )
4185
-                );
4186
-
4187
-                // if message type was invoice then let's make sure we activate the invoice payment method.
4188
-                if ($message_type->name === 'invoice') {
4189
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
4190
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4191
-                    if ($pm instanceof EE_Payment_Method) {
4192
-                        EE_Error::add_attention(
4193
-                            esc_html__(
4194
-                                '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.',
4195
-                                'event_espresso'
4196
-                            )
4197
-                        );
4198
-                    }
4199
-                }
4200
-                // just toggles the entire messenger
4201
-            } else {
4202
-                EE_Error::add_success(
4203
-                    sprintf(
4204
-                        esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4205
-                        ucwords($messenger->label['singular'])
4206
-                    )
4207
-                );
4208
-            }
4209
-
4210
-            return true;
4211
-
4212
-            // possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4213
-            // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4214
-            // in which case we just give a success message for the messenger being successfully activated.
4215
-        } else {
4216
-            if (! $messenger->get_default_message_types()) {
4217
-                // messenger doesn't have any default message types so still a success.
4218
-                EE_Error::add_success(
4219
-                    sprintf(
4220
-                        esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4221
-                        ucwords($messenger->label['singular'])
4222
-                    )
4223
-                );
4224
-
4225
-                return true;
4226
-            } else {
4227
-                EE_Error::add_error(
4228
-                    $message_type instanceof EE_message_type
4229
-                        ? sprintf(
4230
-                            esc_html__(
4231
-                                '%s message type was not successfully activated with the %s messenger',
4232
-                                'event_espresso'
4233
-                            ),
4234
-                            ucwords($message_type->label['singular']),
4235
-                            ucwords($messenger->label['singular'])
4236
-                        )
4237
-                        : sprintf(
4238
-                            esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4239
-                            ucwords($messenger->label['singular'])
4240
-                        ),
4241
-                    __FILE__,
4242
-                    __FUNCTION__,
4243
-                    __LINE__
4244
-                );
4245
-
4246
-                return false;
4247
-            }
4248
-        }
4249
-    }
4250
-
4251
-
4252
-    /**
4253
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
4254
-     *
4255
-     * @param EE_messenger         $messenger
4256
-     * @param EE_message_type|null $message_type
4257
-     * @return bool
4258
-     * @throws DomainException
4259
-     * @throws EE_Error
4260
-     * @throws InvalidArgumentException
4261
-     * @throws ReflectionException
4262
-     * @throws InvalidDataTypeException
4263
-     * @throws InvalidInterfaceException
4264
-     */
4265
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4266
-        $messenger,
4267
-        EE_message_type $message_type = null
4268
-    ) {
4269
-        EE_Error::overwrite_success();
4270
-
4271
-        // if $messenger isn't a valid messenger object then get out.
4272
-        if (! $messenger instanceof EE_Messenger) {
4273
-            EE_Error::add_error(
4274
-                esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4275
-                __FILE__,
4276
-                __FUNCTION__,
4277
-                __LINE__
4278
-            );
4279
-
4280
-            return false;
4281
-        }
4282
-
4283
-        if ($message_type instanceof EE_message_type) {
4284
-            $message_type_name = $message_type->name;
4285
-            EE_Error::add_success(
4286
-                sprintf(
4287
-                    esc_html__(
4288
-                        '%s message type has been successfully deactivated for the %s messenger.',
4289
-                        'event_espresso'
4290
-                    ),
4291
-                    ucwords($message_type->label['singular']),
4292
-                    ucwords($messenger->label['singular'])
4293
-                )
4294
-            );
4295
-        } else {
4296
-            $message_type_name = '';
4297
-            EE_Error::add_success(
4298
-                sprintf(
4299
-                    esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4300
-                    ucwords($messenger->label['singular'])
4301
-                )
4302
-            );
4303
-        }
4304
-
4305
-        // if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4306
-        if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4307
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
4308
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4309
-            if ($count_updated > 0) {
4310
-                $msg = $message_type_name === 'invoice'
4311
-                    ? esc_html__(
4312
-                        '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.',
4313
-                        'event_espresso'
4314
-                    )
4315
-                    : esc_html__(
4316
-                        '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.',
4317
-                        'event_espresso'
4318
-                    );
4319
-                EE_Error::add_attention($msg);
4320
-            }
4321
-        }
4322
-
4323
-        return true;
4324
-    }
4325
-
4326
-
4327
-    /**
4328
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4329
-     *
4330
-     * @throws DomainException
4331
-     */
4332
-    public function update_mt_form()
4333
-    {
4334
-        if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4335
-            EE_Error::add_error(
4336
-                esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4337
-                __FILE__,
4338
-                __FUNCTION__,
4339
-                __LINE__
4340
-            );
4341
-            $this->_return_json();
4342
-        }
4343
-
4344
-        $message_types = $this->get_installed_message_types();
4345
-
4346
-        $message_type = $message_types[ $this->_req_data['message_type'] ];
4347
-        $messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4348
-
4349
-        $content = $this->_message_type_settings_content(
4350
-            $message_type,
4351
-            $messenger,
4352
-            true
4353
-        );
4354
-        $this->_template_args['success'] = true;
4355
-        $this->_template_args['content'] = $content;
4356
-        $this->_return_json();
4357
-    }
4358
-
4359
-
4360
-    /**
4361
-     * this handles saving the settings for a messenger or message type
4362
-     *
4363
-     */
4364
-    public function save_settings()
4365
-    {
4366
-        if (! isset($this->_req_data['type'])) {
4367
-            EE_Error::add_error(
4368
-                esc_html__(
4369
-                    'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4370
-                    'event_espresso'
4371
-                ),
4372
-                __FILE__,
4373
-                __FUNCTION__,
4374
-                __LINE__
4375
-            );
4376
-            $this->_template_args['error'] = true;
4377
-            $this->_return_json();
4378
-        }
4379
-
4380
-
4381
-        if ($this->_req_data['type'] === 'messenger') {
4382
-            // this should be an array.
4383
-            $settings = $this->_req_data['messenger_settings'];
4384
-            $messenger = $settings['messenger'];
4385
-            // let's setup the settings data
4386
-            foreach ($settings as $key => $value) {
4387
-                switch ($key) {
4388
-                    case 'messenger':
4389
-                        unset($settings['messenger']);
4390
-                        break;
4391
-                    case 'message_types':
4392
-                        unset($settings['message_types']);
4393
-                        break;
4394
-                    default:
4395
-                        $settings[ $key ] = $value;
4396
-                        break;
4397
-                }
4398
-            }
4399
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4400
-        } elseif ($this->_req_data['type'] === 'message_type') {
4401
-            $settings = $this->_req_data['message_type_settings'];
4402
-            $messenger = $settings['messenger'];
4403
-            $message_type = $settings['message_type'];
4404
-
4405
-            foreach ($settings as $key => $value) {
4406
-                switch ($key) {
4407
-                    case 'messenger':
4408
-                        unset($settings['messenger']);
4409
-                        break;
4410
-                    case 'message_type':
4411
-                        unset($settings['message_type']);
4412
-                        break;
4413
-                    default:
4414
-                        $settings[ $key ] = $value;
4415
-                        break;
4416
-                }
4417
-            }
4418
-
4419
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4420
-        }
4421
-
4422
-        // okay we should have the data all setup.  Now we just update!
4423
-        $success = $this->_message_resource_manager->update_active_messengers_option();
4424
-
4425
-        if ($success) {
4426
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
4427
-        } else {
4428
-            EE_Error::add_error(
4429
-                esc_html__(
4430
-                    'Settings did not get updated',
4431
-                    'event_espresso'
4432
-                ),
4433
-                __FILE__,
4434
-                __FUNCTION__,
4435
-                __LINE__
4436
-            );
4437
-        }
4438
-
4439
-        $this->_template_args['success'] = $success;
4440
-        $this->_return_json();
4441
-    }
4442
-
4443
-
4444
-
4445
-
4446
-    /**  EE MESSAGE PROCESSING ACTIONS **/
4447
-
4448
-
4449
-    /**
4450
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4451
-     * However, this does not send immediately, it just queues for sending.
4452
-     *
4453
-     * @since 4.9.0
4454
-     * @throws EE_Error
4455
-     * @throws InvalidDataTypeException
4456
-     * @throws InvalidInterfaceException
4457
-     * @throws InvalidArgumentException
4458
-     * @throws ReflectionException
4459
-     */
4460
-    protected function _generate_now()
4461
-    {
4462
-        EED_Messages::generate_now($this->_get_msg_ids_from_request());
4463
-        $this->_redirect_after_action(false, '', '', array(), true);
4464
-    }
4465
-
4466
-
4467
-    /**
4468
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4469
-     * are EEM_Message::status_resend or EEM_Message::status_idle
4470
-     *
4471
-     * @since 4.9.0
4472
-     * @throws EE_Error
4473
-     * @throws InvalidDataTypeException
4474
-     * @throws InvalidInterfaceException
4475
-     * @throws InvalidArgumentException
4476
-     * @throws ReflectionException
4477
-     */
4478
-    protected function _generate_and_send_now()
4479
-    {
4480
-        EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4481
-        $this->_redirect_after_action(false, '', '', array(), true);
4482
-    }
4483
-
4484
-
4485
-    /**
4486
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4487
-     *
4488
-     * @since 4.9.0
4489
-     * @throws EE_Error
4490
-     * @throws InvalidDataTypeException
4491
-     * @throws InvalidInterfaceException
4492
-     * @throws InvalidArgumentException
4493
-     * @throws ReflectionException
4494
-     */
4495
-    protected function _queue_for_resending()
4496
-    {
4497
-        EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4498
-        $this->_redirect_after_action(false, '', '', array(), true);
4499
-    }
4500
-
4501
-
4502
-    /**
4503
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4504
-     *
4505
-     * @since 4.9.0
4506
-     * @throws EE_Error
4507
-     * @throws InvalidDataTypeException
4508
-     * @throws InvalidInterfaceException
4509
-     * @throws InvalidArgumentException
4510
-     * @throws ReflectionException
4511
-     */
4512
-    protected function _send_now()
4513
-    {
4514
-        EED_Messages::send_now($this->_get_msg_ids_from_request());
4515
-        $this->_redirect_after_action(false, '', '', array(), true);
4516
-    }
4517
-
4518
-
4519
-    /**
4520
-     * Deletes EE_messages for IDs in the request.
4521
-     *
4522
-     * @since 4.9.0
4523
-     * @throws EE_Error
4524
-     * @throws InvalidDataTypeException
4525
-     * @throws InvalidInterfaceException
4526
-     * @throws InvalidArgumentException
4527
-     */
4528
-    protected function _delete_ee_messages()
4529
-    {
4530
-        $msg_ids = $this->_get_msg_ids_from_request();
4531
-        $deleted_count = 0;
4532
-        foreach ($msg_ids as $msg_id) {
4533
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4534
-                $deleted_count++;
4535
-            }
4536
-        }
4537
-        if ($deleted_count) {
4538
-            EE_Error::add_success(
4539
-                esc_html(
4540
-                    _n(
4541
-                        'Message successfully deleted',
4542
-                        'Messages successfully deleted',
4543
-                        $deleted_count,
4544
-                        'event_espresso'
4545
-                    )
4546
-                )
4547
-            );
4548
-            $this->_redirect_after_action(
4549
-                false,
4550
-                '',
4551
-                '',
4552
-                array(),
4553
-                true
4554
-            );
4555
-        } else {
4556
-            EE_Error::add_error(
4557
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4558
-                __FILE__,
4559
-                __FUNCTION__,
4560
-                __LINE__
4561
-            );
4562
-            $this->_redirect_after_action(false, '', '', array(), true);
4563
-        }
4564
-    }
4565
-
4566
-
4567
-    /**
4568
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4569
-     *
4570
-     * @since 4.9.0
4571
-     * @return array
4572
-     */
4573
-    protected function _get_msg_ids_from_request()
4574
-    {
4575
-        if (! isset($this->_req_data['MSG_ID'])) {
4576
-            return array();
4577
-        }
4578
-
4579
-        return is_array($this->_req_data['MSG_ID'])
4580
-            ? array_keys($this->_req_data['MSG_ID'])
4581
-            : array($this->_req_data['MSG_ID']);
4582
-    }
2662
+		$output = ob_get_contents();
2663
+		ob_clean();
2664
+		$this->_context_switcher = $output;
2665
+	}
2666
+
2667
+
2668
+	/**
2669
+	 * utility for sanitizing new values coming in.
2670
+	 * Note: this is only used when updating a context.
2671
+	 *
2672
+	 * @access protected
2673
+	 *
2674
+	 * @param int $index This helps us know which template field to select from the request array.
2675
+	 *
2676
+	 * @return array
2677
+	 */
2678
+	protected function _set_message_template_column_values($index)
2679
+	{
2680
+		if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2681
+			foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2682
+				$this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2683
+			}
2684
+		}
2685
+
2686
+
2687
+		$set_column_values = array(
2688
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2689
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2690
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2691
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2692
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2693
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2694
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2695
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2696
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2697
+				? absint($this->_req_data['MTP_is_global'])
2698
+				: 0,
2699
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2700
+				? absint($this->_req_data['MTP_is_override'])
2701
+				: 0,
2702
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2703
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2704
+		);
2705
+
2706
+
2707
+		return $set_column_values;
2708
+	}
2709
+
2710
+
2711
+	protected function _insert_or_update_message_template($new = false)
2712
+	{
2713
+
2714
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2715
+		$success = 0;
2716
+		$override = false;
2717
+
2718
+		// setup notices description
2719
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2720
+
2721
+		// need the message type and messenger objects to be able to use the labels for the notices
2722
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2723
+		$messenger_label = $messenger_object instanceof EE_messenger
2724
+			? ucwords($messenger_object->label['singular'])
2725
+			: '';
2726
+
2727
+		$message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2728
+			? $this->_req_data['MTP_message_type']
2729
+			: '';
2730
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2731
+
2732
+		$message_type_label = $message_type_object instanceof EE_message_type
2733
+			? ucwords($message_type_object->label['singular'])
2734
+			: '';
2735
+
2736
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2737
+			? $this->_req_data['MTP_context']
2738
+			: '';
2739
+		$context = ucwords(str_replace('_', ' ', $context_slug));
2740
+
2741
+		$item_desc = $messenger_label && $message_type_label
2742
+			? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2743
+			: '';
2744
+		$item_desc .= 'Message Template';
2745
+		$query_args = array();
2746
+		$edit_array = array();
2747
+		$action_desc = '';
2748
+
2749
+		// if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2750
+		// user to edit.
2751
+		if ($new) {
2752
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2753
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2754
+				if (empty($edit_array)) {
2755
+					$success = 0;
2756
+				} else {
2757
+					$success = 1;
2758
+					$edit_array = $edit_array[0];
2759
+					$query_args = array(
2760
+						'id'      => $edit_array['GRP_ID'],
2761
+						'context' => $edit_array['MTP_context'],
2762
+						'action'  => 'edit_message_template',
2763
+					);
2764
+				}
2765
+			}
2766
+			$action_desc = 'created';
2767
+		} else {
2768
+			$MTPG = EEM_Message_Template_Group::instance();
2769
+			$MTP = EEM_Message_Template::instance();
2770
+
2771
+
2772
+			// run update for each template field in displayed context
2773
+			if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2774
+				EE_Error::add_error(
2775
+					esc_html__(
2776
+						'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2777
+						'event_espresso'
2778
+					),
2779
+					__FILE__,
2780
+					__FUNCTION__,
2781
+					__LINE__
2782
+				);
2783
+				$success = 0;
2784
+			} else {
2785
+				// first validate all fields!
2786
+				// this filter allows client code to add its own validation to the template fields as well.
2787
+				// returning an empty array means everything passed validation.
2788
+				// errors in validation should be represented in an array with the following shape:
2789
+				// array(
2790
+				//   'fieldname' => array(
2791
+				//          'msg' => 'error message'
2792
+				//          'value' => 'value for field producing error'
2793
+				// )
2794
+				$custom_validation = (array) apply_filters(
2795
+					'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2796
+					array(),
2797
+					$this->_req_data['MTP_template_fields'],
2798
+					$context_slug,
2799
+					$messenger_slug,
2800
+					$message_type_slug
2801
+				);
2802
+
2803
+				$system_validation = $MTPG->validate(
2804
+					$this->_req_data['MTP_template_fields'],
2805
+					$context_slug,
2806
+					$messenger_slug,
2807
+					$message_type_slug
2808
+				);
2809
+
2810
+				$system_validation = ! is_array($system_validation) && $system_validation ? array()
2811
+					: $system_validation;
2812
+				$validates = array_merge($custom_validation, $system_validation);
2813
+
2814
+				// if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2815
+				// appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2816
+				//  WE need to make sure there is no actual error messages in validates.
2817
+				if (is_array($validates) && ! empty($validates)) {
2818
+					// add the transient so when the form loads we know which fields to highlight
2819
+					$this->_add_transient('edit_message_template', $validates);
2820
+
2821
+					$success = 0;
2822
+
2823
+					// setup notices
2824
+					foreach ($validates as $field => $error) {
2825
+						if (isset($error['msg'])) {
2826
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2827
+						}
2828
+					}
2829
+				} else {
2830
+					$set_column_values = array();
2831
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2832
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2833
+
2834
+						$where_cols_n_values = array(
2835
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2836
+						);
2837
+						// if they aren't allowed to use all JS, restrict them to just posty-y tags
2838
+						if (! current_user_can('unfiltered_html')) {
2839
+							if (is_array($set_column_values['MTP_content'])) {
2840
+								foreach ($set_column_values['MTP_content'] as $key => $value) {
2841
+									// remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2842
+									// only removes slashes from double-quotes, so attributes using single quotes always
2843
+									// appear invalid.) But currently the models expect slashed data, so after wp_kses
2844
+									// runs we need to re-slash the data. Sheesh. See
2845
+									// https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2846
+									$set_column_values['MTP_content'][ $key ] = addslashes(
2847
+										wp_kses(
2848
+											stripslashes($value),
2849
+											wp_kses_allowed_html('post')
2850
+										)
2851
+									);
2852
+								}
2853
+							} else {
2854
+								$set_column_values['MTP_content'] = wp_kses(
2855
+									$set_column_values['MTP_content'],
2856
+									wp_kses_allowed_html('post')
2857
+								);
2858
+							}
2859
+						}
2860
+						$message_template_fields = array(
2861
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2862
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2863
+							'MTP_context'        => $set_column_values['MTP_context'],
2864
+							'MTP_content'        => $set_column_values['MTP_content'],
2865
+						);
2866
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2867
+							if ($updated === false) {
2868
+								EE_Error::add_error(
2869
+									sprintf(
2870
+										esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2871
+										$template_field
2872
+									),
2873
+									__FILE__,
2874
+									__FUNCTION__,
2875
+									__LINE__
2876
+								);
2877
+							} else {
2878
+								$success = 1;
2879
+							}
2880
+						} else {
2881
+							// only do this logic if we don't have a MTP_ID for this field
2882
+							if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2883
+								// this has already been through the template field validator and sanitized, so it will be
2884
+								// safe to insert this field.  Why insert?  This typically happens when we introduce a new
2885
+								// message template field in a messenger/message type and existing users don't have the
2886
+								// default setup for it.
2887
+								// @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2888
+								$updated = $MTP->insert($message_template_fields);
2889
+								if (! $updated || is_wp_error($updated)) {
2890
+									EE_Error::add_error(
2891
+										sprintf(
2892
+											esc_html__('%s field could not be updated.', 'event_espresso'),
2893
+											$template_field
2894
+										),
2895
+										__FILE__,
2896
+										__FUNCTION__,
2897
+										__LINE__
2898
+									);
2899
+									$success = 0;
2900
+								} else {
2901
+									$success = 1;
2902
+								}
2903
+							}
2904
+						}
2905
+						$action_desc = 'updated';
2906
+					}
2907
+
2908
+					// we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2909
+					$mtpg_fields = array(
2910
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2911
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2912
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2913
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2914
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2915
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2916
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2917
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2918
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2919
+							: '',
2920
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2921
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2922
+							: '',
2923
+					);
2924
+
2925
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2926
+					$updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2927
+
2928
+					if ($updated === false) {
2929
+						EE_Error::add_error(
2930
+							sprintf(
2931
+								esc_html__(
2932
+									'The Message Template Group (%d) was NOT updated for some reason',
2933
+									'event_espresso'
2934
+								),
2935
+								$set_column_values['GRP_ID']
2936
+							),
2937
+							__FILE__,
2938
+							__FUNCTION__,
2939
+							__LINE__
2940
+						);
2941
+					} else {
2942
+						// k now we need to ensure the template_pack and template_variation fields are set.
2943
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2944
+							? $this->_req_data['MTP_template_pack']
2945
+							: 'default';
2946
+
2947
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2948
+							? $this->_req_data['MTP_template_variation']
2949
+							: 'default';
2950
+
2951
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2952
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2953
+							$mtpg_obj->set_template_pack_name($template_pack);
2954
+							$mtpg_obj->set_template_pack_variation($template_variation);
2955
+						}
2956
+						$success = 1;
2957
+					}
2958
+				}
2959
+			}
2960
+		}
2961
+
2962
+		// we return things differently if doing ajax
2963
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2964
+			$this->_template_args['success'] = $success;
2965
+			$this->_template_args['error'] = ! $success ? true : false;
2966
+			$this->_template_args['content'] = '';
2967
+			$this->_template_args['data'] = array(
2968
+				'grpID'        => $edit_array['GRP_ID'],
2969
+				'templateName' => $edit_array['template_name'],
2970
+			);
2971
+			if ($success) {
2972
+				EE_Error::overwrite_success();
2973
+				EE_Error::add_success(
2974
+					esc_html__(
2975
+						'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.',
2976
+						'event_espresso'
2977
+					)
2978
+				);
2979
+			}
2980
+
2981
+			$this->_return_json();
2982
+		}
2983
+
2984
+
2985
+		// was a test send triggered?
2986
+		if (isset($this->_req_data['test_button'])) {
2987
+			EE_Error::overwrite_success();
2988
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2989
+			$override = true;
2990
+		}
2991
+
2992
+		if (empty($query_args)) {
2993
+			$query_args = array(
2994
+				'id'      => $this->_req_data['GRP_ID'],
2995
+				'context' => $context_slug,
2996
+				'action'  => 'edit_message_template',
2997
+			);
2998
+		}
2999
+
3000
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
3001
+	}
3002
+
3003
+
3004
+	/**
3005
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
3006
+	 *
3007
+	 * @param  string $context      what context being tested
3008
+	 * @param  string $messenger    messenger being tested
3009
+	 * @param  string $message_type message type being tested
3010
+	 * @throws EE_Error
3011
+	 * @throws InvalidArgumentException
3012
+	 * @throws InvalidDataTypeException
3013
+	 * @throws InvalidInterfaceException
3014
+	 */
3015
+	protected function _do_test_send($context, $messenger, $message_type)
3016
+	{
3017
+		// set things up for preview
3018
+		$this->_req_data['messenger'] = $messenger;
3019
+		$this->_req_data['message_type'] = $message_type;
3020
+		$this->_req_data['context'] = $context;
3021
+		$this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
3022
+		$active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
3023
+
3024
+		// let's save any existing fields that might be required by the messenger
3025
+		if (isset($this->_req_data['test_settings_fld'])
3026
+			&& $active_messenger instanceof EE_messenger
3027
+			&& apply_filters(
3028
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3029
+				true,
3030
+				$this->_req_data['test_settings_fld'],
3031
+				$active_messenger
3032
+			)
3033
+		) {
3034
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
3035
+		}
3036
+
3037
+		/**
3038
+		 * Use filter to add additional controls on whether message can send or not
3039
+		 */
3040
+		if (apply_filters(
3041
+			'FHEE__Messages_Admin_Page__do_test_send__can_send',
3042
+			true,
3043
+			$context,
3044
+			$this->_req_data,
3045
+			$messenger,
3046
+			$message_type
3047
+		)) {
3048
+			if (EEM_Event::instance()->count() > 0) {
3049
+				$success = $this->_preview_message(true);
3050
+				if ($success) {
3051
+					EE_Error::add_success(__('Test message sent', 'event_espresso'));
3052
+				} else {
3053
+					EE_Error::add_error(
3054
+						esc_html__('The test message was not sent', 'event_espresso'),
3055
+						__FILE__,
3056
+						__FUNCTION__,
3057
+						__LINE__
3058
+					);
3059
+				}
3060
+			} else {
3061
+				$this->noEventsErrorMessage(true);
3062
+			}
3063
+		}
3064
+	}
3065
+
3066
+
3067
+	/**
3068
+	 * _generate_new_templates
3069
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3070
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3071
+	 * for the event.
3072
+	 *
3073
+	 *
3074
+	 * @param  string $messenger     the messenger we are generating templates for
3075
+	 * @param array   $message_types array of message types that the templates are generated for.
3076
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3077
+	 *                               indicate the message_template_group being used as the base.
3078
+	 *
3079
+	 * @param bool    $global
3080
+	 *
3081
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
3082
+	 *                               encountering problems.
3083
+	 * @throws EE_Error
3084
+	 */
3085
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3086
+	{
3087
+
3088
+		// if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3089
+		// just don't generate any templates.
3090
+		if (empty($message_types)) {
3091
+			return true;
3092
+		}
3093
+
3094
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3095
+	}
3096
+
3097
+
3098
+	/**
3099
+	 * [_trash_or_restore_message_template]
3100
+	 *
3101
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3102
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3103
+	 *                        an individual context (FALSE).
3104
+	 * @return void
3105
+	 * @throws EE_Error
3106
+	 * @throws InvalidArgumentException
3107
+	 * @throws InvalidDataTypeException
3108
+	 * @throws InvalidInterfaceException
3109
+	 */
3110
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
3111
+	{
3112
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3113
+		$MTP = EEM_Message_Template_Group::instance();
3114
+
3115
+		$success = 1;
3116
+
3117
+		// incoming GRP_IDs
3118
+		if ($all) {
3119
+			// Checkboxes
3120
+			if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3121
+				// if array has more than one element then success message should be plural.
3122
+				// todo: what about nonce?
3123
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3124
+
3125
+				// cycle through checkboxes
3126
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3127
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3128
+					if (! $trashed_or_restored) {
3129
+						$success = 0;
3130
+					}
3131
+				}
3132
+			} else {
3133
+				// grab single GRP_ID and handle
3134
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3135
+				if (! empty($GRP_ID)) {
3136
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3137
+					if (! $trashed_or_restored) {
3138
+						$success = 0;
3139
+					}
3140
+				} else {
3141
+					$success = 0;
3142
+				}
3143
+			}
3144
+		}
3145
+
3146
+		$action_desc = $trash
3147
+			? esc_html__('moved to the trash', 'event_espresso')
3148
+			: esc_html__('restored', 'event_espresso');
3149
+
3150
+		$action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3151
+
3152
+		$item_desc = $all ? _n(
3153
+			'Message Template Group',
3154
+			'Message Template Groups',
3155
+			$success,
3156
+			'event_espresso'
3157
+		) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3158
+
3159
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3160
+			'template',
3161
+			'templates',
3162
+			$success,
3163
+			'event_espresso'
3164
+		) : $item_desc;
3165
+
3166
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
3167
+	}
3168
+
3169
+
3170
+	/**
3171
+	 * [_delete_message_template]
3172
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3173
+	 *
3174
+	 * @return void
3175
+	 * @throws EE_Error
3176
+	 * @throws InvalidArgumentException
3177
+	 * @throws InvalidDataTypeException
3178
+	 * @throws InvalidInterfaceException
3179
+	 */
3180
+	protected function _delete_message_template()
3181
+	{
3182
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3183
+
3184
+		// checkboxes
3185
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3186
+			// if array has more than one element then success message should be plural
3187
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3188
+
3189
+			// cycle through bulk action checkboxes
3190
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3191
+				$success = $this->_delete_mtp_permanently($GRP_ID);
3192
+			}
3193
+		} else {
3194
+			// grab single grp_id and delete
3195
+			$GRP_ID = absint($this->_req_data['id']);
3196
+			$success = $this->_delete_mtp_permanently($GRP_ID);
3197
+		}
3198
+
3199
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3200
+	}
3201
+
3202
+
3203
+	/**
3204
+	 * helper for permanently deleting a mtP group and all related message_templates
3205
+	 *
3206
+	 * @param  int  $GRP_ID        The group being deleted
3207
+	 * @param  bool $include_group whether to delete the Message Template Group as well.
3208
+	 * @return bool boolean to indicate the success of the deletes or not.
3209
+	 * @throws EE_Error
3210
+	 * @throws InvalidArgumentException
3211
+	 * @throws InvalidDataTypeException
3212
+	 * @throws InvalidInterfaceException
3213
+	 */
3214
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3215
+	{
3216
+		$success = 1;
3217
+		$MTPG = EEM_Message_Template_Group::instance();
3218
+		// first let's GET this group
3219
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
3220
+		// then delete permanently all the related Message Templates
3221
+		$deleted = $MTG->delete_related_permanently('Message_Template');
3222
+
3223
+		if ($deleted === 0) {
3224
+			$success = 0;
3225
+		}
3226
+
3227
+		// now delete permanently this particular group
3228
+
3229
+		if ($include_group && ! $MTG->delete_permanently()) {
3230
+			$success = 0;
3231
+		}
3232
+
3233
+		return $success;
3234
+	}
3235
+
3236
+
3237
+	/**
3238
+	 *    _learn_more_about_message_templates_link
3239
+	 *
3240
+	 * @access protected
3241
+	 * @return string
3242
+	 */
3243
+	protected function _learn_more_about_message_templates_link()
3244
+	{
3245
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3246
+			   . esc_html__('learn more about how message templates works', 'event_espresso')
3247
+			   . '</a>';
3248
+	}
3249
+
3250
+
3251
+	/**
3252
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3253
+	 * ajax and other routes.
3254
+	 *
3255
+	 * @return void
3256
+	 * @throws DomainException
3257
+	 */
3258
+	protected function _settings()
3259
+	{
3260
+
3261
+
3262
+		$this->_set_m_mt_settings();
3263
+
3264
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3265
+			? $this->_req_data['selected_messenger']
3266
+			: 'email';
3267
+
3268
+		// let's setup the messenger tabs
3269
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3270
+			$this->_m_mt_settings['messenger_tabs'],
3271
+			'messenger_links',
3272
+			'|',
3273
+			$selected_messenger
3274
+		);
3275
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3276
+		$this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3277
+
3278
+		$this->display_admin_page_with_sidebar();
3279
+	}
3280
+
3281
+
3282
+	/**
3283
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3284
+	 *
3285
+	 * @access protected
3286
+	 * @return void
3287
+	 * @throws DomainException
3288
+	 */
3289
+	protected function _set_m_mt_settings()
3290
+	{
3291
+		// first if this is already set then lets get out no need to regenerate data.
3292
+		if (! empty($this->_m_mt_settings)) {
3293
+			return;
3294
+		}
3295
+
3296
+		// get all installed messengers and message_types
3297
+		/** @type EE_messenger[] $messengers */
3298
+		$messengers = $this->_message_resource_manager->installed_messengers();
3299
+		/** @type EE_message_type[] $message_types */
3300
+		$message_types = $this->_message_resource_manager->installed_message_types();
3301
+
3302
+
3303
+		// assemble the array for the _tab_text_links helper
3304
+
3305
+		foreach ($messengers as $messenger) {
3306
+			$this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3307
+				'label' => ucwords($messenger->label['singular']),
3308
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3309
+					? 'messenger-active'
3310
+					: '',
3311
+				'href'  => $messenger->name,
3312
+				'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3313
+				'slug'  => $messenger->name,
3314
+				'obj'   => $messenger,
3315
+			);
3316
+
3317
+
3318
+			$message_types_for_messenger = $messenger->get_valid_message_types();
3319
+
3320
+			foreach ($message_types as $message_type) {
3321
+				// first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3322
+				// it shouldn't show in either the inactive OR active metabox.
3323
+				if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3324
+					continue;
3325
+				}
3326
+
3327
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3328
+					$messenger->name,
3329
+					$message_type->name
3330
+				)
3331
+					? 'active'
3332
+					: 'inactive';
3333
+
3334
+				$this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3335
+					'label'    => ucwords($message_type->label['singular']),
3336
+					'class'    => 'message-type-' . $a_or_i,
3337
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3338
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3339
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3340
+					'title'    => $a_or_i === 'active'
3341
+						? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3342
+						: esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3343
+					'content'  => $a_or_i === 'active'
3344
+						? $this->_message_type_settings_content($message_type, $messenger, true)
3345
+						: $this->_message_type_settings_content($message_type, $messenger),
3346
+					'slug'     => $message_type->name,
3347
+					'active'   => $a_or_i === 'active',
3348
+					'obj'      => $message_type,
3349
+				);
3350
+			}
3351
+		}
3352
+	}
3353
+
3354
+
3355
+	/**
3356
+	 * This just prepares the content for the message type settings
3357
+	 *
3358
+	 * @param  EE_message_type $message_type The message type object
3359
+	 * @param  EE_messenger    $messenger    The messenger object
3360
+	 * @param  boolean         $active       Whether the message type is active or not
3361
+	 * @return string html output for the content
3362
+	 * @throws DomainException
3363
+	 */
3364
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
3365
+	{
3366
+		// get message type fields
3367
+		$fields = $message_type->get_admin_settings_fields();
3368
+		$settings_template_args['template_form_fields'] = '';
3369
+
3370
+		if (! empty($fields) && $active) {
3371
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3372
+			foreach ($fields as $fldname => $fldprops) {
3373
+				$field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3374
+				$template_form_field[ $field_id ] = array(
3375
+					'name'       => 'message_type_settings[' . $fldname . ']',
3376
+					'label'      => $fldprops['label'],
3377
+					'input'      => $fldprops['field_type'],
3378
+					'type'       => $fldprops['value_type'],
3379
+					'required'   => $fldprops['required'],
3380
+					'validation' => $fldprops['validation'],
3381
+					'value'      => isset($existing_settings[ $fldname ])
3382
+						? $existing_settings[ $fldname ]
3383
+						: $fldprops['default'],
3384
+					'options'    => isset($fldprops['options'])
3385
+						? $fldprops['options']
3386
+						: array(),
3387
+					'default'    => isset($existing_settings[ $fldname ])
3388
+						? $existing_settings[ $fldname ]
3389
+						: $fldprops['default'],
3390
+					'css_class'  => 'no-drag',
3391
+					'format'     => $fldprops['format'],
3392
+				);
3393
+			}
3394
+
3395
+
3396
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3397
+				? $this->_generate_admin_form_fields(
3398
+					$template_form_field,
3399
+					'string',
3400
+					'ee_mt_activate_form'
3401
+				)
3402
+				: '';
3403
+		}
3404
+
3405
+		$settings_template_args['description'] = $message_type->description;
3406
+		// we also need some hidden fields
3407
+		$settings_template_args['hidden_fields'] = array(
3408
+			'message_type_settings[messenger]'    => array(
3409
+				'type'  => 'hidden',
3410
+				'value' => $messenger->name,
3411
+			),
3412
+			'message_type_settings[message_type]' => array(
3413
+				'type'  => 'hidden',
3414
+				'value' => $message_type->name,
3415
+			),
3416
+			'type'                                => array(
3417
+				'type'  => 'hidden',
3418
+				'value' => 'message_type',
3419
+			),
3420
+		);
3421
+
3422
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3423
+			$settings_template_args['hidden_fields'],
3424
+			'array'
3425
+		);
3426
+		$settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3427
+			? ' hidden'
3428
+			: '';
3429
+
3430
+
3431
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3432
+		$content = EEH_Template::display_template($template, $settings_template_args, true);
3433
+
3434
+		return $content;
3435
+	}
3436
+
3437
+
3438
+	/**
3439
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
3440
+	 *
3441
+	 * @access protected
3442
+	 * @return void
3443
+	 * @throws DomainException
3444
+	 */
3445
+	protected function _messages_settings_metaboxes()
3446
+	{
3447
+		$this->_set_m_mt_settings();
3448
+		$m_boxes = $mt_boxes = array();
3449
+		$m_template_args = $mt_template_args = array();
3450
+
3451
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3452
+			? $this->_req_data['selected_messenger']
3453
+			: 'email';
3454
+
3455
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
3456
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3457
+				$hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3458
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3459
+				// messenger meta boxes
3460
+				$active = $selected_messenger === $messenger;
3461
+				$active_mt_tabs = isset(
3462
+					$this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3463
+				)
3464
+					? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3465
+					: '';
3466
+				$m_boxes[ $messenger . '_a_box' ] = sprintf(
3467
+					esc_html__('%s Settings', 'event_espresso'),
3468
+					$tab_array['label']
3469
+				);
3470
+				$m_template_args[ $messenger . '_a_box' ] = array(
3471
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3472
+					'inactive_message_types' => isset(
3473
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3474
+					)
3475
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3476
+						: '',
3477
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3478
+					'hidden'                 => $active ? '' : ' hidden',
3479
+					'hide_on_message'        => $hide_on_message,
3480
+					'messenger'              => $messenger,
3481
+					'active'                 => $active,
3482
+				);
3483
+				// message type meta boxes
3484
+				// (which is really just the inactive container for each messenger
3485
+				// showing inactive message types for that messenger)
3486
+				$mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3487
+				$mt_template_args[ $messenger . '_i_box' ] = array(
3488
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3489
+					'inactive_message_types' => isset(
3490
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3491
+					)
3492
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3493
+						: '',
3494
+					'hidden'                 => $active ? '' : ' hidden',
3495
+					'hide_on_message'        => $hide_on_message,
3496
+					'hide_off_message'       => $hide_off_message,
3497
+					'messenger'              => $messenger,
3498
+					'active'                 => $active,
3499
+				);
3500
+			}
3501
+		}
3502
+
3503
+
3504
+		// register messenger metaboxes
3505
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3506
+		foreach ($m_boxes as $box => $label) {
3507
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3508
+			$msgr = str_replace('_a_box', '', $box);
3509
+			add_meta_box(
3510
+				'espresso_' . $msgr . '_settings',
3511
+				$label,
3512
+				function ($post, $metabox) {
3513
+					echo EEH_Template::display_template(
3514
+						$metabox["args"]["template_path"],
3515
+						$metabox["args"]["template_args"],
3516
+						true
3517
+					);
3518
+				},
3519
+				$this->_current_screen->id,
3520
+				'normal',
3521
+				'high',
3522
+				$callback_args
3523
+			);
3524
+		}
3525
+
3526
+		// register message type metaboxes
3527
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3528
+		foreach ($mt_boxes as $box => $label) {
3529
+			$callback_args = array(
3530
+				'template_path' => $mt_template_path,
3531
+				'template_args' => $mt_template_args[ $box ],
3532
+			);
3533
+			$mt = str_replace('_i_box', '', $box);
3534
+			add_meta_box(
3535
+				'espresso_' . $mt . '_inactive_mts',
3536
+				$label,
3537
+				function ($post, $metabox) {
3538
+					echo EEH_Template::display_template(
3539
+						$metabox["args"]["template_path"],
3540
+						$metabox["args"]["template_args"],
3541
+						true
3542
+					);
3543
+				},
3544
+				$this->_current_screen->id,
3545
+				'side',
3546
+				'high',
3547
+				$callback_args
3548
+			);
3549
+		}
3550
+
3551
+		// register metabox for global messages settings but only when on the main site.  On single site installs this
3552
+		// will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3553
+		if (is_main_site()) {
3554
+			add_meta_box(
3555
+				'espresso_global_message_settings',
3556
+				esc_html__('Global Message Settings', 'event_espresso'),
3557
+				array($this, 'global_messages_settings_metabox_content'),
3558
+				$this->_current_screen->id,
3559
+				'normal',
3560
+				'low',
3561
+				array()
3562
+			);
3563
+		}
3564
+	}
3565
+
3566
+
3567
+	/**
3568
+	 *  This generates the content for the global messages settings metabox.
3569
+	 *
3570
+	 * @return string
3571
+	 * @throws EE_Error
3572
+	 * @throws InvalidArgumentException
3573
+	 * @throws ReflectionException
3574
+	 * @throws InvalidDataTypeException
3575
+	 * @throws InvalidInterfaceException
3576
+	 */
3577
+	public function global_messages_settings_metabox_content()
3578
+	{
3579
+		$form = $this->_generate_global_settings_form();
3580
+		echo $form->form_open(
3581
+			$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3582
+			'POST'
3583
+		)
3584
+			 . $form->get_html()
3585
+			 . $form->form_close();
3586
+	}
3587
+
3588
+
3589
+	/**
3590
+	 * This generates and returns the form object for the global messages settings.
3591
+	 *
3592
+	 * @return EE_Form_Section_Proper
3593
+	 * @throws EE_Error
3594
+	 * @throws InvalidArgumentException
3595
+	 * @throws ReflectionException
3596
+	 * @throws InvalidDataTypeException
3597
+	 * @throws InvalidInterfaceException
3598
+	 */
3599
+	protected function _generate_global_settings_form()
3600
+	{
3601
+		EE_Registry::instance()->load_helper('HTML');
3602
+		/** @var EE_Network_Core_Config $network_config */
3603
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3604
+
3605
+		return new EE_Form_Section_Proper(
3606
+			array(
3607
+				'name'            => 'global_messages_settings',
3608
+				'html_id'         => 'global_messages_settings',
3609
+				'html_class'      => 'form-table',
3610
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3611
+				'subsections'     => apply_filters(
3612
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3613
+					array(
3614
+						'do_messages_on_same_request' => new EE_Select_Input(
3615
+							array(
3616
+								true  => esc_html__("On the same request", "event_espresso"),
3617
+								false => esc_html__("On a separate request", "event_espresso"),
3618
+							),
3619
+							array(
3620
+								'default'         => $network_config->do_messages_on_same_request,
3621
+								'html_label_text' => esc_html__(
3622
+									'Generate and send all messages:',
3623
+									'event_espresso'
3624
+								),
3625
+								'html_help_text'  => esc_html__(
3626
+									'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.',
3627
+									'event_espresso'
3628
+								),
3629
+							)
3630
+						),
3631
+						'delete_threshold'            => new EE_Select_Input(
3632
+							array(
3633
+								0  => esc_html__('Forever', 'event_espresso'),
3634
+								3  => esc_html__('3 Months', 'event_espresso'),
3635
+								6  => esc_html__('6 Months', 'event_espresso'),
3636
+								9  => esc_html__('9 Months', 'event_espresso'),
3637
+								12 => esc_html__('12 Months', 'event_espresso'),
3638
+								24 => esc_html__('24 Months', 'event_espresso'),
3639
+								36 => esc_html__('36 Months', 'event_espresso'),
3640
+							),
3641
+							array(
3642
+								'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3643
+								'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3644
+								'html_help_text'  => esc_html__(
3645
+									'You can control how long a record of processed messages is kept via this option.',
3646
+									'event_espresso'
3647
+								),
3648
+							)
3649
+						),
3650
+						'update_settings'             => new EE_Submit_Input(
3651
+							array(
3652
+								'default'         => esc_html__('Update', 'event_espresso'),
3653
+								'html_label_text' => '&nbsp',
3654
+							)
3655
+						),
3656
+					)
3657
+				),
3658
+			)
3659
+		);
3660
+	}
3661
+
3662
+
3663
+	/**
3664
+	 * This handles updating the global settings set on the admin page.
3665
+	 *
3666
+	 * @throws EE_Error
3667
+	 * @throws InvalidDataTypeException
3668
+	 * @throws InvalidInterfaceException
3669
+	 * @throws InvalidArgumentException
3670
+	 * @throws ReflectionException
3671
+	 */
3672
+	protected function _update_global_settings()
3673
+	{
3674
+		/** @var EE_Network_Core_Config $network_config */
3675
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3676
+		$messages_config = EE_Registry::instance()->CFG->messages;
3677
+		$form = $this->_generate_global_settings_form();
3678
+		if ($form->was_submitted()) {
3679
+			$form->receive_form_submission();
3680
+			if ($form->is_valid()) {
3681
+				$valid_data = $form->valid_data();
3682
+				foreach ($valid_data as $property => $value) {
3683
+					$setter = 'set_' . $property;
3684
+					if (method_exists($network_config, $setter)) {
3685
+						$network_config->{$setter}($value);
3686
+					} elseif (property_exists($network_config, $property)
3687
+						&& $network_config->{$property} !== $value
3688
+					) {
3689
+						$network_config->{$property} = $value;
3690
+					} elseif (property_exists($messages_config, $property)
3691
+						&& $messages_config->{$property} !== $value
3692
+					) {
3693
+						$messages_config->{$property} = $value;
3694
+					}
3695
+				}
3696
+				// only update if the form submission was valid!
3697
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3698
+				EE_Registry::instance()->CFG->update_espresso_config();
3699
+				EE_Error::overwrite_success();
3700
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3701
+			}
3702
+		}
3703
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3704
+	}
3705
+
3706
+
3707
+	/**
3708
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3709
+	 *
3710
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3711
+	 * @return string html formatted tabs
3712
+	 * @throws DomainException
3713
+	 */
3714
+	protected function _get_mt_tabs($tab_array)
3715
+	{
3716
+		$tab_array = (array) $tab_array;
3717
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3718
+		$tabs = '';
3719
+
3720
+		foreach ($tab_array as $tab) {
3721
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3722
+		}
3723
+
3724
+		return $tabs;
3725
+	}
3726
+
3727
+
3728
+	/**
3729
+	 * This prepares the content of the messenger meta box admin settings
3730
+	 *
3731
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3732
+	 * @return string html formatted content
3733
+	 * @throws DomainException
3734
+	 */
3735
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3736
+	{
3737
+
3738
+		$fields = $messenger->get_admin_settings_fields();
3739
+		$settings_template_args['template_form_fields'] = '';
3740
+
3741
+		// is $messenger active?
3742
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3743
+
3744
+
3745
+		if (! empty($fields)) {
3746
+			$existing_settings = $messenger->get_existing_admin_settings();
3747
+
3748
+			foreach ($fields as $fldname => $fldprops) {
3749
+				$field_id = $messenger->name . '-' . $fldname;
3750
+				$template_form_field[ $field_id ] = array(
3751
+					'name'       => 'messenger_settings[' . $field_id . ']',
3752
+					'label'      => $fldprops['label'],
3753
+					'input'      => $fldprops['field_type'],
3754
+					'type'       => $fldprops['value_type'],
3755
+					'required'   => $fldprops['required'],
3756
+					'validation' => $fldprops['validation'],
3757
+					'value'      => isset($existing_settings[ $field_id ])
3758
+						? $existing_settings[ $field_id ]
3759
+						: $fldprops['default'],
3760
+					'css_class'  => '',
3761
+					'format'     => $fldprops['format'],
3762
+				);
3763
+			}
3764
+
3765
+
3766
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3767
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3768
+				: '';
3769
+		}
3770
+
3771
+		// we also need some hidden fields
3772
+		$settings_template_args['hidden_fields'] = array(
3773
+			'messenger_settings[messenger]' => array(
3774
+				'type'  => 'hidden',
3775
+				'value' => $messenger->name,
3776
+			),
3777
+			'type'                          => array(
3778
+				'type'  => 'hidden',
3779
+				'value' => 'messenger',
3780
+			),
3781
+		);
3782
+
3783
+		// make sure any active message types that are existing are included in the hidden fields
3784
+		if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3785
+			foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3786
+				$settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3787
+					'type'  => 'hidden',
3788
+					'value' => $mt,
3789
+				);
3790
+			}
3791
+		}
3792
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3793
+			$settings_template_args['hidden_fields'],
3794
+			'array'
3795
+		);
3796
+		$active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3797
+
3798
+		$settings_template_args['messenger'] = $messenger->name;
3799
+		$settings_template_args['description'] = $messenger->description;
3800
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3801
+
3802
+
3803
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3804
+			$messenger->name
3805
+		)
3806
+			? $settings_template_args['show_hide_edit_form']
3807
+			: ' hidden';
3808
+
3809
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3810
+			? ' hidden'
3811
+			: $settings_template_args['show_hide_edit_form'];
3812
+
3813
+
3814
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3815
+		$settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3816
+		$settings_template_args['on_off_status'] = $active ? true : false;
3817
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3818
+		$content = EEH_Template::display_template(
3819
+			$template,
3820
+			$settings_template_args,
3821
+			true
3822
+		);
3823
+
3824
+		return $content;
3825
+	}
3826
+
3827
+
3828
+	/**
3829
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3830
+	 *
3831
+	 * @throws DomainException
3832
+	 * @throws EE_Error
3833
+	 * @throws InvalidDataTypeException
3834
+	 * @throws InvalidInterfaceException
3835
+	 * @throws InvalidArgumentException
3836
+	 * @throws ReflectionException
3837
+	 */
3838
+	public function activate_messenger_toggle()
3839
+	{
3840
+		$success = true;
3841
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3842
+		// let's check that we have required data
3843
+		if (! isset($this->_req_data['messenger'])) {
3844
+			EE_Error::add_error(
3845
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3846
+				__FILE__,
3847
+				__FUNCTION__,
3848
+				__LINE__
3849
+			);
3850
+			$success = false;
3851
+		}
3852
+
3853
+		// do a nonce check here since we're not arriving via a normal route
3854
+		$nonce = isset($this->_req_data['activate_nonce'])
3855
+			? sanitize_text_field($this->_req_data['activate_nonce'])
3856
+			: '';
3857
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3858
+
3859
+		$this->_verify_nonce($nonce, $nonce_ref);
3860
+
3861
+
3862
+		if (! isset($this->_req_data['status'])) {
3863
+			EE_Error::add_error(
3864
+				esc_html__(
3865
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3866
+					'event_espresso'
3867
+				),
3868
+				__FILE__,
3869
+				__FUNCTION__,
3870
+				__LINE__
3871
+			);
3872
+			$success = false;
3873
+		}
3874
+
3875
+		// do check to verify we have a valid status.
3876
+		$status = $this->_req_data['status'];
3877
+
3878
+		if ($status !== 'off' && $status !== 'on') {
3879
+			EE_Error::add_error(
3880
+				sprintf(
3881
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3882
+					$this->_req_data['status']
3883
+				),
3884
+				__FILE__,
3885
+				__FUNCTION__,
3886
+				__LINE__
3887
+			);
3888
+			$success = false;
3889
+		}
3890
+
3891
+		if ($success) {
3892
+			// made it here?  Stop dawdling then!!
3893
+			$success = $status === 'off'
3894
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3895
+				: $this->_activate_messenger($this->_req_data['messenger']);
3896
+		}
3897
+
3898
+		$this->_template_args['success'] = $success;
3899
+
3900
+		// no special instructions so let's just do the json return (which should automatically do all the special stuff).
3901
+		$this->_return_json();
3902
+	}
3903
+
3904
+
3905
+	/**
3906
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3907
+	 *
3908
+	 * @throws DomainException
3909
+	 * @throws EE_Error
3910
+	 * @throws ReflectionException
3911
+	 * @throws InvalidDataTypeException
3912
+	 * @throws InvalidInterfaceException
3913
+	 * @throws InvalidArgumentException
3914
+	 */
3915
+	public function activate_mt_toggle()
3916
+	{
3917
+		$success = true;
3918
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3919
+
3920
+		// let's make sure we have the necessary data
3921
+		if (! isset($this->_req_data['message_type'])) {
3922
+			EE_Error::add_error(
3923
+				esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3924
+				__FILE__,
3925
+				__FUNCTION__,
3926
+				__LINE__
3927
+			);
3928
+			$success = false;
3929
+		}
3930
+
3931
+		if (! isset($this->_req_data['messenger'])) {
3932
+			EE_Error::add_error(
3933
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3934
+				__FILE__,
3935
+				__FUNCTION__,
3936
+				__LINE__
3937
+			);
3938
+			$success = false;
3939
+		}
3940
+
3941
+		if (! isset($this->_req_data['status'])) {
3942
+			EE_Error::add_error(
3943
+				esc_html__(
3944
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3945
+					'event_espresso'
3946
+				),
3947
+				__FILE__,
3948
+				__FUNCTION__,
3949
+				__LINE__
3950
+			);
3951
+			$success = false;
3952
+		}
3953
+
3954
+
3955
+		// do check to verify we have a valid status.
3956
+		$status = $this->_req_data['status'];
3957
+
3958
+		if ($status !== 'activate' && $status !== 'deactivate') {
3959
+			EE_Error::add_error(
3960
+				sprintf(
3961
+					esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3962
+					$this->_req_data['status']
3963
+				),
3964
+				__FILE__,
3965
+				__FUNCTION__,
3966
+				__LINE__
3967
+			);
3968
+			$success = false;
3969
+		}
3970
+
3971
+
3972
+		// do a nonce check here since we're not arriving via a normal route
3973
+		$nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3974
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3975
+
3976
+		$this->_verify_nonce($nonce, $nonce_ref);
3977
+
3978
+		if ($success) {
3979
+			// made it here? um, what are you waiting for then?
3980
+			$success = $status === 'deactivate'
3981
+				? $this->_deactivate_message_type_for_messenger(
3982
+					$this->_req_data['messenger'],
3983
+					$this->_req_data['message_type']
3984
+				)
3985
+				: $this->_activate_message_type_for_messenger(
3986
+					$this->_req_data['messenger'],
3987
+					$this->_req_data['message_type']
3988
+				);
3989
+		}
3990
+
3991
+		$this->_template_args['success'] = $success;
3992
+		$this->_return_json();
3993
+	}
3994
+
3995
+
3996
+	/**
3997
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
3998
+	 *
3999
+	 * @param string $messenger_name The name of the messenger being activated
4000
+	 * @return bool
4001
+	 * @throws DomainException
4002
+	 * @throws EE_Error
4003
+	 * @throws InvalidArgumentException
4004
+	 * @throws ReflectionException
4005
+	 * @throws InvalidDataTypeException
4006
+	 * @throws InvalidInterfaceException
4007
+	 */
4008
+	protected function _activate_messenger($messenger_name)
4009
+	{
4010
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4011
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4012
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger
4013
+			? $active_messenger->get_default_message_types()
4014
+			: array();
4015
+
4016
+		// ensure is active
4017
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
4018
+
4019
+		// set response_data for reload
4020
+		foreach ($message_types_to_activate as $message_type_name) {
4021
+			/** @var EE_message_type $message_type */
4022
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4023
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4024
+				$messenger_name,
4025
+				$message_type_name
4026
+			)
4027
+				&& $message_type instanceof EE_message_type
4028
+			) {
4029
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
4030
+				if ($message_type->get_admin_settings_fields()) {
4031
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
4032
+				}
4033
+			}
4034
+		}
4035
+
4036
+		// add success message for activating messenger
4037
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4038
+	}
4039
+
4040
+
4041
+	/**
4042
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
4043
+	 *
4044
+	 * @param string $messenger_name The name of the messenger being activated
4045
+	 * @return bool
4046
+	 * @throws DomainException
4047
+	 * @throws EE_Error
4048
+	 * @throws InvalidArgumentException
4049
+	 * @throws ReflectionException
4050
+	 * @throws InvalidDataTypeException
4051
+	 * @throws InvalidInterfaceException
4052
+	 */
4053
+	protected function _deactivate_messenger($messenger_name)
4054
+	{
4055
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4056
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4057
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
4058
+
4059
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4060
+	}
4061
+
4062
+
4063
+	/**
4064
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4065
+	 *
4066
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
4067
+	 * @param string $message_type_name The name of the message type being activated for the messenger
4068
+	 * @return bool
4069
+	 * @throws DomainException
4070
+	 * @throws EE_Error
4071
+	 * @throws InvalidArgumentException
4072
+	 * @throws ReflectionException
4073
+	 * @throws InvalidDataTypeException
4074
+	 * @throws InvalidInterfaceException
4075
+	 */
4076
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4077
+	{
4078
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4079
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4080
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4081
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4082
+
4083
+		// ensure is active
4084
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
4085
+
4086
+		// set response for load
4087
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4088
+			$messenger_name,
4089
+			$message_type_name
4090
+		)
4091
+		) {
4092
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
4093
+			if ($message_type_to_activate->get_admin_settings_fields()) {
4094
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
4095
+			}
4096
+		}
4097
+
4098
+		return $this->_setup_response_message_for_activating_messenger_with_message_types(
4099
+			$active_messenger,
4100
+			$message_type_to_activate
4101
+		);
4102
+	}
4103
+
4104
+
4105
+	/**
4106
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4107
+	 *
4108
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4109
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
4110
+	 * @return bool
4111
+	 * @throws DomainException
4112
+	 * @throws EE_Error
4113
+	 * @throws InvalidArgumentException
4114
+	 * @throws ReflectionException
4115
+	 * @throws InvalidDataTypeException
4116
+	 * @throws InvalidInterfaceException
4117
+	 */
4118
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4119
+	{
4120
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4121
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4122
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4123
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4124
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4125
+
4126
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4127
+			$active_messenger,
4128
+			$message_type_to_deactivate
4129
+		);
4130
+	}
4131
+
4132
+
4133
+	/**
4134
+	 * This just initializes the defaults for activating messenger and message type responses.
4135
+	 */
4136
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
4137
+	{
4138
+		$this->_template_args['data']['active_mts'] = array();
4139
+		$this->_template_args['data']['mt_reload'] = array();
4140
+	}
4141
+
4142
+
4143
+	/**
4144
+	 * Setup appropriate response for activating a messenger and/or message types
4145
+	 *
4146
+	 * @param EE_messenger         $messenger
4147
+	 * @param EE_message_type|null $message_type
4148
+	 * @return bool
4149
+	 * @throws DomainException
4150
+	 * @throws EE_Error
4151
+	 * @throws InvalidArgumentException
4152
+	 * @throws ReflectionException
4153
+	 * @throws InvalidDataTypeException
4154
+	 * @throws InvalidInterfaceException
4155
+	 */
4156
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
4157
+		$messenger,
4158
+		EE_Message_Type $message_type = null
4159
+	) {
4160
+		// if $messenger isn't a valid messenger object then get out.
4161
+		if (! $messenger instanceof EE_Messenger) {
4162
+			EE_Error::add_error(
4163
+				esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4164
+				__FILE__,
4165
+				__FUNCTION__,
4166
+				__LINE__
4167
+			);
4168
+
4169
+			return false;
4170
+		}
4171
+		// activated
4172
+		if ($this->_template_args['data']['active_mts']) {
4173
+			EE_Error::overwrite_success();
4174
+			// activated a message type with the messenger
4175
+			if ($message_type instanceof EE_message_type) {
4176
+				EE_Error::add_success(
4177
+					sprintf(
4178
+						esc_html__(
4179
+							'%s message type has been successfully activated with the %s messenger',
4180
+							'event_espresso'
4181
+						),
4182
+						ucwords($message_type->label['singular']),
4183
+						ucwords($messenger->label['singular'])
4184
+					)
4185
+				);
4186
+
4187
+				// if message type was invoice then let's make sure we activate the invoice payment method.
4188
+				if ($message_type->name === 'invoice') {
4189
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
4190
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4191
+					if ($pm instanceof EE_Payment_Method) {
4192
+						EE_Error::add_attention(
4193
+							esc_html__(
4194
+								'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.',
4195
+								'event_espresso'
4196
+							)
4197
+						);
4198
+					}
4199
+				}
4200
+				// just toggles the entire messenger
4201
+			} else {
4202
+				EE_Error::add_success(
4203
+					sprintf(
4204
+						esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4205
+						ucwords($messenger->label['singular'])
4206
+					)
4207
+				);
4208
+			}
4209
+
4210
+			return true;
4211
+
4212
+			// possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4213
+			// message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4214
+			// in which case we just give a success message for the messenger being successfully activated.
4215
+		} else {
4216
+			if (! $messenger->get_default_message_types()) {
4217
+				// messenger doesn't have any default message types so still a success.
4218
+				EE_Error::add_success(
4219
+					sprintf(
4220
+						esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4221
+						ucwords($messenger->label['singular'])
4222
+					)
4223
+				);
4224
+
4225
+				return true;
4226
+			} else {
4227
+				EE_Error::add_error(
4228
+					$message_type instanceof EE_message_type
4229
+						? sprintf(
4230
+							esc_html__(
4231
+								'%s message type was not successfully activated with the %s messenger',
4232
+								'event_espresso'
4233
+							),
4234
+							ucwords($message_type->label['singular']),
4235
+							ucwords($messenger->label['singular'])
4236
+						)
4237
+						: sprintf(
4238
+							esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4239
+							ucwords($messenger->label['singular'])
4240
+						),
4241
+					__FILE__,
4242
+					__FUNCTION__,
4243
+					__LINE__
4244
+				);
4245
+
4246
+				return false;
4247
+			}
4248
+		}
4249
+	}
4250
+
4251
+
4252
+	/**
4253
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
4254
+	 *
4255
+	 * @param EE_messenger         $messenger
4256
+	 * @param EE_message_type|null $message_type
4257
+	 * @return bool
4258
+	 * @throws DomainException
4259
+	 * @throws EE_Error
4260
+	 * @throws InvalidArgumentException
4261
+	 * @throws ReflectionException
4262
+	 * @throws InvalidDataTypeException
4263
+	 * @throws InvalidInterfaceException
4264
+	 */
4265
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4266
+		$messenger,
4267
+		EE_message_type $message_type = null
4268
+	) {
4269
+		EE_Error::overwrite_success();
4270
+
4271
+		// if $messenger isn't a valid messenger object then get out.
4272
+		if (! $messenger instanceof EE_Messenger) {
4273
+			EE_Error::add_error(
4274
+				esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4275
+				__FILE__,
4276
+				__FUNCTION__,
4277
+				__LINE__
4278
+			);
4279
+
4280
+			return false;
4281
+		}
4282
+
4283
+		if ($message_type instanceof EE_message_type) {
4284
+			$message_type_name = $message_type->name;
4285
+			EE_Error::add_success(
4286
+				sprintf(
4287
+					esc_html__(
4288
+						'%s message type has been successfully deactivated for the %s messenger.',
4289
+						'event_espresso'
4290
+					),
4291
+					ucwords($message_type->label['singular']),
4292
+					ucwords($messenger->label['singular'])
4293
+				)
4294
+			);
4295
+		} else {
4296
+			$message_type_name = '';
4297
+			EE_Error::add_success(
4298
+				sprintf(
4299
+					esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4300
+					ucwords($messenger->label['singular'])
4301
+				)
4302
+			);
4303
+		}
4304
+
4305
+		// if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4306
+		if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4307
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
4308
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4309
+			if ($count_updated > 0) {
4310
+				$msg = $message_type_name === 'invoice'
4311
+					? esc_html__(
4312
+						'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.',
4313
+						'event_espresso'
4314
+					)
4315
+					: esc_html__(
4316
+						'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.',
4317
+						'event_espresso'
4318
+					);
4319
+				EE_Error::add_attention($msg);
4320
+			}
4321
+		}
4322
+
4323
+		return true;
4324
+	}
4325
+
4326
+
4327
+	/**
4328
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4329
+	 *
4330
+	 * @throws DomainException
4331
+	 */
4332
+	public function update_mt_form()
4333
+	{
4334
+		if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4335
+			EE_Error::add_error(
4336
+				esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4337
+				__FILE__,
4338
+				__FUNCTION__,
4339
+				__LINE__
4340
+			);
4341
+			$this->_return_json();
4342
+		}
4343
+
4344
+		$message_types = $this->get_installed_message_types();
4345
+
4346
+		$message_type = $message_types[ $this->_req_data['message_type'] ];
4347
+		$messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4348
+
4349
+		$content = $this->_message_type_settings_content(
4350
+			$message_type,
4351
+			$messenger,
4352
+			true
4353
+		);
4354
+		$this->_template_args['success'] = true;
4355
+		$this->_template_args['content'] = $content;
4356
+		$this->_return_json();
4357
+	}
4358
+
4359
+
4360
+	/**
4361
+	 * this handles saving the settings for a messenger or message type
4362
+	 *
4363
+	 */
4364
+	public function save_settings()
4365
+	{
4366
+		if (! isset($this->_req_data['type'])) {
4367
+			EE_Error::add_error(
4368
+				esc_html__(
4369
+					'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4370
+					'event_espresso'
4371
+				),
4372
+				__FILE__,
4373
+				__FUNCTION__,
4374
+				__LINE__
4375
+			);
4376
+			$this->_template_args['error'] = true;
4377
+			$this->_return_json();
4378
+		}
4379
+
4380
+
4381
+		if ($this->_req_data['type'] === 'messenger') {
4382
+			// this should be an array.
4383
+			$settings = $this->_req_data['messenger_settings'];
4384
+			$messenger = $settings['messenger'];
4385
+			// let's setup the settings data
4386
+			foreach ($settings as $key => $value) {
4387
+				switch ($key) {
4388
+					case 'messenger':
4389
+						unset($settings['messenger']);
4390
+						break;
4391
+					case 'message_types':
4392
+						unset($settings['message_types']);
4393
+						break;
4394
+					default:
4395
+						$settings[ $key ] = $value;
4396
+						break;
4397
+				}
4398
+			}
4399
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4400
+		} elseif ($this->_req_data['type'] === 'message_type') {
4401
+			$settings = $this->_req_data['message_type_settings'];
4402
+			$messenger = $settings['messenger'];
4403
+			$message_type = $settings['message_type'];
4404
+
4405
+			foreach ($settings as $key => $value) {
4406
+				switch ($key) {
4407
+					case 'messenger':
4408
+						unset($settings['messenger']);
4409
+						break;
4410
+					case 'message_type':
4411
+						unset($settings['message_type']);
4412
+						break;
4413
+					default:
4414
+						$settings[ $key ] = $value;
4415
+						break;
4416
+				}
4417
+			}
4418
+
4419
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4420
+		}
4421
+
4422
+		// okay we should have the data all setup.  Now we just update!
4423
+		$success = $this->_message_resource_manager->update_active_messengers_option();
4424
+
4425
+		if ($success) {
4426
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
4427
+		} else {
4428
+			EE_Error::add_error(
4429
+				esc_html__(
4430
+					'Settings did not get updated',
4431
+					'event_espresso'
4432
+				),
4433
+				__FILE__,
4434
+				__FUNCTION__,
4435
+				__LINE__
4436
+			);
4437
+		}
4438
+
4439
+		$this->_template_args['success'] = $success;
4440
+		$this->_return_json();
4441
+	}
4442
+
4443
+
4444
+
4445
+
4446
+	/**  EE MESSAGE PROCESSING ACTIONS **/
4447
+
4448
+
4449
+	/**
4450
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4451
+	 * However, this does not send immediately, it just queues for sending.
4452
+	 *
4453
+	 * @since 4.9.0
4454
+	 * @throws EE_Error
4455
+	 * @throws InvalidDataTypeException
4456
+	 * @throws InvalidInterfaceException
4457
+	 * @throws InvalidArgumentException
4458
+	 * @throws ReflectionException
4459
+	 */
4460
+	protected function _generate_now()
4461
+	{
4462
+		EED_Messages::generate_now($this->_get_msg_ids_from_request());
4463
+		$this->_redirect_after_action(false, '', '', array(), true);
4464
+	}
4465
+
4466
+
4467
+	/**
4468
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4469
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
4470
+	 *
4471
+	 * @since 4.9.0
4472
+	 * @throws EE_Error
4473
+	 * @throws InvalidDataTypeException
4474
+	 * @throws InvalidInterfaceException
4475
+	 * @throws InvalidArgumentException
4476
+	 * @throws ReflectionException
4477
+	 */
4478
+	protected function _generate_and_send_now()
4479
+	{
4480
+		EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4481
+		$this->_redirect_after_action(false, '', '', array(), true);
4482
+	}
4483
+
4484
+
4485
+	/**
4486
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4487
+	 *
4488
+	 * @since 4.9.0
4489
+	 * @throws EE_Error
4490
+	 * @throws InvalidDataTypeException
4491
+	 * @throws InvalidInterfaceException
4492
+	 * @throws InvalidArgumentException
4493
+	 * @throws ReflectionException
4494
+	 */
4495
+	protected function _queue_for_resending()
4496
+	{
4497
+		EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4498
+		$this->_redirect_after_action(false, '', '', array(), true);
4499
+	}
4500
+
4501
+
4502
+	/**
4503
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4504
+	 *
4505
+	 * @since 4.9.0
4506
+	 * @throws EE_Error
4507
+	 * @throws InvalidDataTypeException
4508
+	 * @throws InvalidInterfaceException
4509
+	 * @throws InvalidArgumentException
4510
+	 * @throws ReflectionException
4511
+	 */
4512
+	protected function _send_now()
4513
+	{
4514
+		EED_Messages::send_now($this->_get_msg_ids_from_request());
4515
+		$this->_redirect_after_action(false, '', '', array(), true);
4516
+	}
4517
+
4518
+
4519
+	/**
4520
+	 * Deletes EE_messages for IDs in the request.
4521
+	 *
4522
+	 * @since 4.9.0
4523
+	 * @throws EE_Error
4524
+	 * @throws InvalidDataTypeException
4525
+	 * @throws InvalidInterfaceException
4526
+	 * @throws InvalidArgumentException
4527
+	 */
4528
+	protected function _delete_ee_messages()
4529
+	{
4530
+		$msg_ids = $this->_get_msg_ids_from_request();
4531
+		$deleted_count = 0;
4532
+		foreach ($msg_ids as $msg_id) {
4533
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4534
+				$deleted_count++;
4535
+			}
4536
+		}
4537
+		if ($deleted_count) {
4538
+			EE_Error::add_success(
4539
+				esc_html(
4540
+					_n(
4541
+						'Message successfully deleted',
4542
+						'Messages successfully deleted',
4543
+						$deleted_count,
4544
+						'event_espresso'
4545
+					)
4546
+				)
4547
+			);
4548
+			$this->_redirect_after_action(
4549
+				false,
4550
+				'',
4551
+				'',
4552
+				array(),
4553
+				true
4554
+			);
4555
+		} else {
4556
+			EE_Error::add_error(
4557
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4558
+				__FILE__,
4559
+				__FUNCTION__,
4560
+				__LINE__
4561
+			);
4562
+			$this->_redirect_after_action(false, '', '', array(), true);
4563
+		}
4564
+	}
4565
+
4566
+
4567
+	/**
4568
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4569
+	 *
4570
+	 * @since 4.9.0
4571
+	 * @return array
4572
+	 */
4573
+	protected function _get_msg_ids_from_request()
4574
+	{
4575
+		if (! isset($this->_req_data['MSG_ID'])) {
4576
+			return array();
4577
+		}
4578
+
4579
+		return is_array($this->_req_data['MSG_ID'])
4580
+			? array_keys($this->_req_data['MSG_ID'])
4581
+			: array($this->_req_data['MSG_ID']);
4582
+	}
4583 4583
 }
Please login to merge, or discard this patch.
Spacing   +210 added lines, -210 removed lines patch added patch discarded remove patch
@@ -141,8 +141,8 @@  discard block
 block discarded – undo
141 141
         $i = 1;
142 142
         foreach ($active_messengers as $active_messenger) {
143 143
             if ($active_messenger instanceof EE_Message) {
144
-                $m_values[ $i ]['id'] = $active_messenger->messenger();
145
-                $m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
144
+                $m_values[$i]['id'] = $active_messenger->messenger();
145
+                $m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
146 146
                 $i++;
147 147
             }
148 148
         }
@@ -178,8 +178,8 @@  discard block
 block discarded – undo
178 178
         $i = 1;
179 179
         foreach ($active_messages as $active_message) {
180 180
             if ($active_message instanceof EE_Message) {
181
-                $mt_values[ $i ]['id'] = $active_message->message_type();
182
-                $mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
181
+                $mt_values[$i]['id'] = $active_message->message_type();
182
+                $mt_values[$i]['text'] = ucwords($active_message->message_type_label());
183 183
                 $i++;
184 184
             }
185 185
         }
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
                 if ($message_type instanceof EE_message_type) {
219 219
                     $message_type_contexts = $message_type->get_contexts();
220 220
                     foreach ($message_type_contexts as $context => $context_details) {
221
-                        $contexts[ $context ] = $context_details['label'];
221
+                        $contexts[$context] = $context_details['label'];
222 222
                     }
223 223
                 }
224 224
             }
@@ -709,53 +709,53 @@  discard block
 block discarded – undo
709 709
 
710 710
     public function messages_help_tab()
711 711
     {
712
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
712
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_help_tab.template.php');
713 713
     }
714 714
 
715 715
 
716 716
     public function messengers_help_tab()
717 717
     {
718
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
718
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messenger_help_tab.template.php');
719 719
     }
720 720
 
721 721
 
722 722
     public function message_types_help_tab()
723 723
     {
724
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
724
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_type_help_tab.template.php');
725 725
     }
726 726
 
727 727
 
728 728
     public function messages_overview_help_tab()
729 729
     {
730
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
730
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_overview_help_tab.template.php');
731 731
     }
732 732
 
733 733
 
734 734
     public function message_templates_help_tab()
735 735
     {
736
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
736
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_templates_help_tab.template.php');
737 737
     }
738 738
 
739 739
 
740 740
     public function edit_message_template_help_tab()
741 741
     {
742
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
742
+        $args['img1'] = '<img src="'.EE_MSG_ASSETS_URL.'images/editor.png'.'" alt="'
743 743
                         . esc_attr__('Editor Title', 'event_espresso')
744 744
                         . '" />';
745
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
745
+        $args['img2'] = '<img src="'.EE_MSG_ASSETS_URL.'images/switch-context.png'.'" alt="'
746 746
                         . esc_attr__('Context Switcher and Preview', 'event_espresso')
747 747
                         . '" />';
748
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
748
+        $args['img3'] = '<img class="left" src="'.EE_MSG_ASSETS_URL.'images/form-fields.png'.'" alt="'
749 749
                         . esc_attr__('Message Template Form Fields', 'event_espresso')
750 750
                         . '" />';
751
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
751
+        $args['img4'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/shortcodes-metabox.png'.'" alt="'
752 752
                         . esc_attr__('Shortcodes Metabox', 'event_espresso')
753 753
                         . '" />';
754
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
754
+        $args['img5'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/publish-meta-box.png'.'" alt="'
755 755
                         . esc_attr__('Publish Metabox', 'event_espresso')
756 756
                         . '" />';
757 757
         EEH_Template::display_template(
758
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
758
+            EE_MSG_TEMPLATE_PATH.'ee_msg_messages_templates_editor_help_tab.template.php',
759 759
             $args
760 760
         );
761 761
     }
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
         $this->_set_shortcodes();
767 767
         $args['shortcodes'] = $this->_shortcodes;
768 768
         EEH_Template::display_template(
769
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
769
+            EE_MSG_TEMPLATE_PATH.'ee_msg_messages_shortcodes_help_tab.template.php',
770 770
             $args
771 771
         );
772 772
     }
@@ -774,16 +774,16 @@  discard block
 block discarded – undo
774 774
 
775 775
     public function preview_message_help_tab()
776 776
     {
777
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
777
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_preview_help_tab.template.php');
778 778
     }
779 779
 
780 780
 
781 781
     public function settings_help_tab()
782 782
     {
783
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
784
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
785
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
786
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
783
+        $args['img1'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-active.png'
784
+                        . '" alt="'.esc_attr__('Active Email Tab', 'event_espresso').'" />';
785
+        $args['img2'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-inactive.png'
786
+                        . '" alt="'.esc_attr__('Inactive Email Tab', 'event_espresso').'" />';
787 787
         $args['img3'] = '<div class="switch">'
788 788
                         . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
789 789
                         . ' type="checkbox" checked="checked">'
@@ -794,25 +794,25 @@  discard block
 block discarded – undo
794 794
                         . ' type="checkbox">'
795 795
                         . '<label for="ee-on-off-toggle-on"></label>'
796 796
                         . '</div>';
797
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
797
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_settings_help_tab.template.php', $args);
798 798
     }
799 799
 
800 800
 
801 801
     public function load_scripts_styles()
802 802
     {
803
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
803
+        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL.'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
804 804
         wp_enqueue_style('espresso_ee_msg');
805 805
 
806 806
         wp_register_script(
807 807
             'ee-messages-settings',
808
-            EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
808
+            EE_MSG_ASSETS_URL.'ee-messages-settings.js',
809 809
             array('jquery-ui-droppable', 'ee-serialize-full-array'),
810 810
             EVENT_ESPRESSO_VERSION,
811 811
             true
812 812
         );
813 813
         wp_register_script(
814 814
             'ee-msg-list-table-js',
815
-            EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
815
+            EE_MSG_ASSETS_URL.'ee_message_admin_list_table.js',
816 816
             array('ee-dialog'),
817 817
             EVENT_ESPRESSO_VERSION
818 818
         );
@@ -870,7 +870,7 @@  discard block
 block discarded – undo
870 870
 
871 871
         wp_register_script(
872 872
             'ee_msgs_edit_js',
873
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
873
+            EE_MSG_ASSETS_URL.'ee_message_editor.js',
874 874
             array('jquery'),
875 875
             EVENT_ESPRESSO_VERSION
876 876
         );
@@ -914,7 +914,7 @@  discard block
 block discarded – undo
914 914
     {
915 915
         wp_register_style(
916 916
             'ee-message-settings',
917
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
917
+            EE_MSG_ASSETS_URL.'ee_message_settings.css',
918 918
             array(),
919 919
             EVENT_ESPRESSO_VERSION
920 920
         );
@@ -1000,7 +1000,7 @@  discard block
 block discarded – undo
1000 1000
             }
1001 1001
             $status_bulk_actions = $common_bulk_actions;
1002 1002
             // unset bulk actions not applying to status
1003
-            if (! empty($status_bulk_actions)) {
1003
+            if ( ! empty($status_bulk_actions)) {
1004 1004
                 switch ($status) {
1005 1005
                     case EEM_Message::status_idle:
1006 1006
                     case EEM_Message::status_resend:
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
                 continue;
1030 1030
             }
1031 1031
 
1032
-            $this->_views[ strtolower($status) ] = array(
1032
+            $this->_views[strtolower($status)] = array(
1033 1033
                 'slug'        => strtolower($status),
1034 1034
                 'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1035 1035
                 'count'       => 0,
@@ -1068,7 +1068,7 @@  discard block
 block discarded – undo
1068 1068
             if ($action_item === 'see_notifications_for') {
1069 1069
                 continue;
1070 1070
             }
1071
-            $action_items[ $action_item ] = array(
1071
+            $action_items[$action_item] = array(
1072 1072
                 'class' => $action_details['css_class'],
1073 1073
                 'desc'  => $action_details['label'],
1074 1074
             );
@@ -1077,37 +1077,37 @@  discard block
 block discarded – undo
1077 1077
         /** @type array $status_items status legend setup */
1078 1078
         $status_items = array(
1079 1079
             'incomplete_status'          => array(
1080
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1080
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_incomplete,
1081 1081
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1082 1082
             ),
1083 1083
             'idle_status'                => array(
1084
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1084
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_idle,
1085 1085
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1086 1086
             ),
1087 1087
             'resend_status'              => array(
1088
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1088
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_resend,
1089 1089
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1090 1090
             ),
1091 1091
             'messenger_executing_status' => array(
1092
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1092
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_messenger_executing,
1093 1093
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1094 1094
             ),
1095 1095
             'sent_status'                => array(
1096
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1096
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_sent,
1097 1097
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1098 1098
             ),
1099 1099
             'retry_status'               => array(
1100
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1100
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_retry,
1101 1101
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1102 1102
             ),
1103 1103
             'failed_status'              => array(
1104
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1104
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_failed,
1105 1105
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1106 1106
             ),
1107 1107
         );
1108 1108
         if (EEM_Message::debug()) {
1109 1109
             $status_items['debug_only_status'] = array(
1110
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1110
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_debug_only,
1111 1111
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1112 1112
             );
1113 1113
         }
@@ -1119,11 +1119,11 @@  discard block
 block discarded – undo
1119 1119
     protected function _custom_mtps_preview()
1120 1120
     {
1121 1121
         $this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1122
-        $this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1123
-                                               . ' alt="' . esc_attr__(
1122
+        $this->_template_args['preview_img'] = '<img src="'.EE_MSG_ASSETS_URL.'images/custom_mtps_preview.png"'
1123
+                                               . ' alt="'.esc_attr__(
1124 1124
                                                    'Preview Custom Message Templates screenshot',
1125 1125
                                                    'event_espresso'
1126
-                                               ) . '" />';
1126
+                                               ).'" />';
1127 1127
         $this->_template_args['preview_text'] = '<strong>'
1128 1128
                                                 . esc_html__(
1129 1129
                                                     'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
@@ -1203,7 +1203,7 @@  discard block
 block discarded – undo
1203 1203
         $installed = array();
1204 1204
 
1205 1205
         foreach ($installed_message_types as $message_type) {
1206
-            $installed[ $message_type->name ] = $message_type;
1206
+            $installed[$message_type->name] = $message_type;
1207 1207
         }
1208 1208
 
1209 1209
         return $installed;
@@ -1352,7 +1352,7 @@  discard block
 block discarded – undo
1352 1352
         // we need to assemble the title from Various details
1353 1353
         $context_label = sprintf(
1354 1354
             esc_html__('(%s %s)', 'event_espresso'),
1355
-            $c_config[ $context ]['label'],
1355
+            $c_config[$context]['label'],
1356 1356
             ucwords($c_label['label'])
1357 1357
         );
1358 1358
 
@@ -1374,7 +1374,7 @@  discard block
 block discarded – undo
1374 1374
             $message_template_group->message_type()
1375 1375
         );
1376 1376
 
1377
-        if (! $template_field_structure) {
1377
+        if ( ! $template_field_structure) {
1378 1378
             $template_field_structure = false;
1379 1379
             $template_fields = esc_html__(
1380 1380
                 'There was an error in assembling the fields for this display (you should see an error message)',
@@ -1388,21 +1388,21 @@  discard block
 block discarded – undo
1388 1388
 
1389 1389
         // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1390 1390
         // will get handled in the "extra" array.
1391
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1392
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1393
-                unset($template_field_structure[ $context ][ $reference_field ]);
1391
+        if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1392
+            foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1393
+                unset($template_field_structure[$context][$reference_field]);
1394 1394
             }
1395 1395
         }
1396 1396
 
1397 1397
         // let's loop through the template_field_structure and actually assemble the input fields!
1398
-        if (! empty($template_field_structure)) {
1399
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1398
+        if ( ! empty($template_field_structure)) {
1399
+            foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1400 1400
                 // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1401 1401
                 // the extra array and reset them.
1402 1402
                 if ($template_field === 'extra') {
1403 1403
                     $this->_template_args['is_extra_fields'] = true;
1404 1404
                     foreach ($field_setup_array as $reference_field => $new_fields_array) {
1405
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1405
+                        $message_template = $message_templates[$context][$reference_field];
1406 1406
                         $content = $message_template instanceof EE_Message_Template
1407 1407
                             ? $message_template->get('MTP_content')
1408 1408
                             : '';
@@ -1411,7 +1411,7 @@  discard block
 block discarded – undo
1411 1411
                             $continue = false;
1412 1412
                             if (isset($extra_array['shortcodes_required'])) {
1413 1413
                                 foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1414
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1414
+                                    if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1415 1415
                                         $continue = true;
1416 1416
                                     }
1417 1417
                                 }
@@ -1424,57 +1424,57 @@  discard block
 block discarded – undo
1424 1424
                                         . '-'
1425 1425
                                         . $extra_field
1426 1426
                                         . '-content';
1427
-                            $template_form_fields[ $field_id ] = $extra_array;
1428
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1427
+                            $template_form_fields[$field_id] = $extra_array;
1428
+                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields['
1429 1429
                                                                          . $reference_field
1430 1430
                                                                          . '][content]['
1431
-                                                                         . $extra_field . ']';
1431
+                                                                         . $extra_field.']';
1432 1432
                             $css_class = isset($extra_array['css_class'])
1433 1433
                                 ? $extra_array['css_class']
1434 1434
                                 : '';
1435 1435
 
1436
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1436
+                            $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1437 1437
                                                                               && in_array($extra_field, $v_fields, true)
1438 1438
                                                                               &&
1439 1439
                                                                               (
1440
-                                                                                  is_array($validators[ $extra_field ])
1441
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1440
+                                                                                  is_array($validators[$extra_field])
1441
+                                                                                  && isset($validators[$extra_field]['msg'])
1442 1442
                                                                               )
1443
-                                ? 'validate-error ' . $css_class
1443
+                                ? 'validate-error '.$css_class
1444 1444
                                 : $css_class;
1445 1445
 
1446
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1447
-                                                                          && isset($content[ $extra_field ])
1448
-                                ? $content[ $extra_field ]
1446
+                            $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1447
+                                                                          && isset($content[$extra_field])
1448
+                                ? $content[$extra_field]
1449 1449
                                 : '';
1450 1450
 
1451 1451
                             // do we have a validation error?  if we do then let's use that value instead
1452
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1453
-                                ? $validators[ $extra_field ]['value']
1454
-                                : $template_form_fields[ $field_id ]['value'];
1452
+                            $template_form_fields[$field_id]['value'] = isset($validators[$extra_field])
1453
+                                ? $validators[$extra_field]['value']
1454
+                                : $template_form_fields[$field_id]['value'];
1455 1455
 
1456 1456
 
1457
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1457
+                            $template_form_fields[$field_id]['db-col'] = 'MTP_content';
1458 1458
 
1459 1459
                             // shortcode selector
1460 1460
                             $field_name_to_use = $extra_field === 'main'
1461 1461
                                 ? 'content'
1462 1462
                                 : $extra_field;
1463
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1463
+                            $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1464 1464
                                 $field_name_to_use,
1465 1465
                                 $field_id
1466 1466
                             );
1467 1467
 
1468 1468
                             if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1469 1469
                                 // we want to decode the entities
1470
-                                $template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1470
+                                $template_form_fields[$field_id]['value'] = $template_form_fields[$field_id]['value'];
1471 1471
                             }/**/
1472 1472
                         }
1473
-                        $templatefield_MTP_id = $reference_field . '-MTP_ID';
1474
-                        $templatefield_templatename_id = $reference_field . '-name';
1473
+                        $templatefield_MTP_id = $reference_field.'-MTP_ID';
1474
+                        $templatefield_templatename_id = $reference_field.'-name';
1475 1475
 
1476
-                        $template_form_fields[ $templatefield_MTP_id ] = array(
1477
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1476
+                        $template_form_fields[$templatefield_MTP_id] = array(
1477
+                            'name'       => 'MTP_template_fields['.$reference_field.'][MTP_ID]',
1478 1478
                             'label'      => null,
1479 1479
                             'input'      => 'hidden',
1480 1480
                             'type'       => 'int',
@@ -1486,8 +1486,8 @@  discard block
 block discarded – undo
1486 1486
                             'db-col'     => 'MTP_ID',
1487 1487
                         );
1488 1488
 
1489
-                        $template_form_fields[ $templatefield_templatename_id ] = array(
1490
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1489
+                        $template_form_fields[$templatefield_templatename_id] = array(
1490
+                            'name'       => 'MTP_template_fields['.$reference_field.'][name]',
1491 1491
                             'label'      => null,
1492 1492
                             'input'      => 'hidden',
1493 1493
                             'type'       => 'string',
@@ -1501,36 +1501,36 @@  discard block
 block discarded – undo
1501 1501
                     }
1502 1502
                     continue; // skip the next stuff, we got the necessary fields here for this dataset.
1503 1503
                 } else {
1504
-                    $field_id = $template_field . '-content';
1505
-                    $template_form_fields[ $field_id ] = $field_setup_array;
1506
-                    $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1507
-                    $message_template = isset($message_templates[ $context ][ $template_field ])
1508
-                        ? $message_templates[ $context ][ $template_field ]
1504
+                    $field_id = $template_field.'-content';
1505
+                    $template_form_fields[$field_id] = $field_setup_array;
1506
+                    $template_form_fields[$field_id]['name'] = 'MTP_template_fields['.$template_field.'][content]';
1507
+                    $message_template = isset($message_templates[$context][$template_field])
1508
+                        ? $message_templates[$context][$template_field]
1509 1509
                         : null;
1510
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1511
-                                                                  && is_array($message_templates[ $context ])
1510
+                    $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1511
+                                                                  && is_array($message_templates[$context])
1512 1512
                                                                   && $message_template instanceof EE_Message_Template
1513 1513
                         ? $message_template->get('MTP_content')
1514 1514
                         : '';
1515 1515
 
1516 1516
                     // do we have a validator error for this field?  if we do then we'll use that value instead
1517
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1518
-                        ? $validators[ $template_field ]['value']
1519
-                        : $template_form_fields[ $field_id ]['value'];
1517
+                    $template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1518
+                        ? $validators[$template_field]['value']
1519
+                        : $template_form_fields[$field_id]['value'];
1520 1520
 
1521 1521
 
1522
-                    $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1522
+                    $template_form_fields[$field_id]['db-col'] = 'MTP_content';
1523 1523
                     $css_class = isset($field_setup_array['css_class'])
1524 1524
                         ? $field_setup_array['css_class']
1525 1525
                         : '';
1526
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1526
+                    $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1527 1527
                                                                       && in_array($template_field, $v_fields, true)
1528
-                                                                      && isset($validators[ $template_field ]['msg'])
1529
-                        ? 'validate-error ' . $css_class
1528
+                                                                      && isset($validators[$template_field]['msg'])
1529
+                        ? 'validate-error '.$css_class
1530 1530
                         : $css_class;
1531 1531
 
1532 1532
                     // shortcode selector
1533
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1533
+                    $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1534 1534
                         $template_field,
1535 1535
                         $field_id
1536 1536
                     );
@@ -1538,12 +1538,12 @@  discard block
 block discarded – undo
1538 1538
 
1539 1539
                 // k took care of content field(s) now let's take care of others.
1540 1540
 
1541
-                $templatefield_MTP_id = $template_field . '-MTP_ID';
1542
-                $templatefield_field_templatename_id = $template_field . '-name';
1541
+                $templatefield_MTP_id = $template_field.'-MTP_ID';
1542
+                $templatefield_field_templatename_id = $template_field.'-name';
1543 1543
 
1544 1544
                 // foreach template field there are actually two form fields created
1545
-                $template_form_fields[ $templatefield_MTP_id ] = array(
1546
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1545
+                $template_form_fields[$templatefield_MTP_id] = array(
1546
+                    'name'       => 'MTP_template_fields['.$template_field.'][MTP_ID]',
1547 1547
                     'label'      => null,
1548 1548
                     'input'      => 'hidden',
1549 1549
                     'type'       => 'int',
@@ -1555,8 +1555,8 @@  discard block
 block discarded – undo
1555 1555
                     'db-col'     => 'MTP_ID',
1556 1556
                 );
1557 1557
 
1558
-                $template_form_fields[ $templatefield_field_templatename_id ] = array(
1559
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1558
+                $template_form_fields[$templatefield_field_templatename_id] = array(
1559
+                    'name'       => 'MTP_template_fields['.$template_field.'][name]',
1560 1560
                     'label'      => null,
1561 1561
                     'input'      => 'hidden',
1562 1562
                     'type'       => 'string',
@@ -1699,10 +1699,10 @@  discard block
 block discarded – undo
1699 1699
                 'value' => $GRP_ID,
1700 1700
             );
1701 1701
             $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1702
-                'name'  => $action . '_nonce',
1702
+                'name'  => $action.'_nonce',
1703 1703
                 'input' => 'hidden',
1704 1704
                 'type'  => 'string',
1705
-                'value' => wp_create_nonce($action . '_nonce'),
1705
+                'value' => wp_create_nonce($action.'_nonce'),
1706 1706
             );
1707 1707
 
1708 1708
             if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
@@ -1743,7 +1743,7 @@  discard block
 block discarded – undo
1743 1743
             ),
1744 1744
             $this->_admin_base_url
1745 1745
         );
1746
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1746
+        $preview_button = '<a href="'.$preview_url.'" class="button-secondary messages-preview-button">'
1747 1747
                           . esc_html__('Preview', 'event_espresso')
1748 1748
                           . '</a>';
1749 1749
 
@@ -1781,7 +1781,7 @@  discard block
 block discarded – undo
1781 1781
 
1782 1782
         $this->_template_path = $this->_template_args['GRP_ID']
1783 1783
             ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1784
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1784
+            : EE_MSG_TEMPLATE_PATH.'ee_msg_details_main_add_meta_box.template.php';
1785 1785
 
1786 1786
         // send along EE_Message_Template_Group object for further template use.
1787 1787
         $this->_template_args['MTP'] = $message_template_group;
@@ -1836,7 +1836,7 @@  discard block
 block discarded – undo
1836 1836
     ) {
1837 1837
         $template_args = array(
1838 1838
             'context'                   => $context,
1839
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1839
+            'nonce'                     => wp_create_nonce('activate_'.$context.'_toggle_nonce'),
1840 1840
             'is_active'                 => $message_template_group->is_context_active($context),
1841 1841
             'on_off_action'             => $message_template_group->is_context_active($context)
1842 1842
                 ? 'context-off'
@@ -1845,7 +1845,7 @@  discard block
 block discarded – undo
1845 1845
             'message_template_group_id' => $message_template_group->ID(),
1846 1846
         );
1847 1847
         return EEH_Template::display_template(
1848
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1848
+            EE_MSG_TEMPLATE_PATH.'ee_msg_editor_active_context_element.template.php',
1849 1849
             $template_args,
1850 1850
             true
1851 1851
         );
@@ -1866,7 +1866,7 @@  discard block
 block discarded – undo
1866 1866
     {
1867 1867
         $success = true;
1868 1868
         // check for required data
1869
-        if (! isset(
1869
+        if ( ! isset(
1870 1870
             $this->_req_data['message_template_group_id'],
1871 1871
             $this->_req_data['context'],
1872 1872
             $this->_req_data['status']
@@ -1883,7 +1883,7 @@  discard block
 block discarded – undo
1883 1883
         $nonce = isset($this->_req_data['toggle_context_nonce'])
1884 1884
             ? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1885 1885
             : '';
1886
-        $nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1886
+        $nonce_ref = 'activate_'.$this->_req_data['context'].'_toggle_nonce';
1887 1887
         $this->_verify_nonce($nonce, $nonce_ref);
1888 1888
         $status = $this->_req_data['status'];
1889 1889
         if ($status !== 'off' && $status !== 'on') {
@@ -1901,7 +1901,7 @@  discard block
 block discarded – undo
1901 1901
         $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1902 1902
             $this->_req_data['message_template_group_id']
1903 1903
         );
1904
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1904
+        if ( ! $message_template_group instanceof EE_Message_Template_Group) {
1905 1905
             EE_Error::add_error(
1906 1906
                 sprintf(
1907 1907
                     esc_html__(
@@ -2030,7 +2030,7 @@  discard block
 block discarded – undo
2030 2030
         $templates = array();
2031 2031
         $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2032 2032
         // we need to make sure we've got the info we need.
2033
-        if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2033
+        if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2034 2034
             EE_Error::add_error(
2035 2035
                 esc_html__(
2036 2036
                     'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
@@ -2072,7 +2072,7 @@  discard block
 block discarded – undo
2072 2072
         }
2073 2073
 
2074 2074
         // any error messages?
2075
-        if (! $success) {
2075
+        if ( ! $success) {
2076 2076
             EE_Error::add_error(
2077 2077
                 esc_html__(
2078 2078
                     'Something went wrong with deleting existing templates. Unable to reset to default',
@@ -2124,7 +2124,7 @@  discard block
 block discarded – undo
2124 2124
     public function _preview_message($send = false)
2125 2125
     {
2126 2126
         // first make sure we've got the necessary parameters
2127
-        if (! isset(
2127
+        if ( ! isset(
2128 2128
             $this->_req_data['message_type'],
2129 2129
             $this->_req_data['messenger'],
2130 2130
             $this->_req_data['messenger'],
@@ -2182,7 +2182,7 @@  discard block
 block discarded – undo
2182 2182
         $preview_title = sprintf(
2183 2183
             esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2184 2184
             $active_messenger_label,
2185
-            ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2185
+            ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
2186 2186
         );
2187 2187
         if (empty($preview)) {
2188 2188
             $this->noEventsErrorMessage();
@@ -2190,7 +2190,7 @@  discard block
 block discarded – undo
2190 2190
         // setup display of preview.
2191 2191
         $this->_admin_page_title = $preview_title;
2192 2192
         $this->_template_args['admin_page_title'] = $preview_title;
2193
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2193
+        $this->_template_args['admin_page_content'] = $preview_button.'<br />'.$preview;
2194 2194
         $this->_template_args['data']['force_json'] = true;
2195 2195
 
2196 2196
         return '';
@@ -2303,10 +2303,10 @@  discard block
 block discarded – undo
2303 2303
         foreach ($tp_collection as $tp) {
2304 2304
             // only include template packs that support this messenger and message type!
2305 2305
             $supports = $tp->get_supports();
2306
-            if (! isset($supports[ $this->_message_template_group->messenger() ])
2306
+            if ( ! isset($supports[$this->_message_template_group->messenger()])
2307 2307
                 || ! in_array(
2308 2308
                     $this->_message_template_group->message_type(),
2309
-                    $supports[ $this->_message_template_group->messenger() ],
2309
+                    $supports[$this->_message_template_group->messenger()],
2310 2310
                     true
2311 2311
                 )
2312 2312
             ) {
@@ -2359,7 +2359,7 @@  discard block
 block discarded – undo
2359 2359
         $template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2360 2360
         $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2361 2361
 
2362
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2362
+        $template = EE_MSG_TEMPLATE_PATH.'template_pack_and_variations_metabox.template.php';
2363 2363
 
2364 2364
         EEH_Template::display_template($template, $template_args);
2365 2365
     }
@@ -2385,10 +2385,10 @@  discard block
 block discarded – undo
2385 2385
         // first we need to see if there are any fields
2386 2386
         $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2387 2387
 
2388
-        if (! empty($fields)) {
2388
+        if ( ! empty($fields)) {
2389 2389
             // yup there be fields
2390 2390
             foreach ($fields as $field => $config) {
2391
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2391
+                $field_id = $this->_message_template_group->messenger().'_'.$field;
2392 2392
                 $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2393 2393
                 $default = isset($config['default']) ? $config['default'] : '';
2394 2394
                 $default = isset($config['value']) ? $config['value'] : $default;
@@ -2396,22 +2396,22 @@  discard block
 block discarded – undo
2396 2396
                 // if type is hidden and the value is empty
2397 2397
                 // something may have gone wrong so let's correct with the defaults
2398 2398
                 $fix = $config['input'] === 'hidden'
2399
-                       && isset($existing[ $field ])
2400
-                       && empty($existing[ $field ])
2399
+                       && isset($existing[$field])
2400
+                       && empty($existing[$field])
2401 2401
                     ? $default
2402 2402
                     : '';
2403
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2404
-                    ? $existing[ $field ]
2403
+                $existing[$field] = isset($existing[$field]) && empty($fix)
2404
+                    ? $existing[$field]
2405 2405
                     : $fix;
2406 2406
 
2407
-                $template_form_fields[ $field_id ] = array(
2408
-                    'name'       => 'test_settings_fld[' . $field . ']',
2407
+                $template_form_fields[$field_id] = array(
2408
+                    'name'       => 'test_settings_fld['.$field.']',
2409 2409
                     'label'      => $config['label'],
2410 2410
                     'input'      => $config['input'],
2411 2411
                     'type'       => $config['type'],
2412 2412
                     'required'   => $config['required'],
2413 2413
                     'validation' => $config['validation'],
2414
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2414
+                    'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2415 2415
                     'css_class'  => $config['css_class'],
2416 2416
                     'options'    => isset($config['options']) ? $config['options'] : array(),
2417 2417
                     'default'    => $default,
@@ -2426,7 +2426,7 @@  discard block
 block discarded – undo
2426 2426
 
2427 2427
         $test_settings_html = '';
2428 2428
         // print out $test_settings_fields
2429
-        if (! empty($test_settings_fields)) {
2429
+        if ( ! empty($test_settings_fields)) {
2430 2430
             echo $test_settings_fields;
2431 2431
             $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2432 2432
             $test_settings_html .= 'name="test_button" value="';
@@ -2473,7 +2473,7 @@  discard block
 block discarded – undo
2473 2473
         );
2474 2474
 
2475 2475
         return EEH_Template::display_template(
2476
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2476
+            EE_MSG_TEMPLATE_PATH.'shortcode_selector_skeleton.template.php',
2477 2477
             $template_args,
2478 2478
             true
2479 2479
         );
@@ -2498,7 +2498,7 @@  discard block
 block discarded – undo
2498 2498
         // $messenger = $this->_message_template_group->messenger_obj();
2499 2499
         // now let's set the content depending on the status of the shortcodes array
2500 2500
         if (empty($shortcodes)) {
2501
-            $content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2501
+            $content = '<p>'.esc_html__('There are no valid shortcodes available', 'event_espresso').'</p>';
2502 2502
             echo $content;
2503 2503
         } else {
2504 2504
             // $alt = 0;
@@ -2536,7 +2536,7 @@  discard block
 block discarded – undo
2536 2536
     {
2537 2537
 
2538 2538
         // no need to run this if the property is already set
2539
-        if (! empty($this->_shortcodes)) {
2539
+        if ( ! empty($this->_shortcodes)) {
2540 2540
             return;
2541 2541
         }
2542 2542
 
@@ -2590,7 +2590,7 @@  discard block
 block discarded – undo
2590 2590
     protected function _set_message_template_group()
2591 2591
     {
2592 2592
 
2593
-        if (! empty($this->_message_template_group)) {
2593
+        if ( ! empty($this->_message_template_group)) {
2594 2594
             return;
2595 2595
         } //get out if this is already set.
2596 2596
 
@@ -2637,7 +2637,7 @@  discard block
 block discarded – undo
2637 2637
                     <?php
2638 2638
                 }
2639 2639
                 // setup nonce_url
2640
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2640
+                wp_nonce_field($args['action'].'_nonce', $args['action'].'_nonce', false);
2641 2641
                 ?>
2642 2642
                 <select name="context">
2643 2643
                     <?php
@@ -2647,7 +2647,7 @@  discard block
 block discarded – undo
2647 2647
                             $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2648 2648
                             ?>
2649 2649
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2650
-                                <?php echo $context_details[ $context ]['label']; ?>
2650
+                                <?php echo $context_details[$context]['label']; ?>
2651 2651
                             </option>
2652 2652
                         <?php endforeach;
2653 2653
                     endif; ?>
@@ -2677,22 +2677,22 @@  discard block
 block discarded – undo
2677 2677
      */
2678 2678
     protected function _set_message_template_column_values($index)
2679 2679
     {
2680
-        if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2681
-            foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2682
-                $this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2680
+        if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2681
+            foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2682
+                $this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2683 2683
             }
2684 2684
         }
2685 2685
 
2686 2686
 
2687 2687
         $set_column_values = array(
2688
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2688
+            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2689 2689
             'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2690 2690
             'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2691 2691
             'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2692 2692
             'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2693
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2693
+            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2694 2694
             'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2695
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2695
+            'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2696 2696
             'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2697 2697
                 ? absint($this->_req_data['MTP_is_global'])
2698 2698
                 : 0,
@@ -2739,7 +2739,7 @@  discard block
 block discarded – undo
2739 2739
         $context = ucwords(str_replace('_', ' ', $context_slug));
2740 2740
 
2741 2741
         $item_desc = $messenger_label && $message_type_label
2742
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2742
+            ? $messenger_label.' '.$message_type_label.' '.$context.' '
2743 2743
             : '';
2744 2744
         $item_desc .= 'Message Template';
2745 2745
         $query_args = array();
@@ -2770,7 +2770,7 @@  discard block
 block discarded – undo
2770 2770
 
2771 2771
 
2772 2772
             // run update for each template field in displayed context
2773
-            if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2773
+            if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2774 2774
                 EE_Error::add_error(
2775 2775
                     esc_html__(
2776 2776
                         'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
@@ -2832,10 +2832,10 @@  discard block
 block discarded – undo
2832 2832
                         $set_column_values = $this->_set_message_template_column_values($template_field);
2833 2833
 
2834 2834
                         $where_cols_n_values = array(
2835
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2835
+                            'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID'],
2836 2836
                         );
2837 2837
                         // if they aren't allowed to use all JS, restrict them to just posty-y tags
2838
-                        if (! current_user_can('unfiltered_html')) {
2838
+                        if ( ! current_user_can('unfiltered_html')) {
2839 2839
                             if (is_array($set_column_values['MTP_content'])) {
2840 2840
                                 foreach ($set_column_values['MTP_content'] as $key => $value) {
2841 2841
                                     // remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
@@ -2843,7 +2843,7 @@  discard block
 block discarded – undo
2843 2843
                                     // appear invalid.) But currently the models expect slashed data, so after wp_kses
2844 2844
                                     // runs we need to re-slash the data. Sheesh. See
2845 2845
                                     // https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2846
-                                    $set_column_values['MTP_content'][ $key ] = addslashes(
2846
+                                    $set_column_values['MTP_content'][$key] = addslashes(
2847 2847
                                         wp_kses(
2848 2848
                                             stripslashes($value),
2849 2849
                                             wp_kses_allowed_html('post')
@@ -2879,14 +2879,14 @@  discard block
 block discarded – undo
2879 2879
                             }
2880 2880
                         } else {
2881 2881
                             // only do this logic if we don't have a MTP_ID for this field
2882
-                            if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2882
+                            if (empty($this->_req_data['MTP_template_fields'][$template_field]['MTP_ID'])) {
2883 2883
                                 // this has already been through the template field validator and sanitized, so it will be
2884 2884
                                 // safe to insert this field.  Why insert?  This typically happens when we introduce a new
2885 2885
                                 // message template field in a messenger/message type and existing users don't have the
2886 2886
                                 // default setup for it.
2887 2887
                                 // @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2888 2888
                                 $updated = $MTP->insert($message_template_fields);
2889
-                                if (! $updated || is_wp_error($updated)) {
2889
+                                if ( ! $updated || is_wp_error($updated)) {
2890 2890
                                     EE_Error::add_error(
2891 2891
                                         sprintf(
2892 2892
                                             esc_html__('%s field could not be updated.', 'event_espresso'),
@@ -3117,7 +3117,7 @@  discard block
 block discarded – undo
3117 3117
         // incoming GRP_IDs
3118 3118
         if ($all) {
3119 3119
             // Checkboxes
3120
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3120
+            if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3121 3121
                 // if array has more than one element then success message should be plural.
3122 3122
                 // todo: what about nonce?
3123 3123
                 $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
@@ -3125,16 +3125,16 @@  discard block
 block discarded – undo
3125 3125
                 // cycle through checkboxes
3126 3126
                 while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3127 3127
                     $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3128
-                    if (! $trashed_or_restored) {
3128
+                    if ( ! $trashed_or_restored) {
3129 3129
                         $success = 0;
3130 3130
                     }
3131 3131
                 }
3132 3132
             } else {
3133 3133
                 // grab single GRP_ID and handle
3134 3134
                 $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3135
-                if (! empty($GRP_ID)) {
3135
+                if ( ! empty($GRP_ID)) {
3136 3136
                     $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3137
-                    if (! $trashed_or_restored) {
3137
+                    if ( ! $trashed_or_restored) {
3138 3138
                         $success = 0;
3139 3139
                     }
3140 3140
                 } else {
@@ -3182,7 +3182,7 @@  discard block
 block discarded – undo
3182 3182
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3183 3183
 
3184 3184
         // checkboxes
3185
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3185
+        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3186 3186
             // if array has more than one element then success message should be plural
3187 3187
             $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3188 3188
 
@@ -3289,7 +3289,7 @@  discard block
 block discarded – undo
3289 3289
     protected function _set_m_mt_settings()
3290 3290
     {
3291 3291
         // first if this is already set then lets get out no need to regenerate data.
3292
-        if (! empty($this->_m_mt_settings)) {
3292
+        if ( ! empty($this->_m_mt_settings)) {
3293 3293
             return;
3294 3294
         }
3295 3295
 
@@ -3303,7 +3303,7 @@  discard block
 block discarded – undo
3303 3303
         // assemble the array for the _tab_text_links helper
3304 3304
 
3305 3305
         foreach ($messengers as $messenger) {
3306
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3306
+            $this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
3307 3307
                 'label' => ucwords($messenger->label['singular']),
3308 3308
                 'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3309 3309
                     ? 'messenger-active'
@@ -3320,7 +3320,7 @@  discard block
 block discarded – undo
3320 3320
             foreach ($message_types as $message_type) {
3321 3321
                 // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3322 3322
                 // it shouldn't show in either the inactive OR active metabox.
3323
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3323
+                if ( ! in_array($message_type->name, $message_types_for_messenger, true)) {
3324 3324
                     continue;
3325 3325
                 }
3326 3326
 
@@ -3331,12 +3331,12 @@  discard block
 block discarded – undo
3331 3331
                     ? 'active'
3332 3332
                     : 'inactive';
3333 3333
 
3334
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3334
+                $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
3335 3335
                     'label'    => ucwords($message_type->label['singular']),
3336
-                    'class'    => 'message-type-' . $a_or_i,
3337
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3338
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3339
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3336
+                    'class'    => 'message-type-'.$a_or_i,
3337
+                    'slug_id'  => $message_type->name.'-messagetype-'.$messenger->name,
3338
+                    'mt_nonce' => wp_create_nonce($message_type->name.'_nonce'),
3339
+                    'href'     => 'espresso_'.$message_type->name.'_message_type_settings',
3340 3340
                     'title'    => $a_or_i === 'active'
3341 3341
                         ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3342 3342
                         : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
@@ -3367,25 +3367,25 @@  discard block
 block discarded – undo
3367 3367
         $fields = $message_type->get_admin_settings_fields();
3368 3368
         $settings_template_args['template_form_fields'] = '';
3369 3369
 
3370
-        if (! empty($fields) && $active) {
3370
+        if ( ! empty($fields) && $active) {
3371 3371
             $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3372 3372
             foreach ($fields as $fldname => $fldprops) {
3373
-                $field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3374
-                $template_form_field[ $field_id ] = array(
3375
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3373
+                $field_id = $messenger->name.'-'.$message_type->name.'-'.$fldname;
3374
+                $template_form_field[$field_id] = array(
3375
+                    'name'       => 'message_type_settings['.$fldname.']',
3376 3376
                     'label'      => $fldprops['label'],
3377 3377
                     'input'      => $fldprops['field_type'],
3378 3378
                     'type'       => $fldprops['value_type'],
3379 3379
                     'required'   => $fldprops['required'],
3380 3380
                     'validation' => $fldprops['validation'],
3381
-                    'value'      => isset($existing_settings[ $fldname ])
3382
-                        ? $existing_settings[ $fldname ]
3381
+                    'value'      => isset($existing_settings[$fldname])
3382
+                        ? $existing_settings[$fldname]
3383 3383
                         : $fldprops['default'],
3384 3384
                     'options'    => isset($fldprops['options'])
3385 3385
                         ? $fldprops['options']
3386 3386
                         : array(),
3387
-                    'default'    => isset($existing_settings[ $fldname ])
3388
-                        ? $existing_settings[ $fldname ]
3387
+                    'default'    => isset($existing_settings[$fldname])
3388
+                        ? $existing_settings[$fldname]
3389 3389
                         : $fldprops['default'],
3390 3390
                     'css_class'  => 'no-drag',
3391 3391
                     'format'     => $fldprops['format'],
@@ -3428,7 +3428,7 @@  discard block
 block discarded – undo
3428 3428
             : '';
3429 3429
 
3430 3430
 
3431
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3431
+        $template = EE_MSG_TEMPLATE_PATH.'ee_msg_mt_settings_content.template.php';
3432 3432
         $content = EEH_Template::display_template($template, $settings_template_args, true);
3433 3433
 
3434 3434
         return $content;
@@ -3459,20 +3459,20 @@  discard block
 block discarded – undo
3459 3459
                 // messenger meta boxes
3460 3460
                 $active = $selected_messenger === $messenger;
3461 3461
                 $active_mt_tabs = isset(
3462
-                    $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3462
+                    $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
3463 3463
                 )
3464
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3464
+                    ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
3465 3465
                     : '';
3466
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3466
+                $m_boxes[$messenger.'_a_box'] = sprintf(
3467 3467
                     esc_html__('%s Settings', 'event_espresso'),
3468 3468
                     $tab_array['label']
3469 3469
                 );
3470
-                $m_template_args[ $messenger . '_a_box' ] = array(
3470
+                $m_template_args[$messenger.'_a_box'] = array(
3471 3471
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3472 3472
                     'inactive_message_types' => isset(
3473
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3473
+                        $this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
3474 3474
                     )
3475
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3475
+                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
3476 3476
                         : '',
3477 3477
                     'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3478 3478
                     'hidden'                 => $active ? '' : ' hidden',
@@ -3483,13 +3483,13 @@  discard block
 block discarded – undo
3483 3483
                 // message type meta boxes
3484 3484
                 // (which is really just the inactive container for each messenger
3485 3485
                 // showing inactive message types for that messenger)
3486
-                $mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3487
-                $mt_template_args[ $messenger . '_i_box' ] = array(
3486
+                $mt_boxes[$messenger.'_i_box'] = esc_html__('Inactive Message Types', 'event_espresso');
3487
+                $mt_template_args[$messenger.'_i_box'] = array(
3488 3488
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3489 3489
                     'inactive_message_types' => isset(
3490
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3490
+                        $this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
3491 3491
                     )
3492
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3492
+                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
3493 3493
                         : '',
3494 3494
                     'hidden'                 => $active ? '' : ' hidden',
3495 3495
                     'hide_on_message'        => $hide_on_message,
@@ -3502,14 +3502,14 @@  discard block
 block discarded – undo
3502 3502
 
3503 3503
 
3504 3504
         // register messenger metaboxes
3505
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3505
+        $m_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_mt_meta_box.template.php';
3506 3506
         foreach ($m_boxes as $box => $label) {
3507
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3507
+            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
3508 3508
             $msgr = str_replace('_a_box', '', $box);
3509 3509
             add_meta_box(
3510
-                'espresso_' . $msgr . '_settings',
3510
+                'espresso_'.$msgr.'_settings',
3511 3511
                 $label,
3512
-                function ($post, $metabox) {
3512
+                function($post, $metabox) {
3513 3513
                     echo EEH_Template::display_template(
3514 3514
                         $metabox["args"]["template_path"],
3515 3515
                         $metabox["args"]["template_args"],
@@ -3524,17 +3524,17 @@  discard block
 block discarded – undo
3524 3524
         }
3525 3525
 
3526 3526
         // register message type metaboxes
3527
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3527
+        $mt_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_meta_box.template.php';
3528 3528
         foreach ($mt_boxes as $box => $label) {
3529 3529
             $callback_args = array(
3530 3530
                 'template_path' => $mt_template_path,
3531
-                'template_args' => $mt_template_args[ $box ],
3531
+                'template_args' => $mt_template_args[$box],
3532 3532
             );
3533 3533
             $mt = str_replace('_i_box', '', $box);
3534 3534
             add_meta_box(
3535
-                'espresso_' . $mt . '_inactive_mts',
3535
+                'espresso_'.$mt.'_inactive_mts',
3536 3536
                 $label,
3537
-                function ($post, $metabox) {
3537
+                function($post, $metabox) {
3538 3538
                     echo EEH_Template::display_template(
3539 3539
                         $metabox["args"]["template_path"],
3540 3540
                         $metabox["args"]["template_args"],
@@ -3680,7 +3680,7 @@  discard block
 block discarded – undo
3680 3680
             if ($form->is_valid()) {
3681 3681
                 $valid_data = $form->valid_data();
3682 3682
                 foreach ($valid_data as $property => $value) {
3683
-                    $setter = 'set_' . $property;
3683
+                    $setter = 'set_'.$property;
3684 3684
                     if (method_exists($network_config, $setter)) {
3685 3685
                         $network_config->{$setter}($value);
3686 3686
                     } elseif (property_exists($network_config, $property)
@@ -3714,7 +3714,7 @@  discard block
 block discarded – undo
3714 3714
     protected function _get_mt_tabs($tab_array)
3715 3715
     {
3716 3716
         $tab_array = (array) $tab_array;
3717
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3717
+        $template = EE_MSG_TEMPLATE_PATH.'ee_msg_details_mt_settings_tab_item.template.php';
3718 3718
         $tabs = '';
3719 3719
 
3720 3720
         foreach ($tab_array as $tab) {
@@ -3742,20 +3742,20 @@  discard block
 block discarded – undo
3742 3742
         $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3743 3743
 
3744 3744
 
3745
-        if (! empty($fields)) {
3745
+        if ( ! empty($fields)) {
3746 3746
             $existing_settings = $messenger->get_existing_admin_settings();
3747 3747
 
3748 3748
             foreach ($fields as $fldname => $fldprops) {
3749
-                $field_id = $messenger->name . '-' . $fldname;
3750
-                $template_form_field[ $field_id ] = array(
3751
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3749
+                $field_id = $messenger->name.'-'.$fldname;
3750
+                $template_form_field[$field_id] = array(
3751
+                    'name'       => 'messenger_settings['.$field_id.']',
3752 3752
                     'label'      => $fldprops['label'],
3753 3753
                     'input'      => $fldprops['field_type'],
3754 3754
                     'type'       => $fldprops['value_type'],
3755 3755
                     'required'   => $fldprops['required'],
3756 3756
                     'validation' => $fldprops['validation'],
3757
-                    'value'      => isset($existing_settings[ $field_id ])
3758
-                        ? $existing_settings[ $field_id ]
3757
+                    'value'      => isset($existing_settings[$field_id])
3758
+                        ? $existing_settings[$field_id]
3759 3759
                         : $fldprops['default'],
3760 3760
                     'css_class'  => '',
3761 3761
                     'format'     => $fldprops['format'],
@@ -3781,9 +3781,9 @@  discard block
 block discarded – undo
3781 3781
         );
3782 3782
 
3783 3783
         // make sure any active message types that are existing are included in the hidden fields
3784
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3785
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3786
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3784
+        if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3785
+            foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3786
+                $settings_template_args['hidden_fields']['messenger_settings[message_types]['.$mt.']'] = array(
3787 3787
                     'type'  => 'hidden',
3788 3788
                     'value' => $mt,
3789 3789
                 );
@@ -3812,9 +3812,9 @@  discard block
 block discarded – undo
3812 3812
 
3813 3813
 
3814 3814
         $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3815
-        $settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3815
+        $settings_template_args['nonce'] = wp_create_nonce('activate_'.$messenger->name.'_toggle_nonce');
3816 3816
         $settings_template_args['on_off_status'] = $active ? true : false;
3817
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3817
+        $template = EE_MSG_TEMPLATE_PATH.'ee_msg_m_settings_content.template.php';
3818 3818
         $content = EEH_Template::display_template(
3819 3819
             $template,
3820 3820
             $settings_template_args,
@@ -3840,7 +3840,7 @@  discard block
 block discarded – undo
3840 3840
         $success = true;
3841 3841
         $this->_prep_default_response_for_messenger_or_message_type_toggle();
3842 3842
         // let's check that we have required data
3843
-        if (! isset($this->_req_data['messenger'])) {
3843
+        if ( ! isset($this->_req_data['messenger'])) {
3844 3844
             EE_Error::add_error(
3845 3845
                 esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3846 3846
                 __FILE__,
@@ -3854,12 +3854,12 @@  discard block
 block discarded – undo
3854 3854
         $nonce = isset($this->_req_data['activate_nonce'])
3855 3855
             ? sanitize_text_field($this->_req_data['activate_nonce'])
3856 3856
             : '';
3857
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3857
+        $nonce_ref = 'activate_'.$this->_req_data['messenger'].'_toggle_nonce';
3858 3858
 
3859 3859
         $this->_verify_nonce($nonce, $nonce_ref);
3860 3860
 
3861 3861
 
3862
-        if (! isset($this->_req_data['status'])) {
3862
+        if ( ! isset($this->_req_data['status'])) {
3863 3863
             EE_Error::add_error(
3864 3864
                 esc_html__(
3865 3865
                     'Messenger status needed to know whether activation or deactivation is happening. No status is given',
@@ -3918,7 +3918,7 @@  discard block
 block discarded – undo
3918 3918
         $this->_prep_default_response_for_messenger_or_message_type_toggle();
3919 3919
 
3920 3920
         // let's make sure we have the necessary data
3921
-        if (! isset($this->_req_data['message_type'])) {
3921
+        if ( ! isset($this->_req_data['message_type'])) {
3922 3922
             EE_Error::add_error(
3923 3923
                 esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3924 3924
                 __FILE__,
@@ -3928,7 +3928,7 @@  discard block
 block discarded – undo
3928 3928
             $success = false;
3929 3929
         }
3930 3930
 
3931
-        if (! isset($this->_req_data['messenger'])) {
3931
+        if ( ! isset($this->_req_data['messenger'])) {
3932 3932
             EE_Error::add_error(
3933 3933
                 esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3934 3934
                 __FILE__,
@@ -3938,7 +3938,7 @@  discard block
 block discarded – undo
3938 3938
             $success = false;
3939 3939
         }
3940 3940
 
3941
-        if (! isset($this->_req_data['status'])) {
3941
+        if ( ! isset($this->_req_data['status'])) {
3942 3942
             EE_Error::add_error(
3943 3943
                 esc_html__(
3944 3944
                     'Messenger status needed to know whether activation or deactivation is happening. No status is given',
@@ -3971,7 +3971,7 @@  discard block
 block discarded – undo
3971 3971
 
3972 3972
         // do a nonce check here since we're not arriving via a normal route
3973 3973
         $nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3974
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3974
+        $nonce_ref = $this->_req_data['message_type'].'_nonce';
3975 3975
 
3976 3976
         $this->_verify_nonce($nonce, $nonce_ref);
3977 3977
 
@@ -4158,7 +4158,7 @@  discard block
 block discarded – undo
4158 4158
         EE_Message_Type $message_type = null
4159 4159
     ) {
4160 4160
         // if $messenger isn't a valid messenger object then get out.
4161
-        if (! $messenger instanceof EE_Messenger) {
4161
+        if ( ! $messenger instanceof EE_Messenger) {
4162 4162
             EE_Error::add_error(
4163 4163
                 esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4164 4164
                 __FILE__,
@@ -4213,7 +4213,7 @@  discard block
 block discarded – undo
4213 4213
             // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4214 4214
             // in which case we just give a success message for the messenger being successfully activated.
4215 4215
         } else {
4216
-            if (! $messenger->get_default_message_types()) {
4216
+            if ( ! $messenger->get_default_message_types()) {
4217 4217
                 // messenger doesn't have any default message types so still a success.
4218 4218
                 EE_Error::add_success(
4219 4219
                     sprintf(
@@ -4269,7 +4269,7 @@  discard block
 block discarded – undo
4269 4269
         EE_Error::overwrite_success();
4270 4270
 
4271 4271
         // if $messenger isn't a valid messenger object then get out.
4272
-        if (! $messenger instanceof EE_Messenger) {
4272
+        if ( ! $messenger instanceof EE_Messenger) {
4273 4273
             EE_Error::add_error(
4274 4274
                 esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4275 4275
                 __FILE__,
@@ -4331,7 +4331,7 @@  discard block
 block discarded – undo
4331 4331
      */
4332 4332
     public function update_mt_form()
4333 4333
     {
4334
-        if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4334
+        if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4335 4335
             EE_Error::add_error(
4336 4336
                 esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4337 4337
                 __FILE__,
@@ -4343,7 +4343,7 @@  discard block
 block discarded – undo
4343 4343
 
4344 4344
         $message_types = $this->get_installed_message_types();
4345 4345
 
4346
-        $message_type = $message_types[ $this->_req_data['message_type'] ];
4346
+        $message_type = $message_types[$this->_req_data['message_type']];
4347 4347
         $messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4348 4348
 
4349 4349
         $content = $this->_message_type_settings_content(
@@ -4363,7 +4363,7 @@  discard block
 block discarded – undo
4363 4363
      */
4364 4364
     public function save_settings()
4365 4365
     {
4366
-        if (! isset($this->_req_data['type'])) {
4366
+        if ( ! isset($this->_req_data['type'])) {
4367 4367
             EE_Error::add_error(
4368 4368
                 esc_html__(
4369 4369
                     'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
@@ -4392,7 +4392,7 @@  discard block
 block discarded – undo
4392 4392
                         unset($settings['message_types']);
4393 4393
                         break;
4394 4394
                     default:
4395
-                        $settings[ $key ] = $value;
4395
+                        $settings[$key] = $value;
4396 4396
                         break;
4397 4397
                 }
4398 4398
             }
@@ -4411,7 +4411,7 @@  discard block
 block discarded – undo
4411 4411
                         unset($settings['message_type']);
4412 4412
                         break;
4413 4413
                     default:
4414
-                        $settings[ $key ] = $value;
4414
+                        $settings[$key] = $value;
4415 4415
                         break;
4416 4416
                 }
4417 4417
             }
@@ -4572,7 +4572,7 @@  discard block
 block discarded – undo
4572 4572
      */
4573 4573
     protected function _get_msg_ids_from_request()
4574 4574
     {
4575
-        if (! isset($this->_req_data['MSG_ID'])) {
4575
+        if ( ! isset($this->_req_data['MSG_ID'])) {
4576 4576
             return array();
4577 4577
         }
4578 4578
 
Please login to merge, or discard this patch.
core/helpers/EEH_DTT_Helper.helper.php 3 patches
Doc Comments   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -197,8 +197,8 @@  discard block
 block discarded – undo
197 197
      * Get Timezone Offset for given timezone object.
198 198
      *
199 199
      * @param DateTimeZone $date_time_zone
200
-     * @param null         $time
201
-     * @return mixed
200
+     * @param integer|null         $time
201
+     * @return integer
202 202
      * @throws InvalidArgumentException
203 203
      * @throws InvalidDataTypeException
204 204
      * @throws InvalidInterfaceException
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
      * @param  DateTime   $DateTime DateTime object
321 321
      * @param  string     $period   a value to indicate what interval is being used in the calculation. The options are
322 322
      *                              'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
323
-     * @param  int|string $value    What you want to increment the date by
323
+     * @param  integer $value    What you want to increment the date by
324 324
      * @param  string     $operand  What operand you wish to use for the calculation
325 325
      * @return DateTime return whatever type came in.
326 326
      * @throws Exception
@@ -856,7 +856,7 @@  discard block
 block discarded – undo
856 856
      * this method will add that "1" into your date regardless of the format.
857 857
      *
858 858
      * @param string $month
859
-     * @return string
859
+     * @return integer
860 860
      */
861 861
     public static function first_of_month_timestamp($month = '')
862 862
     {
@@ -1004,7 +1004,7 @@  discard block
 block discarded – undo
1004 1004
     /**
1005 1005
      * Shim for the WP function `get_user_locale` that was added in WordPress 4.7.0
1006 1006
      *
1007
-     * @param int|WP_User $user_id
1007
+     * @param integer $user_id
1008 1008
      * @return string
1009 1009
      */
1010 1010
     public static function get_user_locale($user_id = 0)
Please login to merge, or discard this patch.
Indentation   +981 added lines, -981 removed lines patch added patch discarded remove patch
@@ -17,1043 +17,1043 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * return the timezone set for the WP install
22
-     *
23
-     * @return string valid timezone string for PHP DateTimeZone() class
24
-     * @throws InvalidArgumentException
25
-     * @throws InvalidDataTypeException
26
-     * @throws InvalidInterfaceException
27
-     */
28
-    public static function get_timezone()
29
-    {
30
-        return EEH_DTT_Helper::get_valid_timezone_string();
31
-    }
20
+	/**
21
+	 * return the timezone set for the WP install
22
+	 *
23
+	 * @return string valid timezone string for PHP DateTimeZone() class
24
+	 * @throws InvalidArgumentException
25
+	 * @throws InvalidDataTypeException
26
+	 * @throws InvalidInterfaceException
27
+	 */
28
+	public static function get_timezone()
29
+	{
30
+		return EEH_DTT_Helper::get_valid_timezone_string();
31
+	}
32 32
 
33 33
 
34
-    /**
35
-     * get_valid_timezone_string
36
-     *    ensures that a valid timezone string is returned
37
-     *
38
-     * @param string $timezone_string
39
-     * @return string
40
-     * @throws InvalidArgumentException
41
-     * @throws InvalidDataTypeException
42
-     * @throws InvalidInterfaceException
43
-     */
44
-    public static function get_valid_timezone_string($timezone_string = '')
45
-    {
46
-        return self::getHelperAdapter()->getValidTimezoneString($timezone_string);
47
-    }
34
+	/**
35
+	 * get_valid_timezone_string
36
+	 *    ensures that a valid timezone string is returned
37
+	 *
38
+	 * @param string $timezone_string
39
+	 * @return string
40
+	 * @throws InvalidArgumentException
41
+	 * @throws InvalidDataTypeException
42
+	 * @throws InvalidInterfaceException
43
+	 */
44
+	public static function get_valid_timezone_string($timezone_string = '')
45
+	{
46
+		return self::getHelperAdapter()->getValidTimezoneString($timezone_string);
47
+	}
48 48
 
49 49
 
50
-    /**
51
-     * This only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
52
-     *
53
-     * @static
54
-     * @param  string $timezone_string Timezone string to check
55
-     * @param bool    $throw_error
56
-     * @return bool
57
-     * @throws InvalidArgumentException
58
-     * @throws InvalidDataTypeException
59
-     * @throws InvalidInterfaceException
60
-     */
61
-    public static function validate_timezone($timezone_string, $throw_error = true)
62
-    {
63
-        return self::getHelperAdapter()->validateTimezone($timezone_string, $throw_error);
64
-    }
50
+	/**
51
+	 * This only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
52
+	 *
53
+	 * @static
54
+	 * @param  string $timezone_string Timezone string to check
55
+	 * @param bool    $throw_error
56
+	 * @return bool
57
+	 * @throws InvalidArgumentException
58
+	 * @throws InvalidDataTypeException
59
+	 * @throws InvalidInterfaceException
60
+	 */
61
+	public static function validate_timezone($timezone_string, $throw_error = true)
62
+	{
63
+		return self::getHelperAdapter()->validateTimezone($timezone_string, $throw_error);
64
+	}
65 65
 
66 66
 
67
-    /**
68
-     * This returns a string that can represent the provided gmt offset in format that can be passed into
69
-     * DateTimeZone.  This is NOT a string that can be passed as a value on the WordPress timezone_string option.
70
-     *
71
-     * @param float|string $gmt_offset
72
-     * @return string
73
-     * @throws InvalidArgumentException
74
-     * @throws InvalidDataTypeException
75
-     * @throws InvalidInterfaceException
76
-     */
77
-    public static function get_timezone_string_from_gmt_offset($gmt_offset = '')
78
-    {
79
-        return self::getHelperAdapter()->getTimezoneStringFromGmtOffset($gmt_offset);
80
-    }
67
+	/**
68
+	 * This returns a string that can represent the provided gmt offset in format that can be passed into
69
+	 * DateTimeZone.  This is NOT a string that can be passed as a value on the WordPress timezone_string option.
70
+	 *
71
+	 * @param float|string $gmt_offset
72
+	 * @return string
73
+	 * @throws InvalidArgumentException
74
+	 * @throws InvalidDataTypeException
75
+	 * @throws InvalidInterfaceException
76
+	 */
77
+	public static function get_timezone_string_from_gmt_offset($gmt_offset = '')
78
+	{
79
+		return self::getHelperAdapter()->getTimezoneStringFromGmtOffset($gmt_offset);
80
+	}
81 81
 
82 82
 
83
-    /**
84
-     * Gets the site's GMT offset based on either the timezone string
85
-     * (in which case teh gmt offset will vary depending on the location's
86
-     * observance of daylight savings time) or the gmt_offset wp option
87
-     *
88
-     * @return int seconds offset
89
-     * @throws InvalidArgumentException
90
-     * @throws InvalidDataTypeException
91
-     * @throws InvalidInterfaceException
92
-     */
93
-    public static function get_site_timezone_gmt_offset()
94
-    {
95
-        return self::getHelperAdapter()->getSiteTimezoneGmtOffset();
96
-    }
83
+	/**
84
+	 * Gets the site's GMT offset based on either the timezone string
85
+	 * (in which case teh gmt offset will vary depending on the location's
86
+	 * observance of daylight savings time) or the gmt_offset wp option
87
+	 *
88
+	 * @return int seconds offset
89
+	 * @throws InvalidArgumentException
90
+	 * @throws InvalidDataTypeException
91
+	 * @throws InvalidInterfaceException
92
+	 */
93
+	public static function get_site_timezone_gmt_offset()
94
+	{
95
+		return self::getHelperAdapter()->getSiteTimezoneGmtOffset();
96
+	}
97 97
 
98 98
 
99
-    /**
100
-     * Depending on PHP version,
101
-     * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
102
-     * To get around that, for these fringe timezones we bump them to a known valid offset.
103
-     * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
104
-     *
105
-     * @deprecated 4.9.54.rc    Developers this was always meant to only be an internally used method.  This will be
106
-     *                          removed in a future version of EE.
107
-     * @param int $gmt_offset
108
-     * @return int
109
-     * @throws InvalidArgumentException
110
-     * @throws InvalidDataTypeException
111
-     * @throws InvalidInterfaceException
112
-     */
113
-    public static function adjust_invalid_gmt_offsets($gmt_offset = 0)
114
-    {
115
-        return self::getHelperAdapter()->adjustInvalidGmtOffsets($gmt_offset);
116
-    }
99
+	/**
100
+	 * Depending on PHP version,
101
+	 * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
102
+	 * To get around that, for these fringe timezones we bump them to a known valid offset.
103
+	 * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
104
+	 *
105
+	 * @deprecated 4.9.54.rc    Developers this was always meant to only be an internally used method.  This will be
106
+	 *                          removed in a future version of EE.
107
+	 * @param int $gmt_offset
108
+	 * @return int
109
+	 * @throws InvalidArgumentException
110
+	 * @throws InvalidDataTypeException
111
+	 * @throws InvalidInterfaceException
112
+	 */
113
+	public static function adjust_invalid_gmt_offsets($gmt_offset = 0)
114
+	{
115
+		return self::getHelperAdapter()->adjustInvalidGmtOffsets($gmt_offset);
116
+	}
117 117
 
118 118
 
119
-    /**
120
-     * get_timezone_string_from_abbreviations_list
121
-     *
122
-     * @deprecated 4.9.54.rc  Developers, this was never intended to be public.  This is a soft deprecation for now.
123
-     *                        If you are using this, you'll want to work out an alternate way of getting the value.
124
-     * @param int  $gmt_offset
125
-     * @param bool $coerce If true, we attempt to coerce with our adjustment table @see self::adjust_invalid_gmt_offset.
126
-     * @return string
127
-     * @throws EE_Error
128
-     * @throws InvalidArgumentException
129
-     * @throws InvalidDataTypeException
130
-     * @throws InvalidInterfaceException
131
-     */
132
-    public static function get_timezone_string_from_abbreviations_list($gmt_offset = 0, $coerce = true)
133
-    {
134
-        $gmt_offset =  (int) $gmt_offset;
135
-        /** @var array[] $abbreviations */
136
-        $abbreviations = DateTimeZone::listAbbreviations();
137
-        foreach ($abbreviations as $abbreviation) {
138
-            foreach ($abbreviation as $timezone) {
139
-                if ((int) $timezone['offset'] === $gmt_offset && (bool) $timezone['dst'] === false) {
140
-                    try {
141
-                        $offset = self::get_timezone_offset(new DateTimeZone($timezone['timezone_id']));
142
-                        if ($offset !== $gmt_offset) {
143
-                            continue;
144
-                        }
145
-                        return $timezone['timezone_id'];
146
-                    } catch (Exception $e) {
147
-                        continue;
148
-                    }
149
-                }
150
-            }
151
-        }
152
-        // if $coerce is true, let's see if we can get a timezone string after the offset is adjusted
153
-        if ($coerce === true) {
154
-            $timezone_string = self::get_timezone_string_from_abbreviations_list(
155
-                self::adjust_invalid_gmt_offsets($gmt_offset),
156
-                false
157
-            );
158
-            if ($timezone_string) {
159
-                return $timezone_string;
160
-            }
161
-        }
162
-        throw new EE_Error(
163
-            sprintf(
164
-                esc_html__(
165
-                    'The provided GMT offset (%1$s), is invalid, please check with %2$sthis list%3$s for what valid timezones can be used',
166
-                    'event_espresso'
167
-                ),
168
-                $gmt_offset / HOUR_IN_SECONDS,
169
-                '<a href="http://www.php.net/manual/en/timezones.php">',
170
-                '</a>'
171
-            )
172
-        );
173
-    }
119
+	/**
120
+	 * get_timezone_string_from_abbreviations_list
121
+	 *
122
+	 * @deprecated 4.9.54.rc  Developers, this was never intended to be public.  This is a soft deprecation for now.
123
+	 *                        If you are using this, you'll want to work out an alternate way of getting the value.
124
+	 * @param int  $gmt_offset
125
+	 * @param bool $coerce If true, we attempt to coerce with our adjustment table @see self::adjust_invalid_gmt_offset.
126
+	 * @return string
127
+	 * @throws EE_Error
128
+	 * @throws InvalidArgumentException
129
+	 * @throws InvalidDataTypeException
130
+	 * @throws InvalidInterfaceException
131
+	 */
132
+	public static function get_timezone_string_from_abbreviations_list($gmt_offset = 0, $coerce = true)
133
+	{
134
+		$gmt_offset =  (int) $gmt_offset;
135
+		/** @var array[] $abbreviations */
136
+		$abbreviations = DateTimeZone::listAbbreviations();
137
+		foreach ($abbreviations as $abbreviation) {
138
+			foreach ($abbreviation as $timezone) {
139
+				if ((int) $timezone['offset'] === $gmt_offset && (bool) $timezone['dst'] === false) {
140
+					try {
141
+						$offset = self::get_timezone_offset(new DateTimeZone($timezone['timezone_id']));
142
+						if ($offset !== $gmt_offset) {
143
+							continue;
144
+						}
145
+						return $timezone['timezone_id'];
146
+					} catch (Exception $e) {
147
+						continue;
148
+					}
149
+				}
150
+			}
151
+		}
152
+		// if $coerce is true, let's see if we can get a timezone string after the offset is adjusted
153
+		if ($coerce === true) {
154
+			$timezone_string = self::get_timezone_string_from_abbreviations_list(
155
+				self::adjust_invalid_gmt_offsets($gmt_offset),
156
+				false
157
+			);
158
+			if ($timezone_string) {
159
+				return $timezone_string;
160
+			}
161
+		}
162
+		throw new EE_Error(
163
+			sprintf(
164
+				esc_html__(
165
+					'The provided GMT offset (%1$s), is invalid, please check with %2$sthis list%3$s for what valid timezones can be used',
166
+					'event_espresso'
167
+				),
168
+				$gmt_offset / HOUR_IN_SECONDS,
169
+				'<a href="http://www.php.net/manual/en/timezones.php">',
170
+				'</a>'
171
+			)
172
+		);
173
+	}
174 174
 
175 175
 
176
-    /**
177
-     * Get Timezone Transitions
178
-     *
179
-     * @param DateTimeZone $date_time_zone
180
-     * @param int|null     $time
181
-     * @param bool         $first_only
182
-     * @return array
183
-     * @throws InvalidArgumentException
184
-     * @throws InvalidDataTypeException
185
-     * @throws InvalidInterfaceException
186
-     */
187
-    public static function get_timezone_transitions(DateTimeZone $date_time_zone, $time = null, $first_only = true)
188
-    {
189
-        return self::getHelperAdapter()->getTimezoneTransitions($date_time_zone, $time, $first_only);
190
-    }
176
+	/**
177
+	 * Get Timezone Transitions
178
+	 *
179
+	 * @param DateTimeZone $date_time_zone
180
+	 * @param int|null     $time
181
+	 * @param bool         $first_only
182
+	 * @return array
183
+	 * @throws InvalidArgumentException
184
+	 * @throws InvalidDataTypeException
185
+	 * @throws InvalidInterfaceException
186
+	 */
187
+	public static function get_timezone_transitions(DateTimeZone $date_time_zone, $time = null, $first_only = true)
188
+	{
189
+		return self::getHelperAdapter()->getTimezoneTransitions($date_time_zone, $time, $first_only);
190
+	}
191 191
 
192 192
 
193
-    /**
194
-     * Get Timezone Offset for given timezone object.
195
-     *
196
-     * @param DateTimeZone $date_time_zone
197
-     * @param null         $time
198
-     * @return mixed
199
-     * @throws InvalidArgumentException
200
-     * @throws InvalidDataTypeException
201
-     * @throws InvalidInterfaceException
202
-     */
203
-    public static function get_timezone_offset(DateTimeZone $date_time_zone, $time = null)
204
-    {
205
-        return self::getHelperAdapter()->getTimezoneOffset($date_time_zone, $time);
206
-    }
193
+	/**
194
+	 * Get Timezone Offset for given timezone object.
195
+	 *
196
+	 * @param DateTimeZone $date_time_zone
197
+	 * @param null         $time
198
+	 * @return mixed
199
+	 * @throws InvalidArgumentException
200
+	 * @throws InvalidDataTypeException
201
+	 * @throws InvalidInterfaceException
202
+	 */
203
+	public static function get_timezone_offset(DateTimeZone $date_time_zone, $time = null)
204
+	{
205
+		return self::getHelperAdapter()->getTimezoneOffset($date_time_zone, $time);
206
+	}
207 207
 
208 208
 
209
-    /**
210
-     * Prints a select input for the given timezone string.
211
-     * @param string $timezone_string
212
-     * @deprecatd 4.9.54.rc   Soft deprecation.  Consider using \EEH_DTT_Helper::wp_timezone_choice instead.
213
-     * @throws InvalidArgumentException
214
-     * @throws InvalidDataTypeException
215
-     * @throws InvalidInterfaceException
216
-     */
217
-    public static function timezone_select_input($timezone_string = '')
218
-    {
219
-        self::getHelperAdapter()->timezoneSelectInput($timezone_string);
220
-    }
209
+	/**
210
+	 * Prints a select input for the given timezone string.
211
+	 * @param string $timezone_string
212
+	 * @deprecatd 4.9.54.rc   Soft deprecation.  Consider using \EEH_DTT_Helper::wp_timezone_choice instead.
213
+	 * @throws InvalidArgumentException
214
+	 * @throws InvalidDataTypeException
215
+	 * @throws InvalidInterfaceException
216
+	 */
217
+	public static function timezone_select_input($timezone_string = '')
218
+	{
219
+		self::getHelperAdapter()->timezoneSelectInput($timezone_string);
220
+	}
221 221
 
222 222
 
223
-    /**
224
-     * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
225
-     * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
226
-     * the site is used.
227
-     * This is used typically when using a Unix timestamp any core WP functions that expect their specially
228
-     * computed timestamp (i.e. date_i18n() )
229
-     *
230
-     * @param int    $unix_timestamp                  if 0, then time() will be used.
231
-     * @param string $timezone_string                 timezone_string. If empty, then the current set timezone for the
232
-     *                                                site will be used.
233
-     * @return int $unix_timestamp with the offset applied for the given timezone.
234
-     * @throws InvalidArgumentException
235
-     * @throws InvalidDataTypeException
236
-     * @throws InvalidInterfaceException
237
-     */
238
-    public static function get_timestamp_with_offset($unix_timestamp = 0, $timezone_string = '')
239
-    {
240
-        return self::getHelperAdapter()->getTimestampWithOffset($unix_timestamp, $timezone_string);
241
-    }
223
+	/**
224
+	 * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
225
+	 * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
226
+	 * the site is used.
227
+	 * This is used typically when using a Unix timestamp any core WP functions that expect their specially
228
+	 * computed timestamp (i.e. date_i18n() )
229
+	 *
230
+	 * @param int    $unix_timestamp                  if 0, then time() will be used.
231
+	 * @param string $timezone_string                 timezone_string. If empty, then the current set timezone for the
232
+	 *                                                site will be used.
233
+	 * @return int $unix_timestamp with the offset applied for the given timezone.
234
+	 * @throws InvalidArgumentException
235
+	 * @throws InvalidDataTypeException
236
+	 * @throws InvalidInterfaceException
237
+	 */
238
+	public static function get_timestamp_with_offset($unix_timestamp = 0, $timezone_string = '')
239
+	{
240
+		return self::getHelperAdapter()->getTimestampWithOffset($unix_timestamp, $timezone_string);
241
+	}
242 242
 
243 243
 
244
-    /**
245
-     *    _set_date_time_field
246
-     *    modifies EE_Base_Class EE_Datetime_Field objects
247
-     *
248
-     * @param  EE_Base_Class $obj                 EE_Base_Class object
249
-     * @param    DateTime    $DateTime            PHP DateTime object
250
-     * @param  string        $datetime_field_name the datetime fieldname to be manipulated
251
-     * @return EE_Base_Class
252
-     * @throws EE_Error
253
-     */
254
-    protected static function _set_date_time_field(EE_Base_Class $obj, DateTime $DateTime, $datetime_field_name)
255
-    {
256
-        // grab current datetime format
257
-        $current_format = $obj->get_format();
258
-        // set new full timestamp format
259
-        $obj->set_date_format(EE_Datetime_Field::mysql_date_format);
260
-        $obj->set_time_format(EE_Datetime_Field::mysql_time_format);
261
-        // set the new date value using a full timestamp format so that no data is lost
262
-        $obj->set($datetime_field_name, $DateTime->format(EE_Datetime_Field::mysql_timestamp_format));
263
-        // reset datetime formats
264
-        $obj->set_date_format($current_format[0]);
265
-        $obj->set_time_format($current_format[1]);
266
-        return $obj;
267
-    }
244
+	/**
245
+	 *    _set_date_time_field
246
+	 *    modifies EE_Base_Class EE_Datetime_Field objects
247
+	 *
248
+	 * @param  EE_Base_Class $obj                 EE_Base_Class object
249
+	 * @param    DateTime    $DateTime            PHP DateTime object
250
+	 * @param  string        $datetime_field_name the datetime fieldname to be manipulated
251
+	 * @return EE_Base_Class
252
+	 * @throws EE_Error
253
+	 */
254
+	protected static function _set_date_time_field(EE_Base_Class $obj, DateTime $DateTime, $datetime_field_name)
255
+	{
256
+		// grab current datetime format
257
+		$current_format = $obj->get_format();
258
+		// set new full timestamp format
259
+		$obj->set_date_format(EE_Datetime_Field::mysql_date_format);
260
+		$obj->set_time_format(EE_Datetime_Field::mysql_time_format);
261
+		// set the new date value using a full timestamp format so that no data is lost
262
+		$obj->set($datetime_field_name, $DateTime->format(EE_Datetime_Field::mysql_timestamp_format));
263
+		// reset datetime formats
264
+		$obj->set_date_format($current_format[0]);
265
+		$obj->set_time_format($current_format[1]);
266
+		return $obj;
267
+	}
268 268
 
269 269
 
270
-    /**
271
-     *    date_time_add
272
-     *    helper for doing simple datetime calculations on a given datetime from EE_Base_Class
273
-     *    and modifying it IN the EE_Base_Class so you don't have to do anything else.
274
-     *
275
-     * @param  EE_Base_Class $obj                 EE_Base_Class object
276
-     * @param  string        $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
277
-     * @param  string        $period              what you are adding. The options are (years, months, days, hours,
278
-     *                                            minutes, seconds) defaults to years
279
-     * @param  integer       $value               what you want to increment the time by
280
-     * @return EE_Base_Class return the EE_Base_Class object so right away you can do something with it
281
-     *                                            (chaining)
282
-     * @throws EE_Error
283
-     * @throws Exception
284
-     */
285
-    public static function date_time_add(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
286
-    {
287
-        // get the raw UTC date.
288
-        $DateTime = $obj->get_DateTime_object($datetime_field_name);
289
-        $DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value);
290
-        return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
291
-    }
270
+	/**
271
+	 *    date_time_add
272
+	 *    helper for doing simple datetime calculations on a given datetime from EE_Base_Class
273
+	 *    and modifying it IN the EE_Base_Class so you don't have to do anything else.
274
+	 *
275
+	 * @param  EE_Base_Class $obj                 EE_Base_Class object
276
+	 * @param  string        $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
277
+	 * @param  string        $period              what you are adding. The options are (years, months, days, hours,
278
+	 *                                            minutes, seconds) defaults to years
279
+	 * @param  integer       $value               what you want to increment the time by
280
+	 * @return EE_Base_Class return the EE_Base_Class object so right away you can do something with it
281
+	 *                                            (chaining)
282
+	 * @throws EE_Error
283
+	 * @throws Exception
284
+	 */
285
+	public static function date_time_add(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
286
+	{
287
+		// get the raw UTC date.
288
+		$DateTime = $obj->get_DateTime_object($datetime_field_name);
289
+		$DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value);
290
+		return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
291
+	}
292 292
 
293 293
 
294
-    /**
295
-     *    date_time_subtract
296
-     *    same as date_time_add except subtracting value instead of adding.
297
-     *
298
-     * @param EE_Base_Class $obj
299
-     * @param  string       $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
300
-     * @param string        $period
301
-     * @param int           $value
302
-     * @return EE_Base_Class
303
-     * @throws EE_Error
304
-     * @throws Exception
305
-     */
306
-    public static function date_time_subtract(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
307
-    {
308
-        // get the raw UTC date
309
-        $DateTime = $obj->get_DateTime_object($datetime_field_name);
310
-        $DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value, '-');
311
-        return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
312
-    }
294
+	/**
295
+	 *    date_time_subtract
296
+	 *    same as date_time_add except subtracting value instead of adding.
297
+	 *
298
+	 * @param EE_Base_Class $obj
299
+	 * @param  string       $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
300
+	 * @param string        $period
301
+	 * @param int           $value
302
+	 * @return EE_Base_Class
303
+	 * @throws EE_Error
304
+	 * @throws Exception
305
+	 */
306
+	public static function date_time_subtract(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
307
+	{
308
+		// get the raw UTC date
309
+		$DateTime = $obj->get_DateTime_object($datetime_field_name);
310
+		$DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value, '-');
311
+		return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
312
+	}
313 313
 
314 314
 
315
-    /**
316
-     * Simply takes an incoming DateTime object and does calculations on it based on the incoming parameters
317
-     *
318
-     * @param  DateTime   $DateTime DateTime object
319
-     * @param  string     $period   a value to indicate what interval is being used in the calculation. The options are
320
-     *                              'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
321
-     * @param  int|string $value    What you want to increment the date by
322
-     * @param  string     $operand  What operand you wish to use for the calculation
323
-     * @return DateTime return whatever type came in.
324
-     * @throws Exception
325
-     * @throws EE_Error
326
-     */
327
-    protected static function _modify_datetime_object(DateTime $DateTime, $period = 'years', $value = 1, $operand = '+')
328
-    {
329
-        if (! $DateTime instanceof DateTime) {
330
-            throw new EE_Error(
331
-                sprintf(
332
-                    esc_html__('Expected a PHP DateTime object, but instead received %1$s', 'event_espresso'),
333
-                    print_r($DateTime, true)
334
-                )
335
-            );
336
-        }
337
-        switch ($period) {
338
-            case 'years':
339
-                $value = 'P' . $value . 'Y';
340
-                break;
341
-            case 'months':
342
-                $value = 'P' . $value . 'M';
343
-                break;
344
-            case 'weeks':
345
-                $value = 'P' . $value . 'W';
346
-                break;
347
-            case 'days':
348
-                $value = 'P' . $value . 'D';
349
-                break;
350
-            case 'hours':
351
-                $value = 'PT' . $value . 'H';
352
-                break;
353
-            case 'minutes':
354
-                $value = 'PT' . $value . 'M';
355
-                break;
356
-            case 'seconds':
357
-                $value = 'PT' . $value . 'S';
358
-                break;
359
-        }
360
-        switch ($operand) {
361
-            case '+':
362
-                $DateTime->add(new DateInterval($value));
363
-                break;
364
-            case '-':
365
-                $DateTime->sub(new DateInterval($value));
366
-                break;
367
-        }
368
-        return $DateTime;
369
-    }
315
+	/**
316
+	 * Simply takes an incoming DateTime object and does calculations on it based on the incoming parameters
317
+	 *
318
+	 * @param  DateTime   $DateTime DateTime object
319
+	 * @param  string     $period   a value to indicate what interval is being used in the calculation. The options are
320
+	 *                              'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
321
+	 * @param  int|string $value    What you want to increment the date by
322
+	 * @param  string     $operand  What operand you wish to use for the calculation
323
+	 * @return DateTime return whatever type came in.
324
+	 * @throws Exception
325
+	 * @throws EE_Error
326
+	 */
327
+	protected static function _modify_datetime_object(DateTime $DateTime, $period = 'years', $value = 1, $operand = '+')
328
+	{
329
+		if (! $DateTime instanceof DateTime) {
330
+			throw new EE_Error(
331
+				sprintf(
332
+					esc_html__('Expected a PHP DateTime object, but instead received %1$s', 'event_espresso'),
333
+					print_r($DateTime, true)
334
+				)
335
+			);
336
+		}
337
+		switch ($period) {
338
+			case 'years':
339
+				$value = 'P' . $value . 'Y';
340
+				break;
341
+			case 'months':
342
+				$value = 'P' . $value . 'M';
343
+				break;
344
+			case 'weeks':
345
+				$value = 'P' . $value . 'W';
346
+				break;
347
+			case 'days':
348
+				$value = 'P' . $value . 'D';
349
+				break;
350
+			case 'hours':
351
+				$value = 'PT' . $value . 'H';
352
+				break;
353
+			case 'minutes':
354
+				$value = 'PT' . $value . 'M';
355
+				break;
356
+			case 'seconds':
357
+				$value = 'PT' . $value . 'S';
358
+				break;
359
+		}
360
+		switch ($operand) {
361
+			case '+':
362
+				$DateTime->add(new DateInterval($value));
363
+				break;
364
+			case '-':
365
+				$DateTime->sub(new DateInterval($value));
366
+				break;
367
+		}
368
+		return $DateTime;
369
+	}
370 370
 
371 371
 
372
-    /**
373
-     * Simply takes an incoming Unix timestamp and does calculations on it based on the incoming parameters
374
-     *
375
-     * @param  int     $timestamp Unix timestamp
376
-     * @param  string  $period    a value to indicate what interval is being used in the calculation. The options are
377
-     *                            'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
378
-     * @param  integer $value     What you want to increment the date by
379
-     * @param  string  $operand   What operand you wish to use for the calculation
380
-     * @return int
381
-     * @throws EE_Error
382
-     */
383
-    protected static function _modify_timestamp($timestamp, $period = 'years', $value = 1, $operand = '+')
384
-    {
385
-        if (! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
386
-            throw new EE_Error(
387
-                sprintf(
388
-                    esc_html__('Expected a Unix timestamp, but instead received %1$s', 'event_espresso'),
389
-                    print_r($timestamp, true)
390
-                )
391
-            );
392
-        }
393
-        switch ($period) {
394
-            case 'years':
395
-                $value = YEAR_IN_SECONDS * $value;
396
-                break;
397
-            case 'months':
398
-                $value = YEAR_IN_SECONDS / 12 * $value;
399
-                break;
400
-            case 'weeks':
401
-                $value = WEEK_IN_SECONDS * $value;
402
-                break;
403
-            case 'days':
404
-                $value = DAY_IN_SECONDS * $value;
405
-                break;
406
-            case 'hours':
407
-                $value = HOUR_IN_SECONDS * $value;
408
-                break;
409
-            case 'minutes':
410
-                $value = MINUTE_IN_SECONDS * $value;
411
-                break;
412
-        }
413
-        switch ($operand) {
414
-            case '+':
415
-                $timestamp += $value;
416
-                break;
417
-            case '-':
418
-                $timestamp -= $value;
419
-                break;
420
-        }
421
-        return $timestamp;
422
-    }
372
+	/**
373
+	 * Simply takes an incoming Unix timestamp and does calculations on it based on the incoming parameters
374
+	 *
375
+	 * @param  int     $timestamp Unix timestamp
376
+	 * @param  string  $period    a value to indicate what interval is being used in the calculation. The options are
377
+	 *                            'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
378
+	 * @param  integer $value     What you want to increment the date by
379
+	 * @param  string  $operand   What operand you wish to use for the calculation
380
+	 * @return int
381
+	 * @throws EE_Error
382
+	 */
383
+	protected static function _modify_timestamp($timestamp, $period = 'years', $value = 1, $operand = '+')
384
+	{
385
+		if (! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
386
+			throw new EE_Error(
387
+				sprintf(
388
+					esc_html__('Expected a Unix timestamp, but instead received %1$s', 'event_espresso'),
389
+					print_r($timestamp, true)
390
+				)
391
+			);
392
+		}
393
+		switch ($period) {
394
+			case 'years':
395
+				$value = YEAR_IN_SECONDS * $value;
396
+				break;
397
+			case 'months':
398
+				$value = YEAR_IN_SECONDS / 12 * $value;
399
+				break;
400
+			case 'weeks':
401
+				$value = WEEK_IN_SECONDS * $value;
402
+				break;
403
+			case 'days':
404
+				$value = DAY_IN_SECONDS * $value;
405
+				break;
406
+			case 'hours':
407
+				$value = HOUR_IN_SECONDS * $value;
408
+				break;
409
+			case 'minutes':
410
+				$value = MINUTE_IN_SECONDS * $value;
411
+				break;
412
+		}
413
+		switch ($operand) {
414
+			case '+':
415
+				$timestamp += $value;
416
+				break;
417
+			case '-':
418
+				$timestamp -= $value;
419
+				break;
420
+		}
421
+		return $timestamp;
422
+	}
423 423
 
424 424
 
425
-    /**
426
-     * Simply takes an incoming UTC timestamp or DateTime object and does calculations on it based on the incoming
427
-     * parameters and returns the new timestamp or DateTime.
428
-     *
429
-     * @param  int | DateTime $DateTime_or_timestamp DateTime object or Unix timestamp
430
-     * @param  string         $period                a value to indicate what interval is being used in the
431
-     *                                               calculation. The options are 'years', 'months', 'days', 'hours',
432
-     *                                               'minutes', 'seconds'. Defaults to years.
433
-     * @param  integer        $value                 What you want to increment the date by
434
-     * @param  string         $operand               What operand you wish to use for the calculation
435
-     * @return mixed string|DateTime          return whatever type came in.
436
-     * @throws Exception
437
-     * @throws EE_Error
438
-     */
439
-    public static function calc_date($DateTime_or_timestamp, $period = 'years', $value = 1, $operand = '+')
440
-    {
441
-        if ($DateTime_or_timestamp instanceof DateTime) {
442
-            return EEH_DTT_Helper::_modify_datetime_object(
443
-                $DateTime_or_timestamp,
444
-                $period,
445
-                $value,
446
-                $operand
447
-            );
448
-        }
449
-        if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $DateTime_or_timestamp)) {
450
-            return EEH_DTT_Helper::_modify_timestamp(
451
-                $DateTime_or_timestamp,
452
-                $period,
453
-                $value,
454
-                $operand
455
-            );
456
-        }
457
-        // error
458
-        return $DateTime_or_timestamp;
459
-    }
425
+	/**
426
+	 * Simply takes an incoming UTC timestamp or DateTime object and does calculations on it based on the incoming
427
+	 * parameters and returns the new timestamp or DateTime.
428
+	 *
429
+	 * @param  int | DateTime $DateTime_or_timestamp DateTime object or Unix timestamp
430
+	 * @param  string         $period                a value to indicate what interval is being used in the
431
+	 *                                               calculation. The options are 'years', 'months', 'days', 'hours',
432
+	 *                                               'minutes', 'seconds'. Defaults to years.
433
+	 * @param  integer        $value                 What you want to increment the date by
434
+	 * @param  string         $operand               What operand you wish to use for the calculation
435
+	 * @return mixed string|DateTime          return whatever type came in.
436
+	 * @throws Exception
437
+	 * @throws EE_Error
438
+	 */
439
+	public static function calc_date($DateTime_or_timestamp, $period = 'years', $value = 1, $operand = '+')
440
+	{
441
+		if ($DateTime_or_timestamp instanceof DateTime) {
442
+			return EEH_DTT_Helper::_modify_datetime_object(
443
+				$DateTime_or_timestamp,
444
+				$period,
445
+				$value,
446
+				$operand
447
+			);
448
+		}
449
+		if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $DateTime_or_timestamp)) {
450
+			return EEH_DTT_Helper::_modify_timestamp(
451
+				$DateTime_or_timestamp,
452
+				$period,
453
+				$value,
454
+				$operand
455
+			);
456
+		}
457
+		// error
458
+		return $DateTime_or_timestamp;
459
+	}
460 460
 
461 461
 
462
-    /**
463
-     * The purpose of this helper method is to receive an incoming format string in php date/time format
464
-     * and spit out the js and moment.js equivalent formats.
465
-     * Note, if no format string is given, then it is assumed the user wants what is set for WP.
466
-     * Note, js date and time formats are those used by the jquery-ui datepicker and the jquery-ui date-
467
-     * time picker.
468
-     *
469
-     * @see http://stackoverflow.com/posts/16725290/ for the code inspiration.
470
-     * @param string $date_format_string
471
-     * @param string $time_format_string
472
-     * @return array
473
-     *              array(
474
-     *              'js' => array (
475
-     *              'date' => //date format
476
-     *              'time' => //time format
477
-     *              ),
478
-     *              'moment' => //date and time format.
479
-     *              )
480
-     */
481
-    public static function convert_php_to_js_and_moment_date_formats(
482
-        $date_format_string = null,
483
-        $time_format_string = null
484
-    ) {
485
-        if ($date_format_string === null) {
486
-            $date_format_string = (string) get_option('date_format');
487
-        }
488
-        if ($time_format_string === null) {
489
-            $time_format_string = (string) get_option('time_format');
490
-        }
491
-        $date_format = self::_php_to_js_moment_converter($date_format_string);
492
-        $time_format = self::_php_to_js_moment_converter($time_format_string);
493
-        return array(
494
-            'js'     => array(
495
-                'date' => $date_format['js'],
496
-                'time' => $time_format['js'],
497
-            ),
498
-            'moment' => $date_format['moment'] . ' ' . $time_format['moment'],
499
-            'moment_split' => array(
500
-                'date' => $date_format['moment'],
501
-                'time' => $time_format['moment']
502
-            )
503
-        );
504
-    }
462
+	/**
463
+	 * The purpose of this helper method is to receive an incoming format string in php date/time format
464
+	 * and spit out the js and moment.js equivalent formats.
465
+	 * Note, if no format string is given, then it is assumed the user wants what is set for WP.
466
+	 * Note, js date and time formats are those used by the jquery-ui datepicker and the jquery-ui date-
467
+	 * time picker.
468
+	 *
469
+	 * @see http://stackoverflow.com/posts/16725290/ for the code inspiration.
470
+	 * @param string $date_format_string
471
+	 * @param string $time_format_string
472
+	 * @return array
473
+	 *              array(
474
+	 *              'js' => array (
475
+	 *              'date' => //date format
476
+	 *              'time' => //time format
477
+	 *              ),
478
+	 *              'moment' => //date and time format.
479
+	 *              )
480
+	 */
481
+	public static function convert_php_to_js_and_moment_date_formats(
482
+		$date_format_string = null,
483
+		$time_format_string = null
484
+	) {
485
+		if ($date_format_string === null) {
486
+			$date_format_string = (string) get_option('date_format');
487
+		}
488
+		if ($time_format_string === null) {
489
+			$time_format_string = (string) get_option('time_format');
490
+		}
491
+		$date_format = self::_php_to_js_moment_converter($date_format_string);
492
+		$time_format = self::_php_to_js_moment_converter($time_format_string);
493
+		return array(
494
+			'js'     => array(
495
+				'date' => $date_format['js'],
496
+				'time' => $time_format['js'],
497
+			),
498
+			'moment' => $date_format['moment'] . ' ' . $time_format['moment'],
499
+			'moment_split' => array(
500
+				'date' => $date_format['moment'],
501
+				'time' => $time_format['moment']
502
+			)
503
+		);
504
+	}
505 505
 
506 506
 
507
-    /**
508
-     * This converts incoming format string into js and moment variations.
509
-     *
510
-     * @param string $format_string incoming php format string
511
-     * @return array js and moment formats.
512
-     */
513
-    protected static function _php_to_js_moment_converter($format_string)
514
-    {
515
-        /**
516
-         * This is a map of symbols for formats.
517
-         * The index is the php symbol, the equivalent values are in the array.
518
-         *
519
-         * @var array
520
-         */
521
-        $symbols_map          = array(
522
-            // Day
523
-            // 01
524
-            'd' => array(
525
-                'js'     => 'dd',
526
-                'moment' => 'DD',
527
-            ),
528
-            // Mon
529
-            'D' => array(
530
-                'js'     => 'D',
531
-                'moment' => 'ddd',
532
-            ),
533
-            // 1,2,...31
534
-            'j' => array(
535
-                'js'     => 'd',
536
-                'moment' => 'D',
537
-            ),
538
-            // Monday
539
-            'l' => array(
540
-                'js'     => 'DD',
541
-                'moment' => 'dddd',
542
-            ),
543
-            // ISO numeric representation of the day of the week (1-6)
544
-            'N' => array(
545
-                'js'     => '',
546
-                'moment' => 'E',
547
-            ),
548
-            // st,nd.rd
549
-            'S' => array(
550
-                'js'     => '',
551
-                'moment' => 'o',
552
-            ),
553
-            // numeric representation of day of week (0-6)
554
-            'w' => array(
555
-                'js'     => '',
556
-                'moment' => 'd',
557
-            ),
558
-            // day of year starting from 0 (0-365)
559
-            'z' => array(
560
-                'js'     => 'o',
561
-                'moment' => 'DDD' // note moment does not start with 0 so will need to modify by subtracting 1
562
-            ),
563
-            // Week
564
-            // ISO-8601 week number of year (weeks starting on monday)
565
-            'W' => array(
566
-                'js'     => '',
567
-                'moment' => 'w',
568
-            ),
569
-            // Month
570
-            // January...December
571
-            'F' => array(
572
-                'js'     => 'MM',
573
-                'moment' => 'MMMM',
574
-            ),
575
-            // 01...12
576
-            'm' => array(
577
-                'js'     => 'mm',
578
-                'moment' => 'MM',
579
-            ),
580
-            // Jan...Dec
581
-            'M' => array(
582
-                'js'     => 'M',
583
-                'moment' => 'MMM',
584
-            ),
585
-            // 1-12
586
-            'n' => array(
587
-                'js'     => 'm',
588
-                'moment' => 'M',
589
-            ),
590
-            // number of days in given month
591
-            't' => array(
592
-                'js'     => '',
593
-                'moment' => '',
594
-            ),
595
-            // Year
596
-            // whether leap year or not 1/0
597
-            'L' => array(
598
-                'js'     => '',
599
-                'moment' => '',
600
-            ),
601
-            // ISO-8601 year number
602
-            'o' => array(
603
-                'js'     => '',
604
-                'moment' => 'GGGG',
605
-            ),
606
-            // 1999...2003
607
-            'Y' => array(
608
-                'js'     => 'yy',
609
-                'moment' => 'YYYY',
610
-            ),
611
-            // 99...03
612
-            'y' => array(
613
-                'js'     => 'y',
614
-                'moment' => 'YY',
615
-            ),
616
-            // Time
617
-            // am/pm
618
-            'a' => array(
619
-                'js'     => 'tt',
620
-                'moment' => 'a',
621
-            ),
622
-            // AM/PM
623
-            'A' => array(
624
-                'js'     => 'TT',
625
-                'moment' => 'A',
626
-            ),
627
-            // Swatch Internet Time?!?
628
-            'B' => array(
629
-                'js'     => '',
630
-                'moment' => '',
631
-            ),
632
-            // 1...12
633
-            'g' => array(
634
-                'js'     => 'h',
635
-                'moment' => 'h',
636
-            ),
637
-            // 0...23
638
-            'G' => array(
639
-                'js'     => 'H',
640
-                'moment' => 'H',
641
-            ),
642
-            // 01...12
643
-            'h' => array(
644
-                'js'     => 'hh',
645
-                'moment' => 'hh',
646
-            ),
647
-            // 00...23
648
-            'H' => array(
649
-                'js'     => 'HH',
650
-                'moment' => 'HH',
651
-            ),
652
-            // 00..59
653
-            'i' => array(
654
-                'js'     => 'mm',
655
-                'moment' => 'mm',
656
-            ),
657
-            // seconds... 00...59
658
-            's' => array(
659
-                'js'     => 'ss',
660
-                'moment' => 'ss',
661
-            ),
662
-            // microseconds
663
-            'u' => array(
664
-                'js'     => '',
665
-                'moment' => '',
666
-            ),
667
-        );
668
-        $jquery_ui_format     = '';
669
-        $moment_format        = '';
670
-        $escaping             = false;
671
-        $format_string_length = strlen($format_string);
672
-        for ($i = 0; $i < $format_string_length; $i++) {
673
-            $char = $format_string[ $i ];
674
-            if ($char === '\\') { // PHP date format escaping character
675
-                $i++;
676
-                if ($escaping) {
677
-                    $jquery_ui_format .= $format_string[ $i ];
678
-                    $moment_format    .= $format_string[ $i ];
679
-                } else {
680
-                    $jquery_ui_format .= '\'' . $format_string[ $i ];
681
-                    $moment_format    .= $format_string[ $i ];
682
-                }
683
-                $escaping = true;
684
-            } else {
685
-                if ($escaping) {
686
-                    $jquery_ui_format .= "'";
687
-                    $moment_format    .= "'";
688
-                    $escaping         = false;
689
-                }
690
-                if (isset($symbols_map[ $char ])) {
691
-                    $jquery_ui_format .= $symbols_map[ $char ]['js'];
692
-                    $moment_format    .= $symbols_map[ $char ]['moment'];
693
-                } else {
694
-                    $jquery_ui_format .= $char;
695
-                    $moment_format    .= $char;
696
-                }
697
-            }
698
-        }
699
-        return array('js' => $jquery_ui_format, 'moment' => $moment_format);
700
-    }
507
+	/**
508
+	 * This converts incoming format string into js and moment variations.
509
+	 *
510
+	 * @param string $format_string incoming php format string
511
+	 * @return array js and moment formats.
512
+	 */
513
+	protected static function _php_to_js_moment_converter($format_string)
514
+	{
515
+		/**
516
+		 * This is a map of symbols for formats.
517
+		 * The index is the php symbol, the equivalent values are in the array.
518
+		 *
519
+		 * @var array
520
+		 */
521
+		$symbols_map          = array(
522
+			// Day
523
+			// 01
524
+			'd' => array(
525
+				'js'     => 'dd',
526
+				'moment' => 'DD',
527
+			),
528
+			// Mon
529
+			'D' => array(
530
+				'js'     => 'D',
531
+				'moment' => 'ddd',
532
+			),
533
+			// 1,2,...31
534
+			'j' => array(
535
+				'js'     => 'd',
536
+				'moment' => 'D',
537
+			),
538
+			// Monday
539
+			'l' => array(
540
+				'js'     => 'DD',
541
+				'moment' => 'dddd',
542
+			),
543
+			// ISO numeric representation of the day of the week (1-6)
544
+			'N' => array(
545
+				'js'     => '',
546
+				'moment' => 'E',
547
+			),
548
+			// st,nd.rd
549
+			'S' => array(
550
+				'js'     => '',
551
+				'moment' => 'o',
552
+			),
553
+			// numeric representation of day of week (0-6)
554
+			'w' => array(
555
+				'js'     => '',
556
+				'moment' => 'd',
557
+			),
558
+			// day of year starting from 0 (0-365)
559
+			'z' => array(
560
+				'js'     => 'o',
561
+				'moment' => 'DDD' // note moment does not start with 0 so will need to modify by subtracting 1
562
+			),
563
+			// Week
564
+			// ISO-8601 week number of year (weeks starting on monday)
565
+			'W' => array(
566
+				'js'     => '',
567
+				'moment' => 'w',
568
+			),
569
+			// Month
570
+			// January...December
571
+			'F' => array(
572
+				'js'     => 'MM',
573
+				'moment' => 'MMMM',
574
+			),
575
+			// 01...12
576
+			'm' => array(
577
+				'js'     => 'mm',
578
+				'moment' => 'MM',
579
+			),
580
+			// Jan...Dec
581
+			'M' => array(
582
+				'js'     => 'M',
583
+				'moment' => 'MMM',
584
+			),
585
+			// 1-12
586
+			'n' => array(
587
+				'js'     => 'm',
588
+				'moment' => 'M',
589
+			),
590
+			// number of days in given month
591
+			't' => array(
592
+				'js'     => '',
593
+				'moment' => '',
594
+			),
595
+			// Year
596
+			// whether leap year or not 1/0
597
+			'L' => array(
598
+				'js'     => '',
599
+				'moment' => '',
600
+			),
601
+			// ISO-8601 year number
602
+			'o' => array(
603
+				'js'     => '',
604
+				'moment' => 'GGGG',
605
+			),
606
+			// 1999...2003
607
+			'Y' => array(
608
+				'js'     => 'yy',
609
+				'moment' => 'YYYY',
610
+			),
611
+			// 99...03
612
+			'y' => array(
613
+				'js'     => 'y',
614
+				'moment' => 'YY',
615
+			),
616
+			// Time
617
+			// am/pm
618
+			'a' => array(
619
+				'js'     => 'tt',
620
+				'moment' => 'a',
621
+			),
622
+			// AM/PM
623
+			'A' => array(
624
+				'js'     => 'TT',
625
+				'moment' => 'A',
626
+			),
627
+			// Swatch Internet Time?!?
628
+			'B' => array(
629
+				'js'     => '',
630
+				'moment' => '',
631
+			),
632
+			// 1...12
633
+			'g' => array(
634
+				'js'     => 'h',
635
+				'moment' => 'h',
636
+			),
637
+			// 0...23
638
+			'G' => array(
639
+				'js'     => 'H',
640
+				'moment' => 'H',
641
+			),
642
+			// 01...12
643
+			'h' => array(
644
+				'js'     => 'hh',
645
+				'moment' => 'hh',
646
+			),
647
+			// 00...23
648
+			'H' => array(
649
+				'js'     => 'HH',
650
+				'moment' => 'HH',
651
+			),
652
+			// 00..59
653
+			'i' => array(
654
+				'js'     => 'mm',
655
+				'moment' => 'mm',
656
+			),
657
+			// seconds... 00...59
658
+			's' => array(
659
+				'js'     => 'ss',
660
+				'moment' => 'ss',
661
+			),
662
+			// microseconds
663
+			'u' => array(
664
+				'js'     => '',
665
+				'moment' => '',
666
+			),
667
+		);
668
+		$jquery_ui_format     = '';
669
+		$moment_format        = '';
670
+		$escaping             = false;
671
+		$format_string_length = strlen($format_string);
672
+		for ($i = 0; $i < $format_string_length; $i++) {
673
+			$char = $format_string[ $i ];
674
+			if ($char === '\\') { // PHP date format escaping character
675
+				$i++;
676
+				if ($escaping) {
677
+					$jquery_ui_format .= $format_string[ $i ];
678
+					$moment_format    .= $format_string[ $i ];
679
+				} else {
680
+					$jquery_ui_format .= '\'' . $format_string[ $i ];
681
+					$moment_format    .= $format_string[ $i ];
682
+				}
683
+				$escaping = true;
684
+			} else {
685
+				if ($escaping) {
686
+					$jquery_ui_format .= "'";
687
+					$moment_format    .= "'";
688
+					$escaping         = false;
689
+				}
690
+				if (isset($symbols_map[ $char ])) {
691
+					$jquery_ui_format .= $symbols_map[ $char ]['js'];
692
+					$moment_format    .= $symbols_map[ $char ]['moment'];
693
+				} else {
694
+					$jquery_ui_format .= $char;
695
+					$moment_format    .= $char;
696
+				}
697
+			}
698
+		}
699
+		return array('js' => $jquery_ui_format, 'moment' => $moment_format);
700
+	}
701 701
 
702 702
 
703
-    /**
704
-     * This takes an incoming format string and validates it to ensure it will work fine with PHP.
705
-     *
706
-     * @param string $format_string   Incoming format string for php date().
707
-     * @return mixed bool|array  If all is okay then TRUE is returned.  Otherwise an array of validation
708
-     *                                errors is returned.  So for client code calling, check for is_array() to
709
-     *                                indicate failed validations.
710
-     */
711
-    public static function validate_format_string($format_string)
712
-    {
713
-        $error_msg = array();
714
-        // time format checks
715
-        switch (true) {
716
-            case strpos($format_string, 'h') !== false:
717
-            case strpos($format_string, 'g') !== false:
718
-                /**
719
-                 * if the time string has a lowercase 'h' which == 12 hour time format and there
720
-                 * is not any ante meridiem format ('a' or 'A').  Then throw an error because its
721
-                 * too ambiguous and PHP won't be able to figure out whether 1 = 1pm or 1am.
722
-                 */
723
-                if (stripos($format_string, 'A') === false) {
724
-                    $error_msg[] = esc_html__(
725
-                        'There is a  time format for 12 hour time but no  "a" or "A" to indicate am/pm.  Without this distinction, PHP is unable to determine if a "1" for the hour value equals "1pm" or "1am".',
726
-                        'event_espresso'
727
-                    );
728
-                }
729
-                break;
730
-        }
731
-        return empty($error_msg) ? true : $error_msg;
732
-    }
703
+	/**
704
+	 * This takes an incoming format string and validates it to ensure it will work fine with PHP.
705
+	 *
706
+	 * @param string $format_string   Incoming format string for php date().
707
+	 * @return mixed bool|array  If all is okay then TRUE is returned.  Otherwise an array of validation
708
+	 *                                errors is returned.  So for client code calling, check for is_array() to
709
+	 *                                indicate failed validations.
710
+	 */
711
+	public static function validate_format_string($format_string)
712
+	{
713
+		$error_msg = array();
714
+		// time format checks
715
+		switch (true) {
716
+			case strpos($format_string, 'h') !== false:
717
+			case strpos($format_string, 'g') !== false:
718
+				/**
719
+				 * if the time string has a lowercase 'h' which == 12 hour time format and there
720
+				 * is not any ante meridiem format ('a' or 'A').  Then throw an error because its
721
+				 * too ambiguous and PHP won't be able to figure out whether 1 = 1pm or 1am.
722
+				 */
723
+				if (stripos($format_string, 'A') === false) {
724
+					$error_msg[] = esc_html__(
725
+						'There is a  time format for 12 hour time but no  "a" or "A" to indicate am/pm.  Without this distinction, PHP is unable to determine if a "1" for the hour value equals "1pm" or "1am".',
726
+						'event_espresso'
727
+					);
728
+				}
729
+				break;
730
+		}
731
+		return empty($error_msg) ? true : $error_msg;
732
+	}
733 733
 
734 734
 
735
-    /**
736
-     *     If the the first date starts at midnight on one day, and the next date ends at midnight on the
737
-     *     very next day then this method will return true.
738
-     *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-16 00:00:00 then this function will return true.
739
-     *    If $date_1 = 2015-12-15 03:00:00 and $date_2 = 2015-12_16 03:00:00 then this function will return false.
740
-     *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-15 00:00:00 then this function will return true.
741
-     *
742
-     * @param mixed $date_1
743
-     * @param mixed $date_2
744
-     * @return bool
745
-     */
746
-    public static function dates_represent_one_24_hour_date($date_1, $date_2)
747
-    {
735
+	/**
736
+	 *     If the the first date starts at midnight on one day, and the next date ends at midnight on the
737
+	 *     very next day then this method will return true.
738
+	 *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-16 00:00:00 then this function will return true.
739
+	 *    If $date_1 = 2015-12-15 03:00:00 and $date_2 = 2015-12_16 03:00:00 then this function will return false.
740
+	 *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-15 00:00:00 then this function will return true.
741
+	 *
742
+	 * @param mixed $date_1
743
+	 * @param mixed $date_2
744
+	 * @return bool
745
+	 */
746
+	public static function dates_represent_one_24_hour_date($date_1, $date_2)
747
+	{
748 748
 
749
-        if ((! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
750
-            || ($date_1->format(EE_Datetime_Field::mysql_time_format) !== '00:00:00'
751
-                || $date_2->format(
752
-                    EE_Datetime_Field::mysql_time_format
753
-                ) !== '00:00:00')
754
-        ) {
755
-            return false;
756
-        }
757
-        return $date_2->format('U') - $date_1->format('U') === 86400;
758
-    }
749
+		if ((! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
750
+			|| ($date_1->format(EE_Datetime_Field::mysql_time_format) !== '00:00:00'
751
+				|| $date_2->format(
752
+					EE_Datetime_Field::mysql_time_format
753
+				) !== '00:00:00')
754
+		) {
755
+			return false;
756
+		}
757
+		return $date_2->format('U') - $date_1->format('U') === 86400;
758
+	}
759 759
 
760 760
 
761
-    /**
762
-     * This returns the appropriate query interval string that can be used in sql queries involving mysql Date
763
-     * Functions.
764
-     *
765
-     * @param string $timezone_string    A timezone string in a valid format to instantiate a DateTimeZone object.
766
-     * @param string $field_for_interval The Database field that is the interval is applied to in the query.
767
-     * @return string
768
-     */
769
-    public static function get_sql_query_interval_for_offset($timezone_string, $field_for_interval)
770
-    {
771
-        try {
772
-            /** need to account for timezone offset on the selects */
773
-            $DateTimeZone = new DateTimeZone($timezone_string);
774
-        } catch (Exception $e) {
775
-            $DateTimeZone = null;
776
-        }
777
-        /**
778
-         * Note get_option( 'gmt_offset') returns a value in hours, whereas DateTimeZone::getOffset returns values in seconds.
779
-         * Hence we do the calc for DateTimeZone::getOffset.
780
-         */
781
-        $offset         = $DateTimeZone instanceof DateTimeZone
782
-            ? $DateTimeZone->getOffset(new DateTime('now')) / HOUR_IN_SECONDS
783
-            : (float) get_option('gmt_offset');
784
-        $query_interval = $offset < 0
785
-            ? 'DATE_SUB(' . $field_for_interval . ', INTERVAL ' . $offset * -1 . ' HOUR)'
786
-            : 'DATE_ADD(' . $field_for_interval . ', INTERVAL ' . $offset . ' HOUR)';
787
-        return $query_interval;
788
-    }
761
+	/**
762
+	 * This returns the appropriate query interval string that can be used in sql queries involving mysql Date
763
+	 * Functions.
764
+	 *
765
+	 * @param string $timezone_string    A timezone string in a valid format to instantiate a DateTimeZone object.
766
+	 * @param string $field_for_interval The Database field that is the interval is applied to in the query.
767
+	 * @return string
768
+	 */
769
+	public static function get_sql_query_interval_for_offset($timezone_string, $field_for_interval)
770
+	{
771
+		try {
772
+			/** need to account for timezone offset on the selects */
773
+			$DateTimeZone = new DateTimeZone($timezone_string);
774
+		} catch (Exception $e) {
775
+			$DateTimeZone = null;
776
+		}
777
+		/**
778
+		 * Note get_option( 'gmt_offset') returns a value in hours, whereas DateTimeZone::getOffset returns values in seconds.
779
+		 * Hence we do the calc for DateTimeZone::getOffset.
780
+		 */
781
+		$offset         = $DateTimeZone instanceof DateTimeZone
782
+			? $DateTimeZone->getOffset(new DateTime('now')) / HOUR_IN_SECONDS
783
+			: (float) get_option('gmt_offset');
784
+		$query_interval = $offset < 0
785
+			? 'DATE_SUB(' . $field_for_interval . ', INTERVAL ' . $offset * -1 . ' HOUR)'
786
+			: 'DATE_ADD(' . $field_for_interval . ', INTERVAL ' . $offset . ' HOUR)';
787
+		return $query_interval;
788
+	}
789 789
 
790 790
 
791
-    /**
792
-     * Retrieves the site's default timezone and returns it formatted so it's ready for display
793
-     * to users. If you want to customize how its displayed feel free to fetch the 'timezone_string'
794
-     * and 'gmt_offset' WordPress options directly; or use the filter
795
-     * FHEE__EEH_DTT_Helper__get_timezone_string_for_display
796
-     * (although note that we remove any HTML that may be added)
797
-     *
798
-     * @return string
799
-     */
800
-    public static function get_timezone_string_for_display()
801
-    {
802
-        $pretty_timezone = apply_filters('FHEE__EEH_DTT_Helper__get_timezone_string_for_display', '');
803
-        if (! empty($pretty_timezone)) {
804
-            return esc_html($pretty_timezone);
805
-        }
806
-        $timezone_string = get_option('timezone_string');
807
-        if ($timezone_string) {
808
-            static $mo_loaded = false;
809
-            // Load translations for continents and cities just like wp_timezone_choice does
810
-            if (! $mo_loaded) {
811
-                $locale = get_locale();
812
-                $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
813
-                load_textdomain('continents-cities', $mofile);
814
-                $mo_loaded = true;
815
-            }
816
-            // well that was easy.
817
-            $parts = explode('/', $timezone_string);
818
-            // remove the continent
819
-            unset($parts[0]);
820
-            $t_parts = array();
821
-            // phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
822
-            // phpcs:disable WordPress.WP.I18n.TextDomainMismatch
823
-            // disabled because this code is copied from WordPress and is a WordPress domain
824
-            foreach ($parts as $part) {
825
-                $t_parts[] = translate(str_replace('_', ' ', $part), 'continents-cities');
826
-            }
827
-            return implode(' - ', $t_parts);
828
-            // phpcs:enable
829
-        }
830
-        // they haven't set the timezone string, so let's return a string like "UTC+1"
831
-        $gmt_offset = get_option('gmt_offset');
832
-        $prefix     = (int) $gmt_offset >= 0 ? '+' : '';
833
-        $parts      = explode('.', (string) $gmt_offset);
834
-        if (count($parts) === 1) {
835
-            $parts[1] = '00';
836
-        } else {
837
-            // convert the part after the decimal, eg "5" (from x.5) or "25" (from x.25)
838
-            // to minutes, eg 30 or 15, respectively
839
-            $hour_fraction = (float) ('0.' . $parts[1]);
840
-            $parts[1]      = (string) $hour_fraction * 60;
841
-        }
842
-        return sprintf(__('UTC%1$s', 'event_espresso'), $prefix . implode(':', $parts));
843
-    }
791
+	/**
792
+	 * Retrieves the site's default timezone and returns it formatted so it's ready for display
793
+	 * to users. If you want to customize how its displayed feel free to fetch the 'timezone_string'
794
+	 * and 'gmt_offset' WordPress options directly; or use the filter
795
+	 * FHEE__EEH_DTT_Helper__get_timezone_string_for_display
796
+	 * (although note that we remove any HTML that may be added)
797
+	 *
798
+	 * @return string
799
+	 */
800
+	public static function get_timezone_string_for_display()
801
+	{
802
+		$pretty_timezone = apply_filters('FHEE__EEH_DTT_Helper__get_timezone_string_for_display', '');
803
+		if (! empty($pretty_timezone)) {
804
+			return esc_html($pretty_timezone);
805
+		}
806
+		$timezone_string = get_option('timezone_string');
807
+		if ($timezone_string) {
808
+			static $mo_loaded = false;
809
+			// Load translations for continents and cities just like wp_timezone_choice does
810
+			if (! $mo_loaded) {
811
+				$locale = get_locale();
812
+				$mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
813
+				load_textdomain('continents-cities', $mofile);
814
+				$mo_loaded = true;
815
+			}
816
+			// well that was easy.
817
+			$parts = explode('/', $timezone_string);
818
+			// remove the continent
819
+			unset($parts[0]);
820
+			$t_parts = array();
821
+			// phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
822
+			// phpcs:disable WordPress.WP.I18n.TextDomainMismatch
823
+			// disabled because this code is copied from WordPress and is a WordPress domain
824
+			foreach ($parts as $part) {
825
+				$t_parts[] = translate(str_replace('_', ' ', $part), 'continents-cities');
826
+			}
827
+			return implode(' - ', $t_parts);
828
+			// phpcs:enable
829
+		}
830
+		// they haven't set the timezone string, so let's return a string like "UTC+1"
831
+		$gmt_offset = get_option('gmt_offset');
832
+		$prefix     = (int) $gmt_offset >= 0 ? '+' : '';
833
+		$parts      = explode('.', (string) $gmt_offset);
834
+		if (count($parts) === 1) {
835
+			$parts[1] = '00';
836
+		} else {
837
+			// convert the part after the decimal, eg "5" (from x.5) or "25" (from x.25)
838
+			// to minutes, eg 30 or 15, respectively
839
+			$hour_fraction = (float) ('0.' . $parts[1]);
840
+			$parts[1]      = (string) $hour_fraction * 60;
841
+		}
842
+		return sprintf(__('UTC%1$s', 'event_espresso'), $prefix . implode(':', $parts));
843
+	}
844 844
 
845 845
 
846 846
 
847
-    /**
848
-     * So PHP does this awesome thing where if you are trying to get a timestamp
849
-     * for a month using a string like "February" or "February 2017",
850
-     * and you don't specify a day as part of your string,
851
-     * then PHP will use whatever the current day of the month is.
852
-     * IF the current day of the month happens to be the 30th or 31st,
853
-     * then PHP gets really confused by a date like February 30,
854
-     * so instead of saying
855
-     *      "Hey February only has 28 days (this year)...
856
-     *      ...you must have meant the last day of the month!"
857
-     * PHP does the next most logical thing, and bumps the date up to March 2nd,
858
-     * because someone requesting February 30th obviously meant March 1st!
859
-     * The way around this is to always set the day to the first,
860
-     * so that the month will stay on the month you wanted.
861
-     * this method will add that "1" into your date regardless of the format.
862
-     *
863
-     * @param string $month
864
-     * @return string
865
-     */
866
-    public static function first_of_month_timestamp($month = '')
867
-    {
868
-        $month = (string) $month;
869
-        $year  = '';
870
-        // check if the incoming string has a year in it or not
871
-        if (preg_match('/\b\d{4}\b/', $month, $matches)) {
872
-            $year = $matches[0];
873
-            // ten remove that from the month string as well as any spaces
874
-            $month = trim(str_replace($year, '', $month));
875
-            // add a space before the year
876
-            $year = " {$year}";
877
-        }
878
-        // return timestamp for something like "February 1 2017"
879
-        return strtotime("{$month} 1{$year}");
880
-    }
847
+	/**
848
+	 * So PHP does this awesome thing where if you are trying to get a timestamp
849
+	 * for a month using a string like "February" or "February 2017",
850
+	 * and you don't specify a day as part of your string,
851
+	 * then PHP will use whatever the current day of the month is.
852
+	 * IF the current day of the month happens to be the 30th or 31st,
853
+	 * then PHP gets really confused by a date like February 30,
854
+	 * so instead of saying
855
+	 *      "Hey February only has 28 days (this year)...
856
+	 *      ...you must have meant the last day of the month!"
857
+	 * PHP does the next most logical thing, and bumps the date up to March 2nd,
858
+	 * because someone requesting February 30th obviously meant March 1st!
859
+	 * The way around this is to always set the day to the first,
860
+	 * so that the month will stay on the month you wanted.
861
+	 * this method will add that "1" into your date regardless of the format.
862
+	 *
863
+	 * @param string $month
864
+	 * @return string
865
+	 */
866
+	public static function first_of_month_timestamp($month = '')
867
+	{
868
+		$month = (string) $month;
869
+		$year  = '';
870
+		// check if the incoming string has a year in it or not
871
+		if (preg_match('/\b\d{4}\b/', $month, $matches)) {
872
+			$year = $matches[0];
873
+			// ten remove that from the month string as well as any spaces
874
+			$month = trim(str_replace($year, '', $month));
875
+			// add a space before the year
876
+			$year = " {$year}";
877
+		}
878
+		// return timestamp for something like "February 1 2017"
879
+		return strtotime("{$month} 1{$year}");
880
+	}
881 881
 
882 882
 
883
-    /**
884
-     * This simply returns the timestamp for tomorrow (midnight next day) in this sites timezone.  So it may be midnight
885
-     * for this sites timezone, but the timestamp could be some other time GMT.
886
-     */
887
-    public static function tomorrow()
888
-    {
889
-        // The multiplication of -1 ensures that we switch positive offsets to negative and negative offsets to positive
890
-        // before adding to the timestamp.  Why? Because we want tomorrow to be for midnight the next day in THIS timezone
891
-        // not an offset from midnight in UTC.  So if we're starting with UTC 00:00:00, then we want to make sure the
892
-        // final timestamp is equivalent to midnight in this timezone as represented in GMT.
893
-        return strtotime('tomorrow') + (self::get_site_timezone_gmt_offset() * -1);
894
-    }
883
+	/**
884
+	 * This simply returns the timestamp for tomorrow (midnight next day) in this sites timezone.  So it may be midnight
885
+	 * for this sites timezone, but the timestamp could be some other time GMT.
886
+	 */
887
+	public static function tomorrow()
888
+	{
889
+		// The multiplication of -1 ensures that we switch positive offsets to negative and negative offsets to positive
890
+		// before adding to the timestamp.  Why? Because we want tomorrow to be for midnight the next day in THIS timezone
891
+		// not an offset from midnight in UTC.  So if we're starting with UTC 00:00:00, then we want to make sure the
892
+		// final timestamp is equivalent to midnight in this timezone as represented in GMT.
893
+		return strtotime('tomorrow') + (self::get_site_timezone_gmt_offset() * -1);
894
+	}
895 895
 
896 896
 
897
-    /**
898
-     * **
899
-     * Gives a nicely-formatted list of timezone strings.
900
-     * Copied from the core wp function by the same name so we could customize to remove UTC offsets.
901
-     *
902
-     * @since     4.9.40.rc.008
903
-     * @staticvar bool $mo_loaded
904
-     * @staticvar string $locale_loaded
905
-     * @param string $selected_zone Selected timezone.
906
-     * @param string $locale        Optional. Locale to load the timezones in. Default current site locale.
907
-     * @return string
908
-     */
909
-    public static function wp_timezone_choice($selected_zone, $locale = null)
910
-    {
911
-        static $mo_loaded = false, $locale_loaded = null;
912
-        $continents = array(
913
-            'Africa',
914
-            'America',
915
-            'Antarctica',
916
-            'Arctic',
917
-            'Asia',
918
-            'Atlantic',
919
-            'Australia',
920
-            'Europe',
921
-            'Indian',
922
-            'Pacific',
923
-        );
924
-        // Load translations for continents and cities.
925
-        if (! $mo_loaded || $locale !== $locale_loaded) {
926
-            $locale_loaded = $locale ? $locale : get_locale();
927
-            $mofile        = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
928
-            unload_textdomain('continents-cities');
929
-            load_textdomain('continents-cities', $mofile);
930
-            $mo_loaded = true;
931
-        }
932
-        $zone_data = array();
933
-        foreach (timezone_identifiers_list() as $zone) {
934
-            $zone = explode('/', $zone);
935
-            if (! in_array($zone[0], $continents, true)) {
936
-                continue;
937
-            }
938
-            // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
939
-            $exists      = array(
940
-                0 => isset($zone[0]) && $zone[0],
941
-                1 => isset($zone[1]) && $zone[1],
942
-                2 => isset($zone[2]) && $zone[2],
943
-            );
944
-            $exists[3]   = $exists[0] && $zone[0] !== 'Etc';
945
-            $exists[4]   = $exists[1] && $exists[3];
946
-            $exists[5]   = $exists[2] && $exists[3];
947
-            // phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
948
-            // phpcs:disable WordPress.WP.I18n.TextDomainMismatch
949
-            // disabled because this code is copied from WordPress and is a WordPress domain
950
-            $zone_data[] = array(
951
-                'continent'   => $exists[0] ? $zone[0] : '',
952
-                'city'        => $exists[1] ? $zone[1] : '',
953
-                'subcity'     => $exists[2] ? $zone[2] : '',
954
-                't_continent' => $exists[3]
955
-                    ? translate(str_replace('_', ' ', $zone[0]), 'continents-cities')
956
-                    : '',
957
-                't_city'      => $exists[4]
958
-                    ? translate(str_replace('_', ' ', $zone[1]), 'continents-cities')
959
-                    : '',
960
-                't_subcity'   => $exists[5]
961
-                    ? translate(str_replace('_', ' ', $zone[2]), 'continents-cities')
962
-                    : '',
963
-            );
964
-            // phpcs:enable
965
-        }
966
-        usort($zone_data, '_wp_timezone_choice_usort_callback');
967
-        $structure = array();
968
-        if (empty($selected_zone)) {
969
-            $structure[] = '<option selected="selected" value="">' . __('Select a city', 'event_espresso') . '</option>';
970
-        }
971
-        foreach ($zone_data as $key => $zone) {
972
-            // Build value in an array to join later
973
-            $value = array($zone['continent']);
974
-            if (empty($zone['city'])) {
975
-                // It's at the continent level (generally won't happen)
976
-                $display = $zone['t_continent'];
977
-            } else {
978
-                // It's inside a continent group
979
-                // Continent optgroup
980
-                if (! isset($zone_data[ $key - 1 ]) || $zone_data[ $key - 1 ]['continent'] !== $zone['continent']) {
981
-                    $label       = $zone['t_continent'];
982
-                    $structure[] = '<optgroup label="' . esc_attr($label) . '">';
983
-                }
984
-                // Add the city to the value
985
-                $value[] = $zone['city'];
986
-                $display = $zone['t_city'];
987
-                if (! empty($zone['subcity'])) {
988
-                    // Add the subcity to the value
989
-                    $value[] = $zone['subcity'];
990
-                    $display .= ' - ' . $zone['t_subcity'];
991
-                }
992
-            }
993
-            // Build the value
994
-            $value       = implode('/', $value);
995
-            $selected    = $value === $selected_zone ? ' selected="selected"' : '';
996
-            $structure[] = '<option value="' . esc_attr($value) . '"' . $selected . '>'
997
-                           . esc_html($display)
998
-                           . '</option>';
999
-            // Close continent optgroup
1000
-            if (! empty($zone['city'])
1001
-                && (
1002
-                    ! isset($zone_data[ $key + 1 ])
1003
-                    || (isset($zone_data[ $key + 1 ]) && $zone_data[ $key + 1 ]['continent'] !== $zone['continent'])
1004
-                )
1005
-            ) {
1006
-                $structure[] = '</optgroup>';
1007
-            }
1008
-        }
1009
-        return implode("\n", $structure);
1010
-    }
897
+	/**
898
+	 * **
899
+	 * Gives a nicely-formatted list of timezone strings.
900
+	 * Copied from the core wp function by the same name so we could customize to remove UTC offsets.
901
+	 *
902
+	 * @since     4.9.40.rc.008
903
+	 * @staticvar bool $mo_loaded
904
+	 * @staticvar string $locale_loaded
905
+	 * @param string $selected_zone Selected timezone.
906
+	 * @param string $locale        Optional. Locale to load the timezones in. Default current site locale.
907
+	 * @return string
908
+	 */
909
+	public static function wp_timezone_choice($selected_zone, $locale = null)
910
+	{
911
+		static $mo_loaded = false, $locale_loaded = null;
912
+		$continents = array(
913
+			'Africa',
914
+			'America',
915
+			'Antarctica',
916
+			'Arctic',
917
+			'Asia',
918
+			'Atlantic',
919
+			'Australia',
920
+			'Europe',
921
+			'Indian',
922
+			'Pacific',
923
+		);
924
+		// Load translations for continents and cities.
925
+		if (! $mo_loaded || $locale !== $locale_loaded) {
926
+			$locale_loaded = $locale ? $locale : get_locale();
927
+			$mofile        = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
928
+			unload_textdomain('continents-cities');
929
+			load_textdomain('continents-cities', $mofile);
930
+			$mo_loaded = true;
931
+		}
932
+		$zone_data = array();
933
+		foreach (timezone_identifiers_list() as $zone) {
934
+			$zone = explode('/', $zone);
935
+			if (! in_array($zone[0], $continents, true)) {
936
+				continue;
937
+			}
938
+			// This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
939
+			$exists      = array(
940
+				0 => isset($zone[0]) && $zone[0],
941
+				1 => isset($zone[1]) && $zone[1],
942
+				2 => isset($zone[2]) && $zone[2],
943
+			);
944
+			$exists[3]   = $exists[0] && $zone[0] !== 'Etc';
945
+			$exists[4]   = $exists[1] && $exists[3];
946
+			$exists[5]   = $exists[2] && $exists[3];
947
+			// phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
948
+			// phpcs:disable WordPress.WP.I18n.TextDomainMismatch
949
+			// disabled because this code is copied from WordPress and is a WordPress domain
950
+			$zone_data[] = array(
951
+				'continent'   => $exists[0] ? $zone[0] : '',
952
+				'city'        => $exists[1] ? $zone[1] : '',
953
+				'subcity'     => $exists[2] ? $zone[2] : '',
954
+				't_continent' => $exists[3]
955
+					? translate(str_replace('_', ' ', $zone[0]), 'continents-cities')
956
+					: '',
957
+				't_city'      => $exists[4]
958
+					? translate(str_replace('_', ' ', $zone[1]), 'continents-cities')
959
+					: '',
960
+				't_subcity'   => $exists[5]
961
+					? translate(str_replace('_', ' ', $zone[2]), 'continents-cities')
962
+					: '',
963
+			);
964
+			// phpcs:enable
965
+		}
966
+		usort($zone_data, '_wp_timezone_choice_usort_callback');
967
+		$structure = array();
968
+		if (empty($selected_zone)) {
969
+			$structure[] = '<option selected="selected" value="">' . __('Select a city', 'event_espresso') . '</option>';
970
+		}
971
+		foreach ($zone_data as $key => $zone) {
972
+			// Build value in an array to join later
973
+			$value = array($zone['continent']);
974
+			if (empty($zone['city'])) {
975
+				// It's at the continent level (generally won't happen)
976
+				$display = $zone['t_continent'];
977
+			} else {
978
+				// It's inside a continent group
979
+				// Continent optgroup
980
+				if (! isset($zone_data[ $key - 1 ]) || $zone_data[ $key - 1 ]['continent'] !== $zone['continent']) {
981
+					$label       = $zone['t_continent'];
982
+					$structure[] = '<optgroup label="' . esc_attr($label) . '">';
983
+				}
984
+				// Add the city to the value
985
+				$value[] = $zone['city'];
986
+				$display = $zone['t_city'];
987
+				if (! empty($zone['subcity'])) {
988
+					// Add the subcity to the value
989
+					$value[] = $zone['subcity'];
990
+					$display .= ' - ' . $zone['t_subcity'];
991
+				}
992
+			}
993
+			// Build the value
994
+			$value       = implode('/', $value);
995
+			$selected    = $value === $selected_zone ? ' selected="selected"' : '';
996
+			$structure[] = '<option value="' . esc_attr($value) . '"' . $selected . '>'
997
+						   . esc_html($display)
998
+						   . '</option>';
999
+			// Close continent optgroup
1000
+			if (! empty($zone['city'])
1001
+				&& (
1002
+					! isset($zone_data[ $key + 1 ])
1003
+					|| (isset($zone_data[ $key + 1 ]) && $zone_data[ $key + 1 ]['continent'] !== $zone['continent'])
1004
+				)
1005
+			) {
1006
+				$structure[] = '</optgroup>';
1007
+			}
1008
+		}
1009
+		return implode("\n", $structure);
1010
+	}
1011 1011
 
1012 1012
 
1013
-    /**
1014
-     * Shim for the WP function `get_user_locale` that was added in WordPress 4.7.0
1015
-     *
1016
-     * @param int|WP_User $user_id
1017
-     * @return string
1018
-     */
1019
-    public static function get_user_locale($user_id = 0)
1020
-    {
1021
-        if (function_exists('get_user_locale')) {
1022
-            return get_user_locale($user_id);
1023
-        }
1024
-        return get_locale();
1025
-    }
1013
+	/**
1014
+	 * Shim for the WP function `get_user_locale` that was added in WordPress 4.7.0
1015
+	 *
1016
+	 * @param int|WP_User $user_id
1017
+	 * @return string
1018
+	 */
1019
+	public static function get_user_locale($user_id = 0)
1020
+	{
1021
+		if (function_exists('get_user_locale')) {
1022
+			return get_user_locale($user_id);
1023
+		}
1024
+		return get_locale();
1025
+	}
1026 1026
 
1027 1027
 
1028
-    /**
1029
-     * Return the appropriate helper adapter for DTT related things.
1030
-     *
1031
-     * @return HelperInterface
1032
-     * @throws InvalidArgumentException
1033
-     * @throws InvalidDataTypeException
1034
-     * @throws InvalidInterfaceException
1035
-     */
1036
-    private static function getHelperAdapter()
1037
-    {
1038
-        $dtt_helper_fqcn = PHP_VERSION_ID < 50600
1039
-            ? 'EventEspresso\core\services\helpers\datetime\PhpCompatLessFiveSixHelper'
1040
-            : 'EventEspresso\core\services\helpers\datetime\PhpCompatGreaterFiveSixHelper';
1041
-        return LoaderFactory::getLoader()->getShared($dtt_helper_fqcn);
1042
-    }
1028
+	/**
1029
+	 * Return the appropriate helper adapter for DTT related things.
1030
+	 *
1031
+	 * @return HelperInterface
1032
+	 * @throws InvalidArgumentException
1033
+	 * @throws InvalidDataTypeException
1034
+	 * @throws InvalidInterfaceException
1035
+	 */
1036
+	private static function getHelperAdapter()
1037
+	{
1038
+		$dtt_helper_fqcn = PHP_VERSION_ID < 50600
1039
+			? 'EventEspresso\core\services\helpers\datetime\PhpCompatLessFiveSixHelper'
1040
+			: 'EventEspresso\core\services\helpers\datetime\PhpCompatGreaterFiveSixHelper';
1041
+		return LoaderFactory::getLoader()->getShared($dtt_helper_fqcn);
1042
+	}
1043 1043
 
1044 1044
 
1045
-    /**
1046
-     * Helper function for setting the timezone on a DateTime object.
1047
-     * This is implemented to standardize a workaround for a PHP bug outlined in
1048
-     * https://events.codebasehq.com/projects/event-espresso/tickets/11407 and
1049
-     * https://events.codebasehq.com/projects/event-espresso/tickets/11233
1050
-     *
1051
-     * @param DateTime     $datetime
1052
-     * @param DateTimeZone $timezone
1053
-     */
1054
-    public static function setTimezone(DateTime $datetime, DateTimeZone $timezone)
1055
-    {
1056
-        $datetime->setTimezone($timezone);
1057
-        $datetime->getTimestamp();
1058
-    }
1045
+	/**
1046
+	 * Helper function for setting the timezone on a DateTime object.
1047
+	 * This is implemented to standardize a workaround for a PHP bug outlined in
1048
+	 * https://events.codebasehq.com/projects/event-espresso/tickets/11407 and
1049
+	 * https://events.codebasehq.com/projects/event-espresso/tickets/11233
1050
+	 *
1051
+	 * @param DateTime     $datetime
1052
+	 * @param DateTimeZone $timezone
1053
+	 */
1054
+	public static function setTimezone(DateTime $datetime, DateTimeZone $timezone)
1055
+	{
1056
+		$datetime->setTimezone($timezone);
1057
+		$datetime->getTimestamp();
1058
+	}
1059 1059
 }
Please login to merge, or discard this patch.
Spacing   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
      */
132 132
     public static function get_timezone_string_from_abbreviations_list($gmt_offset = 0, $coerce = true)
133 133
     {
134
-        $gmt_offset =  (int) $gmt_offset;
134
+        $gmt_offset = (int) $gmt_offset;
135 135
         /** @var array[] $abbreviations */
136 136
         $abbreviations = DateTimeZone::listAbbreviations();
137 137
         foreach ($abbreviations as $abbreviation) {
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
      */
327 327
     protected static function _modify_datetime_object(DateTime $DateTime, $period = 'years', $value = 1, $operand = '+')
328 328
     {
329
-        if (! $DateTime instanceof DateTime) {
329
+        if ( ! $DateTime instanceof DateTime) {
330 330
             throw new EE_Error(
331 331
                 sprintf(
332 332
                     esc_html__('Expected a PHP DateTime object, but instead received %1$s', 'event_espresso'),
@@ -336,25 +336,25 @@  discard block
 block discarded – undo
336 336
         }
337 337
         switch ($period) {
338 338
             case 'years':
339
-                $value = 'P' . $value . 'Y';
339
+                $value = 'P'.$value.'Y';
340 340
                 break;
341 341
             case 'months':
342
-                $value = 'P' . $value . 'M';
342
+                $value = 'P'.$value.'M';
343 343
                 break;
344 344
             case 'weeks':
345
-                $value = 'P' . $value . 'W';
345
+                $value = 'P'.$value.'W';
346 346
                 break;
347 347
             case 'days':
348
-                $value = 'P' . $value . 'D';
348
+                $value = 'P'.$value.'D';
349 349
                 break;
350 350
             case 'hours':
351
-                $value = 'PT' . $value . 'H';
351
+                $value = 'PT'.$value.'H';
352 352
                 break;
353 353
             case 'minutes':
354
-                $value = 'PT' . $value . 'M';
354
+                $value = 'PT'.$value.'M';
355 355
                 break;
356 356
             case 'seconds':
357
-                $value = 'PT' . $value . 'S';
357
+                $value = 'PT'.$value.'S';
358 358
                 break;
359 359
         }
360 360
         switch ($operand) {
@@ -382,7 +382,7 @@  discard block
 block discarded – undo
382 382
      */
383 383
     protected static function _modify_timestamp($timestamp, $period = 'years', $value = 1, $operand = '+')
384 384
     {
385
-        if (! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
385
+        if ( ! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
386 386
             throw new EE_Error(
387 387
                 sprintf(
388 388
                     esc_html__('Expected a Unix timestamp, but instead received %1$s', 'event_espresso'),
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
                 'date' => $date_format['js'],
496 496
                 'time' => $time_format['js'],
497 497
             ),
498
-            'moment' => $date_format['moment'] . ' ' . $time_format['moment'],
498
+            'moment' => $date_format['moment'].' '.$time_format['moment'],
499 499
             'moment_split' => array(
500 500
                 'date' => $date_format['moment'],
501 501
                 'time' => $time_format['moment']
@@ -518,7 +518,7 @@  discard block
 block discarded – undo
518 518
          *
519 519
          * @var array
520 520
          */
521
-        $symbols_map          = array(
521
+        $symbols_map = array(
522 522
             // Day
523 523
             // 01
524 524
             'd' => array(
@@ -670,26 +670,26 @@  discard block
 block discarded – undo
670 670
         $escaping             = false;
671 671
         $format_string_length = strlen($format_string);
672 672
         for ($i = 0; $i < $format_string_length; $i++) {
673
-            $char = $format_string[ $i ];
673
+            $char = $format_string[$i];
674 674
             if ($char === '\\') { // PHP date format escaping character
675 675
                 $i++;
676 676
                 if ($escaping) {
677
-                    $jquery_ui_format .= $format_string[ $i ];
678
-                    $moment_format    .= $format_string[ $i ];
677
+                    $jquery_ui_format .= $format_string[$i];
678
+                    $moment_format    .= $format_string[$i];
679 679
                 } else {
680
-                    $jquery_ui_format .= '\'' . $format_string[ $i ];
681
-                    $moment_format    .= $format_string[ $i ];
680
+                    $jquery_ui_format .= '\''.$format_string[$i];
681
+                    $moment_format    .= $format_string[$i];
682 682
                 }
683 683
                 $escaping = true;
684 684
             } else {
685 685
                 if ($escaping) {
686 686
                     $jquery_ui_format .= "'";
687 687
                     $moment_format    .= "'";
688
-                    $escaping         = false;
688
+                    $escaping = false;
689 689
                 }
690
-                if (isset($symbols_map[ $char ])) {
691
-                    $jquery_ui_format .= $symbols_map[ $char ]['js'];
692
-                    $moment_format    .= $symbols_map[ $char ]['moment'];
690
+                if (isset($symbols_map[$char])) {
691
+                    $jquery_ui_format .= $symbols_map[$char]['js'];
692
+                    $moment_format    .= $symbols_map[$char]['moment'];
693 693
                 } else {
694 694
                     $jquery_ui_format .= $char;
695 695
                     $moment_format    .= $char;
@@ -746,7 +746,7 @@  discard block
 block discarded – undo
746 746
     public static function dates_represent_one_24_hour_date($date_1, $date_2)
747 747
     {
748 748
 
749
-        if ((! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
749
+        if (( ! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
750 750
             || ($date_1->format(EE_Datetime_Field::mysql_time_format) !== '00:00:00'
751 751
                 || $date_2->format(
752 752
                     EE_Datetime_Field::mysql_time_format
@@ -782,8 +782,8 @@  discard block
 block discarded – undo
782 782
             ? $DateTimeZone->getOffset(new DateTime('now')) / HOUR_IN_SECONDS
783 783
             : (float) get_option('gmt_offset');
784 784
         $query_interval = $offset < 0
785
-            ? 'DATE_SUB(' . $field_for_interval . ', INTERVAL ' . $offset * -1 . ' HOUR)'
786
-            : 'DATE_ADD(' . $field_for_interval . ', INTERVAL ' . $offset . ' HOUR)';
785
+            ? 'DATE_SUB('.$field_for_interval.', INTERVAL '.$offset * -1.' HOUR)'
786
+            : 'DATE_ADD('.$field_for_interval.', INTERVAL '.$offset.' HOUR)';
787 787
         return $query_interval;
788 788
     }
789 789
 
@@ -800,16 +800,16 @@  discard block
 block discarded – undo
800 800
     public static function get_timezone_string_for_display()
801 801
     {
802 802
         $pretty_timezone = apply_filters('FHEE__EEH_DTT_Helper__get_timezone_string_for_display', '');
803
-        if (! empty($pretty_timezone)) {
803
+        if ( ! empty($pretty_timezone)) {
804 804
             return esc_html($pretty_timezone);
805 805
         }
806 806
         $timezone_string = get_option('timezone_string');
807 807
         if ($timezone_string) {
808 808
             static $mo_loaded = false;
809 809
             // Load translations for continents and cities just like wp_timezone_choice does
810
-            if (! $mo_loaded) {
810
+            if ( ! $mo_loaded) {
811 811
                 $locale = get_locale();
812
-                $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
812
+                $mofile = WP_LANG_DIR.'/continents-cities-'.$locale.'.mo';
813 813
                 load_textdomain('continents-cities', $mofile);
814 814
                 $mo_loaded = true;
815 815
             }
@@ -836,10 +836,10 @@  discard block
 block discarded – undo
836 836
         } else {
837 837
             // convert the part after the decimal, eg "5" (from x.5) or "25" (from x.25)
838 838
             // to minutes, eg 30 or 15, respectively
839
-            $hour_fraction = (float) ('0.' . $parts[1]);
839
+            $hour_fraction = (float) ('0.'.$parts[1]);
840 840
             $parts[1]      = (string) $hour_fraction * 60;
841 841
         }
842
-        return sprintf(__('UTC%1$s', 'event_espresso'), $prefix . implode(':', $parts));
842
+        return sprintf(__('UTC%1$s', 'event_espresso'), $prefix.implode(':', $parts));
843 843
     }
844 844
 
845 845
 
@@ -922,9 +922,9 @@  discard block
 block discarded – undo
922 922
             'Pacific',
923 923
         );
924 924
         // Load translations for continents and cities.
925
-        if (! $mo_loaded || $locale !== $locale_loaded) {
925
+        if ( ! $mo_loaded || $locale !== $locale_loaded) {
926 926
             $locale_loaded = $locale ? $locale : get_locale();
927
-            $mofile        = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
927
+            $mofile        = WP_LANG_DIR.'/continents-cities-'.$locale_loaded.'.mo';
928 928
             unload_textdomain('continents-cities');
929 929
             load_textdomain('continents-cities', $mofile);
930 930
             $mo_loaded = true;
@@ -932,11 +932,11 @@  discard block
 block discarded – undo
932 932
         $zone_data = array();
933 933
         foreach (timezone_identifiers_list() as $zone) {
934 934
             $zone = explode('/', $zone);
935
-            if (! in_array($zone[0], $continents, true)) {
935
+            if ( ! in_array($zone[0], $continents, true)) {
936 936
                 continue;
937 937
             }
938 938
             // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
939
-            $exists      = array(
939
+            $exists = array(
940 940
                 0 => isset($zone[0]) && $zone[0],
941 941
                 1 => isset($zone[1]) && $zone[1],
942 942
                 2 => isset($zone[2]) && $zone[2],
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
         usort($zone_data, '_wp_timezone_choice_usort_callback');
967 967
         $structure = array();
968 968
         if (empty($selected_zone)) {
969
-            $structure[] = '<option selected="selected" value="">' . __('Select a city', 'event_espresso') . '</option>';
969
+            $structure[] = '<option selected="selected" value="">'.__('Select a city', 'event_espresso').'</option>';
970 970
         }
971 971
         foreach ($zone_data as $key => $zone) {
972 972
             // Build value in an array to join later
@@ -977,30 +977,30 @@  discard block
 block discarded – undo
977 977
             } else {
978 978
                 // It's inside a continent group
979 979
                 // Continent optgroup
980
-                if (! isset($zone_data[ $key - 1 ]) || $zone_data[ $key - 1 ]['continent'] !== $zone['continent']) {
980
+                if ( ! isset($zone_data[$key - 1]) || $zone_data[$key - 1]['continent'] !== $zone['continent']) {
981 981
                     $label       = $zone['t_continent'];
982
-                    $structure[] = '<optgroup label="' . esc_attr($label) . '">';
982
+                    $structure[] = '<optgroup label="'.esc_attr($label).'">';
983 983
                 }
984 984
                 // Add the city to the value
985 985
                 $value[] = $zone['city'];
986 986
                 $display = $zone['t_city'];
987
-                if (! empty($zone['subcity'])) {
987
+                if ( ! empty($zone['subcity'])) {
988 988
                     // Add the subcity to the value
989 989
                     $value[] = $zone['subcity'];
990
-                    $display .= ' - ' . $zone['t_subcity'];
990
+                    $display .= ' - '.$zone['t_subcity'];
991 991
                 }
992 992
             }
993 993
             // Build the value
994 994
             $value       = implode('/', $value);
995 995
             $selected    = $value === $selected_zone ? ' selected="selected"' : '';
996
-            $structure[] = '<option value="' . esc_attr($value) . '"' . $selected . '>'
996
+            $structure[] = '<option value="'.esc_attr($value).'"'.$selected.'>'
997 997
                            . esc_html($display)
998 998
                            . '</option>';
999 999
             // Close continent optgroup
1000
-            if (! empty($zone['city'])
1000
+            if ( ! empty($zone['city'])
1001 1001
                 && (
1002
-                    ! isset($zone_data[ $key + 1 ])
1003
-                    || (isset($zone_data[ $key + 1 ]) && $zone_data[ $key + 1 ]['continent'] !== $zone['continent'])
1002
+                    ! isset($zone_data[$key + 1])
1003
+                    || (isset($zone_data[$key + 1]) && $zone_data[$key + 1]['continent'] !== $zone['continent'])
1004 1004
                 )
1005 1005
             ) {
1006 1006
                 $structure[] = '</optgroup>';
Please login to merge, or discard this patch.
core/services/helpers/datetime/HelperInterface.php 1 patch
Indentation   +90 added lines, -90 removed lines patch added patch discarded remove patch
@@ -16,94 +16,94 @@
 block discarded – undo
16 16
 interface HelperInterface
17 17
 {
18 18
 
19
-    /**
20
-     * Ensures that a valid timezone string is returned.
21
-     *
22
-     * @param string $timezone_string  When not provided then attempt to use the timezone_string set in the WP Time
23
-     *                                 settings (or derive from set UTC offset).
24
-     * @return string
25
-     */
26
-    public function getValidTimezoneString($timezone_string = '');
27
-
28
-
29
-    /**
30
-     * The only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
31
-     *
32
-     * @param string $timezone_string
33
-     * @param bool   $throw_error
34
-     * @return bool
35
-     */
36
-    public function validateTimezone($timezone_string, $throw_error = true);
37
-
38
-
39
-    /**
40
-     * Returns a timezone string for the provided gmt_offset.
41
-     * @param float|string $gmt_offset
42
-     * @return string
43
-     */
44
-    public function getTimezoneStringFromGmtOffset($gmt_offset = '');
45
-
46
-
47
-    /**
48
-     * Gets the site's GMT offset based on either the timezone string
49
-     * (in which case the gmt offset will vary depending on the location's
50
-     * observance of daylight savings time) or the gmt_offset wp option
51
-     *
52
-     * @return int  seconds offset
53
-     */
54
-    public function getSiteTimezoneGmtOffset();
55
-
56
-
57
-    /**
58
-     * Get timezone transitions
59
-     * @param DateTimeZone $date_time_zone
60
-     * @param int|null     $time
61
-     * @param bool         $first_only
62
-     * @return array
63
-     */
64
-    public function getTimezoneTransitions(DateTimeZone $date_time_zone, $time = null, $first_only = true);
65
-
66
-
67
-    /**
68
-     * Get Timezone offset for given timezone object
69
-     * @param DateTimeZone $date_time_zone
70
-     * @param null|int         $time
71
-     * @return int
72
-     */
73
-    public function getTimezoneOffset(DateTimeZone $date_time_zone, $time = null);
74
-
75
-
76
-    /**
77
-     * Provide a timezone select input
78
-     * @param string $timezone_string
79
-     * @return string
80
-     */
81
-    public function timezoneSelectInput($timezone_string = '');
82
-
83
-
84
-    /**
85
-     * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
86
-     * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
87
-     * the site is used.
88
-     * This is used typically when using a Unix timestamp any core WP functions that expect their specially
89
-     * computed timestamp (i.e. date_i18n() )
90
-     *
91
-     * @param int    $unix_timestamp    if 0, then time() will be used.
92
-     * @param string $timezone_string timezone_string. If empty, then the current set timezone for the
93
-     *                                site will be used.
94
-     * @return int      unix_timestamp value with the offset applied for the given timezone.
95
-     */
96
-    public function getTimestampWithOffset($unix_timestamp = 0, $timezone_string = '');
97
-
98
-
99
-    /**
100
-     * Depending on PHP version,
101
-     * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
102
-     * To get around that, for these fringe timezones we bump them to a known valid offset.
103
-     * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
104
-     *
105
-     * @param int $gmt_offset
106
-     * @return int
107
-     */
108
-    public function adjustInvalidGmtOffsets($gmt_offset);
19
+	/**
20
+	 * Ensures that a valid timezone string is returned.
21
+	 *
22
+	 * @param string $timezone_string  When not provided then attempt to use the timezone_string set in the WP Time
23
+	 *                                 settings (or derive from set UTC offset).
24
+	 * @return string
25
+	 */
26
+	public function getValidTimezoneString($timezone_string = '');
27
+
28
+
29
+	/**
30
+	 * The only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
31
+	 *
32
+	 * @param string $timezone_string
33
+	 * @param bool   $throw_error
34
+	 * @return bool
35
+	 */
36
+	public function validateTimezone($timezone_string, $throw_error = true);
37
+
38
+
39
+	/**
40
+	 * Returns a timezone string for the provided gmt_offset.
41
+	 * @param float|string $gmt_offset
42
+	 * @return string
43
+	 */
44
+	public function getTimezoneStringFromGmtOffset($gmt_offset = '');
45
+
46
+
47
+	/**
48
+	 * Gets the site's GMT offset based on either the timezone string
49
+	 * (in which case the gmt offset will vary depending on the location's
50
+	 * observance of daylight savings time) or the gmt_offset wp option
51
+	 *
52
+	 * @return int  seconds offset
53
+	 */
54
+	public function getSiteTimezoneGmtOffset();
55
+
56
+
57
+	/**
58
+	 * Get timezone transitions
59
+	 * @param DateTimeZone $date_time_zone
60
+	 * @param int|null     $time
61
+	 * @param bool         $first_only
62
+	 * @return array
63
+	 */
64
+	public function getTimezoneTransitions(DateTimeZone $date_time_zone, $time = null, $first_only = true);
65
+
66
+
67
+	/**
68
+	 * Get Timezone offset for given timezone object
69
+	 * @param DateTimeZone $date_time_zone
70
+	 * @param null|int         $time
71
+	 * @return int
72
+	 */
73
+	public function getTimezoneOffset(DateTimeZone $date_time_zone, $time = null);
74
+
75
+
76
+	/**
77
+	 * Provide a timezone select input
78
+	 * @param string $timezone_string
79
+	 * @return string
80
+	 */
81
+	public function timezoneSelectInput($timezone_string = '');
82
+
83
+
84
+	/**
85
+	 * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
86
+	 * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
87
+	 * the site is used.
88
+	 * This is used typically when using a Unix timestamp any core WP functions that expect their specially
89
+	 * computed timestamp (i.e. date_i18n() )
90
+	 *
91
+	 * @param int    $unix_timestamp    if 0, then time() will be used.
92
+	 * @param string $timezone_string timezone_string. If empty, then the current set timezone for the
93
+	 *                                site will be used.
94
+	 * @return int      unix_timestamp value with the offset applied for the given timezone.
95
+	 */
96
+	public function getTimestampWithOffset($unix_timestamp = 0, $timezone_string = '');
97
+
98
+
99
+	/**
100
+	 * Depending on PHP version,
101
+	 * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
102
+	 * To get around that, for these fringe timezones we bump them to a known valid offset.
103
+	 * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
104
+	 *
105
+	 * @param int $gmt_offset
106
+	 * @return int
107
+	 */
108
+	public function adjustInvalidGmtOffsets($gmt_offset);
109 109
 }
Please login to merge, or discard this patch.
core/services/context/ContextChecker.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@
 block discarded – undo
87 87
     {
88 88
         $this->evaluation_callback = $evaluation_callback instanceof Closure
89 89
             ? $evaluation_callback
90
-            : function (ContextInterface $context, $acceptable_values) {
90
+            : function(ContextInterface $context, $acceptable_values) {
91 91
                 return in_array($context->slug(), $acceptable_values, true);
92 92
             };
93 93
     }
Please login to merge, or discard this patch.
Indentation   +141 added lines, -141 removed lines patch added patch discarded remove patch
@@ -17,145 +17,145 @@
 block discarded – undo
17 17
 class ContextChecker
18 18
 {
19 19
 
20
-    /**
21
-     * A unique string used to identify where this ContextChecker is being employed
22
-     * Is currently only used within the hook name for the filterable return value of isAllowed().
23
-     *
24
-     * @var string $identifier
25
-     */
26
-    private $identifier;
27
-
28
-    /**
29
-     * A list of values to be compared against the slug of the Context class passed to isAllowed()
30
-     *
31
-     * @var array $acceptable_values
32
-     */
33
-    private $acceptable_values;
34
-
35
-    /**
36
-     * Closure that will be called to perform the evaluation within isAllowed().
37
-     * If none is provided, then a simple type sensitive in_array() check will be used
38
-     * and return true if the incoming Context::slug() is found within the array of $acceptable_values.
39
-     *
40
-     * @var Closure $evaluation_callback
41
-     */
42
-    private $evaluation_callback;
43
-
44
-
45
-    /**
46
-     * ContextChecker constructor.
47
-     *
48
-     * @param string       $identifier
49
-     * @param array        $acceptable_values
50
-     * @param Closure|null $evaluation_callback [optional]
51
-     */
52
-    public function __construct($identifier, array $acceptable_values, Closure $evaluation_callback = null)
53
-    {
54
-        $this->setIdentifier($identifier);
55
-        $this->setAcceptableValues($acceptable_values);
56
-        $this->setEvaluationCallback($evaluation_callback);
57
-    }
58
-
59
-
60
-    /**
61
-     * @param string $identifier
62
-     */
63
-    private function setIdentifier($identifier)
64
-    {
65
-        $this->identifier = sanitize_key($identifier);
66
-    }
67
-
68
-
69
-    /**
70
-     * @param array $acceptable_values
71
-     */
72
-    private function setAcceptableValues(array $acceptable_values)
73
-    {
74
-        $this->acceptable_values = $acceptable_values;
75
-    }
76
-
77
-
78
-    /**
79
-     * @param Closure $evaluation_callback
80
-     */
81
-    private function setEvaluationCallback(Closure $evaluation_callback = null)
82
-    {
83
-        $this->evaluation_callback = $evaluation_callback instanceof Closure
84
-            ? $evaluation_callback
85
-            : function (ContextInterface $context, $acceptable_values) {
86
-                return in_array($context->slug(), $acceptable_values, true);
87
-            };
88
-    }
89
-
90
-
91
-    /**
92
-     * @return string
93
-     */
94
-    protected function identifier()
95
-    {
96
-        return $this->identifier;
97
-    }
98
-
99
-
100
-    /**
101
-     * @return array
102
-     */
103
-    protected function acceptableValues()
104
-    {
105
-        return apply_filters(
106
-            "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__{$this->identifier}__acceptableValues",
107
-            $this->acceptable_values
108
-        );
109
-    }
110
-
111
-
112
-    /**
113
-     * @return Closure
114
-     */
115
-    protected function evaluationCallback()
116
-    {
117
-        return $this->evaluation_callback;
118
-    }
119
-
120
-
121
-    /**
122
-     * Returns true if the incoming Context class slug matches one of the preset acceptable values.
123
-     * The result is filterable using the identifier for this ContextChecker.
124
-     * example:
125
-     * If this ContextChecker's $identifier was set to "registration-checkout-type",
126
-     * then the filter here would be named:
127
-     *  "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed".
128
-     * Other code could hook into the filter in isAllowed() using the above name
129
-     * and test for additional acceptable values.
130
-     * So if the set of $acceptable_values was: [ "initial-visit",  "revisit" ]
131
-     * then adding a filter to
132
-     *  "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed",
133
-     * would allow you to perform your own conditional and allow "wait-list-checkout" as an acceptable value.
134
-     *  example:
135
-     *      add_filter(
136
-     *          'FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed',
137
-     *          function ($is_allowed, ContextInterface $context) { return $context->slug() === 'wait-list-checkout'
138
-     *                  ? true
139
-     *                  : $is_allowed;
140
-     *          },
141
-     *          10,
142
-     *          2
143
-     *      );
144
-     *
145
-     * @param ContextInterface $context
146
-     * @return boolean
147
-     */
148
-    public function isAllowed(ContextInterface $context)
149
-    {
150
-        $evaluation_callback = $this->evaluationCallback();
151
-        return filter_var(
152
-            apply_filters(
153
-                "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__{$this->identifier}__isAllowed",
154
-                $evaluation_callback($context, $this->acceptableValues()),
155
-                $context,
156
-                $this
157
-            ),
158
-            FILTER_VALIDATE_BOOLEAN
159
-        );
160
-    }
20
+	/**
21
+	 * A unique string used to identify where this ContextChecker is being employed
22
+	 * Is currently only used within the hook name for the filterable return value of isAllowed().
23
+	 *
24
+	 * @var string $identifier
25
+	 */
26
+	private $identifier;
27
+
28
+	/**
29
+	 * A list of values to be compared against the slug of the Context class passed to isAllowed()
30
+	 *
31
+	 * @var array $acceptable_values
32
+	 */
33
+	private $acceptable_values;
34
+
35
+	/**
36
+	 * Closure that will be called to perform the evaluation within isAllowed().
37
+	 * If none is provided, then a simple type sensitive in_array() check will be used
38
+	 * and return true if the incoming Context::slug() is found within the array of $acceptable_values.
39
+	 *
40
+	 * @var Closure $evaluation_callback
41
+	 */
42
+	private $evaluation_callback;
43
+
44
+
45
+	/**
46
+	 * ContextChecker constructor.
47
+	 *
48
+	 * @param string       $identifier
49
+	 * @param array        $acceptable_values
50
+	 * @param Closure|null $evaluation_callback [optional]
51
+	 */
52
+	public function __construct($identifier, array $acceptable_values, Closure $evaluation_callback = null)
53
+	{
54
+		$this->setIdentifier($identifier);
55
+		$this->setAcceptableValues($acceptable_values);
56
+		$this->setEvaluationCallback($evaluation_callback);
57
+	}
58
+
59
+
60
+	/**
61
+	 * @param string $identifier
62
+	 */
63
+	private function setIdentifier($identifier)
64
+	{
65
+		$this->identifier = sanitize_key($identifier);
66
+	}
67
+
68
+
69
+	/**
70
+	 * @param array $acceptable_values
71
+	 */
72
+	private function setAcceptableValues(array $acceptable_values)
73
+	{
74
+		$this->acceptable_values = $acceptable_values;
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param Closure $evaluation_callback
80
+	 */
81
+	private function setEvaluationCallback(Closure $evaluation_callback = null)
82
+	{
83
+		$this->evaluation_callback = $evaluation_callback instanceof Closure
84
+			? $evaluation_callback
85
+			: function (ContextInterface $context, $acceptable_values) {
86
+				return in_array($context->slug(), $acceptable_values, true);
87
+			};
88
+	}
89
+
90
+
91
+	/**
92
+	 * @return string
93
+	 */
94
+	protected function identifier()
95
+	{
96
+		return $this->identifier;
97
+	}
98
+
99
+
100
+	/**
101
+	 * @return array
102
+	 */
103
+	protected function acceptableValues()
104
+	{
105
+		return apply_filters(
106
+			"FHEE__EventEspresso_core_domain_entities_context_ContextChecker__{$this->identifier}__acceptableValues",
107
+			$this->acceptable_values
108
+		);
109
+	}
110
+
111
+
112
+	/**
113
+	 * @return Closure
114
+	 */
115
+	protected function evaluationCallback()
116
+	{
117
+		return $this->evaluation_callback;
118
+	}
119
+
120
+
121
+	/**
122
+	 * Returns true if the incoming Context class slug matches one of the preset acceptable values.
123
+	 * The result is filterable using the identifier for this ContextChecker.
124
+	 * example:
125
+	 * If this ContextChecker's $identifier was set to "registration-checkout-type",
126
+	 * then the filter here would be named:
127
+	 *  "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed".
128
+	 * Other code could hook into the filter in isAllowed() using the above name
129
+	 * and test for additional acceptable values.
130
+	 * So if the set of $acceptable_values was: [ "initial-visit",  "revisit" ]
131
+	 * then adding a filter to
132
+	 *  "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed",
133
+	 * would allow you to perform your own conditional and allow "wait-list-checkout" as an acceptable value.
134
+	 *  example:
135
+	 *      add_filter(
136
+	 *          'FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed',
137
+	 *          function ($is_allowed, ContextInterface $context) { return $context->slug() === 'wait-list-checkout'
138
+	 *                  ? true
139
+	 *                  : $is_allowed;
140
+	 *          },
141
+	 *          10,
142
+	 *          2
143
+	 *      );
144
+	 *
145
+	 * @param ContextInterface $context
146
+	 * @return boolean
147
+	 */
148
+	public function isAllowed(ContextInterface $context)
149
+	{
150
+		$evaluation_callback = $this->evaluationCallback();
151
+		return filter_var(
152
+			apply_filters(
153
+				"FHEE__EventEspresso_core_domain_entities_context_ContextChecker__{$this->identifier}__isAllowed",
154
+				$evaluation_callback($context, $this->acceptableValues()),
155
+				$context,
156
+				$this
157
+			),
158
+			FILTER_VALIDATE_BOOLEAN
159
+		);
160
+	}
161 161
 }
Please login to merge, or discard this patch.
core/domain/entities/contexts/ContextInterface.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -18,14 +18,14 @@
 block discarded – undo
18 18
 interface ContextInterface
19 19
 {
20 20
 
21
-    /**
22
-     * @return string
23
-     */
24
-    public function slug();
21
+	/**
22
+	 * @return string
23
+	 */
24
+	public function slug();
25 25
 
26 26
 
27
-    /**
28
-     * @return string
29
-     */
30
-    public function description();
27
+	/**
28
+	 * @return string
29
+	 */
30
+	public function description();
31 31
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Question.model.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
      * Gets an array for converting between QST_system and QST_IDs for system questions. Eg, if you want to know
365 365
      * which system question QST_ID corresponds to the QST_system 'city', use EEM_Question::instance()->get_Question_ID_from_system_string('city');
366 366
      * @param $QST_system
367
-     * @return int of QST_ID for the question that corresponds to that QST_system
367
+     * @return string of QST_ID for the question that corresponds to that QST_system
368 368
      */
369 369
     public function get_Question_ID_from_system_string($QST_system)
370 370
     {
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 
426 426
 
427 427
     /**
428
-     * @return array
428
+     * @return EEM_Question
429 429
      */
430 430
     public function question_descriptions()
431 431
     {
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -213,10 +213,10 @@  discard block
 block discarded – undo
213 213
             'Question_Group_Question' => new EE_Has_Many_Relation()
214 214
         );
215 215
         // this model is generally available for reading
216
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
217
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Reg_Form('QST_system');
218
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Reg_Form('QST_system');
219
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Reg_Form('QST_system');
216
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
217
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Reg_Form('QST_system');
218
+        $this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Reg_Form('QST_system');
219
+        $this->_cap_restriction_generators[EEM_Base::caps_delete] = new EE_Restriction_Generator_Reg_Form('QST_system');
220 220
         parent::__construct($timezone);
221 221
     }
222 222
 
@@ -256,10 +256,10 @@  discard block
 block discarded – undo
256 256
      */
257 257
     public function question_type_is_in_category($question_type, $category)
258 258
     {
259
-        if (!isset($this->_question_type_categories[ $category ])) {
259
+        if ( ! isset($this->_question_type_categories[$category])) {
260 260
             return false;
261 261
         }
262
-        return in_array($question_type, $this->_question_type_categories[ $category ]);
262
+        return in_array($question_type, $this->_question_type_categories[$category]);
263 263
     }
264 264
 
265 265
 
@@ -270,8 +270,8 @@  discard block
 block discarded – undo
270 270
      */
271 271
     public function question_types_in_category($category)
272 272
     {
273
-        if (isset($this->_question_type_categories[ $category ])) {
274
-            return $this->_question_type_categories[ $category ];
273
+        if (isset($this->_question_type_categories[$category])) {
274
+            return $this->_question_type_categories[$category];
275 275
         }
276 276
         return array();
277 277
     }
@@ -410,8 +410,8 @@  discard block
 block discarded – undo
410 410
     public function absolute_max_for_system_question($system_question_value)
411 411
     {
412 412
         $maxes = $this->system_question_maxes();
413
-        if (isset($maxes[ $system_question_value ])) {
414
-            return $maxes[ $system_question_value ];
413
+        if (isset($maxes[$system_question_value])) {
414
+            return $maxes[$system_question_value];
415 415
         } else {
416 416
             return EE_INF;
417 417
         }
Please login to merge, or discard this patch.
Indentation   +432 added lines, -432 removed lines patch added patch discarded remove patch
@@ -10,437 +10,437 @@
 block discarded – undo
10 10
 class EEM_Question extends EEM_Soft_Delete_Base
11 11
 {
12 12
 
13
-    // constant used to indicate that the question type is COUNTRY
14
-    const QST_type_country = 'COUNTRY';
13
+	// constant used to indicate that the question type is COUNTRY
14
+	const QST_type_country = 'COUNTRY';
15 15
 
16
-    // constant used to indicate that the question type is DATE
17
-    const QST_type_date = 'DATE';
18
-
19
-    // constant used to indicate that the question type is DROPDOWN
20
-    const QST_type_dropdown = 'DROPDOWN';
21
-
22
-    // constant used to indicate that the question type is CHECKBOX
23
-    const QST_type_checkbox = 'CHECKBOX';
24
-
25
-    // constant used to indicate that the question type is RADIO_BTN
26
-    const QST_type_radio = 'RADIO_BTN';
27
-
28
-    // constant used to indicate that the question type is STATE
29
-    const QST_type_state = 'STATE';
30
-
31
-    // constant used to indicate that the question type is TEXT
32
-    const QST_type_text = 'TEXT';
33
-
34
-    // constant used to indicate that the question type is TEXTAREA
35
-    const QST_type_textarea = 'TEXTAREA';
36
-
37
-    // constant used to indicate that the question type is a TEXTAREA that allows simple html
38
-    const QST_type_html_textarea = 'HTML_TEXTAREA';
39
-
40
-    // constant used to indicate that the question type is an email input
41
-    const QST_type_email = 'EMAIL';
42
-
43
-    // constant used to indicate that the question type is an email input
44
-    const QST_type_email_confirm = 'EMAIL_CONFIRM';
45
-
46
-    // constant used to indicate that the question type is a US-formatted phone number
47
-    const QST_type_us_phone = 'US_PHONE';
48
-
49
-    // constant used to indicate that the question type is an integer (whole number)
50
-    const QST_type_int = 'INTEGER';
51
-
52
-    // constant used to indicate that the question type is a decimal (float)
53
-    const QST_type_decimal = 'DECIMAL';
54
-
55
-    // constant used to indicate that the question type is a valid URL
56
-    const QST_type_url = 'URL';
57
-
58
-    // constant used to indicate that the question type is a YEAR
59
-    const QST_type_year = 'YEAR';
60
-
61
-    // constant used to indicate that the question type is a multi-select
62
-    const QST_type_multi_select = 'MULTI_SELECT';
63
-
64
-    /**
65
-     * Question types that are interchangeable, even after answers have been provided for them.
66
-     * Top-level keys are category slugs, next level is an array of question types. If question types
67
-     * aren't in this array, it is assumed they AREN'T interchangeable with any other question types.
68
-     *
69
-     * @access protected
70
-     * @var array $_question_type_categories {
71
-     * @type string $text
72
-     * @type string $single -answer-enum
73
-     * @type string $multi -answer-enum
74
-     *                    }
75
-     */
76
-    protected $_question_type_categories = array();
77
-
78
-    /**
79
-     * lists all the question types which should be allowed. Ideally, this will be extensible.
80
-     *
81
-     * @access protected
82
-     * @var array $_allowed_question_types
83
-     */
84
-    protected $_allowed_question_types = array();
85
-
86
-    /**
87
-     * brief descriptions for all the question types
88
-     *
89
-     * @access protected
90
-     * @var EEM_Question $_instance
91
-     */
92
-    protected $_question_descriptions;
93
-
94
-
95
-    /**
96
-     * Question types that should have an admin-defined max input length
97
-     * @var array
98
-     */
99
-    protected $question_types_with_max_lengh;
100
-
101
-
102
-    // private instance of the Attendee object
103
-    protected static $_instance = null;
104
-
105
-
106
-    /**
107
-     * EEM_Question constructor.
108
-     *
109
-     * @param null $timezone
110
-     */
111
-    protected function __construct($timezone = null)
112
-    {
113
-        $this->singular_item = __('Question', 'event_espresso');
114
-        $this->plural_item = __('Questions', 'event_espresso');
115
-        $this->_allowed_question_types = apply_filters(
116
-            'FHEE__EEM_Question__construct__allowed_question_types',
117
-            array(
118
-                EEM_Question::QST_type_text => __('Text', 'event_espresso'),
119
-                EEM_Question::QST_type_textarea => __('Textarea', 'event_espresso'),
120
-                EEM_Question::QST_type_checkbox => __('Checkboxes', 'event_espresso'),
121
-                EEM_Question::QST_type_radio => __('Radio Buttons', 'event_espresso'),
122
-                EEM_Question::QST_type_dropdown => __('Dropdown', 'event_espresso'),
123
-                EEM_Question::QST_type_state => __('State/Province Dropdown', 'event_espresso'),
124
-                EEM_Question::QST_type_country => __('Country Dropdown', 'event_espresso'),
125
-                EEM_Question::QST_type_date => __('Date Picker', 'event_espresso'),
126
-                EEM_Question::QST_type_html_textarea => __('HTML Textarea', 'event_espresso'),
127
-                EEM_Question::QST_type_email => __('Email', 'event_espresso'),
128
-                EEM_Question::QST_type_email_confirm => __('Confirm Email', 'event_espresso'),
129
-                EEM_Question::QST_type_us_phone => __('USA - Format Phone', 'event_espresso'),
130
-                EEM_Question::QST_type_decimal => __('Number', 'event_espresso'),
131
-                EEM_Question::QST_type_int => __('Whole Number', 'event_espresso'),
132
-                EEM_Question::QST_type_url => __('URL', 'event_espresso'),
133
-                EEM_Question::QST_type_year => __('Year', 'event_espresso'),
134
-                EEM_Question::QST_type_multi_select => __('Multi Select', 'event_espresso')
135
-            )
136
-        );
137
-        $this->_question_descriptions = apply_filters(
138
-            'FHEE__EEM_Question__construct__question_descriptions',
139
-            array(
140
-                EEM_Question::QST_type_text => __('A single line text input field', 'event_espresso'),
141
-                EEM_Question::QST_type_textarea => __('A multi line text input field', 'event_espresso'),
142
-                EEM_Question::QST_type_checkbox => __('Allows multiple preset options to be selected', 'event_espresso'),
143
-                EEM_Question::QST_type_radio => __('Allows a single preset option to be selected', 'event_espresso'),
144
-                EEM_Question::QST_type_dropdown => __('A dropdown that allows a single selection', 'event_espresso'),
145
-                EEM_Question::QST_type_state => __('A dropdown that lists states/provinces', 'event_espresso'),
146
-                EEM_Question::QST_type_country => __('A dropdown that lists countries', 'event_espresso'),
147
-                EEM_Question::QST_type_date => __('A popup calendar that allows date selections', 'event_espresso'),
148
-                EEM_Question::QST_type_html_textarea => __('A multi line text input field that allows HTML', 'event_espresso'),
149
-                EEM_Question::QST_type_email => __('A text field that must contain a valid Email address', 'event_espresso'),
150
-                EEM_Question::QST_type_email_confirm => __('A text field that must contain a valid Email address and be equal to Email field', 'event_espresso'),
151
-                EEM_Question::QST_type_us_phone => __('A text field that must contain a valid US phone number', 'event_espresso'),
152
-                EEM_Question::QST_type_decimal => __('A text field that allows number values with decimals', 'event_espresso'),
153
-                EEM_Question::QST_type_int => __('A text field that only allows whole numbers (no decimals)', 'event_espresso'),
154
-                EEM_Question::QST_type_url => __('A text field that must contain a valid URL', 'event_espresso'),
155
-                EEM_Question::QST_type_year => __('A dropdown that lists the last 100 years', 'event_espresso'),
156
-                EEM_Question::QST_type_multi_select => __('A dropdown that allows multiple selections', 'event_espresso')
157
-            )
158
-        );
159
-        $this->_question_type_categories = (array) apply_filters(
160
-            'FHEE__EEM_Question__construct__question_type_categories',
161
-            array(
162
-                'text' => array(
163
-                    EEM_Question::QST_type_text,
164
-                    EEM_Question::QST_type_textarea,
165
-                    EEM_Question::QST_type_date,
166
-                    EEM_Question::QST_type_html_textarea,
167
-                    EEM_Question::QST_type_email,
168
-                    EEM_Question::QST_type_email_confirm,
169
-                    EEM_Question::QST_type_us_phone,
170
-                    EEM_Question::QST_type_decimal,
171
-                    EEM_Question::QST_type_int,
172
-                    EEM_Question::QST_type_url,
173
-                    EEM_Question::QST_type_year
174
-                ),
175
-                'single-answer-enum' => array(
176
-                    EEM_Question::QST_type_radio,
177
-                    EEM_Question::QST_type_dropdown
178
-                ),
179
-                'multi-answer-enum' => array(
180
-                    EEM_Question::QST_type_checkbox,
181
-                    EEM_Question::QST_type_multi_select
182
-                )
183
-            )
184
-        );
185
-        $this->question_types_with_max_lengh = apply_filters(
186
-            'FHEE__EEM_Question___construct__question_types_with_max_length',
187
-            array(
188
-                EEM_Question::QST_type_text,
189
-                EEM_Question::QST_type_textarea,
190
-                EEM_Question::QST_type_html_textarea
191
-            )
192
-        );
193
-
194
-        $this->_tables = array(
195
-            'Question' => new EE_Primary_Table('esp_question', 'QST_ID')
196
-        );
197
-        $this->_fields = array(
198
-            'Question' => array(
199
-                'QST_ID' => new EE_Primary_Key_Int_Field('QST_ID', __('Question ID', 'event_espresso')),
200
-                'QST_display_text' => new EE_Post_Content_Field('QST_display_text', __('Question Text', 'event_espresso'), true, ''),
201
-                'QST_admin_label' => new EE_Plain_Text_Field('QST_admin_label', __('Question Label (admin-only)', 'event_espresso'), true, ''),
202
-                'QST_system' => new EE_Plain_Text_Field('QST_system', __('Internal string ID for question', 'event_espresso'), false, ''),
203
-                'QST_type' => new EE_Enum_Text_Field('QST_type', __('Question Type', 'event_espresso'), false, 'TEXT', $this->_allowed_question_types),
204
-                'QST_required' => new EE_Boolean_Field('QST_required', __('Required Question?', 'event_espresso'), false, false),
205
-                'QST_required_text' => new EE_Simple_HTML_Field('QST_required_text', __('Text to Display if Not Provided', 'event_espresso'), true, ''),
206
-                'QST_order' => new EE_Integer_Field('QST_order', __('Question Order', 'event_espresso'), false, 0),
207
-                'QST_admin_only' => new EE_Boolean_Field('QST_admin_only', __('Admin-Only Question?', 'event_espresso'), false, false),
208
-                'QST_max' => new EE_Infinite_Integer_Field('QST_max', __('Max Size', 'event_espresso'), false, EE_INF),
209
-                'QST_wp_user' => new EE_WP_User_Field('QST_wp_user', __('Question Creator ID', 'event_espresso'), false),
210
-                'QST_deleted' => new EE_Trashed_Flag_Field('QST_deleted', __('Flag Indicating question was deleted', 'event_espresso'), false, false)
211
-            )
212
-        );
213
-        $this->_model_relations = array(
214
-            'Question_Group' => new EE_HABTM_Relation('Question_Group_Question'),
215
-            'Question_Option' => new EE_Has_Many_Relation(),
216
-            'Answer' => new EE_Has_Many_Relation(),
217
-            'WP_User' => new EE_Belongs_To_Relation(),
218
-            // for QST_order column
219
-            'Question_Group_Question' => new EE_Has_Many_Relation()
220
-        );
221
-        // this model is generally available for reading
222
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
223
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Reg_Form('QST_system');
224
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Reg_Form('QST_system');
225
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Reg_Form('QST_system');
226
-        parent::__construct($timezone);
227
-    }
228
-
229
-    /**
230
-     * Returns the list of allowed question types, which are normally: 'TEXT','TEXTAREA','RADIO_BTN','DROPDOWN','CHECKBOX','DATE'
231
-     * but they can be extended
232
-     * @return string[]
233
-     */
234
-    public function allowed_question_types()
235
-    {
236
-        return $this->_allowed_question_types;
237
-    }
238
-
239
-    /**
240
-     * Gets all the question types in the same category
241
-     * @param string $question_type one of EEM_Question::allowed_question_types(
242
-     * @return string[] like EEM_Question::allowed_question_types()
243
-     */
244
-    public function question_types_in_same_category($question_type)
245
-    {
246
-        $question_types = array($question_type);
247
-        foreach ($this->_question_type_categories as $category => $question_types_in_category) {
248
-            if (in_array($question_type, $question_types_in_category)) {
249
-                $question_types = $question_types_in_category;
250
-                break;
251
-            }
252
-        }
253
-
254
-        return array_intersect_key($this->allowed_question_types(), array_flip($question_types));
255
-    }
256
-
257
-    /**
258
-     * Determines if the given question type is in the given question type category
259
-     * @param string $question_type one of EEM_Question::allowed_question_types()
260
-     * @param string $category one of the top-level keys of EEM_Question::question_type_categories()
261
-     * @return boolean
262
-     */
263
-    public function question_type_is_in_category($question_type, $category)
264
-    {
265
-        if (!isset($this->_question_type_categories[ $category ])) {
266
-            return false;
267
-        }
268
-        return in_array($question_type, $this->_question_type_categories[ $category ]);
269
-    }
270
-
271
-
272
-    /**
273
-     * Returns all the question types in the given category
274
-     * @param string $category
275
-     * @return array|mixed
276
-     */
277
-    public function question_types_in_category($category)
278
-    {
279
-        if (isset($this->_question_type_categories[ $category ])) {
280
-            return $this->_question_type_categories[ $category ];
281
-        }
282
-        return array();
283
-    }
284
-
285
-
286
-    /**
287
-     * Returns all the question types that should have question options
288
-     * @return array
289
-     */
290
-    public function question_types_with_options()
291
-    {
292
-        return array_merge(
293
-            $this->question_types_in_category('single-answer-enum'),
294
-            $this->question_types_in_category('multi-answer-enum')
295
-        );
296
-    }
297
-
298
-    /**
299
-     * Returns the question type categories 2d array
300
-     * @return array see EEM_Question::_question_type_categories
301
-     */
302
-    public function question_type_categories()
303
-    {
304
-        return $this->_question_type_categories;
305
-    }
306
-
307
-    /**
308
-     * Returns an array of all the QST_system values that can be allowed in the system question group
309
-     * identified by $system_question_group_id
310
-     * @param string $system_question_group_id QSG_system
311
-     * @return array of system question names (QST_system)
312
-     */
313
-    public function allowed_system_questions_in_system_question_group($system_question_group_id)
314
-    {
315
-        $question_system_ids = array();
316
-        switch ($system_question_group_id) {
317
-            case EEM_Question_Group::system_personal:
318
-                $question_system_ids = array(
319
-                    EEM_Attendee::system_question_fname,
320
-                    EEM_Attendee::system_question_lname,
321
-                    EEM_Attendee::system_question_email,
322
-                    EEM_Attendee::system_question_email_confirm,
323
-                    EEM_Attendee::system_question_phone
324
-                );
325
-                break;
326
-            case EEM_Question_Group::system_address:
327
-                $question_system_ids = array(
328
-                    EEM_Attendee::system_question_address,
329
-                    EEM_Attendee::system_question_address2,
330
-                    EEM_Attendee::system_question_city,
331
-                    EEM_Attendee::system_question_state,
332
-                    EEM_Attendee::system_question_country,
333
-                    EEM_Attendee::system_question_zip,
334
-                    EEM_Attendee::system_question_phone
335
-                );
336
-                break;
337
-        }
338
-        return apply_filters('FHEE__EEM_Question__system_questions_allowed_in_system_question_group__return', $question_system_ids, $system_question_group_id);
339
-    }
340
-
341
-    /**
342
-     * Returns an array of all the QST_system values that are required in the system question group
343
-     * identified by $system_question_group_id
344
-     * @param string $system_question_group_id QSG_system
345
-     * @return array of system question names (QST_system)
346
-     */
347
-    public function required_system_questions_in_system_question_group($system_question_group_id)
348
-    {
349
-        $question_system_ids = null;
350
-        switch ($system_question_group_id) {
351
-            case EEM_Question_Group::system_personal:
352
-                $question_system_ids = array(
353
-                    EEM_Attendee::system_question_fname,
354
-                    EEM_Attendee::system_question_email,
355
-                );
356
-                break;
357
-            default:
358
-                $question_system_ids = array();
359
-        }
360
-        return apply_filters('FHEE__EEM_Question__system_questions_required_in_system_question_group', $question_system_ids, $system_question_group_id);
361
-    }
362
-
363
-
364
-    /**
365
-     * Gets an array for converting between QST_system and QST_IDs for system questions. Eg, if you want to know
366
-     * which system question QST_ID corresponds to the QST_system 'city', use EEM_Question::instance()->get_Question_ID_from_system_string('city');
367
-     * @param $QST_system
368
-     * @return int of QST_ID for the question that corresponds to that QST_system
369
-     */
370
-    public function get_Question_ID_from_system_string($QST_system)
371
-    {
372
-        return $this->get_var(array(array('QST_system' => $QST_system)));
373
-    }
374
-
375
-
376
-    /**
377
-     * searches the db for the question with the latest question order and returns that value.
378
-     * @access public
379
-     * @return int
380
-     */
381
-    public function get_latest_question_order()
382
-    {
383
-        $columns_to_select = array(
384
-            'max_order' => array("MAX(QST_order)", "%d")
385
-        );
386
-        $max = $this->_get_all_wpdb_results(array(), ARRAY_A, $columns_to_select);
387
-        return isset($max[0], $max[0]['max_order']) ? $max[0]['max_order'] : 0;
388
-    }
389
-
390
-    /**
391
-     * Returns an array where keys are system question QST_system values,
392
-     * and values are the highest question max the admin can set on the question
393
-     * (aka the "max max"; eg, a site admin can change the zip question to have a max
394
-     * of 5, but no larger than 12)
395
-     * @return array
396
-     */
397
-    public function system_question_maxes()
398
-    {
399
-        return array(
400
-            'fname' => 45,
401
-            'lname' => 45,
402
-            'address' => 255,
403
-            'address2' => 255,
404
-            'city' => 45,
405
-            'zip' => 12,
406
-            'email' => 255,
407
-            'email_confirm' => 255,
408
-            'phone' => 45,
409
-        );
410
-    }
411
-
412
-    /**
413
-     * Given a QST_system value, gets the question's largest allowable max input.
414
-     * @see Registration_Form_Admin_Page::system_question_maxes()
415
-     * @param string $system_question_value
416
-     * @return int|float
417
-     */
418
-    public function absolute_max_for_system_question($system_question_value)
419
-    {
420
-        $maxes = $this->system_question_maxes();
421
-        if (isset($maxes[ $system_question_value ])) {
422
-            return $maxes[ $system_question_value ];
423
-        } else {
424
-            return EE_INF;
425
-        }
426
-    }
427
-
428
-
429
-    /**
430
-     * @return array
431
-     */
432
-    public function question_descriptions()
433
-    {
434
-        return $this->_question_descriptions;
435
-    }
436
-
437
-
438
-    /**
439
-     * Returns all the question types that should have an admin-defined max input length
440
-     * @return array
441
-     */
442
-    public function questionTypesWithMaxLength()
443
-    {
444
-        return (array) $this->question_types_with_max_lengh;
445
-    }
16
+	// constant used to indicate that the question type is DATE
17
+	const QST_type_date = 'DATE';
18
+
19
+	// constant used to indicate that the question type is DROPDOWN
20
+	const QST_type_dropdown = 'DROPDOWN';
21
+
22
+	// constant used to indicate that the question type is CHECKBOX
23
+	const QST_type_checkbox = 'CHECKBOX';
24
+
25
+	// constant used to indicate that the question type is RADIO_BTN
26
+	const QST_type_radio = 'RADIO_BTN';
27
+
28
+	// constant used to indicate that the question type is STATE
29
+	const QST_type_state = 'STATE';
30
+
31
+	// constant used to indicate that the question type is TEXT
32
+	const QST_type_text = 'TEXT';
33
+
34
+	// constant used to indicate that the question type is TEXTAREA
35
+	const QST_type_textarea = 'TEXTAREA';
36
+
37
+	// constant used to indicate that the question type is a TEXTAREA that allows simple html
38
+	const QST_type_html_textarea = 'HTML_TEXTAREA';
39
+
40
+	// constant used to indicate that the question type is an email input
41
+	const QST_type_email = 'EMAIL';
42
+
43
+	// constant used to indicate that the question type is an email input
44
+	const QST_type_email_confirm = 'EMAIL_CONFIRM';
45
+
46
+	// constant used to indicate that the question type is a US-formatted phone number
47
+	const QST_type_us_phone = 'US_PHONE';
48
+
49
+	// constant used to indicate that the question type is an integer (whole number)
50
+	const QST_type_int = 'INTEGER';
51
+
52
+	// constant used to indicate that the question type is a decimal (float)
53
+	const QST_type_decimal = 'DECIMAL';
54
+
55
+	// constant used to indicate that the question type is a valid URL
56
+	const QST_type_url = 'URL';
57
+
58
+	// constant used to indicate that the question type is a YEAR
59
+	const QST_type_year = 'YEAR';
60
+
61
+	// constant used to indicate that the question type is a multi-select
62
+	const QST_type_multi_select = 'MULTI_SELECT';
63
+
64
+	/**
65
+	 * Question types that are interchangeable, even after answers have been provided for them.
66
+	 * Top-level keys are category slugs, next level is an array of question types. If question types
67
+	 * aren't in this array, it is assumed they AREN'T interchangeable with any other question types.
68
+	 *
69
+	 * @access protected
70
+	 * @var array $_question_type_categories {
71
+	 * @type string $text
72
+	 * @type string $single -answer-enum
73
+	 * @type string $multi -answer-enum
74
+	 *                    }
75
+	 */
76
+	protected $_question_type_categories = array();
77
+
78
+	/**
79
+	 * lists all the question types which should be allowed. Ideally, this will be extensible.
80
+	 *
81
+	 * @access protected
82
+	 * @var array $_allowed_question_types
83
+	 */
84
+	protected $_allowed_question_types = array();
85
+
86
+	/**
87
+	 * brief descriptions for all the question types
88
+	 *
89
+	 * @access protected
90
+	 * @var EEM_Question $_instance
91
+	 */
92
+	protected $_question_descriptions;
93
+
94
+
95
+	/**
96
+	 * Question types that should have an admin-defined max input length
97
+	 * @var array
98
+	 */
99
+	protected $question_types_with_max_lengh;
100
+
101
+
102
+	// private instance of the Attendee object
103
+	protected static $_instance = null;
104
+
105
+
106
+	/**
107
+	 * EEM_Question constructor.
108
+	 *
109
+	 * @param null $timezone
110
+	 */
111
+	protected function __construct($timezone = null)
112
+	{
113
+		$this->singular_item = __('Question', 'event_espresso');
114
+		$this->plural_item = __('Questions', 'event_espresso');
115
+		$this->_allowed_question_types = apply_filters(
116
+			'FHEE__EEM_Question__construct__allowed_question_types',
117
+			array(
118
+				EEM_Question::QST_type_text => __('Text', 'event_espresso'),
119
+				EEM_Question::QST_type_textarea => __('Textarea', 'event_espresso'),
120
+				EEM_Question::QST_type_checkbox => __('Checkboxes', 'event_espresso'),
121
+				EEM_Question::QST_type_radio => __('Radio Buttons', 'event_espresso'),
122
+				EEM_Question::QST_type_dropdown => __('Dropdown', 'event_espresso'),
123
+				EEM_Question::QST_type_state => __('State/Province Dropdown', 'event_espresso'),
124
+				EEM_Question::QST_type_country => __('Country Dropdown', 'event_espresso'),
125
+				EEM_Question::QST_type_date => __('Date Picker', 'event_espresso'),
126
+				EEM_Question::QST_type_html_textarea => __('HTML Textarea', 'event_espresso'),
127
+				EEM_Question::QST_type_email => __('Email', 'event_espresso'),
128
+				EEM_Question::QST_type_email_confirm => __('Confirm Email', 'event_espresso'),
129
+				EEM_Question::QST_type_us_phone => __('USA - Format Phone', 'event_espresso'),
130
+				EEM_Question::QST_type_decimal => __('Number', 'event_espresso'),
131
+				EEM_Question::QST_type_int => __('Whole Number', 'event_espresso'),
132
+				EEM_Question::QST_type_url => __('URL', 'event_espresso'),
133
+				EEM_Question::QST_type_year => __('Year', 'event_espresso'),
134
+				EEM_Question::QST_type_multi_select => __('Multi Select', 'event_espresso')
135
+			)
136
+		);
137
+		$this->_question_descriptions = apply_filters(
138
+			'FHEE__EEM_Question__construct__question_descriptions',
139
+			array(
140
+				EEM_Question::QST_type_text => __('A single line text input field', 'event_espresso'),
141
+				EEM_Question::QST_type_textarea => __('A multi line text input field', 'event_espresso'),
142
+				EEM_Question::QST_type_checkbox => __('Allows multiple preset options to be selected', 'event_espresso'),
143
+				EEM_Question::QST_type_radio => __('Allows a single preset option to be selected', 'event_espresso'),
144
+				EEM_Question::QST_type_dropdown => __('A dropdown that allows a single selection', 'event_espresso'),
145
+				EEM_Question::QST_type_state => __('A dropdown that lists states/provinces', 'event_espresso'),
146
+				EEM_Question::QST_type_country => __('A dropdown that lists countries', 'event_espresso'),
147
+				EEM_Question::QST_type_date => __('A popup calendar that allows date selections', 'event_espresso'),
148
+				EEM_Question::QST_type_html_textarea => __('A multi line text input field that allows HTML', 'event_espresso'),
149
+				EEM_Question::QST_type_email => __('A text field that must contain a valid Email address', 'event_espresso'),
150
+				EEM_Question::QST_type_email_confirm => __('A text field that must contain a valid Email address and be equal to Email field', 'event_espresso'),
151
+				EEM_Question::QST_type_us_phone => __('A text field that must contain a valid US phone number', 'event_espresso'),
152
+				EEM_Question::QST_type_decimal => __('A text field that allows number values with decimals', 'event_espresso'),
153
+				EEM_Question::QST_type_int => __('A text field that only allows whole numbers (no decimals)', 'event_espresso'),
154
+				EEM_Question::QST_type_url => __('A text field that must contain a valid URL', 'event_espresso'),
155
+				EEM_Question::QST_type_year => __('A dropdown that lists the last 100 years', 'event_espresso'),
156
+				EEM_Question::QST_type_multi_select => __('A dropdown that allows multiple selections', 'event_espresso')
157
+			)
158
+		);
159
+		$this->_question_type_categories = (array) apply_filters(
160
+			'FHEE__EEM_Question__construct__question_type_categories',
161
+			array(
162
+				'text' => array(
163
+					EEM_Question::QST_type_text,
164
+					EEM_Question::QST_type_textarea,
165
+					EEM_Question::QST_type_date,
166
+					EEM_Question::QST_type_html_textarea,
167
+					EEM_Question::QST_type_email,
168
+					EEM_Question::QST_type_email_confirm,
169
+					EEM_Question::QST_type_us_phone,
170
+					EEM_Question::QST_type_decimal,
171
+					EEM_Question::QST_type_int,
172
+					EEM_Question::QST_type_url,
173
+					EEM_Question::QST_type_year
174
+				),
175
+				'single-answer-enum' => array(
176
+					EEM_Question::QST_type_radio,
177
+					EEM_Question::QST_type_dropdown
178
+				),
179
+				'multi-answer-enum' => array(
180
+					EEM_Question::QST_type_checkbox,
181
+					EEM_Question::QST_type_multi_select
182
+				)
183
+			)
184
+		);
185
+		$this->question_types_with_max_lengh = apply_filters(
186
+			'FHEE__EEM_Question___construct__question_types_with_max_length',
187
+			array(
188
+				EEM_Question::QST_type_text,
189
+				EEM_Question::QST_type_textarea,
190
+				EEM_Question::QST_type_html_textarea
191
+			)
192
+		);
193
+
194
+		$this->_tables = array(
195
+			'Question' => new EE_Primary_Table('esp_question', 'QST_ID')
196
+		);
197
+		$this->_fields = array(
198
+			'Question' => array(
199
+				'QST_ID' => new EE_Primary_Key_Int_Field('QST_ID', __('Question ID', 'event_espresso')),
200
+				'QST_display_text' => new EE_Post_Content_Field('QST_display_text', __('Question Text', 'event_espresso'), true, ''),
201
+				'QST_admin_label' => new EE_Plain_Text_Field('QST_admin_label', __('Question Label (admin-only)', 'event_espresso'), true, ''),
202
+				'QST_system' => new EE_Plain_Text_Field('QST_system', __('Internal string ID for question', 'event_espresso'), false, ''),
203
+				'QST_type' => new EE_Enum_Text_Field('QST_type', __('Question Type', 'event_espresso'), false, 'TEXT', $this->_allowed_question_types),
204
+				'QST_required' => new EE_Boolean_Field('QST_required', __('Required Question?', 'event_espresso'), false, false),
205
+				'QST_required_text' => new EE_Simple_HTML_Field('QST_required_text', __('Text to Display if Not Provided', 'event_espresso'), true, ''),
206
+				'QST_order' => new EE_Integer_Field('QST_order', __('Question Order', 'event_espresso'), false, 0),
207
+				'QST_admin_only' => new EE_Boolean_Field('QST_admin_only', __('Admin-Only Question?', 'event_espresso'), false, false),
208
+				'QST_max' => new EE_Infinite_Integer_Field('QST_max', __('Max Size', 'event_espresso'), false, EE_INF),
209
+				'QST_wp_user' => new EE_WP_User_Field('QST_wp_user', __('Question Creator ID', 'event_espresso'), false),
210
+				'QST_deleted' => new EE_Trashed_Flag_Field('QST_deleted', __('Flag Indicating question was deleted', 'event_espresso'), false, false)
211
+			)
212
+		);
213
+		$this->_model_relations = array(
214
+			'Question_Group' => new EE_HABTM_Relation('Question_Group_Question'),
215
+			'Question_Option' => new EE_Has_Many_Relation(),
216
+			'Answer' => new EE_Has_Many_Relation(),
217
+			'WP_User' => new EE_Belongs_To_Relation(),
218
+			// for QST_order column
219
+			'Question_Group_Question' => new EE_Has_Many_Relation()
220
+		);
221
+		// this model is generally available for reading
222
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
223
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Reg_Form('QST_system');
224
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Reg_Form('QST_system');
225
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Reg_Form('QST_system');
226
+		parent::__construct($timezone);
227
+	}
228
+
229
+	/**
230
+	 * Returns the list of allowed question types, which are normally: 'TEXT','TEXTAREA','RADIO_BTN','DROPDOWN','CHECKBOX','DATE'
231
+	 * but they can be extended
232
+	 * @return string[]
233
+	 */
234
+	public function allowed_question_types()
235
+	{
236
+		return $this->_allowed_question_types;
237
+	}
238
+
239
+	/**
240
+	 * Gets all the question types in the same category
241
+	 * @param string $question_type one of EEM_Question::allowed_question_types(
242
+	 * @return string[] like EEM_Question::allowed_question_types()
243
+	 */
244
+	public function question_types_in_same_category($question_type)
245
+	{
246
+		$question_types = array($question_type);
247
+		foreach ($this->_question_type_categories as $category => $question_types_in_category) {
248
+			if (in_array($question_type, $question_types_in_category)) {
249
+				$question_types = $question_types_in_category;
250
+				break;
251
+			}
252
+		}
253
+
254
+		return array_intersect_key($this->allowed_question_types(), array_flip($question_types));
255
+	}
256
+
257
+	/**
258
+	 * Determines if the given question type is in the given question type category
259
+	 * @param string $question_type one of EEM_Question::allowed_question_types()
260
+	 * @param string $category one of the top-level keys of EEM_Question::question_type_categories()
261
+	 * @return boolean
262
+	 */
263
+	public function question_type_is_in_category($question_type, $category)
264
+	{
265
+		if (!isset($this->_question_type_categories[ $category ])) {
266
+			return false;
267
+		}
268
+		return in_array($question_type, $this->_question_type_categories[ $category ]);
269
+	}
270
+
271
+
272
+	/**
273
+	 * Returns all the question types in the given category
274
+	 * @param string $category
275
+	 * @return array|mixed
276
+	 */
277
+	public function question_types_in_category($category)
278
+	{
279
+		if (isset($this->_question_type_categories[ $category ])) {
280
+			return $this->_question_type_categories[ $category ];
281
+		}
282
+		return array();
283
+	}
284
+
285
+
286
+	/**
287
+	 * Returns all the question types that should have question options
288
+	 * @return array
289
+	 */
290
+	public function question_types_with_options()
291
+	{
292
+		return array_merge(
293
+			$this->question_types_in_category('single-answer-enum'),
294
+			$this->question_types_in_category('multi-answer-enum')
295
+		);
296
+	}
297
+
298
+	/**
299
+	 * Returns the question type categories 2d array
300
+	 * @return array see EEM_Question::_question_type_categories
301
+	 */
302
+	public function question_type_categories()
303
+	{
304
+		return $this->_question_type_categories;
305
+	}
306
+
307
+	/**
308
+	 * Returns an array of all the QST_system values that can be allowed in the system question group
309
+	 * identified by $system_question_group_id
310
+	 * @param string $system_question_group_id QSG_system
311
+	 * @return array of system question names (QST_system)
312
+	 */
313
+	public function allowed_system_questions_in_system_question_group($system_question_group_id)
314
+	{
315
+		$question_system_ids = array();
316
+		switch ($system_question_group_id) {
317
+			case EEM_Question_Group::system_personal:
318
+				$question_system_ids = array(
319
+					EEM_Attendee::system_question_fname,
320
+					EEM_Attendee::system_question_lname,
321
+					EEM_Attendee::system_question_email,
322
+					EEM_Attendee::system_question_email_confirm,
323
+					EEM_Attendee::system_question_phone
324
+				);
325
+				break;
326
+			case EEM_Question_Group::system_address:
327
+				$question_system_ids = array(
328
+					EEM_Attendee::system_question_address,
329
+					EEM_Attendee::system_question_address2,
330
+					EEM_Attendee::system_question_city,
331
+					EEM_Attendee::system_question_state,
332
+					EEM_Attendee::system_question_country,
333
+					EEM_Attendee::system_question_zip,
334
+					EEM_Attendee::system_question_phone
335
+				);
336
+				break;
337
+		}
338
+		return apply_filters('FHEE__EEM_Question__system_questions_allowed_in_system_question_group__return', $question_system_ids, $system_question_group_id);
339
+	}
340
+
341
+	/**
342
+	 * Returns an array of all the QST_system values that are required in the system question group
343
+	 * identified by $system_question_group_id
344
+	 * @param string $system_question_group_id QSG_system
345
+	 * @return array of system question names (QST_system)
346
+	 */
347
+	public function required_system_questions_in_system_question_group($system_question_group_id)
348
+	{
349
+		$question_system_ids = null;
350
+		switch ($system_question_group_id) {
351
+			case EEM_Question_Group::system_personal:
352
+				$question_system_ids = array(
353
+					EEM_Attendee::system_question_fname,
354
+					EEM_Attendee::system_question_email,
355
+				);
356
+				break;
357
+			default:
358
+				$question_system_ids = array();
359
+		}
360
+		return apply_filters('FHEE__EEM_Question__system_questions_required_in_system_question_group', $question_system_ids, $system_question_group_id);
361
+	}
362
+
363
+
364
+	/**
365
+	 * Gets an array for converting between QST_system and QST_IDs for system questions. Eg, if you want to know
366
+	 * which system question QST_ID corresponds to the QST_system 'city', use EEM_Question::instance()->get_Question_ID_from_system_string('city');
367
+	 * @param $QST_system
368
+	 * @return int of QST_ID for the question that corresponds to that QST_system
369
+	 */
370
+	public function get_Question_ID_from_system_string($QST_system)
371
+	{
372
+		return $this->get_var(array(array('QST_system' => $QST_system)));
373
+	}
374
+
375
+
376
+	/**
377
+	 * searches the db for the question with the latest question order and returns that value.
378
+	 * @access public
379
+	 * @return int
380
+	 */
381
+	public function get_latest_question_order()
382
+	{
383
+		$columns_to_select = array(
384
+			'max_order' => array("MAX(QST_order)", "%d")
385
+		);
386
+		$max = $this->_get_all_wpdb_results(array(), ARRAY_A, $columns_to_select);
387
+		return isset($max[0], $max[0]['max_order']) ? $max[0]['max_order'] : 0;
388
+	}
389
+
390
+	/**
391
+	 * Returns an array where keys are system question QST_system values,
392
+	 * and values are the highest question max the admin can set on the question
393
+	 * (aka the "max max"; eg, a site admin can change the zip question to have a max
394
+	 * of 5, but no larger than 12)
395
+	 * @return array
396
+	 */
397
+	public function system_question_maxes()
398
+	{
399
+		return array(
400
+			'fname' => 45,
401
+			'lname' => 45,
402
+			'address' => 255,
403
+			'address2' => 255,
404
+			'city' => 45,
405
+			'zip' => 12,
406
+			'email' => 255,
407
+			'email_confirm' => 255,
408
+			'phone' => 45,
409
+		);
410
+	}
411
+
412
+	/**
413
+	 * Given a QST_system value, gets the question's largest allowable max input.
414
+	 * @see Registration_Form_Admin_Page::system_question_maxes()
415
+	 * @param string $system_question_value
416
+	 * @return int|float
417
+	 */
418
+	public function absolute_max_for_system_question($system_question_value)
419
+	{
420
+		$maxes = $this->system_question_maxes();
421
+		if (isset($maxes[ $system_question_value ])) {
422
+			return $maxes[ $system_question_value ];
423
+		} else {
424
+			return EE_INF;
425
+		}
426
+	}
427
+
428
+
429
+	/**
430
+	 * @return array
431
+	 */
432
+	public function question_descriptions()
433
+	{
434
+		return $this->_question_descriptions;
435
+	}
436
+
437
+
438
+	/**
439
+	 * Returns all the question types that should have an admin-defined max input length
440
+	 * @return array
441
+	 */
442
+	public function questionTypesWithMaxLength()
443
+	{
444
+		return (array) $this->question_types_with_max_lengh;
445
+	}
446 446
 }
Please login to merge, or discard this patch.
admin_pages/transactions/Transactions_Admin_Page.core.php 3 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -2166,6 +2166,7 @@
 block discarded – undo
2166 2166
      *
2167 2167
      * @access protected
2168 2168
      * @param \EE_Payment | null $payment
2169
+     * @param EE_Payment $payment
2169 2170
      */
2170 2171
     protected function _maybe_send_notifications($payment = null)
2171 2172
     {
Please login to merge, or discard this patch.
Spacing   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -356,7 +356,7 @@  discard block
 block discarded – undo
356 356
         // enqueue style
357 357
         wp_register_style(
358 358
             'espresso_txn',
359
-            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
359
+            TXN_ASSETS_URL.'espresso_transactions_admin.css',
360 360
             array(),
361 361
             EVENT_ESPRESSO_VERSION
362 362
         );
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
         // scripts
365 365
         wp_register_script(
366 366
             'espresso_txn',
367
-            TXN_ASSETS_URL . 'espresso_transactions_admin.js',
367
+            TXN_ASSETS_URL.'espresso_transactions_admin.js',
368 368
             array(
369 369
                 'ee_admin_js',
370 370
                 'ee-datepicker',
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
             $this->_transaction->verify_abandoned_transaction_status();
493 493
         }
494 494
 
495
-        if (! $this->_transaction instanceof EE_Transaction) {
495
+        if ( ! $this->_transaction instanceof EE_Transaction) {
496 496
             $error_msg = sprintf(
497 497
                 esc_html__(
498 498
                     'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
@@ -585,7 +585,7 @@  discard block
 block discarded – undo
585 585
             'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
586 586
             array(
587 587
                 'overpaid'   => array(
588
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
588
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::overpaid_status_code,
589 589
                     'desc'  => EEH_Template::pretty_status(
590 590
                         EEM_Transaction::overpaid_status_code,
591 591
                         false,
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
                     ),
594 594
                 ),
595 595
                 'complete'   => array(
596
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
596
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::complete_status_code,
597 597
                     'desc'  => EEH_Template::pretty_status(
598 598
                         EEM_Transaction::complete_status_code,
599 599
                         false,
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
                     ),
602 602
                 ),
603 603
                 'incomplete' => array(
604
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
604
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::incomplete_status_code,
605 605
                     'desc'  => EEH_Template::pretty_status(
606 606
                         EEM_Transaction::incomplete_status_code,
607 607
                         false,
@@ -609,7 +609,7 @@  discard block
 block discarded – undo
609 609
                     ),
610 610
                 ),
611 611
                 'abandoned'  => array(
612
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
612
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::abandoned_status_code,
613 613
                     'desc'  => EEH_Template::pretty_status(
614 614
                         EEM_Transaction::abandoned_status_code,
615 615
                         false,
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
                     ),
618 618
                 ),
619 619
                 'failed'     => array(
620
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
620
+                    'class' => 'ee-status-legend ee-status-legend-'.EEM_Transaction::failed_status_code,
621 621
                     'desc'  => EEH_Template::pretty_status(
622 622
                         EEM_Transaction::failed_status_code,
623 623
                         false,
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
                     'Click to Edit event',
667 667
                     'event_espresso'
668 668
                 )
669
-                . '">' . $event->name() . '</a>',
669
+                . '">'.$event->name().'</a>',
670 670
                 '</h3>'
671 671
             )
672 672
             : '';
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
 
701 701
         $this->_set_transaction_object();
702 702
 
703
-        if (! $this->_transaction instanceof EE_Transaction) {
703
+        if ( ! $this->_transaction instanceof EE_Transaction) {
704 704
             return;
705 705
         }
706 706
         $primary_registration = $this->_transaction->primary_registration();
@@ -714,9 +714,9 @@  discard block
 block discarded – undo
714 714
         $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
715 715
         $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
716 716
 
717
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->status_ID() ];
717
+        $this->_template_args['txn_status']['value'] = self::$_txn_status[$this->_transaction->status_ID()];
718 718
         $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
719
-        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->status_ID();
719
+        $this->_template_args['txn_status']['class'] = 'status-'.$this->_transaction->status_ID();
720 720
 
721 721
         $this->_template_args['grand_total'] = $this->_transaction->total();
722 722
         $this->_template_args['total_paid'] = $this->_transaction->paid();
@@ -832,7 +832,7 @@  discard block
 block discarded – undo
832 832
         // grab messages at the last second
833 833
         $this->_template_args['notices'] = EE_Error::get_notices();
834 834
         // path to template
835
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
835
+        $template_path = TXN_TEMPLATE_PATH.'txn_admin_details_header.template.php';
836 836
         $this->_template_args['admin_page_header'] = EEH_Template::display_template(
837 837
             $template_path,
838 838
             $this->_template_args,
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 
862 862
         $this->_set_transaction_object();
863 863
 
864
-        if (! $this->_transaction instanceof EE_Transaction) {
864
+        if ( ! $this->_transaction instanceof EE_Transaction) {
865 865
             return;
866 866
         }
867 867
         add_meta_box(
@@ -917,7 +917,7 @@  discard block
 block discarded – undo
917 917
     {
918 918
         $content = '';
919 919
         $actions = array();
920
-        if (! $transaction instanceof EE_Transaction) {
920
+        if ( ! $transaction instanceof EE_Transaction) {
921 921
             return $content;
922 922
         }
923 923
         /** @var EE_Registration $primary_registration */
@@ -998,7 +998,7 @@  discard block
 block discarded – undo
998 998
         );
999 999
         if ($actions) {
1000 1000
             $content = '<ul>';
1001
-            $content .= '<li>' . implode('</li><li>', $actions) . '</li>';
1001
+            $content .= '<li>'.implode('</li><li>', $actions).'</li>';
1002 1002
             $content .= '</uL>';
1003 1003
         }
1004 1004
         return $content;
@@ -1059,7 +1059,7 @@  discard block
 block discarded – undo
1059 1059
 
1060 1060
         // process payment details
1061 1061
         $payments = $this->_transaction->payments();
1062
-        if (! empty($payments)) {
1062
+        if ( ! empty($payments)) {
1063 1063
             $this->_template_args['payments'] = $payments;
1064 1064
             $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1065 1065
         } else {
@@ -1120,7 +1120,7 @@  discard block
 block discarded – undo
1120 1120
                                   esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1121 1121
                                   ucwords(str_replace('_', ' ', $reg_step)),
1122 1122
                                   date(
1123
-                                      get_option('date_format') . ' ' . get_option('time_format'),
1123
+                                      get_option('date_format').' '.get_option('time_format'),
1124 1124
                                       $reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1125 1125
                                   )
1126 1126
                               )
@@ -1173,7 +1173,7 @@  discard block
 block discarded – undo
1173 1173
 
1174 1174
         // 'espresso_delete_payment_nonce'
1175 1175
 
1176
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1176
+        $template_path = TXN_TEMPLATE_PATH.'txn_admin_details_main_meta_box_txn_details.template.php';
1177 1177
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
1178 1178
     }
1179 1179
 
@@ -1205,18 +1205,18 @@  discard block
 block discarded – undo
1205 1205
                 ),
1206 1206
             )
1207 1207
         );
1208
-        if (! empty($reg_payments)) {
1208
+        if ( ! empty($reg_payments)) {
1209 1209
             foreach ($payments as $payment) {
1210
-                if (! $payment instanceof EE_Payment) {
1210
+                if ( ! $payment instanceof EE_Payment) {
1211 1211
                     continue;
1212
-                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1213
-                    $existing_reg_payments[ $payment->ID() ] = array();
1212
+                } elseif ( ! isset($existing_reg_payments[$payment->ID()])) {
1213
+                    $existing_reg_payments[$payment->ID()] = array();
1214 1214
                 }
1215 1215
                 foreach ($reg_payments as $reg_payment) {
1216 1216
                     if ($reg_payment instanceof EE_Registration_Payment
1217 1217
                         && $reg_payment->payment_ID() === $payment->ID()
1218 1218
                     ) {
1219
-                        $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1219
+                        $existing_reg_payments[$payment->ID()][] = $reg_payment->registration_ID();
1220 1220
                     }
1221 1221
                 }
1222 1222
             }
@@ -1254,22 +1254,22 @@  discard block
 block discarded – undo
1254 1254
                 ),
1255 1255
             ),
1256 1256
         );
1257
-        $registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
1257
+        $registrations_to_apply_payment_to = EEH_HTML::br().EEH_HTML::div(
1258 1258
             '',
1259 1259
             'txn-admin-apply-payment-to-registrations-dv',
1260 1260
             '',
1261 1261
             'clear: both; margin: 1.5em 0 0; display: none;'
1262 1262
         );
1263
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1263
+        $registrations_to_apply_payment_to .= EEH_HTML::br().EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1264 1264
         $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1265 1265
         $registrations_to_apply_payment_to .= EEH_HTML::thead(
1266 1266
             EEH_HTML::tr(
1267
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1268
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1269
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1270
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1271
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1272
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1267
+                EEH_HTML::th(esc_html__('ID', 'event_espresso')).
1268
+                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')).
1269
+                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')).
1270
+                EEH_HTML::th(esc_html__('Event', 'event_espresso')).
1271
+                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr').
1272
+                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr').
1273 1273
                 EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1274 1274
             )
1275 1275
         );
@@ -1284,7 +1284,7 @@  discard block
 block discarded – undo
1284 1284
                     : esc_html__('Unknown Attendee', 'event_espresso');
1285 1285
                 $owing = $registration->final_price() - $registration->paid();
1286 1286
                 $taxable = $registration->ticket()->taxable()
1287
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1287
+                    ? ' <span class="smaller-text lt-grey-text"> '.esc_html__('+ tax', 'event_espresso').'</span>'
1288 1288
                     : '';
1289 1289
                 $checked = empty($existing_reg_payments)
1290 1290
                            || in_array($registration->ID(), $existing_reg_payments, true)
@@ -1292,26 +1292,26 @@  discard block
 block discarded – undo
1292 1292
                     : '';
1293 1293
                 $disabled = $registration->final_price() > 0 ? '' : ' disabled';
1294 1294
                 $registrations_to_apply_payment_to .= EEH_HTML::tr(
1295
-                    EEH_HTML::td($registration->ID()) .
1296
-                    EEH_HTML::td($attendee_name) .
1295
+                    EEH_HTML::td($registration->ID()).
1296
+                    EEH_HTML::td($attendee_name).
1297 1297
                     EEH_HTML::td(
1298
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1299
-                    ) .
1300
-                    EEH_HTML::td($registration->event_name()) .
1301
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1298
+                        $registration->ticket()->name().' : '.$registration->ticket()->pretty_price().$taxable
1299
+                    ).
1300
+                    EEH_HTML::td($registration->event_name()).
1301
+                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr').
1302 1302
                     EEH_HTML::td(
1303 1303
                         EEH_Template::format_currency($owing),
1304 1304
                         '',
1305 1305
                         'txn-admin-payment-owing-td jst-cntr'
1306
-                    ) .
1306
+                    ).
1307 1307
                     EEH_HTML::td(
1308
-                        '<input type="checkbox" value="' . $registration->ID()
1308
+                        '<input type="checkbox" value="'.$registration->ID()
1309 1309
                         . '" name="txn_admin_payment[registrations]"'
1310
-                        . $checked . $disabled . '>',
1310
+                        . $checked.$disabled.'>',
1311 1311
                         '',
1312 1312
                         'jst-cntr'
1313 1313
                     ),
1314
-                    'apply-payment-registration-row-' . $registration->ID()
1314
+                    'apply-payment-registration-row-'.$registration->ID()
1315 1315
                 );
1316 1316
             }
1317 1317
         }
@@ -1392,12 +1392,12 @@  discard block
 block discarded – undo
1392 1392
                 array(
1393 1393
                     'OR*payment_method_for_payment' => array(
1394 1394
                         'PMD_ID'    => array('IN', $payment_methods_of_payments),
1395
-                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1395
+                        'PMD_scope' => array('LIKE', '%'.EEM_Payment_Method::scope_admin.'%'),
1396 1396
                     ),
1397 1397
                 ),
1398 1398
             );
1399 1399
         } else {
1400
-            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1400
+            $query_args = array(array('PMD_scope' => array('LIKE', '%'.EEM_Payment_Method::scope_admin.'%')));
1401 1401
         }
1402 1402
         $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1403 1403
     }
@@ -1430,7 +1430,7 @@  discard block
 block discarded – undo
1430 1430
             'Line_Item',
1431 1431
             array(array('LIN_type' => 'line-item'))
1432 1432
         );
1433
-        if (! empty($line_items)) {
1433
+        if ( ! empty($line_items)) {
1434 1434
             foreach ($line_items as $item) {
1435 1435
                 if ($item instanceof EE_Line_Item) {
1436 1436
                     switch ($item->OBJ_type()) {
@@ -1440,7 +1440,7 @@  discard block
 block discarded – undo
1440 1440
                             $ticket = $item->ticket();
1441 1441
                             // right now we're only handling tickets here.
1442 1442
                             // Cause its expected that only tickets will have attendees right?
1443
-                            if (! $ticket instanceof EE_Ticket) {
1443
+                            if ( ! $ticket instanceof EE_Ticket) {
1444 1444
                                 break;
1445 1445
                             }
1446 1446
                             try {
@@ -1449,45 +1449,45 @@  discard block
 block discarded – undo
1449 1449
                                 EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1450 1450
                                 $event_name = esc_html__('Unknown Event', 'event_espresso');
1451 1451
                             }
1452
-                            $event_name .= ' - ' . $item->name();
1452
+                            $event_name .= ' - '.$item->name();
1453 1453
                             $ticket_price = EEH_Template::format_currency($item->unit_price());
1454 1454
                             // now get all of the registrations for this transaction that use this ticket
1455 1455
                             $registrations = $ticket->registrations(
1456 1456
                                 array(array('TXN_ID' => $this->_transaction->ID()))
1457 1457
                             );
1458 1458
                             foreach ($registrations as $registration) {
1459
-                                if (! $registration instanceof EE_Registration) {
1459
+                                if ( ! $registration instanceof EE_Registration) {
1460 1460
                                     break;
1461 1461
                                 }
1462
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1462
+                                $this->_template_args['event_attendees'][$registration->ID()]['STS_ID']
1463 1463
                                     = $registration->status_ID();
1464
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1464
+                                $this->_template_args['event_attendees'][$registration->ID()]['att_num']
1465 1465
                                     = $registration->count();
1466
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1466
+                                $this->_template_args['event_attendees'][$registration->ID()]['event_ticket_name']
1467 1467
                                     = $event_name;
1468
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1468
+                                $this->_template_args['event_attendees'][$registration->ID()]['ticket_price']
1469 1469
                                     = $ticket_price;
1470 1470
                                 // attendee info
1471 1471
                                 $attendee = $registration->get_first_related('Attendee');
1472 1472
                                 if ($attendee instanceof EE_Attendee) {
1473
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1473
+                                    $this->_template_args['event_attendees'][$registration->ID()]['att_id']
1474 1474
                                         = $attendee->ID();
1475
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1475
+                                    $this->_template_args['event_attendees'][$registration->ID()]['attendee']
1476 1476
                                         = $attendee->full_name();
1477
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']
1478
-                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1477
+                                    $this->_template_args['event_attendees'][$registration->ID()]['email']
1478
+                                        = '<a href="mailto:'.$attendee->email().'?subject='.$event_name
1479 1479
                                           . esc_html__(
1480 1480
                                               ' Event',
1481 1481
                                               'event_espresso'
1482 1482
                                           )
1483
-                                          . '">' . $attendee->email() . '</a>';
1484
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']
1483
+                                          . '">'.$attendee->email().'</a>';
1484
+                                    $this->_template_args['event_attendees'][$registration->ID()]['address']
1485 1485
                                         = EEH_Address::format($attendee, 'inline', false, false);
1486 1486
                                 } else {
1487
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1488
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1489
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1490
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1487
+                                    $this->_template_args['event_attendees'][$registration->ID()]['att_id'] = '';
1488
+                                    $this->_template_args['event_attendees'][$registration->ID()]['attendee'] = '';
1489
+                                    $this->_template_args['event_attendees'][$registration->ID()]['email'] = '';
1490
+                                    $this->_template_args['event_attendees'][$registration->ID()]['address'] = '';
1491 1491
                                 }
1492 1492
                             }
1493 1493
                             break;
@@ -1503,7 +1503,7 @@  discard block
 block discarded – undo
1503 1503
                 TXN_ADMIN_URL
1504 1504
             );
1505 1505
             echo EEH_Template::display_template(
1506
-                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1506
+                TXN_TEMPLATE_PATH.'txn_admin_details_main_meta_box_attendees.template.php',
1507 1507
                 $this->_template_args,
1508 1508
                 true
1509 1509
             );
@@ -1538,7 +1538,7 @@  discard block
 block discarded – undo
1538 1538
         $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1539 1539
             ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1540 1540
             : null;
1541
-        if (! $primary_att instanceof EE_Attendee) {
1541
+        if ( ! $primary_att instanceof EE_Attendee) {
1542 1542
             $this->_template_args['no_attendee_message'] = esc_html__(
1543 1543
                 'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1544 1544
                 'event_espresso'
@@ -1560,7 +1560,7 @@  discard block
 block discarded – undo
1560 1560
         // get formatted address for registrant
1561 1561
         $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1562 1562
         echo EEH_Template::display_template(
1563
-            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1563
+            TXN_TEMPLATE_PATH.'txn_admin_details_side_meta_box_registrant.template.php',
1564 1564
             $this->_template_args,
1565 1565
             true
1566 1566
         );
@@ -1585,7 +1585,7 @@  discard block
 block discarded – undo
1585 1585
             TXN_ADMIN_URL
1586 1586
         );
1587 1587
 
1588
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1588
+        $template_path = TXN_TEMPLATE_PATH.'txn_admin_details_side_meta_box_billing_info.template.php';
1589 1589
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
1590 1590
     }
1591 1591
 
@@ -1611,7 +1611,7 @@  discard block
 block discarded – undo
1611 1611
             'ee_edit_payments',
1612 1612
             'apply_payment_or_refund_from_registration_details'
1613 1613
         );
1614
-        if (! empty($valid_data) && $has_access) {
1614
+        if ( ! empty($valid_data) && $has_access) {
1615 1615
             $PAY_ID = $valid_data['PAY_ID'];
1616 1616
             // save  the new payment
1617 1617
             $payment = $this->_create_payment_from_request_data($valid_data);
@@ -1624,7 +1624,7 @@  discard block
 block discarded – undo
1624 1624
                 $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1625 1625
                 $this->_remove_existing_registration_payments($payment, $PAY_ID);
1626 1626
                 // apply payment to registrations (if applicable)
1627
-                if (! empty($REG_IDs)) {
1627
+                if ( ! empty($REG_IDs)) {
1628 1628
                     $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1629 1629
                     $this->_maybe_send_notifications();
1630 1630
                     // now process status changes for the same registrations
@@ -1695,14 +1695,14 @@  discard block
 block discarded – undo
1695 1695
      */
1696 1696
     protected function _validate_payment_request_data()
1697 1697
     {
1698
-        if (! isset($this->_req_data['txn_admin_payment'])) {
1698
+        if ( ! isset($this->_req_data['txn_admin_payment'])) {
1699 1699
             return array();
1700 1700
         }
1701 1701
         $payment_form = $this->_generate_payment_form_section();
1702 1702
         try {
1703 1703
             if ($payment_form->was_submitted()) {
1704 1704
                 $payment_form->receive_form_submission();
1705
-                if (! $payment_form->is_valid()) {
1705
+                if ( ! $payment_form->is_valid()) {
1706 1706
                     $submission_error_messages = array();
1707 1707
                     foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1708 1708
                         if ($validation_error instanceof EE_Validation_Error) {
@@ -1883,7 +1883,7 @@  discard block
 block discarded – undo
1883 1883
             array('Y-m-d', 'g:i a')
1884 1884
         );
1885 1885
 
1886
-        if (! $payment->save()) {
1886
+        if ( ! $payment->save()) {
1887 1887
             EE_Error::add_error(
1888 1888
                 sprintf(
1889 1889
                     esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
@@ -2088,12 +2088,12 @@  discard block
 block discarded – undo
2088 2088
         // but add in some conditions regarding payment,
2089 2089
         // so that we don't apply payments to registrations that are free or have already been paid for
2090 2090
         // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2091
-        if (! $payment->is_a_refund()) {
2091
+        if ( ! $payment->is_a_refund()) {
2092 2092
             $registration_query_where_params['REG_final_price'] = array('!=', 0);
2093 2093
             $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2094 2094
         }
2095 2095
         $registrations = $transaction->registrations(array($registration_query_where_params));
2096
-        if (! empty($registrations)) {
2096
+        if ( ! empty($registrations)) {
2097 2097
             /** @type EE_Payment_Processor $payment_processor */
2098 2098
             $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2099 2099
             $payment_processor->process_registration_payments($transaction, $payment, $registrations);
@@ -2118,7 +2118,7 @@  discard block
 block discarded – undo
2118 2118
     protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2119 2119
     {
2120 2120
         // first if there is no change in status then we get out.
2121
-        if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2121
+        if ( ! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2122 2122
             || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2123 2123
         ) {
2124 2124
             // no error message, no change requested, just nothing to do man.
@@ -2176,7 +2176,7 @@  discard block
 block discarded – undo
2176 2176
                 'pay_status'       => $payment->STS_ID(),
2177 2177
                 'PAY_ID'           => $payment->ID(),
2178 2178
                 'STS_ID'           => $payment->STS_ID(),
2179
-                'status'           => self::$_pay_status[ $payment->STS_ID() ],
2179
+                'status'           => self::$_pay_status[$payment->STS_ID()],
2180 2180
                 'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2181 2181
                 'method'           => strtoupper($payment->source()),
2182 2182
                 'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
@@ -2296,11 +2296,11 @@  discard block
 block discarded – undo
2296 2296
     {
2297 2297
         $registration_payment_data = array();
2298 2298
         // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2299
-        if (! empty($REG_IDs)) {
2299
+        if ( ! empty($REG_IDs)) {
2300 2300
             $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2301 2301
             foreach ($registrations as $registration) {
2302 2302
                 if ($registration instanceof EE_Registration) {
2303
-                    $registration_payment_data[ $registration->ID() ] = array(
2303
+                    $registration_payment_data[$registration->ID()] = array(
2304 2304
                         'paid'  => $registration->pretty_paid(),
2305 2305
                         'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2306 2306
                     );
@@ -2412,8 +2412,8 @@  discard block
 block discarded – undo
2412 2412
             : date('m/d/Y');
2413 2413
 
2414 2414
         // make sure our timestamps start and end right at the boundaries for each day
2415
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2416
-        $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2415
+        $start_date = date('Y-m-d', strtotime($start_date)).' 00:00:00';
2416
+        $end_date = date('Y-m-d', strtotime($end_date)).' 23:59:59';
2417 2417
 
2418 2418
 
2419 2419
         // convert to timestamps
@@ -2472,7 +2472,7 @@  discard block
 block discarded – undo
2472 2472
         }
2473 2473
 
2474 2474
         if (isset($this->_req_data['s'])) {
2475
-            $search_string = '%' . $this->_req_data['s'] . '%';
2475
+            $search_string = '%'.$this->_req_data['s'].'%';
2476 2476
             $_where['OR'] = array(
2477 2477
                 'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2478 2478
                 'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
@@ -2499,11 +2499,11 @@  discard block
 block discarded – undo
2499 2499
         }
2500 2500
 
2501 2501
         // failed transactions
2502
-        $failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2502
+        $failed = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2503 2503
                   || ($count && $view === 'failed');
2504
-        $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2504
+        $abandoned = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2505 2505
                      || ($count && $view === 'abandoned');
2506
-        $incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count)
2506
+        $incomplete = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count)
2507 2507
                       || ($count && $view === 'incomplete');
2508 2508
 
2509 2509
         if ($failed) {
Please login to merge, or discard this patch.
Indentation   +2549 added lines, -2549 removed lines patch added patch discarded remove patch
@@ -13,2553 +13,2553 @@
 block discarded – undo
13 13
 class Transactions_Admin_Page extends EE_Admin_Page
14 14
 {
15 15
 
16
-    /**
17
-     * @var EE_Transaction
18
-     */
19
-    private $_transaction;
20
-
21
-    /**
22
-     * @var EE_Session
23
-     */
24
-    private $_session;
25
-
26
-    /**
27
-     * @var array $_txn_status
28
-     */
29
-    private static $_txn_status;
30
-
31
-    /**
32
-     * @var array $_pay_status
33
-     */
34
-    private static $_pay_status;
35
-
36
-    /**
37
-     * @var array $_existing_reg_payment_REG_IDs
38
-     */
39
-    protected $_existing_reg_payment_REG_IDs;
40
-
41
-
42
-    /**
43
-     *    _init_page_props
44
-     *
45
-     * @return void
46
-     */
47
-    protected function _init_page_props()
48
-    {
49
-        $this->page_slug = TXN_PG_SLUG;
50
-        $this->page_label = esc_html__('Transactions', 'event_espresso');
51
-        $this->_admin_base_url = TXN_ADMIN_URL;
52
-        $this->_admin_base_path = TXN_ADMIN;
53
-    }
54
-
55
-
56
-    /**
57
-     *    _ajax_hooks
58
-     *
59
-     * @return void
60
-     */
61
-    protected function _ajax_hooks()
62
-    {
63
-        add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
64
-        add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
65
-        add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
66
-    }
67
-
68
-
69
-    /**
70
-     *    _define_page_props
71
-     *
72
-     * @return void
73
-     */
74
-    protected function _define_page_props()
75
-    {
76
-        $this->_admin_page_title = $this->page_label;
77
-        $this->_labels = array(
78
-            'buttons' => array(
79
-                'add'    => esc_html__('Add New Transaction', 'event_espresso'),
80
-                'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
81
-                'delete' => esc_html__('Delete Transaction', 'event_espresso'),
82
-            ),
83
-        );
84
-    }
85
-
86
-
87
-    /**
88
-     *        grab url requests and route them
89
-     *
90
-     * @access private
91
-     * @return void
92
-     * @throws EE_Error
93
-     * @throws InvalidArgumentException
94
-     * @throws InvalidDataTypeException
95
-     * @throws InvalidInterfaceException
96
-     */
97
-    public function _set_page_routes()
98
-    {
99
-
100
-        $this->_set_transaction_status_array();
101
-
102
-        $txn_id = ! empty($this->_req_data['TXN_ID'])
103
-                  && ! is_array($this->_req_data['TXN_ID'])
104
-            ? $this->_req_data['TXN_ID']
105
-            : 0;
106
-
107
-        $this->_page_routes = array(
108
-
109
-            'default' => array(
110
-                'func'       => '_transactions_overview_list_table',
111
-                'capability' => 'ee_read_transactions',
112
-            ),
113
-
114
-            'view_transaction' => array(
115
-                'func'       => '_transaction_details',
116
-                'capability' => 'ee_read_transaction',
117
-                'obj_id'     => $txn_id,
118
-            ),
119
-
120
-            'send_payment_reminder' => array(
121
-                'func'       => '_send_payment_reminder',
122
-                'noheader'   => true,
123
-                'capability' => 'ee_send_message',
124
-            ),
125
-
126
-            'espresso_apply_payment' => array(
127
-                'func'       => 'apply_payments_or_refunds',
128
-                'noheader'   => true,
129
-                'capability' => 'ee_edit_payments',
130
-            ),
131
-
132
-            'espresso_apply_refund' => array(
133
-                'func'       => 'apply_payments_or_refunds',
134
-                'noheader'   => true,
135
-                'capability' => 'ee_edit_payments',
136
-            ),
137
-
138
-            'espresso_delete_payment' => array(
139
-                'func'       => 'delete_payment',
140
-                'noheader'   => true,
141
-                'capability' => 'ee_delete_payments',
142
-            ),
143
-
144
-            'espresso_recalculate_line_items' => array(
145
-                'func'       => 'recalculateLineItems',
146
-                'noheader'   => true,
147
-                'capability' => 'ee_edit_payments',
148
-            ),
149
-
150
-        );
151
-    }
152
-
153
-
154
-    protected function _set_page_config()
155
-    {
156
-        $this->_page_config = array(
157
-            'default'          => array(
158
-                'nav'           => array(
159
-                    'label' => esc_html__('Overview', 'event_espresso'),
160
-                    'order' => 10,
161
-                ),
162
-                'list_table'    => 'EE_Admin_Transactions_List_Table',
163
-                'help_tabs'     => array(
164
-                    'transactions_overview_help_tab'                       => array(
165
-                        'title'    => esc_html__('Transactions Overview', 'event_espresso'),
166
-                        'filename' => 'transactions_overview',
167
-                    ),
168
-                    'transactions_overview_table_column_headings_help_tab' => array(
169
-                        'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
170
-                        'filename' => 'transactions_overview_table_column_headings',
171
-                    ),
172
-                    'transactions_overview_views_filters_help_tab'         => array(
173
-                        'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
174
-                        'filename' => 'transactions_overview_views_filters_search',
175
-                    ),
176
-                ),
177
-                'help_tour'     => array('Transactions_Overview_Help_Tour'),
178
-                /**
179
-                 * commented out because currently we are not displaying tips for transaction list table status but this
180
-                 * may change in a later iteration so want to keep the code for then.
181
-                 */
182
-                // 'qtips' => array( 'Transactions_List_Table_Tips' ),
183
-                'require_nonce' => false,
184
-            ),
185
-            'view_transaction' => array(
186
-                'nav'       => array(
187
-                    'label'      => esc_html__('View Transaction', 'event_espresso'),
188
-                    'order'      => 5,
189
-                    'url'        => isset($this->_req_data['TXN_ID'])
190
-                        ? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
191
-                        : $this->_admin_base_url,
192
-                    'persistent' => false,
193
-                ),
194
-                'help_tabs' => array(
195
-                    'transactions_view_transaction_help_tab'                                              => array(
196
-                        'title'    => esc_html__('View Transaction', 'event_espresso'),
197
-                        'filename' => 'transactions_view_transaction',
198
-                    ),
199
-                    'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
200
-                        'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
201
-                        'filename' => 'transactions_view_transaction_transaction_details_table',
202
-                    ),
203
-                    'transactions_view_transaction_attendees_registered_help_tab'                         => array(
204
-                        'title'    => esc_html__('Attendees Registered', 'event_espresso'),
205
-                        'filename' => 'transactions_view_transaction_attendees_registered',
206
-                    ),
207
-                    'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
208
-                        'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
209
-                        'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
210
-                    ),
211
-                ),
212
-                'qtips'     => array('Transaction_Details_Tips'),
213
-                'help_tour' => array('Transaction_Details_Help_Tour'),
214
-                'metaboxes' => array('_transaction_details_metaboxes'),
215
-
216
-                'require_nonce' => false,
217
-            ),
218
-        );
219
-    }
220
-
221
-
222
-    /**
223
-     * The below methods aren't used by this class currently
224
-     */
225
-    protected function _add_screen_options()
226
-    {
227
-        // noop
228
-    }
229
-
230
-
231
-    protected function _add_feature_pointers()
232
-    {
233
-        // noop
234
-    }
235
-
236
-
237
-    public function admin_init()
238
-    {
239
-        // IF a registration was JUST added via the admin...
240
-        if (isset(
241
-            $this->_req_data['redirect_from'],
242
-            $this->_req_data['EVT_ID'],
243
-            $this->_req_data['event_name']
244
-        )) {
245
-            // then set a cookie so that we can block any attempts to use
246
-            // the back button as a way to enter another registration.
247
-            setcookie(
248
-                'ee_registration_added',
249
-                $this->_req_data['EVT_ID'],
250
-                time() + WEEK_IN_SECONDS,
251
-                '/'
252
-            );
253
-            // and update the global
254
-            $_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
255
-        }
256
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
257
-            'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
258
-            'event_espresso'
259
-        );
260
-        EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
261
-            'An error occurred! Please refresh the page and try again.',
262
-            'event_espresso'
263
-        );
264
-        EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
265
-        EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
266
-        EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
267
-        EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
268
-            'This transaction has been overpaid ! Payments Total',
269
-            'event_espresso'
270
-        );
271
-    }
272
-
273
-
274
-    public function admin_notices()
275
-    {
276
-        // noop
277
-    }
278
-
279
-
280
-    public function admin_footer_scripts()
281
-    {
282
-        // noop
283
-    }
284
-
285
-
286
-    /**
287
-     * _set_transaction_status_array
288
-     * sets list of transaction statuses
289
-     *
290
-     * @access private
291
-     * @return void
292
-     * @throws EE_Error
293
-     * @throws InvalidArgumentException
294
-     * @throws InvalidDataTypeException
295
-     * @throws InvalidInterfaceException
296
-     */
297
-    private function _set_transaction_status_array()
298
-    {
299
-        self::$_txn_status = EEM_Transaction::instance()->status_array(true);
300
-    }
301
-
302
-
303
-    /**
304
-     * get_transaction_status_array
305
-     * return the transaction status array for wp_list_table
306
-     *
307
-     * @access public
308
-     * @return array
309
-     */
310
-    public function get_transaction_status_array()
311
-    {
312
-        return self::$_txn_status;
313
-    }
314
-
315
-
316
-    /**
317
-     *    get list of payment statuses
318
-     *
319
-     * @access private
320
-     * @return void
321
-     * @throws EE_Error
322
-     * @throws InvalidArgumentException
323
-     * @throws InvalidDataTypeException
324
-     * @throws InvalidInterfaceException
325
-     */
326
-    private function _get_payment_status_array()
327
-    {
328
-        self::$_pay_status = EEM_Payment::instance()->status_array(true);
329
-        $this->_template_args['payment_status'] = self::$_pay_status;
330
-    }
331
-
332
-
333
-    /**
334
-     *    _add_screen_options_default
335
-     *
336
-     * @access protected
337
-     * @return void
338
-     * @throws InvalidArgumentException
339
-     * @throws InvalidDataTypeException
340
-     * @throws InvalidInterfaceException
341
-     */
342
-    protected function _add_screen_options_default()
343
-    {
344
-        $this->_per_page_screen_option();
345
-    }
346
-
347
-
348
-    /**
349
-     * load_scripts_styles
350
-     *
351
-     * @access public
352
-     * @return void
353
-     */
354
-    public function load_scripts_styles()
355
-    {
356
-        // enqueue style
357
-        wp_register_style(
358
-            'espresso_txn',
359
-            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
360
-            array(),
361
-            EVENT_ESPRESSO_VERSION
362
-        );
363
-        wp_enqueue_style('espresso_txn');
364
-        // scripts
365
-        wp_register_script(
366
-            'espresso_txn',
367
-            TXN_ASSETS_URL . 'espresso_transactions_admin.js',
368
-            array(
369
-                'ee_admin_js',
370
-                'ee-datepicker',
371
-                'jquery-ui-datepicker',
372
-                'jquery-ui-draggable',
373
-                'ee-dialog',
374
-                'ee-accounting',
375
-                'ee-serialize-full-array',
376
-            ),
377
-            EVENT_ESPRESSO_VERSION,
378
-            true
379
-        );
380
-        wp_enqueue_script('espresso_txn');
381
-    }
382
-
383
-
384
-    /**
385
-     *    load_scripts_styles_view_transaction
386
-     *
387
-     * @access public
388
-     * @return void
389
-     */
390
-    public function load_scripts_styles_view_transaction()
391
-    {
392
-        // styles
393
-        wp_enqueue_style('espresso-ui-theme');
394
-    }
395
-
396
-
397
-    /**
398
-     *    load_scripts_styles_default
399
-     *
400
-     * @access public
401
-     * @return void
402
-     */
403
-    public function load_scripts_styles_default()
404
-    {
405
-        // styles
406
-        wp_enqueue_style('espresso-ui-theme');
407
-    }
408
-
409
-
410
-    /**
411
-     *    _set_list_table_views_default
412
-     *
413
-     * @access protected
414
-     * @return void
415
-     */
416
-    protected function _set_list_table_views_default()
417
-    {
418
-        $this->_views = array(
419
-            'all'        => array(
420
-                'slug'  => 'all',
421
-                'label' => esc_html__('View All Transactions', 'event_espresso'),
422
-                'count' => 0,
423
-            ),
424
-            'abandoned'  => array(
425
-                'slug'  => 'abandoned',
426
-                'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
427
-                'count' => 0,
428
-            ),
429
-            'incomplete' => array(
430
-                'slug'  => 'incomplete',
431
-                'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
432
-                'count' => 0,
433
-            ),
434
-        );
435
-        if (/**
436
-         * Filters whether a link to the "Failed Transactions" list table
437
-         * appears on the Transactions Admin Page list table.
438
-         * List display can be turned back on via the following:
439
-         * add_filter(
440
-         *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
441
-         *     '__return_true'
442
-         * );
443
-         *
444
-         * @since 4.9.70.p
445
-         * @param boolean                 $display_failed_txns_list
446
-         * @param Transactions_Admin_Page $this
447
-         */
448
-        apply_filters(
449
-            'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
450
-            false,
451
-            $this
452
-        )
453
-        ) {
454
-            $this->_views['failed'] = array(
455
-                'slug'  => 'failed',
456
-                'label' => esc_html__('Failed Transactions', 'event_espresso'),
457
-                'count' => 0,
458
-            );
459
-        }
460
-    }
461
-
462
-
463
-    /**
464
-     * _set_transaction_object
465
-     * This sets the _transaction property for the transaction details screen
466
-     *
467
-     * @access private
468
-     * @return void
469
-     * @throws EE_Error
470
-     * @throws InvalidArgumentException
471
-     * @throws RuntimeException
472
-     * @throws InvalidDataTypeException
473
-     * @throws InvalidInterfaceException
474
-     * @throws ReflectionException
475
-     */
476
-    private function _set_transaction_object()
477
-    {
478
-        if ($this->_transaction instanceof EE_Transaction) {
479
-            return;
480
-        } //get out we've already set the object
481
-
482
-        $TXN_ID = ! empty($this->_req_data['TXN_ID'])
483
-            ? absint($this->_req_data['TXN_ID'])
484
-            : false;
485
-
486
-        // get transaction object
487
-        $this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
488
-        $this->_session = $this->_transaction instanceof EE_Transaction
489
-            ? $this->_transaction->session_data()
490
-            : null;
491
-        if ($this->_transaction instanceof EE_Transaction) {
492
-            $this->_transaction->verify_abandoned_transaction_status();
493
-        }
494
-
495
-        if (! $this->_transaction instanceof EE_Transaction) {
496
-            $error_msg = sprintf(
497
-                esc_html__(
498
-                    'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
499
-                    'event_espresso'
500
-                ),
501
-                $TXN_ID
502
-            );
503
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
504
-        }
505
-    }
506
-
507
-
508
-    /**
509
-     *    _transaction_legend_items
510
-     *
511
-     * @access protected
512
-     * @return array
513
-     * @throws EE_Error
514
-     * @throws InvalidArgumentException
515
-     * @throws ReflectionException
516
-     * @throws InvalidDataTypeException
517
-     * @throws InvalidInterfaceException
518
-     */
519
-    protected function _transaction_legend_items()
520
-    {
521
-        EE_Registry::instance()->load_helper('MSG_Template');
522
-        $items = array();
523
-
524
-        if (EE_Registry::instance()->CAP->current_user_can(
525
-            'ee_read_global_messages',
526
-            'view_filtered_messages'
527
-        )) {
528
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
529
-            if (is_array($related_for_icon)
530
-                && isset($related_for_icon['css_class'], $related_for_icon['label'])
531
-            ) {
532
-                $items['view_related_messages'] = array(
533
-                    'class' => $related_for_icon['css_class'],
534
-                    'desc'  => $related_for_icon['label'],
535
-                );
536
-            }
537
-        }
538
-
539
-        $items = apply_filters(
540
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
541
-            array_merge(
542
-                $items,
543
-                array(
544
-                    'view_details'          => array(
545
-                        'class' => 'dashicons dashicons-cart',
546
-                        'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
547
-                    ),
548
-                    'view_invoice'          => array(
549
-                        'class' => 'dashicons dashicons-media-spreadsheet',
550
-                        'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
551
-                    ),
552
-                    'view_receipt'          => array(
553
-                        'class' => 'dashicons dashicons-media-default',
554
-                        'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
555
-                    ),
556
-                    'view_registration'     => array(
557
-                        'class' => 'dashicons dashicons-clipboard',
558
-                        'desc'  => esc_html__('View Registration Details', 'event_espresso'),
559
-                    ),
560
-                    'payment_overview_link' => array(
561
-                        'class' => 'dashicons dashicons-money',
562
-                        'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
563
-                    ),
564
-                )
565
-            )
566
-        );
567
-
568
-        if (EEH_MSG_Template::is_mt_active('payment_reminder')
569
-            && EE_Registry::instance()->CAP->current_user_can(
570
-                'ee_send_message',
571
-                'espresso_transactions_send_payment_reminder'
572
-            )
573
-        ) {
574
-            $items['send_payment_reminder'] = array(
575
-                'class' => 'dashicons dashicons-email-alt',
576
-                'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
577
-            );
578
-        }
579
-        $more_items = apply_filters(
580
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
581
-            array(
582
-                'overpaid'   => array(
583
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
584
-                    'desc'  => EEH_Template::pretty_status(
585
-                        EEM_Transaction::overpaid_status_code,
586
-                        false,
587
-                        'sentence'
588
-                    ),
589
-                ),
590
-                'complete'   => array(
591
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
592
-                    'desc'  => EEH_Template::pretty_status(
593
-                        EEM_Transaction::complete_status_code,
594
-                        false,
595
-                        'sentence'
596
-                    ),
597
-                ),
598
-                'incomplete' => array(
599
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
600
-                    'desc'  => EEH_Template::pretty_status(
601
-                        EEM_Transaction::incomplete_status_code,
602
-                        false,
603
-                        'sentence'
604
-                    ),
605
-                ),
606
-                'abandoned'  => array(
607
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
608
-                    'desc'  => EEH_Template::pretty_status(
609
-                        EEM_Transaction::abandoned_status_code,
610
-                        false,
611
-                        'sentence'
612
-                    ),
613
-                ),
614
-                'failed'     => array(
615
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
616
-                    'desc'  => EEH_Template::pretty_status(
617
-                        EEM_Transaction::failed_status_code,
618
-                        false,
619
-                        'sentence'
620
-                    ),
621
-                ),
622
-            )
623
-        );
624
-
625
-        return array_merge($items, $more_items);
626
-    }
627
-
628
-
629
-    /**
630
-     *    _transactions_overview_list_table
631
-     *
632
-     * @access protected
633
-     * @return void
634
-     * @throws DomainException
635
-     * @throws EE_Error
636
-     * @throws InvalidArgumentException
637
-     * @throws InvalidDataTypeException
638
-     * @throws InvalidInterfaceException
639
-     * @throws ReflectionException
640
-     */
641
-    protected function _transactions_overview_list_table()
642
-    {
643
-        $this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
644
-        $event = isset($this->_req_data['EVT_ID'])
645
-            ? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
646
-            : null;
647
-        $this->_template_args['admin_page_header'] = $event instanceof EE_Event
648
-            ? sprintf(
649
-                esc_html__(
650
-                    '%sViewing Transactions for the Event: %s%s',
651
-                    'event_espresso'
652
-                ),
653
-                '<h3>',
654
-                '<a href="'
655
-                . EE_Admin_Page::add_query_args_and_nonce(
656
-                    array('action' => 'edit', 'post' => $event->ID()),
657
-                    EVENTS_ADMIN_URL
658
-                )
659
-                . '" title="'
660
-                . esc_attr__(
661
-                    'Click to Edit event',
662
-                    'event_espresso'
663
-                )
664
-                . '">' . $event->name() . '</a>',
665
-                '</h3>'
666
-            )
667
-            : '';
668
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
669
-        $this->display_admin_list_table_page_with_no_sidebar();
670
-    }
671
-
672
-
673
-    /**
674
-     *    _transaction_details
675
-     * generates HTML for the View Transaction Details Admin page
676
-     *
677
-     * @access protected
678
-     * @return void
679
-     * @throws DomainException
680
-     * @throws EE_Error
681
-     * @throws InvalidArgumentException
682
-     * @throws InvalidDataTypeException
683
-     * @throws InvalidInterfaceException
684
-     * @throws RuntimeException
685
-     * @throws ReflectionException
686
-     */
687
-    protected function _transaction_details()
688
-    {
689
-        do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
690
-
691
-        $this->_set_transaction_status_array();
692
-
693
-        $this->_template_args = array();
694
-        $this->_template_args['transactions_page'] = $this->_wp_page_slug;
695
-
696
-        $this->_set_transaction_object();
697
-
698
-        if (! $this->_transaction instanceof EE_Transaction) {
699
-            return;
700
-        }
701
-        $primary_registration = $this->_transaction->primary_registration();
702
-        $attendee = $primary_registration instanceof EE_Registration
703
-            ? $primary_registration->attendee()
704
-            : null;
705
-
706
-        $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
707
-        $this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
708
-
709
-        $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
710
-        $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
711
-
712
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->status_ID() ];
713
-        $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
714
-        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->status_ID();
715
-
716
-        $this->_template_args['grand_total'] = $this->_transaction->total();
717
-        $this->_template_args['total_paid'] = $this->_transaction->paid();
718
-
719
-        $amount_due = $this->_transaction->total() - $this->_transaction->paid();
720
-        $this->_template_args['amount_due'] = EEH_Template::format_currency(
721
-            $amount_due,
722
-            true
723
-        );
724
-        if (EE_Registry::instance()->CFG->currency->sign_b4) {
725
-            $this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
726
-                                                  . $this->_template_args['amount_due'];
727
-        } else {
728
-            $this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
729
-        }
730
-        $this->_template_args['amount_due_class'] = '';
731
-
732
-        if ($this->_transaction->paid() === $this->_transaction->total()) {
733
-            // paid in full
734
-            $this->_template_args['amount_due'] = false;
735
-        } elseif ($this->_transaction->paid() > $this->_transaction->total()) {
736
-            // overpaid
737
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
738
-        } elseif ($this->_transaction->total() > (float) 0) {
739
-            if ($this->_transaction->paid() > (float) 0) {
740
-                // monies owing
741
-                $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
742
-            } elseif ($this->_transaction->paid() === (float) 0) {
743
-                // no payments made yet
744
-                $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
745
-            }
746
-        } elseif ($this->_transaction->total() === (float) 0) {
747
-            // free event
748
-            $this->_template_args['amount_due'] = false;
749
-        }
750
-
751
-        $payment_method = $this->_transaction->payment_method();
752
-
753
-        $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
754
-            ? $payment_method->admin_name()
755
-            : esc_html__('Unknown', 'event_espresso');
756
-
757
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
758
-        // link back to overview
759
-        $this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
760
-            ? $_SERVER['HTTP_REFERER']
761
-            : TXN_ADMIN_URL;
762
-
763
-
764
-        // next link
765
-        $next_txn = $this->_transaction->next(
766
-            null,
767
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
768
-            'TXN_ID'
769
-        );
770
-        $this->_template_args['next_transaction'] = $next_txn
771
-            ? $this->_next_link(
772
-                EE_Admin_Page::add_query_args_and_nonce(
773
-                    array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
774
-                    TXN_ADMIN_URL
775
-                ),
776
-                'dashicons dashicons-arrow-right ee-icon-size-22'
777
-            )
778
-            : '';
779
-        // previous link
780
-        $previous_txn = $this->_transaction->previous(
781
-            null,
782
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
783
-            'TXN_ID'
784
-        );
785
-        $this->_template_args['previous_transaction'] = $previous_txn
786
-            ? $this->_previous_link(
787
-                EE_Admin_Page::add_query_args_and_nonce(
788
-                    array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
789
-                    TXN_ADMIN_URL
790
-                ),
791
-                'dashicons dashicons-arrow-left ee-icon-size-22'
792
-            )
793
-            : '';
794
-
795
-        // were we just redirected here after adding a new registration ???
796
-        if (isset(
797
-            $this->_req_data['redirect_from'],
798
-            $this->_req_data['EVT_ID'],
799
-            $this->_req_data['event_name']
800
-        )) {
801
-            if (EE_Registry::instance()->CAP->current_user_can(
802
-                'ee_edit_registrations',
803
-                'espresso_registrations_new_registration',
804
-                $this->_req_data['EVT_ID']
805
-            )) {
806
-                $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
807
-                $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
808
-                    array(
809
-                        'page'     => 'espresso_registrations',
810
-                        'action'   => 'new_registration',
811
-                        'return'   => 'default',
812
-                        'TXN_ID'   => $this->_transaction->ID(),
813
-                        'event_id' => $this->_req_data['EVT_ID'],
814
-                    ),
815
-                    REG_ADMIN_URL
816
-                );
817
-                $this->_admin_page_title .= '">';
818
-
819
-                $this->_admin_page_title .= sprintf(
820
-                    esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
821
-                    htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
822
-                );
823
-                $this->_admin_page_title .= '</a>';
824
-            }
825
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
826
-        }
827
-        // grab messages at the last second
828
-        $this->_template_args['notices'] = EE_Error::get_notices();
829
-        // path to template
830
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
831
-        $this->_template_args['admin_page_header'] = EEH_Template::display_template(
832
-            $template_path,
833
-            $this->_template_args,
834
-            true
835
-        );
836
-
837
-        // the details template wrapper
838
-        $this->display_admin_page_with_sidebar();
839
-    }
840
-
841
-
842
-    /**
843
-     *        _transaction_details_metaboxes
844
-     *
845
-     * @access protected
846
-     * @return void
847
-     * @throws EE_Error
848
-     * @throws InvalidArgumentException
849
-     * @throws InvalidDataTypeException
850
-     * @throws InvalidInterfaceException
851
-     * @throws RuntimeException
852
-     * @throws ReflectionException
853
-     */
854
-    protected function _transaction_details_metaboxes()
855
-    {
856
-
857
-        $this->_set_transaction_object();
858
-
859
-        if (! $this->_transaction instanceof EE_Transaction) {
860
-            return;
861
-        }
862
-        add_meta_box(
863
-            'edit-txn-details-mbox',
864
-            esc_html__('Transaction Details', 'event_espresso'),
865
-            array($this, 'txn_details_meta_box'),
866
-            $this->_wp_page_slug,
867
-            'normal',
868
-            'high'
869
-        );
870
-        add_meta_box(
871
-            'edit-txn-attendees-mbox',
872
-            esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
873
-            array($this, 'txn_attendees_meta_box'),
874
-            $this->_wp_page_slug,
875
-            'normal',
876
-            'high',
877
-            array('TXN_ID' => $this->_transaction->ID())
878
-        );
879
-        add_meta_box(
880
-            'edit-txn-registrant-mbox',
881
-            esc_html__('Primary Contact', 'event_espresso'),
882
-            array($this, 'txn_registrant_side_meta_box'),
883
-            $this->_wp_page_slug,
884
-            'side',
885
-            'high'
886
-        );
887
-        add_meta_box(
888
-            'edit-txn-billing-info-mbox',
889
-            esc_html__('Billing Information', 'event_espresso'),
890
-            array($this, 'txn_billing_info_side_meta_box'),
891
-            $this->_wp_page_slug,
892
-            'side',
893
-            'high'
894
-        );
895
-    }
896
-
897
-
898
-    /**
899
-     * Callback for transaction actions metabox.
900
-     *
901
-     * @param EE_Transaction|null $transaction
902
-     * @return string
903
-     * @throws DomainException
904
-     * @throws EE_Error
905
-     * @throws InvalidArgumentException
906
-     * @throws InvalidDataTypeException
907
-     * @throws InvalidInterfaceException
908
-     * @throws ReflectionException
909
-     * @throws RuntimeException
910
-     */
911
-    public function getActionButtons(EE_Transaction $transaction = null)
912
-    {
913
-        $content = '';
914
-        $actions = array();
915
-        if (! $transaction instanceof EE_Transaction) {
916
-            return $content;
917
-        }
918
-        /** @var EE_Registration $primary_registration */
919
-        $primary_registration = $transaction->primary_registration();
920
-        $attendee = $primary_registration instanceof EE_Registration
921
-            ? $primary_registration->attendee()
922
-            : null;
923
-
924
-        if ($attendee instanceof EE_Attendee
925
-            && EE_Registry::instance()->CAP->current_user_can(
926
-                'ee_send_message',
927
-                'espresso_transactions_send_payment_reminder'
928
-            )
929
-        ) {
930
-            $actions['payment_reminder'] =
931
-                EEH_MSG_Template::is_mt_active('payment_reminder')
932
-                && $this->_transaction->status_ID() !== EEM_Transaction::complete_status_code
933
-                && $this->_transaction->status_ID() !== EEM_Transaction::overpaid_status_code
934
-                    ? EEH_Template::get_button_or_link(
935
-                        EE_Admin_Page::add_query_args_and_nonce(
936
-                            array(
937
-                                'action'      => 'send_payment_reminder',
938
-                                'TXN_ID'      => $this->_transaction->ID(),
939
-                                'redirect_to' => 'view_transaction',
940
-                            ),
941
-                            TXN_ADMIN_URL
942
-                        ),
943
-                        esc_html__(' Send Payment Reminder', 'event_espresso'),
944
-                        'button secondary-button',
945
-                        'dashicons dashicons-email-alt'
946
-                    )
947
-                    : '';
948
-        }
949
-
950
-        if (EE_Registry::instance()->CAP->current_user_can(
951
-            'ee_edit_payments',
952
-            'espresso_transactions_recalculate_line_items'
953
-        )
954
-        ) {
955
-            $actions['recalculate_line_items'] = EEH_Template::get_button_or_link(
956
-                EE_Admin_Page::add_query_args_and_nonce(
957
-                    array(
958
-                        'action'      => 'espresso_recalculate_line_items',
959
-                        'TXN_ID'      => $this->_transaction->ID(),
960
-                        'redirect_to' => 'view_transaction',
961
-                    ),
962
-                    TXN_ADMIN_URL
963
-                ),
964
-                esc_html__(' Recalculate Taxes and Total', 'event_espresso'),
965
-                'button secondary-button',
966
-                'dashicons dashicons-update'
967
-            );
968
-        }
969
-
970
-        if ($primary_registration instanceof EE_Registration
971
-            && EEH_MSG_Template::is_mt_active('receipt')
972
-        ) {
973
-            $actions['receipt'] = EEH_Template::get_button_or_link(
974
-                $primary_registration->receipt_url(),
975
-                esc_html__('View Receipt', 'event_espresso'),
976
-                'button secondary-button',
977
-                'dashicons dashicons-media-default'
978
-            );
979
-        }
980
-
981
-        if ($primary_registration instanceof EE_Registration
982
-            && EEH_MSG_Template::is_mt_active('invoice')
983
-        ) {
984
-            $actions['invoice'] = EEH_Template::get_button_or_link(
985
-                $primary_registration->invoice_url(),
986
-                esc_html__('View Invoice', 'event_espresso'),
987
-                'button secondary-button',
988
-                'dashicons dashicons-media-spreadsheet'
989
-            );
990
-        }
991
-        $actions = array_filter(
992
-            apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
993
-        );
994
-        if ($actions) {
995
-            $content = '<ul>';
996
-            $content .= '<li>' . implode('</li><li>', $actions) . '</li>';
997
-            $content .= '</uL>';
998
-        }
999
-        return $content;
1000
-    }
1001
-
1002
-
1003
-    /**
1004
-     * txn_details_meta_box
1005
-     * generates HTML for the Transaction main meta box
1006
-     *
1007
-     * @return void
1008
-     * @throws DomainException
1009
-     * @throws EE_Error
1010
-     * @throws InvalidArgumentException
1011
-     * @throws InvalidDataTypeException
1012
-     * @throws InvalidInterfaceException
1013
-     * @throws RuntimeException
1014
-     * @throws ReflectionException
1015
-     */
1016
-    public function txn_details_meta_box()
1017
-    {
1018
-        $this->_set_transaction_object();
1019
-        $this->_template_args['TXN_ID'] = $this->_transaction->ID();
1020
-        $this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
1021
-            ? $this->_transaction->primary_registration()->attendee()
1022
-            : null;
1023
-        $this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
1024
-            'ee_edit_payments',
1025
-            'apply_payment_or_refund_from_registration_details'
1026
-        );
1027
-        $this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1028
-            'ee_delete_payments',
1029
-            'delete_payment_from_registration_details'
1030
-        );
1031
-
1032
-        // get line table
1033
-        EEH_Autoloader::register_line_item_display_autoloaders();
1034
-        $Line_Item_Display = new EE_Line_Item_Display(
1035
-            'admin_table',
1036
-            'EE_Admin_Table_Line_Item_Display_Strategy'
1037
-        );
1038
-        $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1039
-            $this->_transaction->total_line_item()
1040
-        );
1041
-        $this->_template_args['REG_code'] = $this->_transaction->primary_registration()->reg_code();
1042
-
1043
-        // process taxes
1044
-        $taxes = $this->_transaction->line_items(array(array('LIN_type' => EEM_Line_Item::type_tax)));
1045
-        $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1046
-
1047
-        $this->_template_args['grand_total'] = EEH_Template::format_currency(
1048
-            $this->_transaction->total(),
1049
-            false,
1050
-            false
1051
-        );
1052
-        $this->_template_args['grand_raw_total'] = $this->_transaction->total();
1053
-        $this->_template_args['TXN_status'] = $this->_transaction->status_ID();
1054
-
1055
-        // process payment details
1056
-        $payments = $this->_transaction->payments();
1057
-        if (! empty($payments)) {
1058
-            $this->_template_args['payments'] = $payments;
1059
-            $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1060
-        } else {
1061
-            $this->_template_args['payments'] = false;
1062
-            $this->_template_args['existing_reg_payments'] = array();
1063
-        }
1064
-
1065
-        $this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1066
-        $this->_template_args['delete_payment_url'] = add_query_arg(
1067
-            array('action' => 'espresso_delete_payment'),
1068
-            TXN_ADMIN_URL
1069
-        );
1070
-
1071
-        if (isset($txn_details['invoice_number'])) {
1072
-            $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1073
-            $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1074
-                'Invoice Number',
1075
-                'event_espresso'
1076
-            );
1077
-        }
1078
-
1079
-        $this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1080
-            ->primary_registration()
1081
-            ->session_ID();
1082
-        $this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1083
-            'Registration Session',
1084
-            'event_espresso'
1085
-        );
1086
-
1087
-        $this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1088
-            ? $this->_session['ip_address']
1089
-            : '';
1090
-        $this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1091
-            'Transaction placed from IP',
1092
-            'event_espresso'
1093
-        );
1094
-
1095
-        $this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1096
-            ? $this->_session['user_agent']
1097
-            : '';
1098
-        $this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1099
-            'Registrant User Agent',
1100
-            'event_espresso'
1101
-        );
1102
-
1103
-        $reg_steps = '<ul>';
1104
-        foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1105
-            if ($reg_step_status === true) {
1106
-                $reg_steps .= '<li style="color:#70cc50">'
1107
-                              . sprintf(
1108
-                                  esc_html__('%1$s : Completed', 'event_espresso'),
1109
-                                  ucwords(str_replace('_', ' ', $reg_step))
1110
-                              )
1111
-                              . '</li>';
1112
-            } elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1113
-                $reg_steps .= '<li style="color:#2EA2CC">'
1114
-                              . sprintf(
1115
-                                  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1116
-                                  ucwords(str_replace('_', ' ', $reg_step)),
1117
-                                  date(
1118
-                                      get_option('date_format') . ' ' . get_option('time_format'),
1119
-                                      $reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1120
-                                  )
1121
-                              )
1122
-                              . '</li>';
1123
-            } else {
1124
-                $reg_steps .= '<li style="color:#E76700">'
1125
-                              . sprintf(
1126
-                                  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1127
-                                  ucwords(str_replace('_', ' ', $reg_step))
1128
-                              )
1129
-                              . '</li>';
1130
-            }
1131
-        }
1132
-        $reg_steps .= '</ul>';
1133
-        $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1134
-        $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1135
-            'Registration Step Progress',
1136
-            'event_espresso'
1137
-        );
1138
-
1139
-
1140
-        $this->_get_registrations_to_apply_payment_to();
1141
-        $this->_get_payment_methods($payments);
1142
-        $this->_get_payment_status_array();
1143
-        $this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1144
-
1145
-        $this->_template_args['transaction_form_url'] = add_query_arg(
1146
-            array(
1147
-                'action'  => 'edit_transaction',
1148
-                'process' => 'transaction',
1149
-            ),
1150
-            TXN_ADMIN_URL
1151
-        );
1152
-        $this->_template_args['apply_payment_form_url'] = add_query_arg(
1153
-            array(
1154
-                'page'   => 'espresso_transactions',
1155
-                'action' => 'espresso_apply_payment',
1156
-            ),
1157
-            WP_AJAX_URL
1158
-        );
1159
-        $this->_template_args['delete_payment_form_url'] = add_query_arg(
1160
-            array(
1161
-                'page'   => 'espresso_transactions',
1162
-                'action' => 'espresso_delete_payment',
1163
-            ),
1164
-            WP_AJAX_URL
1165
-        );
1166
-
1167
-        $this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1168
-
1169
-        // 'espresso_delete_payment_nonce'
1170
-
1171
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1172
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1173
-    }
1174
-
1175
-
1176
-    /**
1177
-     * _get_registration_payment_IDs
1178
-     *    generates an array of Payment IDs and their corresponding Registration IDs
1179
-     *
1180
-     * @access protected
1181
-     * @param EE_Payment[] $payments
1182
-     * @return array
1183
-     * @throws EE_Error
1184
-     * @throws InvalidArgumentException
1185
-     * @throws InvalidDataTypeException
1186
-     * @throws InvalidInterfaceException
1187
-     * @throws ReflectionException
1188
-     */
1189
-    protected function _get_registration_payment_IDs($payments = array())
1190
-    {
1191
-        $existing_reg_payments = array();
1192
-        // get all reg payments for these payments
1193
-        $reg_payments = EEM_Registration_Payment::instance()->get_all(
1194
-            array(
1195
-                array(
1196
-                    'PAY_ID' => array(
1197
-                        'IN',
1198
-                        array_keys($payments),
1199
-                    ),
1200
-                ),
1201
-            )
1202
-        );
1203
-        if (! empty($reg_payments)) {
1204
-            foreach ($payments as $payment) {
1205
-                if (! $payment instanceof EE_Payment) {
1206
-                    continue;
1207
-                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1208
-                    $existing_reg_payments[ $payment->ID() ] = array();
1209
-                }
1210
-                foreach ($reg_payments as $reg_payment) {
1211
-                    if ($reg_payment instanceof EE_Registration_Payment
1212
-                        && $reg_payment->payment_ID() === $payment->ID()
1213
-                    ) {
1214
-                        $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1215
-                    }
1216
-                }
1217
-            }
1218
-        }
1219
-
1220
-        return $existing_reg_payments;
1221
-    }
1222
-
1223
-
1224
-    /**
1225
-     * _get_registrations_to_apply_payment_to
1226
-     *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1227
-     * which allows the admin to only apply the payment to the specific registrations
1228
-     *
1229
-     * @access protected
1230
-     * @return void
1231
-     * @throws EE_Error
1232
-     * @throws InvalidArgumentException
1233
-     * @throws InvalidDataTypeException
1234
-     * @throws InvalidInterfaceException
1235
-     * @throws ReflectionException
1236
-     */
1237
-    protected function _get_registrations_to_apply_payment_to()
1238
-    {
1239
-        // we want any registration with an active status (ie: not deleted or cancelled)
1240
-        $query_params = array(
1241
-            array(
1242
-                'STS_ID' => array(
1243
-                    'IN',
1244
-                    array(
1245
-                        EEM_Registration::status_id_approved,
1246
-                        EEM_Registration::status_id_pending_payment,
1247
-                        EEM_Registration::status_id_not_approved,
1248
-                    ),
1249
-                ),
1250
-            ),
1251
-        );
1252
-        $registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
1253
-            '',
1254
-            'txn-admin-apply-payment-to-registrations-dv',
1255
-            '',
1256
-            'clear: both; margin: 1.5em 0 0; display: none;'
1257
-        );
1258
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1259
-        $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1260
-        $registrations_to_apply_payment_to .= EEH_HTML::thead(
1261
-            EEH_HTML::tr(
1262
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1263
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1264
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1265
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1266
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1267
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1268
-                EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1269
-            )
1270
-        );
1271
-        $registrations_to_apply_payment_to .= EEH_HTML::tbody();
1272
-        // get registrations for TXN
1273
-        $registrations = $this->_transaction->registrations($query_params);
1274
-        $existing_reg_payments = $this->_template_args['existing_reg_payments'];
1275
-        foreach ($registrations as $registration) {
1276
-            if ($registration instanceof EE_Registration) {
1277
-                $attendee_name = $registration->attendee() instanceof EE_Attendee
1278
-                    ? $registration->attendee()->full_name()
1279
-                    : esc_html__('Unknown Attendee', 'event_espresso');
1280
-                $owing = $registration->final_price() - $registration->paid();
1281
-                $taxable = $registration->ticket()->taxable()
1282
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1283
-                    : '';
1284
-                $checked = empty($existing_reg_payments)
1285
-                           || in_array($registration->ID(), $existing_reg_payments, true)
1286
-                    ? ' checked="checked"'
1287
-                    : '';
1288
-                $disabled = $registration->final_price() > 0 ? '' : ' disabled';
1289
-                $registrations_to_apply_payment_to .= EEH_HTML::tr(
1290
-                    EEH_HTML::td($registration->ID()) .
1291
-                    EEH_HTML::td($attendee_name) .
1292
-                    EEH_HTML::td(
1293
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1294
-                    ) .
1295
-                    EEH_HTML::td($registration->event_name()) .
1296
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1297
-                    EEH_HTML::td(
1298
-                        EEH_Template::format_currency($owing),
1299
-                        '',
1300
-                        'txn-admin-payment-owing-td jst-cntr'
1301
-                    ) .
1302
-                    EEH_HTML::td(
1303
-                        '<input type="checkbox" value="' . $registration->ID()
1304
-                        . '" name="txn_admin_payment[registrations]"'
1305
-                        . $checked . $disabled . '>',
1306
-                        '',
1307
-                        'jst-cntr'
1308
-                    ),
1309
-                    'apply-payment-registration-row-' . $registration->ID()
1310
-                );
1311
-            }
1312
-        }
1313
-        $registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1314
-        $registrations_to_apply_payment_to .= EEH_HTML::tablex();
1315
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1316
-        $registrations_to_apply_payment_to .= EEH_HTML::p(
1317
-            esc_html__(
1318
-                'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1319
-                'event_espresso'
1320
-            ),
1321
-            '',
1322
-            'clear description'
1323
-        );
1324
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1325
-        $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1326
-    }
1327
-
1328
-
1329
-    /**
1330
-     * _get_reg_status_selection
1331
-     *
1332
-     * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1333
-     *         instead of events.
1334
-     * @access protected
1335
-     * @return void
1336
-     * @throws EE_Error
1337
-     */
1338
-    protected function _get_reg_status_selection()
1339
-    {
1340
-        // first get all possible statuses
1341
-        $statuses = EEM_Registration::reg_status_array(array(), true);
1342
-        // let's add a "don't change" option.
1343
-        $status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1344
-        $status_array = array_merge($status_array, $statuses);
1345
-        $this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1346
-            'txn_reg_status_change[reg_status]',
1347
-            $status_array,
1348
-            'NAN',
1349
-            'id="txn-admin-payment-reg-status-inp"',
1350
-            'txn-reg-status-change-reg-status'
1351
-        );
1352
-        $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1353
-            'delete_txn_reg_status_change[reg_status]',
1354
-            $status_array,
1355
-            'NAN',
1356
-            'delete-txn-admin-payment-reg-status-inp',
1357
-            'delete-txn-reg-status-change-reg-status'
1358
-        );
1359
-    }
1360
-
1361
-
1362
-    /**
1363
-     *    _get_payment_methods
1364
-     * Gets all the payment methods available generally, or the ones that are already
1365
-     * selected on these payments (in case their payment methods are no longer active).
1366
-     * Has the side-effect of updating the template args' payment_methods item
1367
-     *
1368
-     * @access private
1369
-     * @param EE_Payment[] to show on this page
1370
-     * @return void
1371
-     * @throws EE_Error
1372
-     * @throws InvalidArgumentException
1373
-     * @throws InvalidDataTypeException
1374
-     * @throws InvalidInterfaceException
1375
-     * @throws ReflectionException
1376
-     */
1377
-    private function _get_payment_methods($payments = array())
1378
-    {
1379
-        $payment_methods_of_payments = array();
1380
-        foreach ($payments as $payment) {
1381
-            if ($payment instanceof EE_Payment) {
1382
-                $payment_methods_of_payments[] = $payment->ID();
1383
-            }
1384
-        }
1385
-        if ($payment_methods_of_payments) {
1386
-            $query_args = array(
1387
-                array(
1388
-                    'OR*payment_method_for_payment' => array(
1389
-                        'PMD_ID'    => array('IN', $payment_methods_of_payments),
1390
-                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1391
-                    ),
1392
-                ),
1393
-            );
1394
-        } else {
1395
-            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1396
-        }
1397
-        $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1398
-    }
1399
-
1400
-
1401
-    /**
1402
-     * txn_attendees_meta_box
1403
-     *    generates HTML for the Attendees Transaction main meta box
1404
-     *
1405
-     * @access public
1406
-     * @param WP_Post $post
1407
-     * @param array   $metabox
1408
-     * @return void
1409
-     * @throws DomainException
1410
-     * @throws EE_Error
1411
-     * @throws InvalidArgumentException
1412
-     * @throws InvalidDataTypeException
1413
-     * @throws InvalidInterfaceException
1414
-     * @throws ReflectionException
1415
-     */
1416
-    public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1417
-    {
1418
-
1419
-        /** @noinspection NonSecureExtractUsageInspection */
1420
-        extract($metabox['args']);
1421
-        $this->_template_args['post'] = $post;
1422
-        $this->_template_args['event_attendees'] = array();
1423
-        // process items in cart
1424
-        $line_items = $this->_transaction->get_many_related(
1425
-            'Line_Item',
1426
-            array(array('LIN_type' => 'line-item'))
1427
-        );
1428
-        if (! empty($line_items)) {
1429
-            foreach ($line_items as $item) {
1430
-                if ($item instanceof EE_Line_Item) {
1431
-                    switch ($item->OBJ_type()) {
1432
-                        case 'Event':
1433
-                            break;
1434
-                        case 'Ticket':
1435
-                            $ticket = $item->ticket();
1436
-                            // right now we're only handling tickets here.
1437
-                            // Cause its expected that only tickets will have attendees right?
1438
-                            if (! $ticket instanceof EE_Ticket) {
1439
-                                break;
1440
-                            }
1441
-                            try {
1442
-                                $event_name = $ticket->get_event_name();
1443
-                            } catch (Exception $e) {
1444
-                                EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1445
-                                $event_name = esc_html__('Unknown Event', 'event_espresso');
1446
-                            }
1447
-                            $event_name .= ' - ' . $item->name();
1448
-                            $ticket_price = EEH_Template::format_currency($item->unit_price());
1449
-                            // now get all of the registrations for this transaction that use this ticket
1450
-                            $registrations = $ticket->registrations(
1451
-                                array(array('TXN_ID' => $this->_transaction->ID()))
1452
-                            );
1453
-                            foreach ($registrations as $registration) {
1454
-                                if (! $registration instanceof EE_Registration) {
1455
-                                    break;
1456
-                                }
1457
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1458
-                                    = $registration->status_ID();
1459
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1460
-                                    = $registration->count();
1461
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1462
-                                    = $event_name;
1463
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1464
-                                    = $ticket_price;
1465
-                                // attendee info
1466
-                                $attendee = $registration->get_first_related('Attendee');
1467
-                                if ($attendee instanceof EE_Attendee) {
1468
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1469
-                                        = $attendee->ID();
1470
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1471
-                                        = $attendee->full_name();
1472
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']
1473
-                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1474
-                                          . esc_html__(
1475
-                                              ' Event',
1476
-                                              'event_espresso'
1477
-                                          )
1478
-                                          . '">' . $attendee->email() . '</a>';
1479
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']
1480
-                                        = EEH_Address::format($attendee, 'inline', false, false);
1481
-                                } else {
1482
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1483
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1484
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1485
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1486
-                                }
1487
-                            }
1488
-                            break;
1489
-                    }
1490
-                }
1491
-            }
1492
-
1493
-            $this->_template_args['transaction_form_url'] = add_query_arg(
1494
-                array(
1495
-                    'action'  => 'edit_transaction',
1496
-                    'process' => 'attendees',
1497
-                ),
1498
-                TXN_ADMIN_URL
1499
-            );
1500
-            echo EEH_Template::display_template(
1501
-                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1502
-                $this->_template_args,
1503
-                true
1504
-            );
1505
-        } else {
1506
-            echo sprintf(
1507
-                esc_html__(
1508
-                    '%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1509
-                    'event_espresso'
1510
-                ),
1511
-                '<p class="important-notice">',
1512
-                '</p>'
1513
-            );
1514
-        }
1515
-    }
1516
-
1517
-
1518
-    /**
1519
-     * txn_registrant_side_meta_box
1520
-     * generates HTML for the Edit Transaction side meta box
1521
-     *
1522
-     * @access public
1523
-     * @return void
1524
-     * @throws DomainException
1525
-     * @throws EE_Error
1526
-     * @throws InvalidArgumentException
1527
-     * @throws InvalidDataTypeException
1528
-     * @throws InvalidInterfaceException
1529
-     * @throws ReflectionException
1530
-     */
1531
-    public function txn_registrant_side_meta_box()
1532
-    {
1533
-        $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1534
-            ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1535
-            : null;
1536
-        if (! $primary_att instanceof EE_Attendee) {
1537
-            $this->_template_args['no_attendee_message'] = esc_html__(
1538
-                'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1539
-                'event_espresso'
1540
-            );
1541
-            $primary_att = EEM_Attendee::instance()->create_default_object();
1542
-        }
1543
-        $this->_template_args['ATT_ID'] = $primary_att->ID();
1544
-        $this->_template_args['prime_reg_fname'] = $primary_att->fname();
1545
-        $this->_template_args['prime_reg_lname'] = $primary_att->lname();
1546
-        $this->_template_args['prime_reg_email'] = $primary_att->email();
1547
-        $this->_template_args['prime_reg_phone'] = $primary_att->phone();
1548
-        $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1549
-            array(
1550
-                'action' => 'edit_attendee',
1551
-                'post'   => $primary_att->ID(),
1552
-            ),
1553
-            REG_ADMIN_URL
1554
-        );
1555
-        // get formatted address for registrant
1556
-        $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1557
-        echo EEH_Template::display_template(
1558
-            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1559
-            $this->_template_args,
1560
-            true
1561
-        );
1562
-    }
1563
-
1564
-
1565
-    /**
1566
-     * txn_billing_info_side_meta_box
1567
-     *    generates HTML for the Edit Transaction side meta box
1568
-     *
1569
-     * @access public
1570
-     * @return void
1571
-     * @throws DomainException
1572
-     * @throws EE_Error
1573
-     */
1574
-    public function txn_billing_info_side_meta_box()
1575
-    {
1576
-
1577
-        $this->_template_args['billing_form'] = $this->_transaction->billing_info();
1578
-        $this->_template_args['billing_form_url'] = add_query_arg(
1579
-            array('action' => 'edit_transaction', 'process' => 'billing'),
1580
-            TXN_ADMIN_URL
1581
-        );
1582
-
1583
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1584
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1585
-    }
1586
-
1587
-
1588
-    /**
1589
-     * apply_payments_or_refunds
1590
-     *    registers a payment or refund made towards a transaction
1591
-     *
1592
-     * @access public
1593
-     * @return void
1594
-     * @throws EE_Error
1595
-     * @throws InvalidArgumentException
1596
-     * @throws ReflectionException
1597
-     * @throws RuntimeException
1598
-     * @throws InvalidDataTypeException
1599
-     * @throws InvalidInterfaceException
1600
-     */
1601
-    public function apply_payments_or_refunds()
1602
-    {
1603
-        $json_response_data = array('return_data' => false);
1604
-        $valid_data = $this->_validate_payment_request_data();
1605
-        $has_access = EE_Registry::instance()->CAP->current_user_can(
1606
-            'ee_edit_payments',
1607
-            'apply_payment_or_refund_from_registration_details'
1608
-        );
1609
-        if (! empty($valid_data) && $has_access) {
1610
-            $PAY_ID = $valid_data['PAY_ID'];
1611
-            // save  the new payment
1612
-            $payment = $this->_create_payment_from_request_data($valid_data);
1613
-            // get the TXN for this payment
1614
-            $transaction = $payment->transaction();
1615
-            // verify transaction
1616
-            if ($transaction instanceof EE_Transaction) {
1617
-                // calculate_total_payments_and_update_status
1618
-                $this->_process_transaction_payments($transaction);
1619
-                $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1620
-                $this->_remove_existing_registration_payments($payment, $PAY_ID);
1621
-                // apply payment to registrations (if applicable)
1622
-                if (! empty($REG_IDs)) {
1623
-                    $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1624
-                    $this->_maybe_send_notifications();
1625
-                    // now process status changes for the same registrations
1626
-                    $this->_process_registration_status_change($transaction, $REG_IDs);
1627
-                }
1628
-                $this->_maybe_send_notifications($payment);
1629
-                // prepare to render page
1630
-                $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1631
-                do_action(
1632
-                    'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1633
-                    $transaction,
1634
-                    $payment
1635
-                );
1636
-            } else {
1637
-                EE_Error::add_error(
1638
-                    esc_html__(
1639
-                        'A valid Transaction for this payment could not be retrieved.',
1640
-                        'event_espresso'
1641
-                    ),
1642
-                    __FILE__,
1643
-                    __FUNCTION__,
1644
-                    __LINE__
1645
-                );
1646
-            }
1647
-        } elseif ($has_access) {
1648
-            EE_Error::add_error(
1649
-                esc_html__(
1650
-                    'The payment form data could not be processed. Please try again.',
1651
-                    'event_espresso'
1652
-                ),
1653
-                __FILE__,
1654
-                __FUNCTION__,
1655
-                __LINE__
1656
-            );
1657
-        } else {
1658
-            EE_Error::add_error(
1659
-                esc_html__(
1660
-                    'You do not have access to apply payments or refunds to a registration.',
1661
-                    'event_espresso'
1662
-                ),
1663
-                __FILE__,
1664
-                __FUNCTION__,
1665
-                __LINE__
1666
-            );
1667
-        }
1668
-        $notices = EE_Error::get_notices(
1669
-            false,
1670
-            false,
1671
-            false
1672
-        );
1673
-        $this->_template_args = array(
1674
-            'data'    => $json_response_data,
1675
-            'error'   => $notices['errors'],
1676
-            'success' => $notices['success'],
1677
-        );
1678
-        $this->_return_json();
1679
-    }
1680
-
1681
-
1682
-    /**
1683
-     * _validate_payment_request_data
1684
-     *
1685
-     * @return array
1686
-     * @throws EE_Error
1687
-     * @throws InvalidArgumentException
1688
-     * @throws InvalidDataTypeException
1689
-     * @throws InvalidInterfaceException
1690
-     */
1691
-    protected function _validate_payment_request_data()
1692
-    {
1693
-        if (! isset($this->_req_data['txn_admin_payment'])) {
1694
-            return array();
1695
-        }
1696
-        $payment_form = $this->_generate_payment_form_section();
1697
-        try {
1698
-            if ($payment_form->was_submitted()) {
1699
-                $payment_form->receive_form_submission();
1700
-                if (! $payment_form->is_valid()) {
1701
-                    $submission_error_messages = array();
1702
-                    foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1703
-                        if ($validation_error instanceof EE_Validation_Error) {
1704
-                            $submission_error_messages[] = sprintf(
1705
-                                _x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1706
-                                $validation_error->get_form_section()->html_label_text(),
1707
-                                $validation_error->getMessage()
1708
-                            );
1709
-                        }
1710
-                    }
1711
-                    EE_Error::add_error(
1712
-                        implode('<br />', $submission_error_messages),
1713
-                        __FILE__,
1714
-                        __FUNCTION__,
1715
-                        __LINE__
1716
-                    );
1717
-                    return array();
1718
-                }
1719
-            }
1720
-        } catch (EE_Error $e) {
1721
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1722
-            return array();
1723
-        }
1724
-
1725
-        return $payment_form->valid_data();
1726
-    }
1727
-
1728
-
1729
-    /**
1730
-     * _generate_payment_form_section
1731
-     *
1732
-     * @return EE_Form_Section_Proper
1733
-     * @throws EE_Error
1734
-     */
1735
-    protected function _generate_payment_form_section()
1736
-    {
1737
-        return new EE_Form_Section_Proper(
1738
-            array(
1739
-                'name'        => 'txn_admin_payment',
1740
-                'subsections' => array(
1741
-                    'PAY_ID'          => new EE_Text_Input(
1742
-                        array(
1743
-                            'default'               => 0,
1744
-                            'required'              => false,
1745
-                            'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1746
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1747
-                        )
1748
-                    ),
1749
-                    'TXN_ID'          => new EE_Text_Input(
1750
-                        array(
1751
-                            'default'               => 0,
1752
-                            'required'              => true,
1753
-                            'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1754
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1755
-                        )
1756
-                    ),
1757
-                    'type'            => new EE_Text_Input(
1758
-                        array(
1759
-                            'default'               => 1,
1760
-                            'required'              => true,
1761
-                            'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1762
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1763
-                        )
1764
-                    ),
1765
-                    'amount'          => new EE_Text_Input(
1766
-                        array(
1767
-                            'default'               => 0,
1768
-                            'required'              => true,
1769
-                            'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1770
-                            'validation_strategies' => array(new EE_Float_Normalization()),
1771
-                        )
1772
-                    ),
1773
-                    'status'          => new EE_Text_Input(
1774
-                        array(
1775
-                            'default'         => EEM_Payment::status_id_approved,
1776
-                            'required'        => true,
1777
-                            'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1778
-                        )
1779
-                    ),
1780
-                    'PMD_ID'          => new EE_Text_Input(
1781
-                        array(
1782
-                            'default'               => 2,
1783
-                            'required'              => true,
1784
-                            'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1785
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1786
-                        )
1787
-                    ),
1788
-                    'date'            => new EE_Text_Input(
1789
-                        array(
1790
-                            'default'         => time(),
1791
-                            'required'        => true,
1792
-                            'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1793
-                        )
1794
-                    ),
1795
-                    'txn_id_chq_nmbr' => new EE_Text_Input(
1796
-                        array(
1797
-                            'default'               => '',
1798
-                            'required'              => false,
1799
-                            'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1800
-                            'validation_strategies' => array(
1801
-                                new EE_Max_Length_Validation_Strategy(
1802
-                                    esc_html__('Input too long', 'event_espresso'),
1803
-                                    100
1804
-                                ),
1805
-                            ),
1806
-                        )
1807
-                    ),
1808
-                    'po_number'       => new EE_Text_Input(
1809
-                        array(
1810
-                            'default'               => '',
1811
-                            'required'              => false,
1812
-                            'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1813
-                            'validation_strategies' => array(
1814
-                                new EE_Max_Length_Validation_Strategy(
1815
-                                    esc_html__('Input too long', 'event_espresso'),
1816
-                                    100
1817
-                                ),
1818
-                            ),
1819
-                        )
1820
-                    ),
1821
-                    'accounting'      => new EE_Text_Input(
1822
-                        array(
1823
-                            'default'               => '',
1824
-                            'required'              => false,
1825
-                            'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1826
-                            'validation_strategies' => array(
1827
-                                new EE_Max_Length_Validation_Strategy(
1828
-                                    esc_html__('Input too long', 'event_espresso'),
1829
-                                    100
1830
-                                ),
1831
-                            ),
1832
-                        )
1833
-                    ),
1834
-                ),
1835
-            )
1836
-        );
1837
-    }
1838
-
1839
-
1840
-    /**
1841
-     * _create_payment_from_request_data
1842
-     *
1843
-     * @param array $valid_data
1844
-     * @return EE_Payment
1845
-     * @throws EE_Error
1846
-     * @throws InvalidArgumentException
1847
-     * @throws InvalidDataTypeException
1848
-     * @throws InvalidInterfaceException
1849
-     * @throws ReflectionException
1850
-     */
1851
-    protected function _create_payment_from_request_data($valid_data)
1852
-    {
1853
-        $PAY_ID = $valid_data['PAY_ID'];
1854
-        // get payment amount
1855
-        $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1856
-        // payments have a type value of 1 and refunds have a type value of -1
1857
-        // so multiplying amount by type will give a positive value for payments, and negative values for refunds
1858
-        $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1859
-        // for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1860
-        $date = $valid_data['date']
1861
-            ? preg_replace('/\s+/', ' ', $valid_data['date'])
1862
-            : date('Y-m-d g:i a', current_time('timestamp'));
1863
-        $payment = EE_Payment::new_instance(
1864
-            array(
1865
-                'TXN_ID'              => $valid_data['TXN_ID'],
1866
-                'STS_ID'              => $valid_data['status'],
1867
-                'PAY_timestamp'       => $date,
1868
-                'PAY_source'          => EEM_Payment_Method::scope_admin,
1869
-                'PMD_ID'              => $valid_data['PMD_ID'],
1870
-                'PAY_amount'          => $amount,
1871
-                'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1872
-                'PAY_po_number'       => $valid_data['po_number'],
1873
-                'PAY_extra_accntng'   => $valid_data['accounting'],
1874
-                'PAY_details'         => $valid_data,
1875
-                'PAY_ID'              => $PAY_ID,
1876
-            ),
1877
-            '',
1878
-            array('Y-m-d', 'g:i a')
1879
-        );
1880
-
1881
-        if (! $payment->save()) {
1882
-            EE_Error::add_error(
1883
-                sprintf(
1884
-                    esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1885
-                    $payment->ID()
1886
-                ),
1887
-                __FILE__,
1888
-                __FUNCTION__,
1889
-                __LINE__
1890
-            );
1891
-        }
1892
-
1893
-        return $payment;
1894
-    }
1895
-
1896
-
1897
-    /**
1898
-     * _process_transaction_payments
1899
-     *
1900
-     * @param \EE_Transaction $transaction
1901
-     * @return void
1902
-     * @throws EE_Error
1903
-     * @throws InvalidArgumentException
1904
-     * @throws ReflectionException
1905
-     * @throws InvalidDataTypeException
1906
-     * @throws InvalidInterfaceException
1907
-     */
1908
-    protected function _process_transaction_payments(EE_Transaction $transaction)
1909
-    {
1910
-        /** @type EE_Transaction_Payments $transaction_payments */
1911
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1912
-        // update the transaction with this payment
1913
-        if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1914
-            EE_Error::add_success(
1915
-                esc_html__(
1916
-                    'The payment has been processed successfully.',
1917
-                    'event_espresso'
1918
-                ),
1919
-                __FILE__,
1920
-                __FUNCTION__,
1921
-                __LINE__
1922
-            );
1923
-        } else {
1924
-            EE_Error::add_error(
1925
-                esc_html__(
1926
-                    'The payment was processed successfully but the amount paid for the transaction was not updated.',
1927
-                    'event_espresso'
1928
-                ),
1929
-                __FILE__,
1930
-                __FUNCTION__,
1931
-                __LINE__
1932
-            );
1933
-        }
1934
-    }
1935
-
1936
-
1937
-    /**
1938
-     * _get_REG_IDs_to_apply_payment_to
1939
-     * returns a list of registration IDs that the payment will apply to
1940
-     *
1941
-     * @param \EE_Payment $payment
1942
-     * @return array
1943
-     * @throws EE_Error
1944
-     * @throws InvalidArgumentException
1945
-     * @throws InvalidDataTypeException
1946
-     * @throws InvalidInterfaceException
1947
-     * @throws ReflectionException
1948
-     */
1949
-    protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1950
-    {
1951
-        $REG_IDs = array();
1952
-        // grab array of IDs for specific registrations to apply changes to
1953
-        if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1954
-            $REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1955
-        }
1956
-        // nothing specified ? then get all reg IDs
1957
-        if (empty($REG_IDs)) {
1958
-            $registrations = $payment->transaction()->registrations();
1959
-            $REG_IDs = ! empty($registrations)
1960
-                ? array_keys($registrations)
1961
-                : $this->_get_existing_reg_payment_REG_IDs($payment);
1962
-        }
1963
-
1964
-        // ensure that REG_IDs are integers and NOT strings
1965
-        return array_map('intval', $REG_IDs);
1966
-    }
1967
-
1968
-
1969
-    /**
1970
-     * @return array
1971
-     */
1972
-    public function existing_reg_payment_REG_IDs()
1973
-    {
1974
-        return $this->_existing_reg_payment_REG_IDs;
1975
-    }
1976
-
1977
-
1978
-    /**
1979
-     * @param array $existing_reg_payment_REG_IDs
1980
-     */
1981
-    public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1982
-    {
1983
-        $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1984
-    }
1985
-
1986
-
1987
-    /**
1988
-     * _get_existing_reg_payment_REG_IDs
1989
-     * returns a list of registration IDs that the payment is currently related to
1990
-     * as recorded in the database
1991
-     *
1992
-     * @param \EE_Payment $payment
1993
-     * @return array
1994
-     * @throws EE_Error
1995
-     * @throws InvalidArgumentException
1996
-     * @throws InvalidDataTypeException
1997
-     * @throws InvalidInterfaceException
1998
-     * @throws ReflectionException
1999
-     */
2000
-    protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
2001
-    {
2002
-        if ($this->existing_reg_payment_REG_IDs() === null) {
2003
-            // let's get any existing reg payment records for this payment
2004
-            $existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
2005
-            // but we only want the REG IDs, so grab the array keys
2006
-            $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
2007
-                ? array_keys($existing_reg_payment_REG_IDs)
2008
-                : array();
2009
-            $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
2010
-        }
2011
-
2012
-        return $this->existing_reg_payment_REG_IDs();
2013
-    }
2014
-
2015
-
2016
-    /**
2017
-     * _remove_existing_registration_payments
2018
-     * this calculates the difference between existing relations
2019
-     * to the supplied payment and the new list registration IDs,
2020
-     * removes any related registrations that no longer apply,
2021
-     * and then updates the registration paid fields
2022
-     *
2023
-     * @param \EE_Payment $payment
2024
-     * @param int         $PAY_ID
2025
-     * @return bool;
2026
-     * @throws EE_Error
2027
-     * @throws InvalidArgumentException
2028
-     * @throws ReflectionException
2029
-     * @throws InvalidDataTypeException
2030
-     * @throws InvalidInterfaceException
2031
-     */
2032
-    protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2033
-    {
2034
-        // newly created payments will have nothing recorded for $PAY_ID
2035
-        if (absint($PAY_ID) === 0) {
2036
-            return false;
2037
-        }
2038
-        $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2039
-        if (empty($existing_reg_payment_REG_IDs)) {
2040
-            return false;
2041
-        }
2042
-        /** @type EE_Transaction_Payments $transaction_payments */
2043
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2044
-
2045
-        return $transaction_payments->delete_registration_payments_and_update_registrations(
2046
-            $payment,
2047
-            array(
2048
-                array(
2049
-                    'PAY_ID' => $payment->ID(),
2050
-                    'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2051
-                ),
2052
-            )
2053
-        );
2054
-    }
2055
-
2056
-
2057
-    /**
2058
-     * _update_registration_payments
2059
-     * this applies the payments to the selected registrations
2060
-     * but only if they have not already been paid for
2061
-     *
2062
-     * @param  EE_Transaction $transaction
2063
-     * @param \EE_Payment     $payment
2064
-     * @param array           $REG_IDs
2065
-     * @return void
2066
-     * @throws EE_Error
2067
-     * @throws InvalidArgumentException
2068
-     * @throws ReflectionException
2069
-     * @throws RuntimeException
2070
-     * @throws InvalidDataTypeException
2071
-     * @throws InvalidInterfaceException
2072
-     */
2073
-    protected function _update_registration_payments(
2074
-        EE_Transaction $transaction,
2075
-        EE_Payment $payment,
2076
-        $REG_IDs = array()
2077
-    ) {
2078
-        // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2079
-        // so let's do that using our set of REG_IDs from the form
2080
-        $registration_query_where_params = array(
2081
-            'REG_ID' => array('IN', $REG_IDs),
2082
-        );
2083
-        // but add in some conditions regarding payment,
2084
-        // so that we don't apply payments to registrations that are free or have already been paid for
2085
-        // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2086
-        if (! $payment->is_a_refund()) {
2087
-            $registration_query_where_params['REG_final_price'] = array('!=', 0);
2088
-            $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2089
-        }
2090
-        $registrations = $transaction->registrations(array($registration_query_where_params));
2091
-        if (! empty($registrations)) {
2092
-            /** @type EE_Payment_Processor $payment_processor */
2093
-            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2094
-            $payment_processor->process_registration_payments($transaction, $payment, $registrations);
2095
-        }
2096
-    }
2097
-
2098
-
2099
-    /**
2100
-     * _process_registration_status_change
2101
-     * This processes requested registration status changes for all the registrations
2102
-     * on a given transaction and (optionally) sends out notifications for the changes.
2103
-     *
2104
-     * @param  EE_Transaction $transaction
2105
-     * @param array           $REG_IDs
2106
-     * @return bool
2107
-     * @throws EE_Error
2108
-     * @throws InvalidArgumentException
2109
-     * @throws ReflectionException
2110
-     * @throws InvalidDataTypeException
2111
-     * @throws InvalidInterfaceException
2112
-     */
2113
-    protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2114
-    {
2115
-        // first if there is no change in status then we get out.
2116
-        if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2117
-            || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2118
-        ) {
2119
-            // no error message, no change requested, just nothing to do man.
2120
-            return false;
2121
-        }
2122
-        /** @type EE_Transaction_Processor $transaction_processor */
2123
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2124
-
2125
-        // made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2126
-        return $transaction_processor->manually_update_registration_statuses(
2127
-            $transaction,
2128
-            sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2129
-            array(array('REG_ID' => array('IN', $REG_IDs)))
2130
-        );
2131
-    }
2132
-
2133
-
2134
-    /**
2135
-     * _build_payment_json_response
2136
-     *
2137
-     * @access public
2138
-     * @param \EE_Payment $payment
2139
-     * @param array       $REG_IDs
2140
-     * @param bool | null $delete_txn_reg_status_change
2141
-     * @return array
2142
-     * @throws EE_Error
2143
-     * @throws InvalidArgumentException
2144
-     * @throws InvalidDataTypeException
2145
-     * @throws InvalidInterfaceException
2146
-     * @throws ReflectionException
2147
-     */
2148
-    protected function _build_payment_json_response(
2149
-        EE_Payment $payment,
2150
-        $REG_IDs = array(),
2151
-        $delete_txn_reg_status_change = null
2152
-    ) {
2153
-        // was the payment deleted ?
2154
-        if (is_bool($delete_txn_reg_status_change)) {
2155
-            return array(
2156
-                'PAY_ID'                       => $payment->ID(),
2157
-                'amount'                       => $payment->amount(),
2158
-                'total_paid'                   => $payment->transaction()->paid(),
2159
-                'txn_status'                   => $payment->transaction()->status_ID(),
2160
-                'pay_status'                   => $payment->STS_ID(),
2161
-                'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2162
-                'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2163
-            );
2164
-        } else {
2165
-            $this->_get_payment_status_array();
2166
-
2167
-            return array(
2168
-                'amount'           => $payment->amount(),
2169
-                'total_paid'       => $payment->transaction()->paid(),
2170
-                'txn_status'       => $payment->transaction()->status_ID(),
2171
-                'pay_status'       => $payment->STS_ID(),
2172
-                'PAY_ID'           => $payment->ID(),
2173
-                'STS_ID'           => $payment->STS_ID(),
2174
-                'status'           => self::$_pay_status[ $payment->STS_ID() ],
2175
-                'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2176
-                'method'           => strtoupper($payment->source()),
2177
-                'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2178
-                'gateway'          => $payment->payment_method()
2179
-                    ? $payment->payment_method()->admin_name()
2180
-                    : esc_html__('Unknown', 'event_espresso'),
2181
-                'gateway_response' => $payment->gateway_response(),
2182
-                'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2183
-                'po_number'        => $payment->po_number(),
2184
-                'extra_accntng'    => $payment->extra_accntng(),
2185
-                'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2186
-            );
2187
-        }
2188
-    }
2189
-
2190
-
2191
-    /**
2192
-     * delete_payment
2193
-     *    delete a payment or refund made towards a transaction
2194
-     *
2195
-     * @access public
2196
-     * @return void
2197
-     * @throws EE_Error
2198
-     * @throws InvalidArgumentException
2199
-     * @throws ReflectionException
2200
-     * @throws InvalidDataTypeException
2201
-     * @throws InvalidInterfaceException
2202
-     */
2203
-    public function delete_payment()
2204
-    {
2205
-        $json_response_data = array('return_data' => false);
2206
-        $PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2207
-            ? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2208
-            : 0;
2209
-        $can_delete = EE_Registry::instance()->CAP->current_user_can(
2210
-            'ee_delete_payments',
2211
-            'delete_payment_from_registration_details'
2212
-        );
2213
-        if ($PAY_ID && $can_delete) {
2214
-            $delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2215
-                ? $this->_req_data['delete_txn_reg_status_change']
2216
-                : false;
2217
-            $payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2218
-            if ($payment instanceof EE_Payment) {
2219
-                $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2220
-                /** @type EE_Transaction_Payments $transaction_payments */
2221
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2222
-                if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2223
-                    $json_response_data['return_data'] = $this->_build_payment_json_response(
2224
-                        $payment,
2225
-                        $REG_IDs,
2226
-                        $delete_txn_reg_status_change
2227
-                    );
2228
-                    if ($delete_txn_reg_status_change) {
2229
-                        $this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2230
-                        // MAKE sure we also add the delete_txn_req_status_change to the
2231
-                        // $_REQUEST global because that's how messages will be looking for it.
2232
-                        $_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2233
-                        $this->_maybe_send_notifications();
2234
-                        $this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2235
-                    }
2236
-                }
2237
-            } else {
2238
-                EE_Error::add_error(
2239
-                    esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2240
-                    __FILE__,
2241
-                    __FUNCTION__,
2242
-                    __LINE__
2243
-                );
2244
-            }
2245
-        } elseif ($can_delete) {
2246
-            EE_Error::add_error(
2247
-                esc_html__(
2248
-                    'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2249
-                    'event_espresso'
2250
-                ),
2251
-                __FILE__,
2252
-                __FUNCTION__,
2253
-                __LINE__
2254
-            );
2255
-        } else {
2256
-            EE_Error::add_error(
2257
-                esc_html__(
2258
-                    'You do not have access to delete a payment.',
2259
-                    'event_espresso'
2260
-                ),
2261
-                __FILE__,
2262
-                __FUNCTION__,
2263
-                __LINE__
2264
-            );
2265
-        }
2266
-        $notices = EE_Error::get_notices(false, false, false);
2267
-        $this->_template_args = array(
2268
-            'data'      => $json_response_data,
2269
-            'success'   => $notices['success'],
2270
-            'error'     => $notices['errors'],
2271
-            'attention' => $notices['attention'],
2272
-        );
2273
-        $this->_return_json();
2274
-    }
2275
-
2276
-
2277
-    /**
2278
-     * _registration_payment_data_array
2279
-     * adds info for 'owing' and 'paid' for each registration to the json response
2280
-     *
2281
-     * @access protected
2282
-     * @param array $REG_IDs
2283
-     * @return array
2284
-     * @throws EE_Error
2285
-     * @throws InvalidArgumentException
2286
-     * @throws InvalidDataTypeException
2287
-     * @throws InvalidInterfaceException
2288
-     * @throws ReflectionException
2289
-     */
2290
-    protected function _registration_payment_data_array($REG_IDs)
2291
-    {
2292
-        $registration_payment_data = array();
2293
-        // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2294
-        if (! empty($REG_IDs)) {
2295
-            $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2296
-            foreach ($registrations as $registration) {
2297
-                if ($registration instanceof EE_Registration) {
2298
-                    $registration_payment_data[ $registration->ID() ] = array(
2299
-                        'paid'  => $registration->pretty_paid(),
2300
-                        'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2301
-                    );
2302
-                }
2303
-            }
2304
-        }
2305
-
2306
-        return $registration_payment_data;
2307
-    }
2308
-
2309
-
2310
-    /**
2311
-     * _maybe_send_notifications
2312
-     * determines whether or not the admin has indicated that notifications should be sent.
2313
-     * If so, will toggle a filter switch for delivering registration notices.
2314
-     * If passed an EE_Payment object, then it will trigger payment notifications instead.
2315
-     *
2316
-     * @access protected
2317
-     * @param \EE_Payment | null $payment
2318
-     */
2319
-    protected function _maybe_send_notifications($payment = null)
2320
-    {
2321
-        switch ($payment instanceof EE_Payment) {
2322
-            // payment notifications
2323
-            case true:
2324
-                if (isset($this->_req_data['txn_payments']['send_notifications'])
2325
-                    && filter_var(
2326
-                        $this->_req_data['txn_payments']['send_notifications'],
2327
-                        FILTER_VALIDATE_BOOLEAN
2328
-                    )
2329
-                ) {
2330
-                    $this->_process_payment_notification($payment);
2331
-                }
2332
-                break;
2333
-            // registration notifications
2334
-            case false:
2335
-                if (isset($this->_req_data['txn_reg_status_change']['send_notifications'])
2336
-                    && filter_var(
2337
-                        $this->_req_data['txn_reg_status_change']['send_notifications'],
2338
-                        FILTER_VALIDATE_BOOLEAN
2339
-                    )
2340
-                ) {
2341
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2342
-                }
2343
-                break;
2344
-        }
2345
-    }
2346
-
2347
-
2348
-    /**
2349
-     * _send_payment_reminder
2350
-     *    generates HTML for the View Transaction Details Admin page
2351
-     *
2352
-     * @access protected
2353
-     * @return void
2354
-     * @throws EE_Error
2355
-     * @throws InvalidArgumentException
2356
-     * @throws InvalidDataTypeException
2357
-     * @throws InvalidInterfaceException
2358
-     */
2359
-    protected function _send_payment_reminder()
2360
-    {
2361
-        $TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2362
-        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2363
-        $query_args = isset($this->_req_data['redirect_to']) ? array(
2364
-            'action' => $this->_req_data['redirect_to'],
2365
-            'TXN_ID' => $this->_req_data['TXN_ID'],
2366
-        ) : array();
2367
-        do_action(
2368
-            'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2369
-            $transaction
2370
-        );
2371
-        $this->_redirect_after_action(
2372
-            false,
2373
-            esc_html__('payment reminder', 'event_espresso'),
2374
-            esc_html__('sent', 'event_espresso'),
2375
-            $query_args,
2376
-            true
2377
-        );
2378
-    }
2379
-
2380
-
2381
-    /**
2382
-     *  get_transactions
2383
-     *    get transactions for given parameters (used by list table)
2384
-     *
2385
-     * @param  int     $perpage how many transactions displayed per page
2386
-     * @param  boolean $count   return the count or objects
2387
-     * @param string   $view
2388
-     * @return mixed int = count || array of transaction objects
2389
-     * @throws EE_Error
2390
-     * @throws InvalidArgumentException
2391
-     * @throws InvalidDataTypeException
2392
-     * @throws InvalidInterfaceException
2393
-     */
2394
-    public function get_transactions($perpage, $count = false, $view = '')
2395
-    {
2396
-
2397
-        $TXN = EEM_Transaction::instance();
2398
-
2399
-        $start_date = isset($this->_req_data['txn-filter-start-date'])
2400
-            ? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2401
-            : date(
2402
-                'm/d/Y',
2403
-                strtotime('-10 year')
2404
-            );
2405
-        $end_date = isset($this->_req_data['txn-filter-end-date'])
2406
-            ? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2407
-            : date('m/d/Y');
2408
-
2409
-        // make sure our timestamps start and end right at the boundaries for each day
2410
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2411
-        $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2412
-
2413
-
2414
-        // convert to timestamps
2415
-        $start_date = strtotime($start_date);
2416
-        $end_date = strtotime($end_date);
2417
-
2418
-        // makes sure start date is the lowest value and vice versa
2419
-        $start_date = min($start_date, $end_date);
2420
-        $end_date = max($start_date, $end_date);
2421
-
2422
-        // convert to correct format for query
2423
-        $start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2424
-            'TXN_timestamp',
2425
-            date('Y-m-d H:i:s', $start_date),
2426
-            'Y-m-d H:i:s'
2427
-        );
2428
-        $end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2429
-            'TXN_timestamp',
2430
-            date('Y-m-d H:i:s', $end_date),
2431
-            'Y-m-d H:i:s'
2432
-        );
2433
-
2434
-
2435
-        // set orderby
2436
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2437
-
2438
-        switch ($this->_req_data['orderby']) {
2439
-            case 'TXN_ID':
2440
-                $orderby = 'TXN_ID';
2441
-                break;
2442
-            case 'ATT_fname':
2443
-                $orderby = 'Registration.Attendee.ATT_fname';
2444
-                break;
2445
-            case 'event_name':
2446
-                $orderby = 'Registration.Event.EVT_name';
2447
-                break;
2448
-            default: // 'TXN_timestamp'
2449
-                $orderby = 'TXN_timestamp';
2450
-        }
2451
-
2452
-        $sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2453
-        $current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2454
-        $per_page = ! empty($perpage) ? $perpage : 10;
2455
-        $per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2456
-
2457
-        $offset = ($current_page - 1) * $per_page;
2458
-        $limit = array($offset, $per_page);
2459
-
2460
-        $_where = array(
2461
-            'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2462
-            'Registration.REG_count' => 1,
2463
-        );
2464
-
2465
-        if (isset($this->_req_data['EVT_ID'])) {
2466
-            $_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2467
-        }
2468
-
2469
-        if (isset($this->_req_data['s'])) {
2470
-            $search_string = '%' . $this->_req_data['s'] . '%';
2471
-            $_where['OR'] = array(
2472
-                'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2473
-                'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2474
-                'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2475
-                'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2476
-                'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2477
-                'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2478
-                'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2479
-                'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2480
-                'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2481
-                'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2482
-                'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2483
-                'Registration.REG_final_price'        => array('LIKE', $search_string),
2484
-                'Registration.REG_code'               => array('LIKE', $search_string),
2485
-                'Registration.REG_count'              => array('LIKE', $search_string),
2486
-                'Registration.REG_group_size'         => array('LIKE', $search_string),
2487
-                'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2488
-                'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2489
-                'Payment.PAY_source'                  => array('LIKE', $search_string),
2490
-                'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2491
-                'TXN_session_data'                    => array('LIKE', $search_string),
2492
-                'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2493
-            );
2494
-        }
2495
-
2496
-        // failed transactions
2497
-        $failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2498
-                  || ($count && $view === 'failed');
2499
-        $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2500
-                     || ($count && $view === 'abandoned');
2501
-        $incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count)
2502
-                      || ($count && $view === 'incomplete');
2503
-
2504
-        if ($failed) {
2505
-            $_where['STS_ID'] = EEM_Transaction::failed_status_code;
2506
-        } elseif ($abandoned) {
2507
-            $_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2508
-        } elseif ($incomplete) {
2509
-            $_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2510
-        } else {
2511
-            $_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2512
-            $_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2513
-        }
2514
-
2515
-        $query_params = apply_filters(
2516
-            'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2517
-            array(
2518
-                $_where,
2519
-                'order_by'                 => array($orderby => $sort),
2520
-                'limit'                    => $limit,
2521
-                'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2522
-            ),
2523
-            $this->_req_data,
2524
-            $view,
2525
-            $count
2526
-        );
2527
-
2528
-        $transactions = $count
2529
-            ? $TXN->count(array($query_params[0]), 'TXN_ID', true)
2530
-            : $TXN->get_all($query_params);
2531
-
2532
-        return $transactions;
2533
-    }
2534
-
2535
-
2536
-    /**
2537
-     * @since 4.9.79.p
2538
-     * @throws EE_Error
2539
-     * @throws InvalidArgumentException
2540
-     * @throws InvalidDataTypeException
2541
-     * @throws InvalidInterfaceException
2542
-     * @throws ReflectionException
2543
-     * @throws RuntimeException
2544
-     */
2545
-    public function recalculateLineItems()
2546
-    {
2547
-        $TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2548
-        /** @var EE_Transaction $transaction */
2549
-        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2550
-        $total_line_item = $transaction->total_line_item(false);
2551
-        $success = $transaction->recalculateLineItems();
2552
-        $this->_redirect_after_action(
2553
-            (bool) $success,
2554
-            esc_html__('Transaction taxes and totals', 'event_espresso'),
2555
-            esc_html__('recalculated', 'event_espresso'),
2556
-            isset($this->_req_data['redirect_to'])
2557
-                ? array(
2558
-                'action' => $this->_req_data['redirect_to'],
2559
-                'TXN_ID' => $this->_req_data['TXN_ID'],
2560
-            )
2561
-                : array(),
2562
-            true
2563
-        );
2564
-    }
16
+	/**
17
+	 * @var EE_Transaction
18
+	 */
19
+	private $_transaction;
20
+
21
+	/**
22
+	 * @var EE_Session
23
+	 */
24
+	private $_session;
25
+
26
+	/**
27
+	 * @var array $_txn_status
28
+	 */
29
+	private static $_txn_status;
30
+
31
+	/**
32
+	 * @var array $_pay_status
33
+	 */
34
+	private static $_pay_status;
35
+
36
+	/**
37
+	 * @var array $_existing_reg_payment_REG_IDs
38
+	 */
39
+	protected $_existing_reg_payment_REG_IDs;
40
+
41
+
42
+	/**
43
+	 *    _init_page_props
44
+	 *
45
+	 * @return void
46
+	 */
47
+	protected function _init_page_props()
48
+	{
49
+		$this->page_slug = TXN_PG_SLUG;
50
+		$this->page_label = esc_html__('Transactions', 'event_espresso');
51
+		$this->_admin_base_url = TXN_ADMIN_URL;
52
+		$this->_admin_base_path = TXN_ADMIN;
53
+	}
54
+
55
+
56
+	/**
57
+	 *    _ajax_hooks
58
+	 *
59
+	 * @return void
60
+	 */
61
+	protected function _ajax_hooks()
62
+	{
63
+		add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
64
+		add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
65
+		add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
66
+	}
67
+
68
+
69
+	/**
70
+	 *    _define_page_props
71
+	 *
72
+	 * @return void
73
+	 */
74
+	protected function _define_page_props()
75
+	{
76
+		$this->_admin_page_title = $this->page_label;
77
+		$this->_labels = array(
78
+			'buttons' => array(
79
+				'add'    => esc_html__('Add New Transaction', 'event_espresso'),
80
+				'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
81
+				'delete' => esc_html__('Delete Transaction', 'event_espresso'),
82
+			),
83
+		);
84
+	}
85
+
86
+
87
+	/**
88
+	 *        grab url requests and route them
89
+	 *
90
+	 * @access private
91
+	 * @return void
92
+	 * @throws EE_Error
93
+	 * @throws InvalidArgumentException
94
+	 * @throws InvalidDataTypeException
95
+	 * @throws InvalidInterfaceException
96
+	 */
97
+	public function _set_page_routes()
98
+	{
99
+
100
+		$this->_set_transaction_status_array();
101
+
102
+		$txn_id = ! empty($this->_req_data['TXN_ID'])
103
+				  && ! is_array($this->_req_data['TXN_ID'])
104
+			? $this->_req_data['TXN_ID']
105
+			: 0;
106
+
107
+		$this->_page_routes = array(
108
+
109
+			'default' => array(
110
+				'func'       => '_transactions_overview_list_table',
111
+				'capability' => 'ee_read_transactions',
112
+			),
113
+
114
+			'view_transaction' => array(
115
+				'func'       => '_transaction_details',
116
+				'capability' => 'ee_read_transaction',
117
+				'obj_id'     => $txn_id,
118
+			),
119
+
120
+			'send_payment_reminder' => array(
121
+				'func'       => '_send_payment_reminder',
122
+				'noheader'   => true,
123
+				'capability' => 'ee_send_message',
124
+			),
125
+
126
+			'espresso_apply_payment' => array(
127
+				'func'       => 'apply_payments_or_refunds',
128
+				'noheader'   => true,
129
+				'capability' => 'ee_edit_payments',
130
+			),
131
+
132
+			'espresso_apply_refund' => array(
133
+				'func'       => 'apply_payments_or_refunds',
134
+				'noheader'   => true,
135
+				'capability' => 'ee_edit_payments',
136
+			),
137
+
138
+			'espresso_delete_payment' => array(
139
+				'func'       => 'delete_payment',
140
+				'noheader'   => true,
141
+				'capability' => 'ee_delete_payments',
142
+			),
143
+
144
+			'espresso_recalculate_line_items' => array(
145
+				'func'       => 'recalculateLineItems',
146
+				'noheader'   => true,
147
+				'capability' => 'ee_edit_payments',
148
+			),
149
+
150
+		);
151
+	}
152
+
153
+
154
+	protected function _set_page_config()
155
+	{
156
+		$this->_page_config = array(
157
+			'default'          => array(
158
+				'nav'           => array(
159
+					'label' => esc_html__('Overview', 'event_espresso'),
160
+					'order' => 10,
161
+				),
162
+				'list_table'    => 'EE_Admin_Transactions_List_Table',
163
+				'help_tabs'     => array(
164
+					'transactions_overview_help_tab'                       => array(
165
+						'title'    => esc_html__('Transactions Overview', 'event_espresso'),
166
+						'filename' => 'transactions_overview',
167
+					),
168
+					'transactions_overview_table_column_headings_help_tab' => array(
169
+						'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
170
+						'filename' => 'transactions_overview_table_column_headings',
171
+					),
172
+					'transactions_overview_views_filters_help_tab'         => array(
173
+						'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
174
+						'filename' => 'transactions_overview_views_filters_search',
175
+					),
176
+				),
177
+				'help_tour'     => array('Transactions_Overview_Help_Tour'),
178
+				/**
179
+				 * commented out because currently we are not displaying tips for transaction list table status but this
180
+				 * may change in a later iteration so want to keep the code for then.
181
+				 */
182
+				// 'qtips' => array( 'Transactions_List_Table_Tips' ),
183
+				'require_nonce' => false,
184
+			),
185
+			'view_transaction' => array(
186
+				'nav'       => array(
187
+					'label'      => esc_html__('View Transaction', 'event_espresso'),
188
+					'order'      => 5,
189
+					'url'        => isset($this->_req_data['TXN_ID'])
190
+						? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
191
+						: $this->_admin_base_url,
192
+					'persistent' => false,
193
+				),
194
+				'help_tabs' => array(
195
+					'transactions_view_transaction_help_tab'                                              => array(
196
+						'title'    => esc_html__('View Transaction', 'event_espresso'),
197
+						'filename' => 'transactions_view_transaction',
198
+					),
199
+					'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
200
+						'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
201
+						'filename' => 'transactions_view_transaction_transaction_details_table',
202
+					),
203
+					'transactions_view_transaction_attendees_registered_help_tab'                         => array(
204
+						'title'    => esc_html__('Attendees Registered', 'event_espresso'),
205
+						'filename' => 'transactions_view_transaction_attendees_registered',
206
+					),
207
+					'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
208
+						'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
209
+						'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
210
+					),
211
+				),
212
+				'qtips'     => array('Transaction_Details_Tips'),
213
+				'help_tour' => array('Transaction_Details_Help_Tour'),
214
+				'metaboxes' => array('_transaction_details_metaboxes'),
215
+
216
+				'require_nonce' => false,
217
+			),
218
+		);
219
+	}
220
+
221
+
222
+	/**
223
+	 * The below methods aren't used by this class currently
224
+	 */
225
+	protected function _add_screen_options()
226
+	{
227
+		// noop
228
+	}
229
+
230
+
231
+	protected function _add_feature_pointers()
232
+	{
233
+		// noop
234
+	}
235
+
236
+
237
+	public function admin_init()
238
+	{
239
+		// IF a registration was JUST added via the admin...
240
+		if (isset(
241
+			$this->_req_data['redirect_from'],
242
+			$this->_req_data['EVT_ID'],
243
+			$this->_req_data['event_name']
244
+		)) {
245
+			// then set a cookie so that we can block any attempts to use
246
+			// the back button as a way to enter another registration.
247
+			setcookie(
248
+				'ee_registration_added',
249
+				$this->_req_data['EVT_ID'],
250
+				time() + WEEK_IN_SECONDS,
251
+				'/'
252
+			);
253
+			// and update the global
254
+			$_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
255
+		}
256
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
257
+			'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
258
+			'event_espresso'
259
+		);
260
+		EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
261
+			'An error occurred! Please refresh the page and try again.',
262
+			'event_espresso'
263
+		);
264
+		EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
265
+		EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
266
+		EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
267
+		EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
268
+			'This transaction has been overpaid ! Payments Total',
269
+			'event_espresso'
270
+		);
271
+	}
272
+
273
+
274
+	public function admin_notices()
275
+	{
276
+		// noop
277
+	}
278
+
279
+
280
+	public function admin_footer_scripts()
281
+	{
282
+		// noop
283
+	}
284
+
285
+
286
+	/**
287
+	 * _set_transaction_status_array
288
+	 * sets list of transaction statuses
289
+	 *
290
+	 * @access private
291
+	 * @return void
292
+	 * @throws EE_Error
293
+	 * @throws InvalidArgumentException
294
+	 * @throws InvalidDataTypeException
295
+	 * @throws InvalidInterfaceException
296
+	 */
297
+	private function _set_transaction_status_array()
298
+	{
299
+		self::$_txn_status = EEM_Transaction::instance()->status_array(true);
300
+	}
301
+
302
+
303
+	/**
304
+	 * get_transaction_status_array
305
+	 * return the transaction status array for wp_list_table
306
+	 *
307
+	 * @access public
308
+	 * @return array
309
+	 */
310
+	public function get_transaction_status_array()
311
+	{
312
+		return self::$_txn_status;
313
+	}
314
+
315
+
316
+	/**
317
+	 *    get list of payment statuses
318
+	 *
319
+	 * @access private
320
+	 * @return void
321
+	 * @throws EE_Error
322
+	 * @throws InvalidArgumentException
323
+	 * @throws InvalidDataTypeException
324
+	 * @throws InvalidInterfaceException
325
+	 */
326
+	private function _get_payment_status_array()
327
+	{
328
+		self::$_pay_status = EEM_Payment::instance()->status_array(true);
329
+		$this->_template_args['payment_status'] = self::$_pay_status;
330
+	}
331
+
332
+
333
+	/**
334
+	 *    _add_screen_options_default
335
+	 *
336
+	 * @access protected
337
+	 * @return void
338
+	 * @throws InvalidArgumentException
339
+	 * @throws InvalidDataTypeException
340
+	 * @throws InvalidInterfaceException
341
+	 */
342
+	protected function _add_screen_options_default()
343
+	{
344
+		$this->_per_page_screen_option();
345
+	}
346
+
347
+
348
+	/**
349
+	 * load_scripts_styles
350
+	 *
351
+	 * @access public
352
+	 * @return void
353
+	 */
354
+	public function load_scripts_styles()
355
+	{
356
+		// enqueue style
357
+		wp_register_style(
358
+			'espresso_txn',
359
+			TXN_ASSETS_URL . 'espresso_transactions_admin.css',
360
+			array(),
361
+			EVENT_ESPRESSO_VERSION
362
+		);
363
+		wp_enqueue_style('espresso_txn');
364
+		// scripts
365
+		wp_register_script(
366
+			'espresso_txn',
367
+			TXN_ASSETS_URL . 'espresso_transactions_admin.js',
368
+			array(
369
+				'ee_admin_js',
370
+				'ee-datepicker',
371
+				'jquery-ui-datepicker',
372
+				'jquery-ui-draggable',
373
+				'ee-dialog',
374
+				'ee-accounting',
375
+				'ee-serialize-full-array',
376
+			),
377
+			EVENT_ESPRESSO_VERSION,
378
+			true
379
+		);
380
+		wp_enqueue_script('espresso_txn');
381
+	}
382
+
383
+
384
+	/**
385
+	 *    load_scripts_styles_view_transaction
386
+	 *
387
+	 * @access public
388
+	 * @return void
389
+	 */
390
+	public function load_scripts_styles_view_transaction()
391
+	{
392
+		// styles
393
+		wp_enqueue_style('espresso-ui-theme');
394
+	}
395
+
396
+
397
+	/**
398
+	 *    load_scripts_styles_default
399
+	 *
400
+	 * @access public
401
+	 * @return void
402
+	 */
403
+	public function load_scripts_styles_default()
404
+	{
405
+		// styles
406
+		wp_enqueue_style('espresso-ui-theme');
407
+	}
408
+
409
+
410
+	/**
411
+	 *    _set_list_table_views_default
412
+	 *
413
+	 * @access protected
414
+	 * @return void
415
+	 */
416
+	protected function _set_list_table_views_default()
417
+	{
418
+		$this->_views = array(
419
+			'all'        => array(
420
+				'slug'  => 'all',
421
+				'label' => esc_html__('View All Transactions', 'event_espresso'),
422
+				'count' => 0,
423
+			),
424
+			'abandoned'  => array(
425
+				'slug'  => 'abandoned',
426
+				'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
427
+				'count' => 0,
428
+			),
429
+			'incomplete' => array(
430
+				'slug'  => 'incomplete',
431
+				'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
432
+				'count' => 0,
433
+			),
434
+		);
435
+		if (/**
436
+		 * Filters whether a link to the "Failed Transactions" list table
437
+		 * appears on the Transactions Admin Page list table.
438
+		 * List display can be turned back on via the following:
439
+		 * add_filter(
440
+		 *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
441
+		 *     '__return_true'
442
+		 * );
443
+		 *
444
+		 * @since 4.9.70.p
445
+		 * @param boolean                 $display_failed_txns_list
446
+		 * @param Transactions_Admin_Page $this
447
+		 */
448
+		apply_filters(
449
+			'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
450
+			false,
451
+			$this
452
+		)
453
+		) {
454
+			$this->_views['failed'] = array(
455
+				'slug'  => 'failed',
456
+				'label' => esc_html__('Failed Transactions', 'event_espresso'),
457
+				'count' => 0,
458
+			);
459
+		}
460
+	}
461
+
462
+
463
+	/**
464
+	 * _set_transaction_object
465
+	 * This sets the _transaction property for the transaction details screen
466
+	 *
467
+	 * @access private
468
+	 * @return void
469
+	 * @throws EE_Error
470
+	 * @throws InvalidArgumentException
471
+	 * @throws RuntimeException
472
+	 * @throws InvalidDataTypeException
473
+	 * @throws InvalidInterfaceException
474
+	 * @throws ReflectionException
475
+	 */
476
+	private function _set_transaction_object()
477
+	{
478
+		if ($this->_transaction instanceof EE_Transaction) {
479
+			return;
480
+		} //get out we've already set the object
481
+
482
+		$TXN_ID = ! empty($this->_req_data['TXN_ID'])
483
+			? absint($this->_req_data['TXN_ID'])
484
+			: false;
485
+
486
+		// get transaction object
487
+		$this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
488
+		$this->_session = $this->_transaction instanceof EE_Transaction
489
+			? $this->_transaction->session_data()
490
+			: null;
491
+		if ($this->_transaction instanceof EE_Transaction) {
492
+			$this->_transaction->verify_abandoned_transaction_status();
493
+		}
494
+
495
+		if (! $this->_transaction instanceof EE_Transaction) {
496
+			$error_msg = sprintf(
497
+				esc_html__(
498
+					'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
499
+					'event_espresso'
500
+				),
501
+				$TXN_ID
502
+			);
503
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
504
+		}
505
+	}
506
+
507
+
508
+	/**
509
+	 *    _transaction_legend_items
510
+	 *
511
+	 * @access protected
512
+	 * @return array
513
+	 * @throws EE_Error
514
+	 * @throws InvalidArgumentException
515
+	 * @throws ReflectionException
516
+	 * @throws InvalidDataTypeException
517
+	 * @throws InvalidInterfaceException
518
+	 */
519
+	protected function _transaction_legend_items()
520
+	{
521
+		EE_Registry::instance()->load_helper('MSG_Template');
522
+		$items = array();
523
+
524
+		if (EE_Registry::instance()->CAP->current_user_can(
525
+			'ee_read_global_messages',
526
+			'view_filtered_messages'
527
+		)) {
528
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
529
+			if (is_array($related_for_icon)
530
+				&& isset($related_for_icon['css_class'], $related_for_icon['label'])
531
+			) {
532
+				$items['view_related_messages'] = array(
533
+					'class' => $related_for_icon['css_class'],
534
+					'desc'  => $related_for_icon['label'],
535
+				);
536
+			}
537
+		}
538
+
539
+		$items = apply_filters(
540
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
541
+			array_merge(
542
+				$items,
543
+				array(
544
+					'view_details'          => array(
545
+						'class' => 'dashicons dashicons-cart',
546
+						'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
547
+					),
548
+					'view_invoice'          => array(
549
+						'class' => 'dashicons dashicons-media-spreadsheet',
550
+						'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
551
+					),
552
+					'view_receipt'          => array(
553
+						'class' => 'dashicons dashicons-media-default',
554
+						'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
555
+					),
556
+					'view_registration'     => array(
557
+						'class' => 'dashicons dashicons-clipboard',
558
+						'desc'  => esc_html__('View Registration Details', 'event_espresso'),
559
+					),
560
+					'payment_overview_link' => array(
561
+						'class' => 'dashicons dashicons-money',
562
+						'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
563
+					),
564
+				)
565
+			)
566
+		);
567
+
568
+		if (EEH_MSG_Template::is_mt_active('payment_reminder')
569
+			&& EE_Registry::instance()->CAP->current_user_can(
570
+				'ee_send_message',
571
+				'espresso_transactions_send_payment_reminder'
572
+			)
573
+		) {
574
+			$items['send_payment_reminder'] = array(
575
+				'class' => 'dashicons dashicons-email-alt',
576
+				'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
577
+			);
578
+		}
579
+		$more_items = apply_filters(
580
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
581
+			array(
582
+				'overpaid'   => array(
583
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
584
+					'desc'  => EEH_Template::pretty_status(
585
+						EEM_Transaction::overpaid_status_code,
586
+						false,
587
+						'sentence'
588
+					),
589
+				),
590
+				'complete'   => array(
591
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
592
+					'desc'  => EEH_Template::pretty_status(
593
+						EEM_Transaction::complete_status_code,
594
+						false,
595
+						'sentence'
596
+					),
597
+				),
598
+				'incomplete' => array(
599
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
600
+					'desc'  => EEH_Template::pretty_status(
601
+						EEM_Transaction::incomplete_status_code,
602
+						false,
603
+						'sentence'
604
+					),
605
+				),
606
+				'abandoned'  => array(
607
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
608
+					'desc'  => EEH_Template::pretty_status(
609
+						EEM_Transaction::abandoned_status_code,
610
+						false,
611
+						'sentence'
612
+					),
613
+				),
614
+				'failed'     => array(
615
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
616
+					'desc'  => EEH_Template::pretty_status(
617
+						EEM_Transaction::failed_status_code,
618
+						false,
619
+						'sentence'
620
+					),
621
+				),
622
+			)
623
+		);
624
+
625
+		return array_merge($items, $more_items);
626
+	}
627
+
628
+
629
+	/**
630
+	 *    _transactions_overview_list_table
631
+	 *
632
+	 * @access protected
633
+	 * @return void
634
+	 * @throws DomainException
635
+	 * @throws EE_Error
636
+	 * @throws InvalidArgumentException
637
+	 * @throws InvalidDataTypeException
638
+	 * @throws InvalidInterfaceException
639
+	 * @throws ReflectionException
640
+	 */
641
+	protected function _transactions_overview_list_table()
642
+	{
643
+		$this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
644
+		$event = isset($this->_req_data['EVT_ID'])
645
+			? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
646
+			: null;
647
+		$this->_template_args['admin_page_header'] = $event instanceof EE_Event
648
+			? sprintf(
649
+				esc_html__(
650
+					'%sViewing Transactions for the Event: %s%s',
651
+					'event_espresso'
652
+				),
653
+				'<h3>',
654
+				'<a href="'
655
+				. EE_Admin_Page::add_query_args_and_nonce(
656
+					array('action' => 'edit', 'post' => $event->ID()),
657
+					EVENTS_ADMIN_URL
658
+				)
659
+				. '" title="'
660
+				. esc_attr__(
661
+					'Click to Edit event',
662
+					'event_espresso'
663
+				)
664
+				. '">' . $event->name() . '</a>',
665
+				'</h3>'
666
+			)
667
+			: '';
668
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
669
+		$this->display_admin_list_table_page_with_no_sidebar();
670
+	}
671
+
672
+
673
+	/**
674
+	 *    _transaction_details
675
+	 * generates HTML for the View Transaction Details Admin page
676
+	 *
677
+	 * @access protected
678
+	 * @return void
679
+	 * @throws DomainException
680
+	 * @throws EE_Error
681
+	 * @throws InvalidArgumentException
682
+	 * @throws InvalidDataTypeException
683
+	 * @throws InvalidInterfaceException
684
+	 * @throws RuntimeException
685
+	 * @throws ReflectionException
686
+	 */
687
+	protected function _transaction_details()
688
+	{
689
+		do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
690
+
691
+		$this->_set_transaction_status_array();
692
+
693
+		$this->_template_args = array();
694
+		$this->_template_args['transactions_page'] = $this->_wp_page_slug;
695
+
696
+		$this->_set_transaction_object();
697
+
698
+		if (! $this->_transaction instanceof EE_Transaction) {
699
+			return;
700
+		}
701
+		$primary_registration = $this->_transaction->primary_registration();
702
+		$attendee = $primary_registration instanceof EE_Registration
703
+			? $primary_registration->attendee()
704
+			: null;
705
+
706
+		$this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
707
+		$this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
708
+
709
+		$this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
710
+		$this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
711
+
712
+		$this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->status_ID() ];
713
+		$this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
714
+		$this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->status_ID();
715
+
716
+		$this->_template_args['grand_total'] = $this->_transaction->total();
717
+		$this->_template_args['total_paid'] = $this->_transaction->paid();
718
+
719
+		$amount_due = $this->_transaction->total() - $this->_transaction->paid();
720
+		$this->_template_args['amount_due'] = EEH_Template::format_currency(
721
+			$amount_due,
722
+			true
723
+		);
724
+		if (EE_Registry::instance()->CFG->currency->sign_b4) {
725
+			$this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
726
+												  . $this->_template_args['amount_due'];
727
+		} else {
728
+			$this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
729
+		}
730
+		$this->_template_args['amount_due_class'] = '';
731
+
732
+		if ($this->_transaction->paid() === $this->_transaction->total()) {
733
+			// paid in full
734
+			$this->_template_args['amount_due'] = false;
735
+		} elseif ($this->_transaction->paid() > $this->_transaction->total()) {
736
+			// overpaid
737
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
738
+		} elseif ($this->_transaction->total() > (float) 0) {
739
+			if ($this->_transaction->paid() > (float) 0) {
740
+				// monies owing
741
+				$this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
742
+			} elseif ($this->_transaction->paid() === (float) 0) {
743
+				// no payments made yet
744
+				$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
745
+			}
746
+		} elseif ($this->_transaction->total() === (float) 0) {
747
+			// free event
748
+			$this->_template_args['amount_due'] = false;
749
+		}
750
+
751
+		$payment_method = $this->_transaction->payment_method();
752
+
753
+		$this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
754
+			? $payment_method->admin_name()
755
+			: esc_html__('Unknown', 'event_espresso');
756
+
757
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
758
+		// link back to overview
759
+		$this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
760
+			? $_SERVER['HTTP_REFERER']
761
+			: TXN_ADMIN_URL;
762
+
763
+
764
+		// next link
765
+		$next_txn = $this->_transaction->next(
766
+			null,
767
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
768
+			'TXN_ID'
769
+		);
770
+		$this->_template_args['next_transaction'] = $next_txn
771
+			? $this->_next_link(
772
+				EE_Admin_Page::add_query_args_and_nonce(
773
+					array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
774
+					TXN_ADMIN_URL
775
+				),
776
+				'dashicons dashicons-arrow-right ee-icon-size-22'
777
+			)
778
+			: '';
779
+		// previous link
780
+		$previous_txn = $this->_transaction->previous(
781
+			null,
782
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
783
+			'TXN_ID'
784
+		);
785
+		$this->_template_args['previous_transaction'] = $previous_txn
786
+			? $this->_previous_link(
787
+				EE_Admin_Page::add_query_args_and_nonce(
788
+					array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
789
+					TXN_ADMIN_URL
790
+				),
791
+				'dashicons dashicons-arrow-left ee-icon-size-22'
792
+			)
793
+			: '';
794
+
795
+		// were we just redirected here after adding a new registration ???
796
+		if (isset(
797
+			$this->_req_data['redirect_from'],
798
+			$this->_req_data['EVT_ID'],
799
+			$this->_req_data['event_name']
800
+		)) {
801
+			if (EE_Registry::instance()->CAP->current_user_can(
802
+				'ee_edit_registrations',
803
+				'espresso_registrations_new_registration',
804
+				$this->_req_data['EVT_ID']
805
+			)) {
806
+				$this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
807
+				$this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
808
+					array(
809
+						'page'     => 'espresso_registrations',
810
+						'action'   => 'new_registration',
811
+						'return'   => 'default',
812
+						'TXN_ID'   => $this->_transaction->ID(),
813
+						'event_id' => $this->_req_data['EVT_ID'],
814
+					),
815
+					REG_ADMIN_URL
816
+				);
817
+				$this->_admin_page_title .= '">';
818
+
819
+				$this->_admin_page_title .= sprintf(
820
+					esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
821
+					htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
822
+				);
823
+				$this->_admin_page_title .= '</a>';
824
+			}
825
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
826
+		}
827
+		// grab messages at the last second
828
+		$this->_template_args['notices'] = EE_Error::get_notices();
829
+		// path to template
830
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
831
+		$this->_template_args['admin_page_header'] = EEH_Template::display_template(
832
+			$template_path,
833
+			$this->_template_args,
834
+			true
835
+		);
836
+
837
+		// the details template wrapper
838
+		$this->display_admin_page_with_sidebar();
839
+	}
840
+
841
+
842
+	/**
843
+	 *        _transaction_details_metaboxes
844
+	 *
845
+	 * @access protected
846
+	 * @return void
847
+	 * @throws EE_Error
848
+	 * @throws InvalidArgumentException
849
+	 * @throws InvalidDataTypeException
850
+	 * @throws InvalidInterfaceException
851
+	 * @throws RuntimeException
852
+	 * @throws ReflectionException
853
+	 */
854
+	protected function _transaction_details_metaboxes()
855
+	{
856
+
857
+		$this->_set_transaction_object();
858
+
859
+		if (! $this->_transaction instanceof EE_Transaction) {
860
+			return;
861
+		}
862
+		add_meta_box(
863
+			'edit-txn-details-mbox',
864
+			esc_html__('Transaction Details', 'event_espresso'),
865
+			array($this, 'txn_details_meta_box'),
866
+			$this->_wp_page_slug,
867
+			'normal',
868
+			'high'
869
+		);
870
+		add_meta_box(
871
+			'edit-txn-attendees-mbox',
872
+			esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
873
+			array($this, 'txn_attendees_meta_box'),
874
+			$this->_wp_page_slug,
875
+			'normal',
876
+			'high',
877
+			array('TXN_ID' => $this->_transaction->ID())
878
+		);
879
+		add_meta_box(
880
+			'edit-txn-registrant-mbox',
881
+			esc_html__('Primary Contact', 'event_espresso'),
882
+			array($this, 'txn_registrant_side_meta_box'),
883
+			$this->_wp_page_slug,
884
+			'side',
885
+			'high'
886
+		);
887
+		add_meta_box(
888
+			'edit-txn-billing-info-mbox',
889
+			esc_html__('Billing Information', 'event_espresso'),
890
+			array($this, 'txn_billing_info_side_meta_box'),
891
+			$this->_wp_page_slug,
892
+			'side',
893
+			'high'
894
+		);
895
+	}
896
+
897
+
898
+	/**
899
+	 * Callback for transaction actions metabox.
900
+	 *
901
+	 * @param EE_Transaction|null $transaction
902
+	 * @return string
903
+	 * @throws DomainException
904
+	 * @throws EE_Error
905
+	 * @throws InvalidArgumentException
906
+	 * @throws InvalidDataTypeException
907
+	 * @throws InvalidInterfaceException
908
+	 * @throws ReflectionException
909
+	 * @throws RuntimeException
910
+	 */
911
+	public function getActionButtons(EE_Transaction $transaction = null)
912
+	{
913
+		$content = '';
914
+		$actions = array();
915
+		if (! $transaction instanceof EE_Transaction) {
916
+			return $content;
917
+		}
918
+		/** @var EE_Registration $primary_registration */
919
+		$primary_registration = $transaction->primary_registration();
920
+		$attendee = $primary_registration instanceof EE_Registration
921
+			? $primary_registration->attendee()
922
+			: null;
923
+
924
+		if ($attendee instanceof EE_Attendee
925
+			&& EE_Registry::instance()->CAP->current_user_can(
926
+				'ee_send_message',
927
+				'espresso_transactions_send_payment_reminder'
928
+			)
929
+		) {
930
+			$actions['payment_reminder'] =
931
+				EEH_MSG_Template::is_mt_active('payment_reminder')
932
+				&& $this->_transaction->status_ID() !== EEM_Transaction::complete_status_code
933
+				&& $this->_transaction->status_ID() !== EEM_Transaction::overpaid_status_code
934
+					? EEH_Template::get_button_or_link(
935
+						EE_Admin_Page::add_query_args_and_nonce(
936
+							array(
937
+								'action'      => 'send_payment_reminder',
938
+								'TXN_ID'      => $this->_transaction->ID(),
939
+								'redirect_to' => 'view_transaction',
940
+							),
941
+							TXN_ADMIN_URL
942
+						),
943
+						esc_html__(' Send Payment Reminder', 'event_espresso'),
944
+						'button secondary-button',
945
+						'dashicons dashicons-email-alt'
946
+					)
947
+					: '';
948
+		}
949
+
950
+		if (EE_Registry::instance()->CAP->current_user_can(
951
+			'ee_edit_payments',
952
+			'espresso_transactions_recalculate_line_items'
953
+		)
954
+		) {
955
+			$actions['recalculate_line_items'] = EEH_Template::get_button_or_link(
956
+				EE_Admin_Page::add_query_args_and_nonce(
957
+					array(
958
+						'action'      => 'espresso_recalculate_line_items',
959
+						'TXN_ID'      => $this->_transaction->ID(),
960
+						'redirect_to' => 'view_transaction',
961
+					),
962
+					TXN_ADMIN_URL
963
+				),
964
+				esc_html__(' Recalculate Taxes and Total', 'event_espresso'),
965
+				'button secondary-button',
966
+				'dashicons dashicons-update'
967
+			);
968
+		}
969
+
970
+		if ($primary_registration instanceof EE_Registration
971
+			&& EEH_MSG_Template::is_mt_active('receipt')
972
+		) {
973
+			$actions['receipt'] = EEH_Template::get_button_or_link(
974
+				$primary_registration->receipt_url(),
975
+				esc_html__('View Receipt', 'event_espresso'),
976
+				'button secondary-button',
977
+				'dashicons dashicons-media-default'
978
+			);
979
+		}
980
+
981
+		if ($primary_registration instanceof EE_Registration
982
+			&& EEH_MSG_Template::is_mt_active('invoice')
983
+		) {
984
+			$actions['invoice'] = EEH_Template::get_button_or_link(
985
+				$primary_registration->invoice_url(),
986
+				esc_html__('View Invoice', 'event_espresso'),
987
+				'button secondary-button',
988
+				'dashicons dashicons-media-spreadsheet'
989
+			);
990
+		}
991
+		$actions = array_filter(
992
+			apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
993
+		);
994
+		if ($actions) {
995
+			$content = '<ul>';
996
+			$content .= '<li>' . implode('</li><li>', $actions) . '</li>';
997
+			$content .= '</uL>';
998
+		}
999
+		return $content;
1000
+	}
1001
+
1002
+
1003
+	/**
1004
+	 * txn_details_meta_box
1005
+	 * generates HTML for the Transaction main meta box
1006
+	 *
1007
+	 * @return void
1008
+	 * @throws DomainException
1009
+	 * @throws EE_Error
1010
+	 * @throws InvalidArgumentException
1011
+	 * @throws InvalidDataTypeException
1012
+	 * @throws InvalidInterfaceException
1013
+	 * @throws RuntimeException
1014
+	 * @throws ReflectionException
1015
+	 */
1016
+	public function txn_details_meta_box()
1017
+	{
1018
+		$this->_set_transaction_object();
1019
+		$this->_template_args['TXN_ID'] = $this->_transaction->ID();
1020
+		$this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
1021
+			? $this->_transaction->primary_registration()->attendee()
1022
+			: null;
1023
+		$this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
1024
+			'ee_edit_payments',
1025
+			'apply_payment_or_refund_from_registration_details'
1026
+		);
1027
+		$this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1028
+			'ee_delete_payments',
1029
+			'delete_payment_from_registration_details'
1030
+		);
1031
+
1032
+		// get line table
1033
+		EEH_Autoloader::register_line_item_display_autoloaders();
1034
+		$Line_Item_Display = new EE_Line_Item_Display(
1035
+			'admin_table',
1036
+			'EE_Admin_Table_Line_Item_Display_Strategy'
1037
+		);
1038
+		$this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1039
+			$this->_transaction->total_line_item()
1040
+		);
1041
+		$this->_template_args['REG_code'] = $this->_transaction->primary_registration()->reg_code();
1042
+
1043
+		// process taxes
1044
+		$taxes = $this->_transaction->line_items(array(array('LIN_type' => EEM_Line_Item::type_tax)));
1045
+		$this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1046
+
1047
+		$this->_template_args['grand_total'] = EEH_Template::format_currency(
1048
+			$this->_transaction->total(),
1049
+			false,
1050
+			false
1051
+		);
1052
+		$this->_template_args['grand_raw_total'] = $this->_transaction->total();
1053
+		$this->_template_args['TXN_status'] = $this->_transaction->status_ID();
1054
+
1055
+		// process payment details
1056
+		$payments = $this->_transaction->payments();
1057
+		if (! empty($payments)) {
1058
+			$this->_template_args['payments'] = $payments;
1059
+			$this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1060
+		} else {
1061
+			$this->_template_args['payments'] = false;
1062
+			$this->_template_args['existing_reg_payments'] = array();
1063
+		}
1064
+
1065
+		$this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1066
+		$this->_template_args['delete_payment_url'] = add_query_arg(
1067
+			array('action' => 'espresso_delete_payment'),
1068
+			TXN_ADMIN_URL
1069
+		);
1070
+
1071
+		if (isset($txn_details['invoice_number'])) {
1072
+			$this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1073
+			$this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1074
+				'Invoice Number',
1075
+				'event_espresso'
1076
+			);
1077
+		}
1078
+
1079
+		$this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1080
+			->primary_registration()
1081
+			->session_ID();
1082
+		$this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1083
+			'Registration Session',
1084
+			'event_espresso'
1085
+		);
1086
+
1087
+		$this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1088
+			? $this->_session['ip_address']
1089
+			: '';
1090
+		$this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1091
+			'Transaction placed from IP',
1092
+			'event_espresso'
1093
+		);
1094
+
1095
+		$this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1096
+			? $this->_session['user_agent']
1097
+			: '';
1098
+		$this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1099
+			'Registrant User Agent',
1100
+			'event_espresso'
1101
+		);
1102
+
1103
+		$reg_steps = '<ul>';
1104
+		foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1105
+			if ($reg_step_status === true) {
1106
+				$reg_steps .= '<li style="color:#70cc50">'
1107
+							  . sprintf(
1108
+								  esc_html__('%1$s : Completed', 'event_espresso'),
1109
+								  ucwords(str_replace('_', ' ', $reg_step))
1110
+							  )
1111
+							  . '</li>';
1112
+			} elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1113
+				$reg_steps .= '<li style="color:#2EA2CC">'
1114
+							  . sprintf(
1115
+								  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1116
+								  ucwords(str_replace('_', ' ', $reg_step)),
1117
+								  date(
1118
+									  get_option('date_format') . ' ' . get_option('time_format'),
1119
+									  $reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1120
+								  )
1121
+							  )
1122
+							  . '</li>';
1123
+			} else {
1124
+				$reg_steps .= '<li style="color:#E76700">'
1125
+							  . sprintf(
1126
+								  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1127
+								  ucwords(str_replace('_', ' ', $reg_step))
1128
+							  )
1129
+							  . '</li>';
1130
+			}
1131
+		}
1132
+		$reg_steps .= '</ul>';
1133
+		$this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1134
+		$this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1135
+			'Registration Step Progress',
1136
+			'event_espresso'
1137
+		);
1138
+
1139
+
1140
+		$this->_get_registrations_to_apply_payment_to();
1141
+		$this->_get_payment_methods($payments);
1142
+		$this->_get_payment_status_array();
1143
+		$this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1144
+
1145
+		$this->_template_args['transaction_form_url'] = add_query_arg(
1146
+			array(
1147
+				'action'  => 'edit_transaction',
1148
+				'process' => 'transaction',
1149
+			),
1150
+			TXN_ADMIN_URL
1151
+		);
1152
+		$this->_template_args['apply_payment_form_url'] = add_query_arg(
1153
+			array(
1154
+				'page'   => 'espresso_transactions',
1155
+				'action' => 'espresso_apply_payment',
1156
+			),
1157
+			WP_AJAX_URL
1158
+		);
1159
+		$this->_template_args['delete_payment_form_url'] = add_query_arg(
1160
+			array(
1161
+				'page'   => 'espresso_transactions',
1162
+				'action' => 'espresso_delete_payment',
1163
+			),
1164
+			WP_AJAX_URL
1165
+		);
1166
+
1167
+		$this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1168
+
1169
+		// 'espresso_delete_payment_nonce'
1170
+
1171
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1172
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1173
+	}
1174
+
1175
+
1176
+	/**
1177
+	 * _get_registration_payment_IDs
1178
+	 *    generates an array of Payment IDs and their corresponding Registration IDs
1179
+	 *
1180
+	 * @access protected
1181
+	 * @param EE_Payment[] $payments
1182
+	 * @return array
1183
+	 * @throws EE_Error
1184
+	 * @throws InvalidArgumentException
1185
+	 * @throws InvalidDataTypeException
1186
+	 * @throws InvalidInterfaceException
1187
+	 * @throws ReflectionException
1188
+	 */
1189
+	protected function _get_registration_payment_IDs($payments = array())
1190
+	{
1191
+		$existing_reg_payments = array();
1192
+		// get all reg payments for these payments
1193
+		$reg_payments = EEM_Registration_Payment::instance()->get_all(
1194
+			array(
1195
+				array(
1196
+					'PAY_ID' => array(
1197
+						'IN',
1198
+						array_keys($payments),
1199
+					),
1200
+				),
1201
+			)
1202
+		);
1203
+		if (! empty($reg_payments)) {
1204
+			foreach ($payments as $payment) {
1205
+				if (! $payment instanceof EE_Payment) {
1206
+					continue;
1207
+				} elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1208
+					$existing_reg_payments[ $payment->ID() ] = array();
1209
+				}
1210
+				foreach ($reg_payments as $reg_payment) {
1211
+					if ($reg_payment instanceof EE_Registration_Payment
1212
+						&& $reg_payment->payment_ID() === $payment->ID()
1213
+					) {
1214
+						$existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1215
+					}
1216
+				}
1217
+			}
1218
+		}
1219
+
1220
+		return $existing_reg_payments;
1221
+	}
1222
+
1223
+
1224
+	/**
1225
+	 * _get_registrations_to_apply_payment_to
1226
+	 *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1227
+	 * which allows the admin to only apply the payment to the specific registrations
1228
+	 *
1229
+	 * @access protected
1230
+	 * @return void
1231
+	 * @throws EE_Error
1232
+	 * @throws InvalidArgumentException
1233
+	 * @throws InvalidDataTypeException
1234
+	 * @throws InvalidInterfaceException
1235
+	 * @throws ReflectionException
1236
+	 */
1237
+	protected function _get_registrations_to_apply_payment_to()
1238
+	{
1239
+		// we want any registration with an active status (ie: not deleted or cancelled)
1240
+		$query_params = array(
1241
+			array(
1242
+				'STS_ID' => array(
1243
+					'IN',
1244
+					array(
1245
+						EEM_Registration::status_id_approved,
1246
+						EEM_Registration::status_id_pending_payment,
1247
+						EEM_Registration::status_id_not_approved,
1248
+					),
1249
+				),
1250
+			),
1251
+		);
1252
+		$registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
1253
+			'',
1254
+			'txn-admin-apply-payment-to-registrations-dv',
1255
+			'',
1256
+			'clear: both; margin: 1.5em 0 0; display: none;'
1257
+		);
1258
+		$registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1259
+		$registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1260
+		$registrations_to_apply_payment_to .= EEH_HTML::thead(
1261
+			EEH_HTML::tr(
1262
+				EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1263
+				EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1264
+				EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1265
+				EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1266
+				EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1267
+				EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1268
+				EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1269
+			)
1270
+		);
1271
+		$registrations_to_apply_payment_to .= EEH_HTML::tbody();
1272
+		// get registrations for TXN
1273
+		$registrations = $this->_transaction->registrations($query_params);
1274
+		$existing_reg_payments = $this->_template_args['existing_reg_payments'];
1275
+		foreach ($registrations as $registration) {
1276
+			if ($registration instanceof EE_Registration) {
1277
+				$attendee_name = $registration->attendee() instanceof EE_Attendee
1278
+					? $registration->attendee()->full_name()
1279
+					: esc_html__('Unknown Attendee', 'event_espresso');
1280
+				$owing = $registration->final_price() - $registration->paid();
1281
+				$taxable = $registration->ticket()->taxable()
1282
+					? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1283
+					: '';
1284
+				$checked = empty($existing_reg_payments)
1285
+						   || in_array($registration->ID(), $existing_reg_payments, true)
1286
+					? ' checked="checked"'
1287
+					: '';
1288
+				$disabled = $registration->final_price() > 0 ? '' : ' disabled';
1289
+				$registrations_to_apply_payment_to .= EEH_HTML::tr(
1290
+					EEH_HTML::td($registration->ID()) .
1291
+					EEH_HTML::td($attendee_name) .
1292
+					EEH_HTML::td(
1293
+						$registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1294
+					) .
1295
+					EEH_HTML::td($registration->event_name()) .
1296
+					EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1297
+					EEH_HTML::td(
1298
+						EEH_Template::format_currency($owing),
1299
+						'',
1300
+						'txn-admin-payment-owing-td jst-cntr'
1301
+					) .
1302
+					EEH_HTML::td(
1303
+						'<input type="checkbox" value="' . $registration->ID()
1304
+						. '" name="txn_admin_payment[registrations]"'
1305
+						. $checked . $disabled . '>',
1306
+						'',
1307
+						'jst-cntr'
1308
+					),
1309
+					'apply-payment-registration-row-' . $registration->ID()
1310
+				);
1311
+			}
1312
+		}
1313
+		$registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1314
+		$registrations_to_apply_payment_to .= EEH_HTML::tablex();
1315
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1316
+		$registrations_to_apply_payment_to .= EEH_HTML::p(
1317
+			esc_html__(
1318
+				'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1319
+				'event_espresso'
1320
+			),
1321
+			'',
1322
+			'clear description'
1323
+		);
1324
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1325
+		$this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1326
+	}
1327
+
1328
+
1329
+	/**
1330
+	 * _get_reg_status_selection
1331
+	 *
1332
+	 * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1333
+	 *         instead of events.
1334
+	 * @access protected
1335
+	 * @return void
1336
+	 * @throws EE_Error
1337
+	 */
1338
+	protected function _get_reg_status_selection()
1339
+	{
1340
+		// first get all possible statuses
1341
+		$statuses = EEM_Registration::reg_status_array(array(), true);
1342
+		// let's add a "don't change" option.
1343
+		$status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1344
+		$status_array = array_merge($status_array, $statuses);
1345
+		$this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1346
+			'txn_reg_status_change[reg_status]',
1347
+			$status_array,
1348
+			'NAN',
1349
+			'id="txn-admin-payment-reg-status-inp"',
1350
+			'txn-reg-status-change-reg-status'
1351
+		);
1352
+		$this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1353
+			'delete_txn_reg_status_change[reg_status]',
1354
+			$status_array,
1355
+			'NAN',
1356
+			'delete-txn-admin-payment-reg-status-inp',
1357
+			'delete-txn-reg-status-change-reg-status'
1358
+		);
1359
+	}
1360
+
1361
+
1362
+	/**
1363
+	 *    _get_payment_methods
1364
+	 * Gets all the payment methods available generally, or the ones that are already
1365
+	 * selected on these payments (in case their payment methods are no longer active).
1366
+	 * Has the side-effect of updating the template args' payment_methods item
1367
+	 *
1368
+	 * @access private
1369
+	 * @param EE_Payment[] to show on this page
1370
+	 * @return void
1371
+	 * @throws EE_Error
1372
+	 * @throws InvalidArgumentException
1373
+	 * @throws InvalidDataTypeException
1374
+	 * @throws InvalidInterfaceException
1375
+	 * @throws ReflectionException
1376
+	 */
1377
+	private function _get_payment_methods($payments = array())
1378
+	{
1379
+		$payment_methods_of_payments = array();
1380
+		foreach ($payments as $payment) {
1381
+			if ($payment instanceof EE_Payment) {
1382
+				$payment_methods_of_payments[] = $payment->ID();
1383
+			}
1384
+		}
1385
+		if ($payment_methods_of_payments) {
1386
+			$query_args = array(
1387
+				array(
1388
+					'OR*payment_method_for_payment' => array(
1389
+						'PMD_ID'    => array('IN', $payment_methods_of_payments),
1390
+						'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1391
+					),
1392
+				),
1393
+			);
1394
+		} else {
1395
+			$query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1396
+		}
1397
+		$this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1398
+	}
1399
+
1400
+
1401
+	/**
1402
+	 * txn_attendees_meta_box
1403
+	 *    generates HTML for the Attendees Transaction main meta box
1404
+	 *
1405
+	 * @access public
1406
+	 * @param WP_Post $post
1407
+	 * @param array   $metabox
1408
+	 * @return void
1409
+	 * @throws DomainException
1410
+	 * @throws EE_Error
1411
+	 * @throws InvalidArgumentException
1412
+	 * @throws InvalidDataTypeException
1413
+	 * @throws InvalidInterfaceException
1414
+	 * @throws ReflectionException
1415
+	 */
1416
+	public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1417
+	{
1418
+
1419
+		/** @noinspection NonSecureExtractUsageInspection */
1420
+		extract($metabox['args']);
1421
+		$this->_template_args['post'] = $post;
1422
+		$this->_template_args['event_attendees'] = array();
1423
+		// process items in cart
1424
+		$line_items = $this->_transaction->get_many_related(
1425
+			'Line_Item',
1426
+			array(array('LIN_type' => 'line-item'))
1427
+		);
1428
+		if (! empty($line_items)) {
1429
+			foreach ($line_items as $item) {
1430
+				if ($item instanceof EE_Line_Item) {
1431
+					switch ($item->OBJ_type()) {
1432
+						case 'Event':
1433
+							break;
1434
+						case 'Ticket':
1435
+							$ticket = $item->ticket();
1436
+							// right now we're only handling tickets here.
1437
+							// Cause its expected that only tickets will have attendees right?
1438
+							if (! $ticket instanceof EE_Ticket) {
1439
+								break;
1440
+							}
1441
+							try {
1442
+								$event_name = $ticket->get_event_name();
1443
+							} catch (Exception $e) {
1444
+								EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1445
+								$event_name = esc_html__('Unknown Event', 'event_espresso');
1446
+							}
1447
+							$event_name .= ' - ' . $item->name();
1448
+							$ticket_price = EEH_Template::format_currency($item->unit_price());
1449
+							// now get all of the registrations for this transaction that use this ticket
1450
+							$registrations = $ticket->registrations(
1451
+								array(array('TXN_ID' => $this->_transaction->ID()))
1452
+							);
1453
+							foreach ($registrations as $registration) {
1454
+								if (! $registration instanceof EE_Registration) {
1455
+									break;
1456
+								}
1457
+								$this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1458
+									= $registration->status_ID();
1459
+								$this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1460
+									= $registration->count();
1461
+								$this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1462
+									= $event_name;
1463
+								$this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1464
+									= $ticket_price;
1465
+								// attendee info
1466
+								$attendee = $registration->get_first_related('Attendee');
1467
+								if ($attendee instanceof EE_Attendee) {
1468
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1469
+										= $attendee->ID();
1470
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1471
+										= $attendee->full_name();
1472
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email']
1473
+										= '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1474
+										  . esc_html__(
1475
+											  ' Event',
1476
+											  'event_espresso'
1477
+										  )
1478
+										  . '">' . $attendee->email() . '</a>';
1479
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address']
1480
+										= EEH_Address::format($attendee, 'inline', false, false);
1481
+								} else {
1482
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1483
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1484
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1485
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1486
+								}
1487
+							}
1488
+							break;
1489
+					}
1490
+				}
1491
+			}
1492
+
1493
+			$this->_template_args['transaction_form_url'] = add_query_arg(
1494
+				array(
1495
+					'action'  => 'edit_transaction',
1496
+					'process' => 'attendees',
1497
+				),
1498
+				TXN_ADMIN_URL
1499
+			);
1500
+			echo EEH_Template::display_template(
1501
+				TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1502
+				$this->_template_args,
1503
+				true
1504
+			);
1505
+		} else {
1506
+			echo sprintf(
1507
+				esc_html__(
1508
+					'%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1509
+					'event_espresso'
1510
+				),
1511
+				'<p class="important-notice">',
1512
+				'</p>'
1513
+			);
1514
+		}
1515
+	}
1516
+
1517
+
1518
+	/**
1519
+	 * txn_registrant_side_meta_box
1520
+	 * generates HTML for the Edit Transaction side meta box
1521
+	 *
1522
+	 * @access public
1523
+	 * @return void
1524
+	 * @throws DomainException
1525
+	 * @throws EE_Error
1526
+	 * @throws InvalidArgumentException
1527
+	 * @throws InvalidDataTypeException
1528
+	 * @throws InvalidInterfaceException
1529
+	 * @throws ReflectionException
1530
+	 */
1531
+	public function txn_registrant_side_meta_box()
1532
+	{
1533
+		$primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1534
+			? $this->_transaction->primary_registration()->get_first_related('Attendee')
1535
+			: null;
1536
+		if (! $primary_att instanceof EE_Attendee) {
1537
+			$this->_template_args['no_attendee_message'] = esc_html__(
1538
+				'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1539
+				'event_espresso'
1540
+			);
1541
+			$primary_att = EEM_Attendee::instance()->create_default_object();
1542
+		}
1543
+		$this->_template_args['ATT_ID'] = $primary_att->ID();
1544
+		$this->_template_args['prime_reg_fname'] = $primary_att->fname();
1545
+		$this->_template_args['prime_reg_lname'] = $primary_att->lname();
1546
+		$this->_template_args['prime_reg_email'] = $primary_att->email();
1547
+		$this->_template_args['prime_reg_phone'] = $primary_att->phone();
1548
+		$this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1549
+			array(
1550
+				'action' => 'edit_attendee',
1551
+				'post'   => $primary_att->ID(),
1552
+			),
1553
+			REG_ADMIN_URL
1554
+		);
1555
+		// get formatted address for registrant
1556
+		$this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1557
+		echo EEH_Template::display_template(
1558
+			TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1559
+			$this->_template_args,
1560
+			true
1561
+		);
1562
+	}
1563
+
1564
+
1565
+	/**
1566
+	 * txn_billing_info_side_meta_box
1567
+	 *    generates HTML for the Edit Transaction side meta box
1568
+	 *
1569
+	 * @access public
1570
+	 * @return void
1571
+	 * @throws DomainException
1572
+	 * @throws EE_Error
1573
+	 */
1574
+	public function txn_billing_info_side_meta_box()
1575
+	{
1576
+
1577
+		$this->_template_args['billing_form'] = $this->_transaction->billing_info();
1578
+		$this->_template_args['billing_form_url'] = add_query_arg(
1579
+			array('action' => 'edit_transaction', 'process' => 'billing'),
1580
+			TXN_ADMIN_URL
1581
+		);
1582
+
1583
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1584
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1585
+	}
1586
+
1587
+
1588
+	/**
1589
+	 * apply_payments_or_refunds
1590
+	 *    registers a payment or refund made towards a transaction
1591
+	 *
1592
+	 * @access public
1593
+	 * @return void
1594
+	 * @throws EE_Error
1595
+	 * @throws InvalidArgumentException
1596
+	 * @throws ReflectionException
1597
+	 * @throws RuntimeException
1598
+	 * @throws InvalidDataTypeException
1599
+	 * @throws InvalidInterfaceException
1600
+	 */
1601
+	public function apply_payments_or_refunds()
1602
+	{
1603
+		$json_response_data = array('return_data' => false);
1604
+		$valid_data = $this->_validate_payment_request_data();
1605
+		$has_access = EE_Registry::instance()->CAP->current_user_can(
1606
+			'ee_edit_payments',
1607
+			'apply_payment_or_refund_from_registration_details'
1608
+		);
1609
+		if (! empty($valid_data) && $has_access) {
1610
+			$PAY_ID = $valid_data['PAY_ID'];
1611
+			// save  the new payment
1612
+			$payment = $this->_create_payment_from_request_data($valid_data);
1613
+			// get the TXN for this payment
1614
+			$transaction = $payment->transaction();
1615
+			// verify transaction
1616
+			if ($transaction instanceof EE_Transaction) {
1617
+				// calculate_total_payments_and_update_status
1618
+				$this->_process_transaction_payments($transaction);
1619
+				$REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1620
+				$this->_remove_existing_registration_payments($payment, $PAY_ID);
1621
+				// apply payment to registrations (if applicable)
1622
+				if (! empty($REG_IDs)) {
1623
+					$this->_update_registration_payments($transaction, $payment, $REG_IDs);
1624
+					$this->_maybe_send_notifications();
1625
+					// now process status changes for the same registrations
1626
+					$this->_process_registration_status_change($transaction, $REG_IDs);
1627
+				}
1628
+				$this->_maybe_send_notifications($payment);
1629
+				// prepare to render page
1630
+				$json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1631
+				do_action(
1632
+					'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1633
+					$transaction,
1634
+					$payment
1635
+				);
1636
+			} else {
1637
+				EE_Error::add_error(
1638
+					esc_html__(
1639
+						'A valid Transaction for this payment could not be retrieved.',
1640
+						'event_espresso'
1641
+					),
1642
+					__FILE__,
1643
+					__FUNCTION__,
1644
+					__LINE__
1645
+				);
1646
+			}
1647
+		} elseif ($has_access) {
1648
+			EE_Error::add_error(
1649
+				esc_html__(
1650
+					'The payment form data could not be processed. Please try again.',
1651
+					'event_espresso'
1652
+				),
1653
+				__FILE__,
1654
+				__FUNCTION__,
1655
+				__LINE__
1656
+			);
1657
+		} else {
1658
+			EE_Error::add_error(
1659
+				esc_html__(
1660
+					'You do not have access to apply payments or refunds to a registration.',
1661
+					'event_espresso'
1662
+				),
1663
+				__FILE__,
1664
+				__FUNCTION__,
1665
+				__LINE__
1666
+			);
1667
+		}
1668
+		$notices = EE_Error::get_notices(
1669
+			false,
1670
+			false,
1671
+			false
1672
+		);
1673
+		$this->_template_args = array(
1674
+			'data'    => $json_response_data,
1675
+			'error'   => $notices['errors'],
1676
+			'success' => $notices['success'],
1677
+		);
1678
+		$this->_return_json();
1679
+	}
1680
+
1681
+
1682
+	/**
1683
+	 * _validate_payment_request_data
1684
+	 *
1685
+	 * @return array
1686
+	 * @throws EE_Error
1687
+	 * @throws InvalidArgumentException
1688
+	 * @throws InvalidDataTypeException
1689
+	 * @throws InvalidInterfaceException
1690
+	 */
1691
+	protected function _validate_payment_request_data()
1692
+	{
1693
+		if (! isset($this->_req_data['txn_admin_payment'])) {
1694
+			return array();
1695
+		}
1696
+		$payment_form = $this->_generate_payment_form_section();
1697
+		try {
1698
+			if ($payment_form->was_submitted()) {
1699
+				$payment_form->receive_form_submission();
1700
+				if (! $payment_form->is_valid()) {
1701
+					$submission_error_messages = array();
1702
+					foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1703
+						if ($validation_error instanceof EE_Validation_Error) {
1704
+							$submission_error_messages[] = sprintf(
1705
+								_x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1706
+								$validation_error->get_form_section()->html_label_text(),
1707
+								$validation_error->getMessage()
1708
+							);
1709
+						}
1710
+					}
1711
+					EE_Error::add_error(
1712
+						implode('<br />', $submission_error_messages),
1713
+						__FILE__,
1714
+						__FUNCTION__,
1715
+						__LINE__
1716
+					);
1717
+					return array();
1718
+				}
1719
+			}
1720
+		} catch (EE_Error $e) {
1721
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1722
+			return array();
1723
+		}
1724
+
1725
+		return $payment_form->valid_data();
1726
+	}
1727
+
1728
+
1729
+	/**
1730
+	 * _generate_payment_form_section
1731
+	 *
1732
+	 * @return EE_Form_Section_Proper
1733
+	 * @throws EE_Error
1734
+	 */
1735
+	protected function _generate_payment_form_section()
1736
+	{
1737
+		return new EE_Form_Section_Proper(
1738
+			array(
1739
+				'name'        => 'txn_admin_payment',
1740
+				'subsections' => array(
1741
+					'PAY_ID'          => new EE_Text_Input(
1742
+						array(
1743
+							'default'               => 0,
1744
+							'required'              => false,
1745
+							'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1746
+							'validation_strategies' => array(new EE_Int_Normalization()),
1747
+						)
1748
+					),
1749
+					'TXN_ID'          => new EE_Text_Input(
1750
+						array(
1751
+							'default'               => 0,
1752
+							'required'              => true,
1753
+							'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1754
+							'validation_strategies' => array(new EE_Int_Normalization()),
1755
+						)
1756
+					),
1757
+					'type'            => new EE_Text_Input(
1758
+						array(
1759
+							'default'               => 1,
1760
+							'required'              => true,
1761
+							'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1762
+							'validation_strategies' => array(new EE_Int_Normalization()),
1763
+						)
1764
+					),
1765
+					'amount'          => new EE_Text_Input(
1766
+						array(
1767
+							'default'               => 0,
1768
+							'required'              => true,
1769
+							'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1770
+							'validation_strategies' => array(new EE_Float_Normalization()),
1771
+						)
1772
+					),
1773
+					'status'          => new EE_Text_Input(
1774
+						array(
1775
+							'default'         => EEM_Payment::status_id_approved,
1776
+							'required'        => true,
1777
+							'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1778
+						)
1779
+					),
1780
+					'PMD_ID'          => new EE_Text_Input(
1781
+						array(
1782
+							'default'               => 2,
1783
+							'required'              => true,
1784
+							'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1785
+							'validation_strategies' => array(new EE_Int_Normalization()),
1786
+						)
1787
+					),
1788
+					'date'            => new EE_Text_Input(
1789
+						array(
1790
+							'default'         => time(),
1791
+							'required'        => true,
1792
+							'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1793
+						)
1794
+					),
1795
+					'txn_id_chq_nmbr' => new EE_Text_Input(
1796
+						array(
1797
+							'default'               => '',
1798
+							'required'              => false,
1799
+							'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1800
+							'validation_strategies' => array(
1801
+								new EE_Max_Length_Validation_Strategy(
1802
+									esc_html__('Input too long', 'event_espresso'),
1803
+									100
1804
+								),
1805
+							),
1806
+						)
1807
+					),
1808
+					'po_number'       => new EE_Text_Input(
1809
+						array(
1810
+							'default'               => '',
1811
+							'required'              => false,
1812
+							'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1813
+							'validation_strategies' => array(
1814
+								new EE_Max_Length_Validation_Strategy(
1815
+									esc_html__('Input too long', 'event_espresso'),
1816
+									100
1817
+								),
1818
+							),
1819
+						)
1820
+					),
1821
+					'accounting'      => new EE_Text_Input(
1822
+						array(
1823
+							'default'               => '',
1824
+							'required'              => false,
1825
+							'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1826
+							'validation_strategies' => array(
1827
+								new EE_Max_Length_Validation_Strategy(
1828
+									esc_html__('Input too long', 'event_espresso'),
1829
+									100
1830
+								),
1831
+							),
1832
+						)
1833
+					),
1834
+				),
1835
+			)
1836
+		);
1837
+	}
1838
+
1839
+
1840
+	/**
1841
+	 * _create_payment_from_request_data
1842
+	 *
1843
+	 * @param array $valid_data
1844
+	 * @return EE_Payment
1845
+	 * @throws EE_Error
1846
+	 * @throws InvalidArgumentException
1847
+	 * @throws InvalidDataTypeException
1848
+	 * @throws InvalidInterfaceException
1849
+	 * @throws ReflectionException
1850
+	 */
1851
+	protected function _create_payment_from_request_data($valid_data)
1852
+	{
1853
+		$PAY_ID = $valid_data['PAY_ID'];
1854
+		// get payment amount
1855
+		$amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1856
+		// payments have a type value of 1 and refunds have a type value of -1
1857
+		// so multiplying amount by type will give a positive value for payments, and negative values for refunds
1858
+		$amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1859
+		// for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1860
+		$date = $valid_data['date']
1861
+			? preg_replace('/\s+/', ' ', $valid_data['date'])
1862
+			: date('Y-m-d g:i a', current_time('timestamp'));
1863
+		$payment = EE_Payment::new_instance(
1864
+			array(
1865
+				'TXN_ID'              => $valid_data['TXN_ID'],
1866
+				'STS_ID'              => $valid_data['status'],
1867
+				'PAY_timestamp'       => $date,
1868
+				'PAY_source'          => EEM_Payment_Method::scope_admin,
1869
+				'PMD_ID'              => $valid_data['PMD_ID'],
1870
+				'PAY_amount'          => $amount,
1871
+				'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1872
+				'PAY_po_number'       => $valid_data['po_number'],
1873
+				'PAY_extra_accntng'   => $valid_data['accounting'],
1874
+				'PAY_details'         => $valid_data,
1875
+				'PAY_ID'              => $PAY_ID,
1876
+			),
1877
+			'',
1878
+			array('Y-m-d', 'g:i a')
1879
+		);
1880
+
1881
+		if (! $payment->save()) {
1882
+			EE_Error::add_error(
1883
+				sprintf(
1884
+					esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1885
+					$payment->ID()
1886
+				),
1887
+				__FILE__,
1888
+				__FUNCTION__,
1889
+				__LINE__
1890
+			);
1891
+		}
1892
+
1893
+		return $payment;
1894
+	}
1895
+
1896
+
1897
+	/**
1898
+	 * _process_transaction_payments
1899
+	 *
1900
+	 * @param \EE_Transaction $transaction
1901
+	 * @return void
1902
+	 * @throws EE_Error
1903
+	 * @throws InvalidArgumentException
1904
+	 * @throws ReflectionException
1905
+	 * @throws InvalidDataTypeException
1906
+	 * @throws InvalidInterfaceException
1907
+	 */
1908
+	protected function _process_transaction_payments(EE_Transaction $transaction)
1909
+	{
1910
+		/** @type EE_Transaction_Payments $transaction_payments */
1911
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1912
+		// update the transaction with this payment
1913
+		if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1914
+			EE_Error::add_success(
1915
+				esc_html__(
1916
+					'The payment has been processed successfully.',
1917
+					'event_espresso'
1918
+				),
1919
+				__FILE__,
1920
+				__FUNCTION__,
1921
+				__LINE__
1922
+			);
1923
+		} else {
1924
+			EE_Error::add_error(
1925
+				esc_html__(
1926
+					'The payment was processed successfully but the amount paid for the transaction was not updated.',
1927
+					'event_espresso'
1928
+				),
1929
+				__FILE__,
1930
+				__FUNCTION__,
1931
+				__LINE__
1932
+			);
1933
+		}
1934
+	}
1935
+
1936
+
1937
+	/**
1938
+	 * _get_REG_IDs_to_apply_payment_to
1939
+	 * returns a list of registration IDs that the payment will apply to
1940
+	 *
1941
+	 * @param \EE_Payment $payment
1942
+	 * @return array
1943
+	 * @throws EE_Error
1944
+	 * @throws InvalidArgumentException
1945
+	 * @throws InvalidDataTypeException
1946
+	 * @throws InvalidInterfaceException
1947
+	 * @throws ReflectionException
1948
+	 */
1949
+	protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1950
+	{
1951
+		$REG_IDs = array();
1952
+		// grab array of IDs for specific registrations to apply changes to
1953
+		if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1954
+			$REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1955
+		}
1956
+		// nothing specified ? then get all reg IDs
1957
+		if (empty($REG_IDs)) {
1958
+			$registrations = $payment->transaction()->registrations();
1959
+			$REG_IDs = ! empty($registrations)
1960
+				? array_keys($registrations)
1961
+				: $this->_get_existing_reg_payment_REG_IDs($payment);
1962
+		}
1963
+
1964
+		// ensure that REG_IDs are integers and NOT strings
1965
+		return array_map('intval', $REG_IDs);
1966
+	}
1967
+
1968
+
1969
+	/**
1970
+	 * @return array
1971
+	 */
1972
+	public function existing_reg_payment_REG_IDs()
1973
+	{
1974
+		return $this->_existing_reg_payment_REG_IDs;
1975
+	}
1976
+
1977
+
1978
+	/**
1979
+	 * @param array $existing_reg_payment_REG_IDs
1980
+	 */
1981
+	public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1982
+	{
1983
+		$this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1984
+	}
1985
+
1986
+
1987
+	/**
1988
+	 * _get_existing_reg_payment_REG_IDs
1989
+	 * returns a list of registration IDs that the payment is currently related to
1990
+	 * as recorded in the database
1991
+	 *
1992
+	 * @param \EE_Payment $payment
1993
+	 * @return array
1994
+	 * @throws EE_Error
1995
+	 * @throws InvalidArgumentException
1996
+	 * @throws InvalidDataTypeException
1997
+	 * @throws InvalidInterfaceException
1998
+	 * @throws ReflectionException
1999
+	 */
2000
+	protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
2001
+	{
2002
+		if ($this->existing_reg_payment_REG_IDs() === null) {
2003
+			// let's get any existing reg payment records for this payment
2004
+			$existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
2005
+			// but we only want the REG IDs, so grab the array keys
2006
+			$existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
2007
+				? array_keys($existing_reg_payment_REG_IDs)
2008
+				: array();
2009
+			$this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
2010
+		}
2011
+
2012
+		return $this->existing_reg_payment_REG_IDs();
2013
+	}
2014
+
2015
+
2016
+	/**
2017
+	 * _remove_existing_registration_payments
2018
+	 * this calculates the difference between existing relations
2019
+	 * to the supplied payment and the new list registration IDs,
2020
+	 * removes any related registrations that no longer apply,
2021
+	 * and then updates the registration paid fields
2022
+	 *
2023
+	 * @param \EE_Payment $payment
2024
+	 * @param int         $PAY_ID
2025
+	 * @return bool;
2026
+	 * @throws EE_Error
2027
+	 * @throws InvalidArgumentException
2028
+	 * @throws ReflectionException
2029
+	 * @throws InvalidDataTypeException
2030
+	 * @throws InvalidInterfaceException
2031
+	 */
2032
+	protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2033
+	{
2034
+		// newly created payments will have nothing recorded for $PAY_ID
2035
+		if (absint($PAY_ID) === 0) {
2036
+			return false;
2037
+		}
2038
+		$existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2039
+		if (empty($existing_reg_payment_REG_IDs)) {
2040
+			return false;
2041
+		}
2042
+		/** @type EE_Transaction_Payments $transaction_payments */
2043
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2044
+
2045
+		return $transaction_payments->delete_registration_payments_and_update_registrations(
2046
+			$payment,
2047
+			array(
2048
+				array(
2049
+					'PAY_ID' => $payment->ID(),
2050
+					'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2051
+				),
2052
+			)
2053
+		);
2054
+	}
2055
+
2056
+
2057
+	/**
2058
+	 * _update_registration_payments
2059
+	 * this applies the payments to the selected registrations
2060
+	 * but only if they have not already been paid for
2061
+	 *
2062
+	 * @param  EE_Transaction $transaction
2063
+	 * @param \EE_Payment     $payment
2064
+	 * @param array           $REG_IDs
2065
+	 * @return void
2066
+	 * @throws EE_Error
2067
+	 * @throws InvalidArgumentException
2068
+	 * @throws ReflectionException
2069
+	 * @throws RuntimeException
2070
+	 * @throws InvalidDataTypeException
2071
+	 * @throws InvalidInterfaceException
2072
+	 */
2073
+	protected function _update_registration_payments(
2074
+		EE_Transaction $transaction,
2075
+		EE_Payment $payment,
2076
+		$REG_IDs = array()
2077
+	) {
2078
+		// we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2079
+		// so let's do that using our set of REG_IDs from the form
2080
+		$registration_query_where_params = array(
2081
+			'REG_ID' => array('IN', $REG_IDs),
2082
+		);
2083
+		// but add in some conditions regarding payment,
2084
+		// so that we don't apply payments to registrations that are free or have already been paid for
2085
+		// but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2086
+		if (! $payment->is_a_refund()) {
2087
+			$registration_query_where_params['REG_final_price'] = array('!=', 0);
2088
+			$registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2089
+		}
2090
+		$registrations = $transaction->registrations(array($registration_query_where_params));
2091
+		if (! empty($registrations)) {
2092
+			/** @type EE_Payment_Processor $payment_processor */
2093
+			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2094
+			$payment_processor->process_registration_payments($transaction, $payment, $registrations);
2095
+		}
2096
+	}
2097
+
2098
+
2099
+	/**
2100
+	 * _process_registration_status_change
2101
+	 * This processes requested registration status changes for all the registrations
2102
+	 * on a given transaction and (optionally) sends out notifications for the changes.
2103
+	 *
2104
+	 * @param  EE_Transaction $transaction
2105
+	 * @param array           $REG_IDs
2106
+	 * @return bool
2107
+	 * @throws EE_Error
2108
+	 * @throws InvalidArgumentException
2109
+	 * @throws ReflectionException
2110
+	 * @throws InvalidDataTypeException
2111
+	 * @throws InvalidInterfaceException
2112
+	 */
2113
+	protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2114
+	{
2115
+		// first if there is no change in status then we get out.
2116
+		if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2117
+			|| $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2118
+		) {
2119
+			// no error message, no change requested, just nothing to do man.
2120
+			return false;
2121
+		}
2122
+		/** @type EE_Transaction_Processor $transaction_processor */
2123
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2124
+
2125
+		// made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2126
+		return $transaction_processor->manually_update_registration_statuses(
2127
+			$transaction,
2128
+			sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2129
+			array(array('REG_ID' => array('IN', $REG_IDs)))
2130
+		);
2131
+	}
2132
+
2133
+
2134
+	/**
2135
+	 * _build_payment_json_response
2136
+	 *
2137
+	 * @access public
2138
+	 * @param \EE_Payment $payment
2139
+	 * @param array       $REG_IDs
2140
+	 * @param bool | null $delete_txn_reg_status_change
2141
+	 * @return array
2142
+	 * @throws EE_Error
2143
+	 * @throws InvalidArgumentException
2144
+	 * @throws InvalidDataTypeException
2145
+	 * @throws InvalidInterfaceException
2146
+	 * @throws ReflectionException
2147
+	 */
2148
+	protected function _build_payment_json_response(
2149
+		EE_Payment $payment,
2150
+		$REG_IDs = array(),
2151
+		$delete_txn_reg_status_change = null
2152
+	) {
2153
+		// was the payment deleted ?
2154
+		if (is_bool($delete_txn_reg_status_change)) {
2155
+			return array(
2156
+				'PAY_ID'                       => $payment->ID(),
2157
+				'amount'                       => $payment->amount(),
2158
+				'total_paid'                   => $payment->transaction()->paid(),
2159
+				'txn_status'                   => $payment->transaction()->status_ID(),
2160
+				'pay_status'                   => $payment->STS_ID(),
2161
+				'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2162
+				'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2163
+			);
2164
+		} else {
2165
+			$this->_get_payment_status_array();
2166
+
2167
+			return array(
2168
+				'amount'           => $payment->amount(),
2169
+				'total_paid'       => $payment->transaction()->paid(),
2170
+				'txn_status'       => $payment->transaction()->status_ID(),
2171
+				'pay_status'       => $payment->STS_ID(),
2172
+				'PAY_ID'           => $payment->ID(),
2173
+				'STS_ID'           => $payment->STS_ID(),
2174
+				'status'           => self::$_pay_status[ $payment->STS_ID() ],
2175
+				'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2176
+				'method'           => strtoupper($payment->source()),
2177
+				'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2178
+				'gateway'          => $payment->payment_method()
2179
+					? $payment->payment_method()->admin_name()
2180
+					: esc_html__('Unknown', 'event_espresso'),
2181
+				'gateway_response' => $payment->gateway_response(),
2182
+				'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2183
+				'po_number'        => $payment->po_number(),
2184
+				'extra_accntng'    => $payment->extra_accntng(),
2185
+				'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2186
+			);
2187
+		}
2188
+	}
2189
+
2190
+
2191
+	/**
2192
+	 * delete_payment
2193
+	 *    delete a payment or refund made towards a transaction
2194
+	 *
2195
+	 * @access public
2196
+	 * @return void
2197
+	 * @throws EE_Error
2198
+	 * @throws InvalidArgumentException
2199
+	 * @throws ReflectionException
2200
+	 * @throws InvalidDataTypeException
2201
+	 * @throws InvalidInterfaceException
2202
+	 */
2203
+	public function delete_payment()
2204
+	{
2205
+		$json_response_data = array('return_data' => false);
2206
+		$PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2207
+			? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2208
+			: 0;
2209
+		$can_delete = EE_Registry::instance()->CAP->current_user_can(
2210
+			'ee_delete_payments',
2211
+			'delete_payment_from_registration_details'
2212
+		);
2213
+		if ($PAY_ID && $can_delete) {
2214
+			$delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2215
+				? $this->_req_data['delete_txn_reg_status_change']
2216
+				: false;
2217
+			$payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2218
+			if ($payment instanceof EE_Payment) {
2219
+				$REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2220
+				/** @type EE_Transaction_Payments $transaction_payments */
2221
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2222
+				if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2223
+					$json_response_data['return_data'] = $this->_build_payment_json_response(
2224
+						$payment,
2225
+						$REG_IDs,
2226
+						$delete_txn_reg_status_change
2227
+					);
2228
+					if ($delete_txn_reg_status_change) {
2229
+						$this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2230
+						// MAKE sure we also add the delete_txn_req_status_change to the
2231
+						// $_REQUEST global because that's how messages will be looking for it.
2232
+						$_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2233
+						$this->_maybe_send_notifications();
2234
+						$this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2235
+					}
2236
+				}
2237
+			} else {
2238
+				EE_Error::add_error(
2239
+					esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2240
+					__FILE__,
2241
+					__FUNCTION__,
2242
+					__LINE__
2243
+				);
2244
+			}
2245
+		} elseif ($can_delete) {
2246
+			EE_Error::add_error(
2247
+				esc_html__(
2248
+					'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2249
+					'event_espresso'
2250
+				),
2251
+				__FILE__,
2252
+				__FUNCTION__,
2253
+				__LINE__
2254
+			);
2255
+		} else {
2256
+			EE_Error::add_error(
2257
+				esc_html__(
2258
+					'You do not have access to delete a payment.',
2259
+					'event_espresso'
2260
+				),
2261
+				__FILE__,
2262
+				__FUNCTION__,
2263
+				__LINE__
2264
+			);
2265
+		}
2266
+		$notices = EE_Error::get_notices(false, false, false);
2267
+		$this->_template_args = array(
2268
+			'data'      => $json_response_data,
2269
+			'success'   => $notices['success'],
2270
+			'error'     => $notices['errors'],
2271
+			'attention' => $notices['attention'],
2272
+		);
2273
+		$this->_return_json();
2274
+	}
2275
+
2276
+
2277
+	/**
2278
+	 * _registration_payment_data_array
2279
+	 * adds info for 'owing' and 'paid' for each registration to the json response
2280
+	 *
2281
+	 * @access protected
2282
+	 * @param array $REG_IDs
2283
+	 * @return array
2284
+	 * @throws EE_Error
2285
+	 * @throws InvalidArgumentException
2286
+	 * @throws InvalidDataTypeException
2287
+	 * @throws InvalidInterfaceException
2288
+	 * @throws ReflectionException
2289
+	 */
2290
+	protected function _registration_payment_data_array($REG_IDs)
2291
+	{
2292
+		$registration_payment_data = array();
2293
+		// if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2294
+		if (! empty($REG_IDs)) {
2295
+			$registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2296
+			foreach ($registrations as $registration) {
2297
+				if ($registration instanceof EE_Registration) {
2298
+					$registration_payment_data[ $registration->ID() ] = array(
2299
+						'paid'  => $registration->pretty_paid(),
2300
+						'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2301
+					);
2302
+				}
2303
+			}
2304
+		}
2305
+
2306
+		return $registration_payment_data;
2307
+	}
2308
+
2309
+
2310
+	/**
2311
+	 * _maybe_send_notifications
2312
+	 * determines whether or not the admin has indicated that notifications should be sent.
2313
+	 * If so, will toggle a filter switch for delivering registration notices.
2314
+	 * If passed an EE_Payment object, then it will trigger payment notifications instead.
2315
+	 *
2316
+	 * @access protected
2317
+	 * @param \EE_Payment | null $payment
2318
+	 */
2319
+	protected function _maybe_send_notifications($payment = null)
2320
+	{
2321
+		switch ($payment instanceof EE_Payment) {
2322
+			// payment notifications
2323
+			case true:
2324
+				if (isset($this->_req_data['txn_payments']['send_notifications'])
2325
+					&& filter_var(
2326
+						$this->_req_data['txn_payments']['send_notifications'],
2327
+						FILTER_VALIDATE_BOOLEAN
2328
+					)
2329
+				) {
2330
+					$this->_process_payment_notification($payment);
2331
+				}
2332
+				break;
2333
+			// registration notifications
2334
+			case false:
2335
+				if (isset($this->_req_data['txn_reg_status_change']['send_notifications'])
2336
+					&& filter_var(
2337
+						$this->_req_data['txn_reg_status_change']['send_notifications'],
2338
+						FILTER_VALIDATE_BOOLEAN
2339
+					)
2340
+				) {
2341
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2342
+				}
2343
+				break;
2344
+		}
2345
+	}
2346
+
2347
+
2348
+	/**
2349
+	 * _send_payment_reminder
2350
+	 *    generates HTML for the View Transaction Details Admin page
2351
+	 *
2352
+	 * @access protected
2353
+	 * @return void
2354
+	 * @throws EE_Error
2355
+	 * @throws InvalidArgumentException
2356
+	 * @throws InvalidDataTypeException
2357
+	 * @throws InvalidInterfaceException
2358
+	 */
2359
+	protected function _send_payment_reminder()
2360
+	{
2361
+		$TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2362
+		$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2363
+		$query_args = isset($this->_req_data['redirect_to']) ? array(
2364
+			'action' => $this->_req_data['redirect_to'],
2365
+			'TXN_ID' => $this->_req_data['TXN_ID'],
2366
+		) : array();
2367
+		do_action(
2368
+			'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2369
+			$transaction
2370
+		);
2371
+		$this->_redirect_after_action(
2372
+			false,
2373
+			esc_html__('payment reminder', 'event_espresso'),
2374
+			esc_html__('sent', 'event_espresso'),
2375
+			$query_args,
2376
+			true
2377
+		);
2378
+	}
2379
+
2380
+
2381
+	/**
2382
+	 *  get_transactions
2383
+	 *    get transactions for given parameters (used by list table)
2384
+	 *
2385
+	 * @param  int     $perpage how many transactions displayed per page
2386
+	 * @param  boolean $count   return the count or objects
2387
+	 * @param string   $view
2388
+	 * @return mixed int = count || array of transaction objects
2389
+	 * @throws EE_Error
2390
+	 * @throws InvalidArgumentException
2391
+	 * @throws InvalidDataTypeException
2392
+	 * @throws InvalidInterfaceException
2393
+	 */
2394
+	public function get_transactions($perpage, $count = false, $view = '')
2395
+	{
2396
+
2397
+		$TXN = EEM_Transaction::instance();
2398
+
2399
+		$start_date = isset($this->_req_data['txn-filter-start-date'])
2400
+			? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2401
+			: date(
2402
+				'm/d/Y',
2403
+				strtotime('-10 year')
2404
+			);
2405
+		$end_date = isset($this->_req_data['txn-filter-end-date'])
2406
+			? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2407
+			: date('m/d/Y');
2408
+
2409
+		// make sure our timestamps start and end right at the boundaries for each day
2410
+		$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2411
+		$end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2412
+
2413
+
2414
+		// convert to timestamps
2415
+		$start_date = strtotime($start_date);
2416
+		$end_date = strtotime($end_date);
2417
+
2418
+		// makes sure start date is the lowest value and vice versa
2419
+		$start_date = min($start_date, $end_date);
2420
+		$end_date = max($start_date, $end_date);
2421
+
2422
+		// convert to correct format for query
2423
+		$start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2424
+			'TXN_timestamp',
2425
+			date('Y-m-d H:i:s', $start_date),
2426
+			'Y-m-d H:i:s'
2427
+		);
2428
+		$end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2429
+			'TXN_timestamp',
2430
+			date('Y-m-d H:i:s', $end_date),
2431
+			'Y-m-d H:i:s'
2432
+		);
2433
+
2434
+
2435
+		// set orderby
2436
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2437
+
2438
+		switch ($this->_req_data['orderby']) {
2439
+			case 'TXN_ID':
2440
+				$orderby = 'TXN_ID';
2441
+				break;
2442
+			case 'ATT_fname':
2443
+				$orderby = 'Registration.Attendee.ATT_fname';
2444
+				break;
2445
+			case 'event_name':
2446
+				$orderby = 'Registration.Event.EVT_name';
2447
+				break;
2448
+			default: // 'TXN_timestamp'
2449
+				$orderby = 'TXN_timestamp';
2450
+		}
2451
+
2452
+		$sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2453
+		$current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2454
+		$per_page = ! empty($perpage) ? $perpage : 10;
2455
+		$per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2456
+
2457
+		$offset = ($current_page - 1) * $per_page;
2458
+		$limit = array($offset, $per_page);
2459
+
2460
+		$_where = array(
2461
+			'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2462
+			'Registration.REG_count' => 1,
2463
+		);
2464
+
2465
+		if (isset($this->_req_data['EVT_ID'])) {
2466
+			$_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2467
+		}
2468
+
2469
+		if (isset($this->_req_data['s'])) {
2470
+			$search_string = '%' . $this->_req_data['s'] . '%';
2471
+			$_where['OR'] = array(
2472
+				'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2473
+				'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2474
+				'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2475
+				'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2476
+				'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2477
+				'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2478
+				'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2479
+				'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2480
+				'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2481
+				'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2482
+				'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2483
+				'Registration.REG_final_price'        => array('LIKE', $search_string),
2484
+				'Registration.REG_code'               => array('LIKE', $search_string),
2485
+				'Registration.REG_count'              => array('LIKE', $search_string),
2486
+				'Registration.REG_group_size'         => array('LIKE', $search_string),
2487
+				'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2488
+				'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2489
+				'Payment.PAY_source'                  => array('LIKE', $search_string),
2490
+				'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2491
+				'TXN_session_data'                    => array('LIKE', $search_string),
2492
+				'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2493
+			);
2494
+		}
2495
+
2496
+		// failed transactions
2497
+		$failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2498
+				  || ($count && $view === 'failed');
2499
+		$abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2500
+					 || ($count && $view === 'abandoned');
2501
+		$incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count)
2502
+					  || ($count && $view === 'incomplete');
2503
+
2504
+		if ($failed) {
2505
+			$_where['STS_ID'] = EEM_Transaction::failed_status_code;
2506
+		} elseif ($abandoned) {
2507
+			$_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2508
+		} elseif ($incomplete) {
2509
+			$_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2510
+		} else {
2511
+			$_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2512
+			$_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2513
+		}
2514
+
2515
+		$query_params = apply_filters(
2516
+			'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2517
+			array(
2518
+				$_where,
2519
+				'order_by'                 => array($orderby => $sort),
2520
+				'limit'                    => $limit,
2521
+				'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2522
+			),
2523
+			$this->_req_data,
2524
+			$view,
2525
+			$count
2526
+		);
2527
+
2528
+		$transactions = $count
2529
+			? $TXN->count(array($query_params[0]), 'TXN_ID', true)
2530
+			: $TXN->get_all($query_params);
2531
+
2532
+		return $transactions;
2533
+	}
2534
+
2535
+
2536
+	/**
2537
+	 * @since 4.9.79.p
2538
+	 * @throws EE_Error
2539
+	 * @throws InvalidArgumentException
2540
+	 * @throws InvalidDataTypeException
2541
+	 * @throws InvalidInterfaceException
2542
+	 * @throws ReflectionException
2543
+	 * @throws RuntimeException
2544
+	 */
2545
+	public function recalculateLineItems()
2546
+	{
2547
+		$TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2548
+		/** @var EE_Transaction $transaction */
2549
+		$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2550
+		$total_line_item = $transaction->total_line_item(false);
2551
+		$success = $transaction->recalculateLineItems();
2552
+		$this->_redirect_after_action(
2553
+			(bool) $success,
2554
+			esc_html__('Transaction taxes and totals', 'event_espresso'),
2555
+			esc_html__('recalculated', 'event_espresso'),
2556
+			isset($this->_req_data['redirect_to'])
2557
+				? array(
2558
+				'action' => $this->_req_data['redirect_to'],
2559
+				'TXN_ID' => $this->_req_data['TXN_ID'],
2560
+			)
2561
+				: array(),
2562
+			true
2563
+		);
2564
+	}
2565 2565
 }
Please login to merge, or discard this patch.
core/domain/services/factories/CartFactory.php 1 patch
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -23,14 +23,14 @@
 block discarded – undo
23 23
 class CartFactory
24 24
 {
25 25
 
26
-    /**
27
-     * @return EE_Cart
28
-     * @throws InvalidArgumentException
29
-     * @throws InvalidInterfaceException
30
-     * @throws InvalidDataTypeException
31
-     */
32
-    public static function getCart()
33
-    {
34
-        return LoaderFactory::getLoader()->getShared('EE_Cart');
35
-    }
26
+	/**
27
+	 * @return EE_Cart
28
+	 * @throws InvalidArgumentException
29
+	 * @throws InvalidInterfaceException
30
+	 * @throws InvalidDataTypeException
31
+	 */
32
+	public static function getCart()
33
+	{
34
+		return LoaderFactory::getLoader()->getShared('EE_Cart');
35
+	}
36 36
 }
Please login to merge, or discard this patch.