Completed
Branch FIX/fatal-error-in-ProcessTick... (711b33)
by
unknown
24:40 queued 16:48
created
core/services/request/RequestStack.php 2 patches
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -19,59 +19,59 @@
 block discarded – undo
19 19
 class RequestStack
20 20
 {
21 21
 
22
-    /**
23
-     * @var RequestDecoratorInterface $request_stack_app
24
-     */
25
-    protected $request_stack_app;
22
+	/**
23
+	 * @var RequestDecoratorInterface $request_stack_app
24
+	 */
25
+	protected $request_stack_app;
26 26
 
27
-    /**
28
-     * @var RequestStackCoreAppInterface $core_app
29
-     */
30
-    protected $core_app;
27
+	/**
28
+	 * @var RequestStackCoreAppInterface $core_app
29
+	 */
30
+	protected $core_app;
31 31
 
32
-    /**
33
-     * @var RequestInterface $request
34
-     */
35
-    protected $request;
32
+	/**
33
+	 * @var RequestInterface $request
34
+	 */
35
+	protected $request;
36 36
 
37
-    /**
38
-     * @var ResponseInterface $response
39
-     */
40
-    protected $response;
37
+	/**
38
+	 * @var ResponseInterface $response
39
+	 */
40
+	protected $response;
41 41
 
42 42
 
43
-    /**
44
-     * @param RequestDecoratorInterface    $request_stack_app
45
-     * @param RequestStackCoreAppInterface $core_app
46
-     */
47
-    public function __construct(RequestDecoratorInterface $request_stack_app, RequestStackCoreAppInterface $core_app)
48
-    {
49
-        $this->request_stack_app = $request_stack_app;
50
-        $this->core_app      = $core_app;
51
-    }
43
+	/**
44
+	 * @param RequestDecoratorInterface    $request_stack_app
45
+	 * @param RequestStackCoreAppInterface $core_app
46
+	 */
47
+	public function __construct(RequestDecoratorInterface $request_stack_app, RequestStackCoreAppInterface $core_app)
48
+	{
49
+		$this->request_stack_app = $request_stack_app;
50
+		$this->core_app      = $core_app;
51
+	}
52 52
 
53 53
 
54
-    /**
55
-     * @param RequestInterface  $request
56
-     * @param ResponseInterface $response
57
-     * @return ResponseInterface
58
-     */
59
-    public function handleRequest(RequestInterface $request, ResponseInterface $response)
60
-    {
61
-        $this->request  = $request;
62
-        $this->response = $response;
63
-        return $this->request_stack_app->handleRequest($request, $response);
64
-    }
54
+	/**
55
+	 * @param RequestInterface  $request
56
+	 * @param ResponseInterface $response
57
+	 * @return ResponseInterface
58
+	 */
59
+	public function handleRequest(RequestInterface $request, ResponseInterface $response)
60
+	{
61
+		$this->request  = $request;
62
+		$this->response = $response;
63
+		return $this->request_stack_app->handleRequest($request, $response);
64
+	}
65 65
 
66 66
 
67
-    /**
68
-     * handle_response
69
-     * executes the handle_response() method on the RequestStackCoreAppInterface object
70
-     * after the request stack has been fully processed
71
-     */
72
-    public function handleResponse()
73
-    {
74
-        $this->core_app->handleResponse($this->request, $this->response);
75
-    }
67
+	/**
68
+	 * handle_response
69
+	 * executes the handle_response() method on the RequestStackCoreAppInterface object
70
+	 * after the request stack has been fully processed
71
+	 */
72
+	public function handleResponse()
73
+	{
74
+		$this->core_app->handleResponse($this->request, $this->response);
75
+	}
76 76
 }
77 77
 // Location: RequestStack.php
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@
 block discarded – undo
47 47
     public function __construct(RequestDecoratorInterface $request_stack_app, RequestStackCoreAppInterface $core_app)
48 48
     {
49 49
         $this->request_stack_app = $request_stack_app;
50
-        $this->core_app      = $core_app;
50
+        $this->core_app = $core_app;
51 51
     }
52 52
 
53 53
 
Please login to merge, or discard this patch.
modules/core_rest_api/EED_Core_Rest_Api.module.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -1,7 +1,6 @@
 block discarded – undo
1 1
 <?php
2 2
 
3 3
 use EventEspresso\core\domain\Domain;
4
-use EventEspresso\core\domain\entities\notifications\PersistentAdminNotice;
5 4
 use EventEspresso\core\domain\services\factories\EmailAddressFactory;
6 5
 use EventEspresso\core\domain\services\validation\email\EmailValidationException;
7 6
 use EventEspresso\core\exceptions\InvalidDataTypeException;
Please login to merge, or discard this patch.
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -765,6 +765,9 @@
 block discarded – undo
765 765
         );
766 766
     }
767 767
 
768
+    /**
769
+     * @param string $version
770
+     */
768 771
     protected function _get_add_relation_query_params(\EEM_Base $source_model, \EEM_Base $related_model, $version)
769 772
     {
770 773
         // if they're related through a HABTM relation, check for any non-FKs
Please login to merge, or discard this patch.
Indentation   +1329 added lines, -1329 removed lines patch added patch discarded remove patch
@@ -23,1333 +23,1333 @@
 block discarded – undo
23 23
 class EED_Core_Rest_Api extends \EED_Module
24 24
 {
25 25
 
26
-    const ee_api_namespace = Domain::API_NAMESPACE;
27
-
28
-    const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
29
-
30
-    const saved_routes_option_names = 'ee_core_routes';
31
-
32
-    /**
33
-     * string used in _links response bodies to make them globally unique.
34
-     *
35
-     * @see http://v2.wp-api.org/extending/linking/
36
-     */
37
-    const ee_api_link_namespace = 'https://api.eventespresso.com/';
38
-
39
-    /**
40
-     * @var CalculatedModelFields
41
-     */
42
-    protected static $_field_calculator;
43
-
44
-
45
-    /**
46
-     * @return EED_Core_Rest_Api|EED_Module
47
-     */
48
-    public static function instance()
49
-    {
50
-        self::$_field_calculator = LoaderFactory::getLoader()->load('EventEspresso\core\libraries\rest_api\CalculatedModelFields');
51
-        return parent::get_instance(__CLASS__);
52
-    }
53
-
54
-
55
-    /**
56
-     *    set_hooks - for hooking into EE Core, other modules, etc
57
-     *
58
-     * @access    public
59
-     * @return    void
60
-     */
61
-    public static function set_hooks()
62
-    {
63
-        self::set_hooks_both();
64
-    }
65
-
66
-
67
-    /**
68
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
69
-     *
70
-     * @access    public
71
-     * @return    void
72
-     */
73
-    public static function set_hooks_admin()
74
-    {
75
-        self::set_hooks_both();
76
-    }
77
-
78
-
79
-    public static function set_hooks_both()
80
-    {
81
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
82
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
83
-        add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
84
-        add_filter(
85
-            'rest_index',
86
-            array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex')
87
-        );
88
-        EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
89
-    }
90
-
91
-
92
-    /**
93
-     * sets up hooks which only need to be included as part of REST API requests;
94
-     * other requests like to the frontend or admin etc don't need them
95
-     *
96
-     * @throws \EE_Error
97
-     */
98
-    public static function set_hooks_rest_api()
99
-    {
100
-        // set hooks which account for changes made to the API
101
-        EED_Core_Rest_Api::_set_hooks_for_changes();
102
-    }
103
-
104
-
105
-    /**
106
-     * public wrapper of _set_hooks_for_changes.
107
-     * Loads all the hooks which make requests to old versions of the API
108
-     * appear the same as they always did
109
-     *
110
-     * @throws EE_Error
111
-     */
112
-    public static function set_hooks_for_changes()
113
-    {
114
-        self::_set_hooks_for_changes();
115
-    }
116
-
117
-
118
-    /**
119
-     * Loads all the hooks which make requests to old versions of the API
120
-     * appear the same as they always did
121
-     *
122
-     * @throws EE_Error
123
-     */
124
-    protected static function _set_hooks_for_changes()
125
-    {
126
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api/changes'), false);
127
-        foreach ($folder_contents as $classname_in_namespace => $filepath) {
128
-            // ignore the base parent class
129
-            // and legacy named classes
130
-            if ($classname_in_namespace === 'ChangesInBase'
131
-                || strpos($classname_in_namespace, 'Changes_In_') === 0
132
-            ) {
133
-                continue;
134
-            }
135
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
136
-            if (class_exists($full_classname)) {
137
-                $instance_of_class = new $full_classname;
138
-                if ($instance_of_class instanceof ChangesInBase) {
139
-                    $instance_of_class->setHooks();
140
-                }
141
-            }
142
-        }
143
-    }
144
-
145
-
146
-    /**
147
-     * Filters the WP routes to add our EE-related ones. This takes a bit of time
148
-     * so we actually prefer to only do it when an EE plugin is activated or upgraded
149
-     *
150
-     * @throws \EE_Error
151
-     */
152
-    public static function register_routes()
153
-    {
154
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
155
-            foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
156
-                /**
157
-                 * @var array     $data_for_multiple_endpoints numerically indexed array
158
-                 *                                         but can also contain route options like {
159
-                 * @type array    $schema                      {
160
-                 * @type callable $schema_callback
161
-                 * @type array    $callback_args               arguments that will be passed to the callback, after the
162
-                 * WP_REST_Request of course
163
-                 * }
164
-                 * }
165
-                 */
166
-                // when registering routes, register all the endpoints' data at the same time
167
-                $multiple_endpoint_args = array();
168
-                foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
169
-                    /**
170
-                     * @var array     $data_for_single_endpoint {
171
-                     * @type callable $callback
172
-                     * @type string methods
173
-                     * @type array args
174
-                     * @type array _links
175
-                     * @type array    $callback_args            arguments that will be passed to the callback, after the
176
-                     * WP_REST_Request of course
177
-                     * }
178
-                     */
179
-                    // skip route options
180
-                    if (! is_numeric($endpoint_key)) {
181
-                        continue;
182
-                    }
183
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
184
-                        throw new EE_Error(
185
-                            esc_html__(
186
-                            // @codingStandardsIgnoreStart
187
-                                'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
188
-                                // @codingStandardsIgnoreEnd
189
-                                'event_espresso'
190
-                            )
191
-                        );
192
-                    }
193
-                    $callback = $data_for_single_endpoint['callback'];
194
-                    $single_endpoint_args = array(
195
-                        'methods' => $data_for_single_endpoint['methods'],
196
-                        'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
197
-                            : array(),
198
-                    );
199
-                    if (isset($data_for_single_endpoint['_links'])) {
200
-                        $single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
201
-                    }
202
-                    if (isset($data_for_single_endpoint['callback_args'])) {
203
-                        $callback_args = $data_for_single_endpoint['callback_args'];
204
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
205
-                            $callback,
206
-                            $callback_args
207
-                        ) {
208
-                            array_unshift($callback_args, $request);
209
-                            return call_user_func_array(
210
-                                $callback,
211
-                                $callback_args
212
-                            );
213
-                        };
214
-                    } else {
215
-                        $single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
216
-                    }
217
-                    $multiple_endpoint_args[] = $single_endpoint_args;
218
-                }
219
-                if (isset($data_for_multiple_endpoints['schema'])) {
220
-                    $schema_route_data = $data_for_multiple_endpoints['schema'];
221
-                    $schema_callback = $schema_route_data['schema_callback'];
222
-                    $callback_args = $schema_route_data['callback_args'];
223
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
224
-                        return call_user_func_array(
225
-                            $schema_callback,
226
-                            $callback_args
227
-                        );
228
-                    };
229
-                }
230
-                register_rest_route(
231
-                    $namespace,
232
-                    $relative_route,
233
-                    $multiple_endpoint_args
234
-                );
235
-            }
236
-        }
237
-    }
238
-
239
-
240
-    /**
241
-     * Checks if there was a version change or something that merits invalidating the cached
242
-     * route data. If so, invalidates the cached route data so that it gets refreshed
243
-     * next time the WP API is used
244
-     */
245
-    public static function invalidate_cached_route_data_on_version_change()
246
-    {
247
-        if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
248
-            EED_Core_Rest_Api::invalidate_cached_route_data();
249
-        }
250
-        foreach (EE_Registry::instance()->addons as $addon) {
251
-            if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
252
-                EED_Core_Rest_Api::invalidate_cached_route_data();
253
-            }
254
-        }
255
-    }
256
-
257
-
258
-    /**
259
-     * Removes the cached route data so it will get refreshed next time the WP API is used
260
-     */
261
-    public static function invalidate_cached_route_data()
262
-    {
263
-        // delete the saved EE REST API routes
264
-        foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
265
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
266
-        }
267
-    }
268
-
269
-
270
-    /**
271
-     * Gets the EE route data
272
-     *
273
-     * @return array top-level key is the namespace, next-level key is the route and its value is array{
274
-     * @throws \EE_Error
275
-     * @type string|array $callback
276
-     * @type string       $methods
277
-     * @type boolean      $hidden_endpoint
278
-     * }
279
-     */
280
-    public static function get_ee_route_data()
281
-    {
282
-        $ee_routes = array();
283
-        foreach (self::versions_served() as $version => $hidden_endpoints) {
284
-            $ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version(
285
-                $version,
286
-                $hidden_endpoints
287
-            );
288
-        }
289
-        return $ee_routes;
290
-    }
291
-
292
-
293
-    /**
294
-     * Gets the EE route data from the wp options if it exists already,
295
-     * otherwise re-generates it and saves it to the option
296
-     *
297
-     * @param string  $version
298
-     * @param boolean $hidden_endpoints
299
-     * @return array
300
-     * @throws \EE_Error
301
-     */
302
-    protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
303
-    {
304
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
305
-        if (! $ee_routes || EED_Core_Rest_Api::debugMode()) {
306
-            $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
307
-        }
308
-        return $ee_routes;
309
-    }
310
-
311
-
312
-    /**
313
-     * Saves the EE REST API route data to a wp option and returns it
314
-     *
315
-     * @param string  $version
316
-     * @param boolean $hidden_endpoints
317
-     * @return mixed|null
318
-     * @throws \EE_Error
319
-     */
320
-    protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
321
-    {
322
-        $instance = self::instance();
323
-        $routes = apply_filters(
324
-            'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
325
-            array_replace_recursive(
326
-                $instance->_get_config_route_data_for_version($version, $hidden_endpoints),
327
-                $instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
328
-                $instance->_get_model_route_data_for_version($version, $hidden_endpoints),
329
-                $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
330
-            )
331
-        );
332
-        $option_name = self::saved_routes_option_names . $version;
333
-        if (get_option($option_name)) {
334
-            update_option($option_name, $routes, true);
335
-        } else {
336
-            add_option($option_name, $routes, null, 'no');
337
-        }
338
-        return $routes;
339
-    }
340
-
341
-
342
-    /**
343
-     * Calculates all the EE routes and saves it to a WordPress option so we don't
344
-     * need to calculate it on every request
345
-     *
346
-     * @deprecated since version 4.9.1
347
-     * @return void
348
-     */
349
-    public static function save_ee_routes()
350
-    {
351
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
352
-            $instance = self::instance();
353
-            $routes = apply_filters(
354
-                'EED_Core_Rest_Api__save_ee_routes__routes',
355
-                array_replace_recursive(
356
-                    $instance->_register_config_routes(),
357
-                    $instance->_register_meta_routes(),
358
-                    $instance->_register_model_routes(),
359
-                    $instance->_register_rpc_routes()
360
-                )
361
-            );
362
-            update_option(self::saved_routes_option_names, $routes, true);
363
-        }
364
-    }
365
-
366
-
367
-    /**
368
-     * Gets all the route information relating to EE models
369
-     *
370
-     * @return array @see get_ee_route_data
371
-     * @deprecated since version 4.9.1
372
-     */
373
-    protected function _register_model_routes()
374
-    {
375
-        $model_routes = array();
376
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
377
-            $model_routes[ EED_Core_Rest_Api::ee_api_namespace
378
-                           . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
379
-        }
380
-        return $model_routes;
381
-    }
382
-
383
-
384
-    /**
385
-     * Decides whether or not to add write endpoints for this model.
386
-     *
387
-     * Currently, this defaults to exclude all global tables and models
388
-     * which would allow inserting WP core data (we don't want to duplicate
389
-     * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
390
-     *
391
-     * @param EEM_Base $model
392
-     * @return bool
393
-     */
394
-    public static function should_have_write_endpoints(EEM_Base $model)
395
-    {
396
-        if ($model->is_wp_core_model()) {
397
-            return false;
398
-        }
399
-        foreach ($model->get_tables() as $table) {
400
-            if ($table->is_global()) {
401
-                return false;
402
-            }
403
-        }
404
-        return true;
405
-    }
406
-
407
-
408
-    /**
409
-     * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
410
-     * in this versioned namespace of EE4
411
-     *
412
-     * @param $version
413
-     * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
414
-     */
415
-    public static function model_names_with_plural_routes($version)
416
-    {
417
-        $model_version_info = new ModelVersionInfo($version);
418
-        $models_to_register = $model_version_info->modelsForRequestedVersion();
419
-        // let's not bother having endpoints for extra metas
420
-        unset(
421
-            $models_to_register['Extra_Meta'],
422
-            $models_to_register['Extra_Join'],
423
-            $models_to_register['Post_Meta']
424
-        );
425
-        return apply_filters(
426
-            'FHEE__EED_Core_REST_API___register_model_routes',
427
-            $models_to_register
428
-        );
429
-    }
430
-
431
-
432
-    /**
433
-     * Gets the route data for EE models in the specified version
434
-     *
435
-     * @param string  $version
436
-     * @param boolean $hidden_endpoint
437
-     * @return array
438
-     * @throws EE_Error
439
-     */
440
-    protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
441
-    {
442
-        $model_routes = array();
443
-        $model_version_info = new ModelVersionInfo($version);
444
-        foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
445
-            $model = \EE_Registry::instance()->load_model($model_name);
446
-            // if this isn't a valid model then let's skip iterate to the next item in the loop.
447
-            if (! $model instanceof EEM_Base) {
448
-                continue;
449
-            }
450
-            // yes we could just register one route for ALL models, but then they wouldn't show up in the index
451
-            $plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
452
-            $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
453
-            $model_routes[ $plural_model_route ] = array(
454
-                array(
455
-                    'callback'        => array(
456
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
457
-                        'handleRequestGetAll',
458
-                    ),
459
-                    'callback_args'   => array($version, $model_name),
460
-                    'methods'         => WP_REST_Server::READABLE,
461
-                    'hidden_endpoint' => $hidden_endpoint,
462
-                    'args'            => $this->_get_read_query_params($model, $version),
463
-                    '_links'          => array(
464
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
465
-                    ),
466
-                ),
467
-                'schema' => array(
468
-                    'schema_callback' => array(
469
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
470
-                        'handleSchemaRequest',
471
-                    ),
472
-                    'callback_args'   => array($version, $model_name),
473
-                ),
474
-            );
475
-            $model_routes[ $singular_model_route ] = array(
476
-                array(
477
-                    'callback'        => array(
478
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
479
-                        'handleRequestGetOne',
480
-                    ),
481
-                    'callback_args'   => array($version, $model_name),
482
-                    'methods'         => WP_REST_Server::READABLE,
483
-                    'hidden_endpoint' => $hidden_endpoint,
484
-                    'args'            => $this->_get_response_selection_query_params($model, $version, true),
485
-                ),
486
-            );
487
-            if (apply_filters(
488
-                'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
489
-                EED_Core_Rest_Api::should_have_write_endpoints($model),
490
-                $model
491
-            )) {
492
-                $model_routes[ $plural_model_route ][] = array(
493
-                    'callback'        => array(
494
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Write',
495
-                        'handleRequestInsert',
496
-                    ),
497
-                    'callback_args'   => array($version, $model_name),
498
-                    'methods'         => WP_REST_Server::CREATABLE,
499
-                    'hidden_endpoint' => $hidden_endpoint,
500
-                    'args'            => $this->_get_write_params($model_name, $model_version_info, true),
501
-                );
502
-                $model_routes[ $singular_model_route ] = array_merge(
503
-                    $model_routes[ $singular_model_route ],
504
-                    array(
505
-                        array(
506
-                            'callback'        => array(
507
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
508
-                                'handleRequestUpdate',
509
-                            ),
510
-                            'callback_args'   => array($version, $model_name),
511
-                            'methods'         => WP_REST_Server::EDITABLE,
512
-                            'hidden_endpoint' => $hidden_endpoint,
513
-                            'args'            => $this->_get_write_params($model_name, $model_version_info),
514
-                        ),
515
-                        array(
516
-                            'callback'        => array(
517
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
518
-                                'handleRequestDelete',
519
-                            ),
520
-                            'callback_args'   => array($version, $model_name),
521
-                            'methods'         => WP_REST_Server::DELETABLE,
522
-                            'hidden_endpoint' => $hidden_endpoint,
523
-                            'args'            => $this->_get_delete_query_params($model, $version),
524
-                        ),
525
-                    )
526
-                );
527
-            }
528
-            foreach ($model->relation_settings() as $relation_name => $relation_obj) {
529
-                $related_route = EED_Core_Rest_Api::get_relation_route_via(
530
-                    $model,
531
-                    '(?P<id>[^\/]+)',
532
-                    $relation_obj
533
-                );
534
-                $model_routes[ $related_route ] = array(
535
-                    array(
536
-                        'callback'        => array(
537
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Read',
538
-                            'handleRequestGetRelated',
539
-                        ),
540
-                        'callback_args'   => array($version, $model_name, $relation_name),
541
-                        'methods'         => WP_REST_Server::READABLE,
542
-                        'hidden_endpoint' => $hidden_endpoint,
543
-                        'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
544
-                    ),
545
-                );
546
-
547
-                $related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)';
548
-                $model_routes[ $related_write_route ] = array(
549
-                    array(
550
-                        'callback'        => array(
551
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Write',
552
-                            'handleRequestAddRelation',
553
-                        ),
554
-                        'callback_args'   => array($version, $model_name, $relation_name),
555
-                        'methods'         => WP_REST_Server::EDITABLE,
556
-                        'hidden_endpoint' => $hidden_endpoint,
557
-                        'args'            => $this->_get_add_relation_query_params($model, $relation_obj->get_other_model(), $version)
558
-                    ),
559
-                    array(
560
-                        'callback'        => array(
561
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Write',
562
-                            'handleRequestRemoveRelation',
563
-                        ),
564
-                        'callback_args'   => array($version, $model_name, $relation_name),
565
-                        'methods'         => WP_REST_Server::DELETABLE,
566
-                        'hidden_endpoint' => $hidden_endpoint,
567
-                        'args'            => array()
568
-                    ),
569
-                );
570
-            }
571
-        }
572
-        return $model_routes;
573
-    }
574
-
575
-
576
-    /**
577
-     * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
578
-     * excluding the preceding slash.
579
-     * Eg you pass get_plural_route_to('Event') = 'events'
580
-     *
581
-     * @param EEM_Base $model
582
-     * @return string
583
-     */
584
-    public static function get_collection_route(EEM_Base $model)
585
-    {
586
-        return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
587
-    }
588
-
589
-
590
-    /**
591
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
592
-     * excluding the preceding slash.
593
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
594
-     *
595
-     * @param EEM_Base $model eg Event or Venue
596
-     * @param string   $id
597
-     * @return string
598
-     */
599
-    public static function get_entity_route($model, $id)
600
-    {
601
-        return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id;
602
-    }
603
-
604
-
605
-    /**
606
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
607
-     * excluding the preceding slash.
608
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
609
-     *
610
-     * @param EEM_Base               $model eg Event or Venue
611
-     * @param string                 $id
612
-     * @param EE_Model_Relation_Base $relation_obj
613
-     * @return string
614
-     */
615
-    public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
616
-    {
617
-        $related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
618
-            $relation_obj->get_other_model()->get_this_model_name(),
619
-            $relation_obj
620
-        );
621
-        return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
622
-    }
623
-
624
-
625
-    /**
626
-     * Adds onto the $relative_route the EE4 REST API versioned namespace.
627
-     * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
628
-     *
629
-     * @param string $relative_route
630
-     * @param string $version
631
-     * @return string
632
-     */
633
-    public static function get_versioned_route_to($relative_route, $version = '4.8.36')
634
-    {
635
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
636
-    }
637
-
638
-
639
-    /**
640
-     * Adds all the RPC-style routes (remote procedure call-like routes, ie
641
-     * routes that don't conform to the traditional REST CRUD-style).
642
-     *
643
-     * @deprecated since 4.9.1
644
-     */
645
-    protected function _register_rpc_routes()
646
-    {
647
-        $routes = array();
648
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
649
-            $routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version(
650
-                $version,
651
-                $hidden_endpoint
652
-            );
653
-        }
654
-        return $routes;
655
-    }
656
-
657
-
658
-    /**
659
-     * @param string  $version
660
-     * @param boolean $hidden_endpoint
661
-     * @return array
662
-     */
663
-    protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
664
-    {
665
-        $this_versions_routes = array();
666
-        // checkin endpoint
667
-        $this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
668
-            array(
669
-                'callback'        => array(
670
-                    'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
671
-                    'handleRequestToggleCheckin',
672
-                ),
673
-                'methods'         => WP_REST_Server::CREATABLE,
674
-                'hidden_endpoint' => $hidden_endpoint,
675
-                'args'            => array(
676
-                    'force' => array(
677
-                        'required'    => false,
678
-                        'default'     => false,
679
-                        'description' => __(
680
-                        // @codingStandardsIgnoreStart
681
-                            'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
682
-                            // @codingStandardsIgnoreEnd
683
-                            'event_espresso'
684
-                        ),
685
-                    ),
686
-                ),
687
-                'callback_args'   => array($version),
688
-            ),
689
-        );
690
-        return apply_filters(
691
-            'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
692
-            $this_versions_routes,
693
-            $version,
694
-            $hidden_endpoint
695
-        );
696
-    }
697
-
698
-
699
-    /**
700
-     * Gets the query params that can be used when request one or many
701
-     *
702
-     * @param EEM_Base $model
703
-     * @param string   $version
704
-     * @return array
705
-     */
706
-    protected function _get_response_selection_query_params(\EEM_Base $model, $version, $single_only = false)
707
-    {
708
-        $query_params = array(
709
-            'include'   => array(
710
-                'required' => false,
711
-                'default'  => '*',
712
-                'type'     => 'string',
713
-            ),
714
-            'calculate' => array(
715
-                'required'          => false,
716
-                'default'           => '',
717
-                'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
718
-                'type'              => 'string',
719
-                // because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
720
-                // freaks out. We'll just validate this argument while handling the request
721
-                'validate_callback' => null,
722
-                'sanitize_callback' => null,
723
-            ),
724
-            'password' => array(
725
-                'required' => false,
726
-                'default' => '',
727
-                'type' => 'string'
728
-            )
729
-        );
730
-        return apply_filters(
731
-            'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
732
-            $query_params,
733
-            $model,
734
-            $version
735
-        );
736
-    }
737
-
738
-
739
-    /**
740
-     * Gets the parameters acceptable for delete requests
741
-     *
742
-     * @param \EEM_Base $model
743
-     * @param string    $version
744
-     * @return array
745
-     */
746
-    protected function _get_delete_query_params(\EEM_Base $model, $version)
747
-    {
748
-        $params_for_delete = array(
749
-            'allow_blocking' => array(
750
-                'required' => false,
751
-                'default'  => true,
752
-                'type'     => 'boolean',
753
-            ),
754
-        );
755
-        $params_for_delete['force'] = array(
756
-            'required' => false,
757
-            'default'  => false,
758
-            'type'     => 'boolean',
759
-        );
760
-        return apply_filters(
761
-            'FHEE__EED_Core_Rest_Api___get_delete_query_params',
762
-            $params_for_delete,
763
-            $model,
764
-            $version
765
-        );
766
-    }
767
-
768
-    protected function _get_add_relation_query_params(\EEM_Base $source_model, \EEM_Base $related_model, $version)
769
-    {
770
-        // if they're related through a HABTM relation, check for any non-FKs
771
-        $all_relation_settings = $source_model->relation_settings();
772
-        $relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ];
773
-        $params = array();
774
-        if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) {
775
-            foreach ($relation_settings->getNonKeyFields() as $field) {
776
-                /* @var $field EE_Model_Field_Base */
777
-                $params[ $field->get_name() ] = array(
778
-                    'required' => ! $field->is_nullable(),
779
-                    'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version),
780
-                    'type' => $field->getSchemaType(),
781
-                    'validate_callbaack' => null,
782
-                    'sanitize_callback' => null
783
-                );
784
-            }
785
-        }
786
-        return $params;
787
-    }
788
-
789
-
790
-    /**
791
-     * Gets info about reading query params that are acceptable
792
-     *
793
-     * @param \EEM_Base $model eg 'Event' or 'Venue'
794
-     * @param  string   $version
795
-     * @return array    describing the args acceptable when querying this model
796
-     * @throws EE_Error
797
-     */
798
-    protected function _get_read_query_params(\EEM_Base $model, $version)
799
-    {
800
-        $default_orderby = array();
801
-        foreach ($model->get_combined_primary_key_fields() as $key_field) {
802
-            $default_orderby[ $key_field->get_name() ] = 'ASC';
803
-        }
804
-        return array_merge(
805
-            $this->_get_response_selection_query_params($model, $version),
806
-            array(
807
-                'where'    => array(
808
-                    'required'          => false,
809
-                    'default'           => array(),
810
-                    'type'              => 'object',
811
-                    // because we accept an almost infinite list of possible where conditions, WP
812
-                    // core validation and sanitization freaks out. We'll just validate this argument
813
-                    // while handling the request
814
-                    'validate_callback' => null,
815
-                    'sanitize_callback' => null,
816
-                ),
817
-                'limit'    => array(
818
-                    'required'          => false,
819
-                    'default'           => EED_Core_Rest_Api::get_default_query_limit(),
820
-                    'type'              => array(
821
-                        'array',
822
-                        'string',
823
-                        'integer',
824
-                    ),
825
-                    // because we accept a variety of types, WP core validation and sanitization
826
-                    // freaks out. We'll just validate this argument while handling the request
827
-                    'validate_callback' => null,
828
-                    'sanitize_callback' => null,
829
-                ),
830
-                'order_by' => array(
831
-                    'required'          => false,
832
-                    'default'           => $default_orderby,
833
-                    'type'              => array(
834
-                        'object',
835
-                        'string',
836
-                    ),// because we accept a variety of types, WP core validation and sanitization
837
-                    // freaks out. We'll just validate this argument while handling the request
838
-                    'validate_callback' => null,
839
-                    'sanitize_callback' => null,
840
-                ),
841
-                'group_by' => array(
842
-                    'required'          => false,
843
-                    'default'           => null,
844
-                    'type'              => array(
845
-                        'object',
846
-                        'string',
847
-                    ),
848
-                    // because we accept  an almost infinite list of possible groupings,
849
-                    // WP core validation and sanitization
850
-                    // freaks out. We'll just validate this argument while handling the request
851
-                    'validate_callback' => null,
852
-                    'sanitize_callback' => null,
853
-                ),
854
-                'having'   => array(
855
-                    'required'          => false,
856
-                    'default'           => null,
857
-                    'type'              => 'object',
858
-                    // because we accept an almost infinite list of possible where conditions, WP
859
-                    // core validation and sanitization freaks out. We'll just validate this argument
860
-                    // while handling the request
861
-                    'validate_callback' => null,
862
-                    'sanitize_callback' => null,
863
-                ),
864
-                'caps'     => array(
865
-                    'required' => false,
866
-                    'default'  => EEM_Base::caps_read,
867
-                    'type'     => 'string',
868
-                    'enum'     => array(
869
-                        EEM_Base::caps_read,
870
-                        EEM_Base::caps_read_admin,
871
-                        EEM_Base::caps_edit,
872
-                        EEM_Base::caps_delete,
873
-                    ),
874
-                ),
875
-            )
876
-        );
877
-    }
878
-
879
-
880
-    /**
881
-     * Gets parameter information for a model regarding writing data
882
-     *
883
-     * @param string           $model_name
884
-     * @param ModelVersionInfo $model_version_info
885
-     * @param boolean          $create                                       whether this is for request to create (in
886
-     *                                                                       which case we need all required params) or
887
-     *                                                                       just to update (in which case we don't
888
-     *                                                                       need those on every request)
889
-     * @return array
890
-     */
891
-    protected function _get_write_params(
892
-        $model_name,
893
-        ModelVersionInfo $model_version_info,
894
-        $create = false
895
-    ) {
896
-        $model = EE_Registry::instance()->load_model($model_name);
897
-        $fields = $model_version_info->fieldsOnModelInThisVersion($model);
898
-        $args_info = array();
899
-        foreach ($fields as $field_name => $field_obj) {
900
-            if ($field_obj->is_auto_increment()) {
901
-                // totally ignore auto increment IDs
902
-                continue;
903
-            }
904
-            $arg_info = $field_obj->getSchema();
905
-            $required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
906
-            $arg_info['required'] = $required;
907
-            // remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
908
-            unset($arg_info['readonly']);
909
-            $schema_properties = $field_obj->getSchemaProperties();
910
-            if (isset($schema_properties['raw'])
911
-                && $field_obj->getSchemaType() === 'object'
912
-            ) {
913
-                // if there's a "raw" form of this argument, use those properties instead
914
-                $arg_info = array_replace(
915
-                    $arg_info,
916
-                    $schema_properties['raw']
917
-                );
918
-            }
919
-            $arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
920
-                $field_obj,
921
-                $field_obj->get_default_value(),
922
-                $model_version_info->requestedVersion()
923
-            );
924
-            // we do our own validation and sanitization within the controller
925
-            if (function_exists('rest_validate_value_from_schema')) {
926
-                $sanitize_callback = array(
927
-                    'EED_Core_Rest_Api',
928
-                    'default_sanitize_callback',
929
-                );
930
-            } else {
931
-                $sanitize_callback = null;
932
-            }
933
-            $arg_info['sanitize_callback'] = $sanitize_callback;
934
-            $args_info[ $field_name ] = $arg_info;
935
-            if ($field_obj instanceof EE_Datetime_Field) {
936
-                $gmt_arg_info = $arg_info;
937
-                $gmt_arg_info['description'] = sprintf(
938
-                    esc_html__(
939
-                        '%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
940
-                        'event_espresso'
941
-                    ),
942
-                    $field_obj->get_nicename(),
943
-                    $field_name
944
-                );
945
-                $args_info[ $field_name . '_gmt' ] = $gmt_arg_info;
946
-            }
947
-        }
948
-        return $args_info;
949
-    }
950
-
951
-
952
-    /**
953
-     * Replacement for WP API's 'rest_parse_request_arg'.
954
-     * If the value is blank but not required, don't bother validating it.
955
-     * Also, it uses our email validation instead of WP API's default.
956
-     *
957
-     * @param                 $value
958
-     * @param WP_REST_Request $request
959
-     * @param                 $param
960
-     * @return bool|true|WP_Error
961
-     * @throws InvalidArgumentException
962
-     * @throws InvalidInterfaceException
963
-     * @throws InvalidDataTypeException
964
-     */
965
-    public static function default_sanitize_callback($value, WP_REST_Request $request, $param)
966
-    {
967
-        $attributes = $request->get_attributes();
968
-        if (! isset($attributes['args'][ $param ])
969
-            || ! is_array($attributes['args'][ $param ])) {
970
-            $validation_result = true;
971
-        } else {
972
-            $args = $attributes['args'][ $param ];
973
-            if ((
974
-                    $value === ''
975
-                    || $value === null
976
-                )
977
-                && (! isset($args['required'])
978
-                    || $args['required'] === false
979
-                )
980
-            ) {
981
-                // not required and not provided? that's cool
982
-                $validation_result = true;
983
-            } elseif (isset($args['format'])
984
-                      && $args['format'] === 'email'
985
-            ) {
986
-                $validation_result = true;
987
-                if (! self::_validate_email($value)) {
988
-                    $validation_result = new WP_Error(
989
-                        'rest_invalid_param',
990
-                        esc_html__(
991
-                            'The email address is not valid or does not exist.',
992
-                            'event_espresso'
993
-                        )
994
-                    );
995
-                }
996
-            } else {
997
-                $validation_result = rest_validate_value_from_schema($value, $args, $param);
998
-            }
999
-        }
1000
-        if (is_wp_error($validation_result)) {
1001
-            return $validation_result;
1002
-        }
1003
-        return rest_sanitize_request_arg($value, $request, $param);
1004
-    }
1005
-
1006
-
1007
-    /**
1008
-     * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
1009
-     *
1010
-     * @param $email
1011
-     * @return bool
1012
-     * @throws InvalidArgumentException
1013
-     * @throws InvalidInterfaceException
1014
-     * @throws InvalidDataTypeException
1015
-     */
1016
-    protected static function _validate_email($email)
1017
-    {
1018
-        try {
1019
-            EmailAddressFactory::create($email);
1020
-            return true;
1021
-        } catch (EmailValidationException $e) {
1022
-            return false;
1023
-        }
1024
-    }
1025
-
1026
-
1027
-    /**
1028
-     * Gets routes for the config
1029
-     *
1030
-     * @return array @see _register_model_routes
1031
-     * @deprecated since version 4.9.1
1032
-     */
1033
-    protected function _register_config_routes()
1034
-    {
1035
-        $config_routes = array();
1036
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1037
-            $config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version(
1038
-                $version,
1039
-                $hidden_endpoint
1040
-            );
1041
-        }
1042
-        return $config_routes;
1043
-    }
1044
-
1045
-
1046
-    /**
1047
-     * Gets routes for the config for the specified version
1048
-     *
1049
-     * @param string  $version
1050
-     * @param boolean $hidden_endpoint
1051
-     * @return array
1052
-     */
1053
-    protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1054
-    {
1055
-        return array(
1056
-            'config'    => array(
1057
-                array(
1058
-                    'callback'        => array(
1059
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1060
-                        'handleRequest',
1061
-                    ),
1062
-                    'methods'         => WP_REST_Server::READABLE,
1063
-                    'hidden_endpoint' => $hidden_endpoint,
1064
-                    'callback_args'   => array($version),
1065
-                ),
1066
-            ),
1067
-            'site_info' => array(
1068
-                array(
1069
-                    'callback'        => array(
1070
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1071
-                        'handleRequestSiteInfo',
1072
-                    ),
1073
-                    'methods'         => WP_REST_Server::READABLE,
1074
-                    'hidden_endpoint' => $hidden_endpoint,
1075
-                    'callback_args'   => array($version),
1076
-                ),
1077
-            ),
1078
-        );
1079
-    }
1080
-
1081
-
1082
-    /**
1083
-     * Gets the meta info routes
1084
-     *
1085
-     * @return array @see _register_model_routes
1086
-     * @deprecated since version 4.9.1
1087
-     */
1088
-    protected function _register_meta_routes()
1089
-    {
1090
-        $meta_routes = array();
1091
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1092
-            $meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version(
1093
-                $version,
1094
-                $hidden_endpoint
1095
-            );
1096
-        }
1097
-        return $meta_routes;
1098
-    }
1099
-
1100
-
1101
-    /**
1102
-     * @param string  $version
1103
-     * @param boolean $hidden_endpoint
1104
-     * @return array
1105
-     */
1106
-    protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1107
-    {
1108
-        return array(
1109
-            'resources' => array(
1110
-                array(
1111
-                    'callback'        => array(
1112
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1113
-                        'handleRequestModelsMeta',
1114
-                    ),
1115
-                    'methods'         => WP_REST_Server::READABLE,
1116
-                    'hidden_endpoint' => $hidden_endpoint,
1117
-                    'callback_args'   => array($version),
1118
-                ),
1119
-            ),
1120
-        );
1121
-    }
1122
-
1123
-
1124
-    /**
1125
-     * Tries to hide old 4.6 endpoints from the
1126
-     *
1127
-     * @param array $route_data
1128
-     * @return array
1129
-     * @throws \EE_Error
1130
-     */
1131
-    public static function hide_old_endpoints($route_data)
1132
-    {
1133
-        // allow API clients to override which endpoints get hidden, in case
1134
-        // they want to discover particular endpoints
1135
-        // also, we don't have access to the request so we have to just grab it from the superglobal
1136
-        $force_show_ee_namespace = ltrim(
1137
-            EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1138
-            '/'
1139
-        );
1140
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1141
-            foreach ($relative_urls as $resource_name => $endpoints) {
1142
-                foreach ($endpoints as $key => $endpoint) {
1143
-                    // skip schema and other route options
1144
-                    if (! is_numeric($key)) {
1145
-                        continue;
1146
-                    }
1147
-                    // by default, hide "hidden_endpoint"s, unless the request indicates
1148
-                    // to $force_show_ee_namespace, in which case only show that one
1149
-                    // namespace's endpoints (and hide all others)
1150
-                    if (($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1151
-                        || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1152
-                    ) {
1153
-                        $full_route = '/' . ltrim($namespace, '/');
1154
-                        $full_route .= '/' . ltrim($resource_name, '/');
1155
-                        unset($route_data[ $full_route ]);
1156
-                    }
1157
-                }
1158
-            }
1159
-        }
1160
-        return $route_data;
1161
-    }
1162
-
1163
-
1164
-    /**
1165
-     * Returns an array describing which versions of core support serving requests for.
1166
-     * Keys are core versions' major and minor version, and values are the
1167
-     * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1168
-     * data by just removing a few models and fields from the responses. However, 4.15 might remove
1169
-     * the answers table entirely, in which case it would be very difficult for
1170
-     * it to serve 4.6-style responses.
1171
-     * Versions of core that are missing from this array are unknowns.
1172
-     * previous ver
1173
-     *
1174
-     * @return array
1175
-     */
1176
-    public static function version_compatibilities()
1177
-    {
1178
-        return apply_filters(
1179
-            'FHEE__EED_Core_REST_API__version_compatibilities',
1180
-            array(
1181
-                '4.8.29' => '4.8.29',
1182
-                '4.8.33' => '4.8.29',
1183
-                '4.8.34' => '4.8.29',
1184
-                '4.8.36' => '4.8.29',
1185
-            )
1186
-        );
1187
-    }
1188
-
1189
-
1190
-    /**
1191
-     * Gets the latest API version served. Eg if there
1192
-     * are two versions served of the API, 4.8.29 and 4.8.32, and
1193
-     * we are on core version 4.8.34, it will return the string "4.8.32"
1194
-     *
1195
-     * @return string
1196
-     */
1197
-    public static function latest_rest_api_version()
1198
-    {
1199
-        $versions_served = \EED_Core_Rest_Api::versions_served();
1200
-        $versions_served_keys = array_keys($versions_served);
1201
-        return end($versions_served_keys);
1202
-    }
1203
-
1204
-
1205
-    /**
1206
-     * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1207
-     * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1208
-     * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1209
-     * We also indicate whether or not this version should be put in the index or not
1210
-     *
1211
-     * @return array keys are API version numbers (just major and minor numbers), and values
1212
-     * are whether or not they should be hidden
1213
-     */
1214
-    public static function versions_served()
1215
-    {
1216
-        $versions_served = array();
1217
-        $possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1218
-        $lowest_compatible_version = end($possibly_served_versions);
1219
-        reset($possibly_served_versions);
1220
-        $versions_served_historically = array_keys($possibly_served_versions);
1221
-        $latest_version = end($versions_served_historically);
1222
-        reset($versions_served_historically);
1223
-        // for each version of core we have ever served:
1224
-        foreach ($versions_served_historically as $key_versioned_endpoint) {
1225
-            // if it's not above the current core version, and it's compatible with the current version of core
1226
-
1227
-            if ($key_versioned_endpoint === $latest_version) {
1228
-                // don't hide the latest version in the index
1229
-                $versions_served[ $key_versioned_endpoint ] = false;
1230
-            } elseif (version_compare($key_versioned_endpoint, $lowest_compatible_version, '>=')
1231
-                && version_compare($key_versioned_endpoint, EED_Core_Rest_Api::core_version(), '<')
1232
-            ) {
1233
-                // include, but hide, previous versions which are still supported
1234
-                $versions_served[ $key_versioned_endpoint ] = true;
1235
-            } elseif (apply_filters(
1236
-                'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1237
-                false,
1238
-                $possibly_served_versions
1239
-            )) {
1240
-                // if a version is no longer supported, don't include it in index or list of versions served
1241
-                $versions_served[ $key_versioned_endpoint ] = true;
1242
-            }
1243
-        }
1244
-        return $versions_served;
1245
-    }
1246
-
1247
-
1248
-    /**
1249
-     * Gets the major and minor version of EE core's version string
1250
-     *
1251
-     * @return string
1252
-     */
1253
-    public static function core_version()
1254
-    {
1255
-        return apply_filters(
1256
-            'FHEE__EED_Core_REST_API__core_version',
1257
-            implode(
1258
-                '.',
1259
-                array_slice(
1260
-                    explode(
1261
-                        '.',
1262
-                        espresso_version()
1263
-                    ),
1264
-                    0,
1265
-                    3
1266
-                )
1267
-            )
1268
-        );
1269
-    }
1270
-
1271
-
1272
-    /**
1273
-     * Gets the default limit that should be used when querying for resources
1274
-     *
1275
-     * @return int
1276
-     */
1277
-    public static function get_default_query_limit()
1278
-    {
1279
-        // we actually don't use a const because we want folks to always use
1280
-        // this method, not the const directly
1281
-        return apply_filters(
1282
-            'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1283
-            50
1284
-        );
1285
-    }
1286
-
1287
-
1288
-    /**
1289
-     *
1290
-     * @param string $version api version string (i.e. '4.8.36')
1291
-     * @return array
1292
-     */
1293
-    public static function getCollectionRoutesIndexedByModelName($version = '')
1294
-    {
1295
-        $version = empty($version) ? self::latest_rest_api_version() : $version;
1296
-        $model_names = self::model_names_with_plural_routes($version);
1297
-        $collection_routes = array();
1298
-        foreach ($model_names as $model_name => $model_class_name) {
1299
-            $collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/'
1300
-                                                            . EEH_Inflector::pluralize_and_lower($model_name);
1301
-        }
1302
-        return $collection_routes;
1303
-    }
1304
-
1305
-
1306
-    /**
1307
-     * Returns an array of primary key names indexed by model names.
1308
-     * @param string $version
1309
-     * @return array
1310
-     */
1311
-    public static function getPrimaryKeyNamesIndexedByModelName($version = '')
1312
-    {
1313
-        $version = empty($version) ? self::latest_rest_api_version() : $version;
1314
-        $model_names = self::model_names_with_plural_routes($version);
1315
-        $primary_key_items = array();
1316
-        foreach ($model_names as $model_name => $model_class_name) {
1317
-            $primary_keys = $model_class_name::instance()->get_combined_primary_key_fields();
1318
-            foreach ($primary_keys as $primary_key_name => $primary_key_field) {
1319
-                if (count($primary_keys) > 1) {
1320
-                    $primary_key_items[ strtolower($model_name) ][] = $primary_key_name;
1321
-                } else {
1322
-                    $primary_key_items[ strtolower($model_name) ] = $primary_key_name;
1323
-                }
1324
-            }
1325
-        }
1326
-        return $primary_key_items;
1327
-    }
1328
-
1329
-    /**
1330
-     * Determines the EE REST API debug mode is activated, or not.
1331
-     * @since 4.9.76.p
1332
-     * @return bool
1333
-     */
1334
-    public static function debugMode()
1335
-    {
1336
-        static $debug_mode = null; // could be class prop
1337
-        if ($debug_mode === null) {
1338
-            $debug_mode = defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE;
1339
-        }
1340
-        return $debug_mode;
1341
-    }
1342
-
1343
-
1344
-
1345
-    /**
1346
-     *    run - initial module setup
1347
-     *
1348
-     * @access    public
1349
-     * @param  WP $WP
1350
-     * @return    void
1351
-     */
1352
-    public function run($WP)
1353
-    {
1354
-    }
26
+	const ee_api_namespace = Domain::API_NAMESPACE;
27
+
28
+	const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
29
+
30
+	const saved_routes_option_names = 'ee_core_routes';
31
+
32
+	/**
33
+	 * string used in _links response bodies to make them globally unique.
34
+	 *
35
+	 * @see http://v2.wp-api.org/extending/linking/
36
+	 */
37
+	const ee_api_link_namespace = 'https://api.eventespresso.com/';
38
+
39
+	/**
40
+	 * @var CalculatedModelFields
41
+	 */
42
+	protected static $_field_calculator;
43
+
44
+
45
+	/**
46
+	 * @return EED_Core_Rest_Api|EED_Module
47
+	 */
48
+	public static function instance()
49
+	{
50
+		self::$_field_calculator = LoaderFactory::getLoader()->load('EventEspresso\core\libraries\rest_api\CalculatedModelFields');
51
+		return parent::get_instance(__CLASS__);
52
+	}
53
+
54
+
55
+	/**
56
+	 *    set_hooks - for hooking into EE Core, other modules, etc
57
+	 *
58
+	 * @access    public
59
+	 * @return    void
60
+	 */
61
+	public static function set_hooks()
62
+	{
63
+		self::set_hooks_both();
64
+	}
65
+
66
+
67
+	/**
68
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
69
+	 *
70
+	 * @access    public
71
+	 * @return    void
72
+	 */
73
+	public static function set_hooks_admin()
74
+	{
75
+		self::set_hooks_both();
76
+	}
77
+
78
+
79
+	public static function set_hooks_both()
80
+	{
81
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
82
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
83
+		add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
84
+		add_filter(
85
+			'rest_index',
86
+			array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex')
87
+		);
88
+		EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
89
+	}
90
+
91
+
92
+	/**
93
+	 * sets up hooks which only need to be included as part of REST API requests;
94
+	 * other requests like to the frontend or admin etc don't need them
95
+	 *
96
+	 * @throws \EE_Error
97
+	 */
98
+	public static function set_hooks_rest_api()
99
+	{
100
+		// set hooks which account for changes made to the API
101
+		EED_Core_Rest_Api::_set_hooks_for_changes();
102
+	}
103
+
104
+
105
+	/**
106
+	 * public wrapper of _set_hooks_for_changes.
107
+	 * Loads all the hooks which make requests to old versions of the API
108
+	 * appear the same as they always did
109
+	 *
110
+	 * @throws EE_Error
111
+	 */
112
+	public static function set_hooks_for_changes()
113
+	{
114
+		self::_set_hooks_for_changes();
115
+	}
116
+
117
+
118
+	/**
119
+	 * Loads all the hooks which make requests to old versions of the API
120
+	 * appear the same as they always did
121
+	 *
122
+	 * @throws EE_Error
123
+	 */
124
+	protected static function _set_hooks_for_changes()
125
+	{
126
+		$folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api/changes'), false);
127
+		foreach ($folder_contents as $classname_in_namespace => $filepath) {
128
+			// ignore the base parent class
129
+			// and legacy named classes
130
+			if ($classname_in_namespace === 'ChangesInBase'
131
+				|| strpos($classname_in_namespace, 'Changes_In_') === 0
132
+			) {
133
+				continue;
134
+			}
135
+			$full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
136
+			if (class_exists($full_classname)) {
137
+				$instance_of_class = new $full_classname;
138
+				if ($instance_of_class instanceof ChangesInBase) {
139
+					$instance_of_class->setHooks();
140
+				}
141
+			}
142
+		}
143
+	}
144
+
145
+
146
+	/**
147
+	 * Filters the WP routes to add our EE-related ones. This takes a bit of time
148
+	 * so we actually prefer to only do it when an EE plugin is activated or upgraded
149
+	 *
150
+	 * @throws \EE_Error
151
+	 */
152
+	public static function register_routes()
153
+	{
154
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
155
+			foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
156
+				/**
157
+				 * @var array     $data_for_multiple_endpoints numerically indexed array
158
+				 *                                         but can also contain route options like {
159
+				 * @type array    $schema                      {
160
+				 * @type callable $schema_callback
161
+				 * @type array    $callback_args               arguments that will be passed to the callback, after the
162
+				 * WP_REST_Request of course
163
+				 * }
164
+				 * }
165
+				 */
166
+				// when registering routes, register all the endpoints' data at the same time
167
+				$multiple_endpoint_args = array();
168
+				foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
169
+					/**
170
+					 * @var array     $data_for_single_endpoint {
171
+					 * @type callable $callback
172
+					 * @type string methods
173
+					 * @type array args
174
+					 * @type array _links
175
+					 * @type array    $callback_args            arguments that will be passed to the callback, after the
176
+					 * WP_REST_Request of course
177
+					 * }
178
+					 */
179
+					// skip route options
180
+					if (! is_numeric($endpoint_key)) {
181
+						continue;
182
+					}
183
+					if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
184
+						throw new EE_Error(
185
+							esc_html__(
186
+							// @codingStandardsIgnoreStart
187
+								'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
188
+								// @codingStandardsIgnoreEnd
189
+								'event_espresso'
190
+							)
191
+						);
192
+					}
193
+					$callback = $data_for_single_endpoint['callback'];
194
+					$single_endpoint_args = array(
195
+						'methods' => $data_for_single_endpoint['methods'],
196
+						'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
197
+							: array(),
198
+					);
199
+					if (isset($data_for_single_endpoint['_links'])) {
200
+						$single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
201
+					}
202
+					if (isset($data_for_single_endpoint['callback_args'])) {
203
+						$callback_args = $data_for_single_endpoint['callback_args'];
204
+						$single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
205
+							$callback,
206
+							$callback_args
207
+						) {
208
+							array_unshift($callback_args, $request);
209
+							return call_user_func_array(
210
+								$callback,
211
+								$callback_args
212
+							);
213
+						};
214
+					} else {
215
+						$single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
216
+					}
217
+					$multiple_endpoint_args[] = $single_endpoint_args;
218
+				}
219
+				if (isset($data_for_multiple_endpoints['schema'])) {
220
+					$schema_route_data = $data_for_multiple_endpoints['schema'];
221
+					$schema_callback = $schema_route_data['schema_callback'];
222
+					$callback_args = $schema_route_data['callback_args'];
223
+					$multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
224
+						return call_user_func_array(
225
+							$schema_callback,
226
+							$callback_args
227
+						);
228
+					};
229
+				}
230
+				register_rest_route(
231
+					$namespace,
232
+					$relative_route,
233
+					$multiple_endpoint_args
234
+				);
235
+			}
236
+		}
237
+	}
238
+
239
+
240
+	/**
241
+	 * Checks if there was a version change or something that merits invalidating the cached
242
+	 * route data. If so, invalidates the cached route data so that it gets refreshed
243
+	 * next time the WP API is used
244
+	 */
245
+	public static function invalidate_cached_route_data_on_version_change()
246
+	{
247
+		if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
248
+			EED_Core_Rest_Api::invalidate_cached_route_data();
249
+		}
250
+		foreach (EE_Registry::instance()->addons as $addon) {
251
+			if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
252
+				EED_Core_Rest_Api::invalidate_cached_route_data();
253
+			}
254
+		}
255
+	}
256
+
257
+
258
+	/**
259
+	 * Removes the cached route data so it will get refreshed next time the WP API is used
260
+	 */
261
+	public static function invalidate_cached_route_data()
262
+	{
263
+		// delete the saved EE REST API routes
264
+		foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
265
+			delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
266
+		}
267
+	}
268
+
269
+
270
+	/**
271
+	 * Gets the EE route data
272
+	 *
273
+	 * @return array top-level key is the namespace, next-level key is the route and its value is array{
274
+	 * @throws \EE_Error
275
+	 * @type string|array $callback
276
+	 * @type string       $methods
277
+	 * @type boolean      $hidden_endpoint
278
+	 * }
279
+	 */
280
+	public static function get_ee_route_data()
281
+	{
282
+		$ee_routes = array();
283
+		foreach (self::versions_served() as $version => $hidden_endpoints) {
284
+			$ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version(
285
+				$version,
286
+				$hidden_endpoints
287
+			);
288
+		}
289
+		return $ee_routes;
290
+	}
291
+
292
+
293
+	/**
294
+	 * Gets the EE route data from the wp options if it exists already,
295
+	 * otherwise re-generates it and saves it to the option
296
+	 *
297
+	 * @param string  $version
298
+	 * @param boolean $hidden_endpoints
299
+	 * @return array
300
+	 * @throws \EE_Error
301
+	 */
302
+	protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
303
+	{
304
+		$ee_routes = get_option(self::saved_routes_option_names . $version, null);
305
+		if (! $ee_routes || EED_Core_Rest_Api::debugMode()) {
306
+			$ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
307
+		}
308
+		return $ee_routes;
309
+	}
310
+
311
+
312
+	/**
313
+	 * Saves the EE REST API route data to a wp option and returns it
314
+	 *
315
+	 * @param string  $version
316
+	 * @param boolean $hidden_endpoints
317
+	 * @return mixed|null
318
+	 * @throws \EE_Error
319
+	 */
320
+	protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
321
+	{
322
+		$instance = self::instance();
323
+		$routes = apply_filters(
324
+			'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
325
+			array_replace_recursive(
326
+				$instance->_get_config_route_data_for_version($version, $hidden_endpoints),
327
+				$instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
328
+				$instance->_get_model_route_data_for_version($version, $hidden_endpoints),
329
+				$instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
330
+			)
331
+		);
332
+		$option_name = self::saved_routes_option_names . $version;
333
+		if (get_option($option_name)) {
334
+			update_option($option_name, $routes, true);
335
+		} else {
336
+			add_option($option_name, $routes, null, 'no');
337
+		}
338
+		return $routes;
339
+	}
340
+
341
+
342
+	/**
343
+	 * Calculates all the EE routes and saves it to a WordPress option so we don't
344
+	 * need to calculate it on every request
345
+	 *
346
+	 * @deprecated since version 4.9.1
347
+	 * @return void
348
+	 */
349
+	public static function save_ee_routes()
350
+	{
351
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
352
+			$instance = self::instance();
353
+			$routes = apply_filters(
354
+				'EED_Core_Rest_Api__save_ee_routes__routes',
355
+				array_replace_recursive(
356
+					$instance->_register_config_routes(),
357
+					$instance->_register_meta_routes(),
358
+					$instance->_register_model_routes(),
359
+					$instance->_register_rpc_routes()
360
+				)
361
+			);
362
+			update_option(self::saved_routes_option_names, $routes, true);
363
+		}
364
+	}
365
+
366
+
367
+	/**
368
+	 * Gets all the route information relating to EE models
369
+	 *
370
+	 * @return array @see get_ee_route_data
371
+	 * @deprecated since version 4.9.1
372
+	 */
373
+	protected function _register_model_routes()
374
+	{
375
+		$model_routes = array();
376
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
377
+			$model_routes[ EED_Core_Rest_Api::ee_api_namespace
378
+						   . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
379
+		}
380
+		return $model_routes;
381
+	}
382
+
383
+
384
+	/**
385
+	 * Decides whether or not to add write endpoints for this model.
386
+	 *
387
+	 * Currently, this defaults to exclude all global tables and models
388
+	 * which would allow inserting WP core data (we don't want to duplicate
389
+	 * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
390
+	 *
391
+	 * @param EEM_Base $model
392
+	 * @return bool
393
+	 */
394
+	public static function should_have_write_endpoints(EEM_Base $model)
395
+	{
396
+		if ($model->is_wp_core_model()) {
397
+			return false;
398
+		}
399
+		foreach ($model->get_tables() as $table) {
400
+			if ($table->is_global()) {
401
+				return false;
402
+			}
403
+		}
404
+		return true;
405
+	}
406
+
407
+
408
+	/**
409
+	 * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
410
+	 * in this versioned namespace of EE4
411
+	 *
412
+	 * @param $version
413
+	 * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
414
+	 */
415
+	public static function model_names_with_plural_routes($version)
416
+	{
417
+		$model_version_info = new ModelVersionInfo($version);
418
+		$models_to_register = $model_version_info->modelsForRequestedVersion();
419
+		// let's not bother having endpoints for extra metas
420
+		unset(
421
+			$models_to_register['Extra_Meta'],
422
+			$models_to_register['Extra_Join'],
423
+			$models_to_register['Post_Meta']
424
+		);
425
+		return apply_filters(
426
+			'FHEE__EED_Core_REST_API___register_model_routes',
427
+			$models_to_register
428
+		);
429
+	}
430
+
431
+
432
+	/**
433
+	 * Gets the route data for EE models in the specified version
434
+	 *
435
+	 * @param string  $version
436
+	 * @param boolean $hidden_endpoint
437
+	 * @return array
438
+	 * @throws EE_Error
439
+	 */
440
+	protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
441
+	{
442
+		$model_routes = array();
443
+		$model_version_info = new ModelVersionInfo($version);
444
+		foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
445
+			$model = \EE_Registry::instance()->load_model($model_name);
446
+			// if this isn't a valid model then let's skip iterate to the next item in the loop.
447
+			if (! $model instanceof EEM_Base) {
448
+				continue;
449
+			}
450
+			// yes we could just register one route for ALL models, but then they wouldn't show up in the index
451
+			$plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
452
+			$singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
453
+			$model_routes[ $plural_model_route ] = array(
454
+				array(
455
+					'callback'        => array(
456
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
457
+						'handleRequestGetAll',
458
+					),
459
+					'callback_args'   => array($version, $model_name),
460
+					'methods'         => WP_REST_Server::READABLE,
461
+					'hidden_endpoint' => $hidden_endpoint,
462
+					'args'            => $this->_get_read_query_params($model, $version),
463
+					'_links'          => array(
464
+						'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
465
+					),
466
+				),
467
+				'schema' => array(
468
+					'schema_callback' => array(
469
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
470
+						'handleSchemaRequest',
471
+					),
472
+					'callback_args'   => array($version, $model_name),
473
+				),
474
+			);
475
+			$model_routes[ $singular_model_route ] = array(
476
+				array(
477
+					'callback'        => array(
478
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
479
+						'handleRequestGetOne',
480
+					),
481
+					'callback_args'   => array($version, $model_name),
482
+					'methods'         => WP_REST_Server::READABLE,
483
+					'hidden_endpoint' => $hidden_endpoint,
484
+					'args'            => $this->_get_response_selection_query_params($model, $version, true),
485
+				),
486
+			);
487
+			if (apply_filters(
488
+				'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
489
+				EED_Core_Rest_Api::should_have_write_endpoints($model),
490
+				$model
491
+			)) {
492
+				$model_routes[ $plural_model_route ][] = array(
493
+					'callback'        => array(
494
+						'EventEspresso\core\libraries\rest_api\controllers\model\Write',
495
+						'handleRequestInsert',
496
+					),
497
+					'callback_args'   => array($version, $model_name),
498
+					'methods'         => WP_REST_Server::CREATABLE,
499
+					'hidden_endpoint' => $hidden_endpoint,
500
+					'args'            => $this->_get_write_params($model_name, $model_version_info, true),
501
+				);
502
+				$model_routes[ $singular_model_route ] = array_merge(
503
+					$model_routes[ $singular_model_route ],
504
+					array(
505
+						array(
506
+							'callback'        => array(
507
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
508
+								'handleRequestUpdate',
509
+							),
510
+							'callback_args'   => array($version, $model_name),
511
+							'methods'         => WP_REST_Server::EDITABLE,
512
+							'hidden_endpoint' => $hidden_endpoint,
513
+							'args'            => $this->_get_write_params($model_name, $model_version_info),
514
+						),
515
+						array(
516
+							'callback'        => array(
517
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
518
+								'handleRequestDelete',
519
+							),
520
+							'callback_args'   => array($version, $model_name),
521
+							'methods'         => WP_REST_Server::DELETABLE,
522
+							'hidden_endpoint' => $hidden_endpoint,
523
+							'args'            => $this->_get_delete_query_params($model, $version),
524
+						),
525
+					)
526
+				);
527
+			}
528
+			foreach ($model->relation_settings() as $relation_name => $relation_obj) {
529
+				$related_route = EED_Core_Rest_Api::get_relation_route_via(
530
+					$model,
531
+					'(?P<id>[^\/]+)',
532
+					$relation_obj
533
+				);
534
+				$model_routes[ $related_route ] = array(
535
+					array(
536
+						'callback'        => array(
537
+							'EventEspresso\core\libraries\rest_api\controllers\model\Read',
538
+							'handleRequestGetRelated',
539
+						),
540
+						'callback_args'   => array($version, $model_name, $relation_name),
541
+						'methods'         => WP_REST_Server::READABLE,
542
+						'hidden_endpoint' => $hidden_endpoint,
543
+						'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
544
+					),
545
+				);
546
+
547
+				$related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)';
548
+				$model_routes[ $related_write_route ] = array(
549
+					array(
550
+						'callback'        => array(
551
+							'EventEspresso\core\libraries\rest_api\controllers\model\Write',
552
+							'handleRequestAddRelation',
553
+						),
554
+						'callback_args'   => array($version, $model_name, $relation_name),
555
+						'methods'         => WP_REST_Server::EDITABLE,
556
+						'hidden_endpoint' => $hidden_endpoint,
557
+						'args'            => $this->_get_add_relation_query_params($model, $relation_obj->get_other_model(), $version)
558
+					),
559
+					array(
560
+						'callback'        => array(
561
+							'EventEspresso\core\libraries\rest_api\controllers\model\Write',
562
+							'handleRequestRemoveRelation',
563
+						),
564
+						'callback_args'   => array($version, $model_name, $relation_name),
565
+						'methods'         => WP_REST_Server::DELETABLE,
566
+						'hidden_endpoint' => $hidden_endpoint,
567
+						'args'            => array()
568
+					),
569
+				);
570
+			}
571
+		}
572
+		return $model_routes;
573
+	}
574
+
575
+
576
+	/**
577
+	 * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
578
+	 * excluding the preceding slash.
579
+	 * Eg you pass get_plural_route_to('Event') = 'events'
580
+	 *
581
+	 * @param EEM_Base $model
582
+	 * @return string
583
+	 */
584
+	public static function get_collection_route(EEM_Base $model)
585
+	{
586
+		return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
587
+	}
588
+
589
+
590
+	/**
591
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
592
+	 * excluding the preceding slash.
593
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
594
+	 *
595
+	 * @param EEM_Base $model eg Event or Venue
596
+	 * @param string   $id
597
+	 * @return string
598
+	 */
599
+	public static function get_entity_route($model, $id)
600
+	{
601
+		return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id;
602
+	}
603
+
604
+
605
+	/**
606
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
607
+	 * excluding the preceding slash.
608
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
609
+	 *
610
+	 * @param EEM_Base               $model eg Event or Venue
611
+	 * @param string                 $id
612
+	 * @param EE_Model_Relation_Base $relation_obj
613
+	 * @return string
614
+	 */
615
+	public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
616
+	{
617
+		$related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
618
+			$relation_obj->get_other_model()->get_this_model_name(),
619
+			$relation_obj
620
+		);
621
+		return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
622
+	}
623
+
624
+
625
+	/**
626
+	 * Adds onto the $relative_route the EE4 REST API versioned namespace.
627
+	 * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
628
+	 *
629
+	 * @param string $relative_route
630
+	 * @param string $version
631
+	 * @return string
632
+	 */
633
+	public static function get_versioned_route_to($relative_route, $version = '4.8.36')
634
+	{
635
+		return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
636
+	}
637
+
638
+
639
+	/**
640
+	 * Adds all the RPC-style routes (remote procedure call-like routes, ie
641
+	 * routes that don't conform to the traditional REST CRUD-style).
642
+	 *
643
+	 * @deprecated since 4.9.1
644
+	 */
645
+	protected function _register_rpc_routes()
646
+	{
647
+		$routes = array();
648
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
649
+			$routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version(
650
+				$version,
651
+				$hidden_endpoint
652
+			);
653
+		}
654
+		return $routes;
655
+	}
656
+
657
+
658
+	/**
659
+	 * @param string  $version
660
+	 * @param boolean $hidden_endpoint
661
+	 * @return array
662
+	 */
663
+	protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
664
+	{
665
+		$this_versions_routes = array();
666
+		// checkin endpoint
667
+		$this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
668
+			array(
669
+				'callback'        => array(
670
+					'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
671
+					'handleRequestToggleCheckin',
672
+				),
673
+				'methods'         => WP_REST_Server::CREATABLE,
674
+				'hidden_endpoint' => $hidden_endpoint,
675
+				'args'            => array(
676
+					'force' => array(
677
+						'required'    => false,
678
+						'default'     => false,
679
+						'description' => __(
680
+						// @codingStandardsIgnoreStart
681
+							'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
682
+							// @codingStandardsIgnoreEnd
683
+							'event_espresso'
684
+						),
685
+					),
686
+				),
687
+				'callback_args'   => array($version),
688
+			),
689
+		);
690
+		return apply_filters(
691
+			'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
692
+			$this_versions_routes,
693
+			$version,
694
+			$hidden_endpoint
695
+		);
696
+	}
697
+
698
+
699
+	/**
700
+	 * Gets the query params that can be used when request one or many
701
+	 *
702
+	 * @param EEM_Base $model
703
+	 * @param string   $version
704
+	 * @return array
705
+	 */
706
+	protected function _get_response_selection_query_params(\EEM_Base $model, $version, $single_only = false)
707
+	{
708
+		$query_params = array(
709
+			'include'   => array(
710
+				'required' => false,
711
+				'default'  => '*',
712
+				'type'     => 'string',
713
+			),
714
+			'calculate' => array(
715
+				'required'          => false,
716
+				'default'           => '',
717
+				'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
718
+				'type'              => 'string',
719
+				// because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
720
+				// freaks out. We'll just validate this argument while handling the request
721
+				'validate_callback' => null,
722
+				'sanitize_callback' => null,
723
+			),
724
+			'password' => array(
725
+				'required' => false,
726
+				'default' => '',
727
+				'type' => 'string'
728
+			)
729
+		);
730
+		return apply_filters(
731
+			'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
732
+			$query_params,
733
+			$model,
734
+			$version
735
+		);
736
+	}
737
+
738
+
739
+	/**
740
+	 * Gets the parameters acceptable for delete requests
741
+	 *
742
+	 * @param \EEM_Base $model
743
+	 * @param string    $version
744
+	 * @return array
745
+	 */
746
+	protected function _get_delete_query_params(\EEM_Base $model, $version)
747
+	{
748
+		$params_for_delete = array(
749
+			'allow_blocking' => array(
750
+				'required' => false,
751
+				'default'  => true,
752
+				'type'     => 'boolean',
753
+			),
754
+		);
755
+		$params_for_delete['force'] = array(
756
+			'required' => false,
757
+			'default'  => false,
758
+			'type'     => 'boolean',
759
+		);
760
+		return apply_filters(
761
+			'FHEE__EED_Core_Rest_Api___get_delete_query_params',
762
+			$params_for_delete,
763
+			$model,
764
+			$version
765
+		);
766
+	}
767
+
768
+	protected function _get_add_relation_query_params(\EEM_Base $source_model, \EEM_Base $related_model, $version)
769
+	{
770
+		// if they're related through a HABTM relation, check for any non-FKs
771
+		$all_relation_settings = $source_model->relation_settings();
772
+		$relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ];
773
+		$params = array();
774
+		if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) {
775
+			foreach ($relation_settings->getNonKeyFields() as $field) {
776
+				/* @var $field EE_Model_Field_Base */
777
+				$params[ $field->get_name() ] = array(
778
+					'required' => ! $field->is_nullable(),
779
+					'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version),
780
+					'type' => $field->getSchemaType(),
781
+					'validate_callbaack' => null,
782
+					'sanitize_callback' => null
783
+				);
784
+			}
785
+		}
786
+		return $params;
787
+	}
788
+
789
+
790
+	/**
791
+	 * Gets info about reading query params that are acceptable
792
+	 *
793
+	 * @param \EEM_Base $model eg 'Event' or 'Venue'
794
+	 * @param  string   $version
795
+	 * @return array    describing the args acceptable when querying this model
796
+	 * @throws EE_Error
797
+	 */
798
+	protected function _get_read_query_params(\EEM_Base $model, $version)
799
+	{
800
+		$default_orderby = array();
801
+		foreach ($model->get_combined_primary_key_fields() as $key_field) {
802
+			$default_orderby[ $key_field->get_name() ] = 'ASC';
803
+		}
804
+		return array_merge(
805
+			$this->_get_response_selection_query_params($model, $version),
806
+			array(
807
+				'where'    => array(
808
+					'required'          => false,
809
+					'default'           => array(),
810
+					'type'              => 'object',
811
+					// because we accept an almost infinite list of possible where conditions, WP
812
+					// core validation and sanitization freaks out. We'll just validate this argument
813
+					// while handling the request
814
+					'validate_callback' => null,
815
+					'sanitize_callback' => null,
816
+				),
817
+				'limit'    => array(
818
+					'required'          => false,
819
+					'default'           => EED_Core_Rest_Api::get_default_query_limit(),
820
+					'type'              => array(
821
+						'array',
822
+						'string',
823
+						'integer',
824
+					),
825
+					// because we accept a variety of types, WP core validation and sanitization
826
+					// freaks out. We'll just validate this argument while handling the request
827
+					'validate_callback' => null,
828
+					'sanitize_callback' => null,
829
+				),
830
+				'order_by' => array(
831
+					'required'          => false,
832
+					'default'           => $default_orderby,
833
+					'type'              => array(
834
+						'object',
835
+						'string',
836
+					),// because we accept a variety of types, WP core validation and sanitization
837
+					// freaks out. We'll just validate this argument while handling the request
838
+					'validate_callback' => null,
839
+					'sanitize_callback' => null,
840
+				),
841
+				'group_by' => array(
842
+					'required'          => false,
843
+					'default'           => null,
844
+					'type'              => array(
845
+						'object',
846
+						'string',
847
+					),
848
+					// because we accept  an almost infinite list of possible groupings,
849
+					// WP core validation and sanitization
850
+					// freaks out. We'll just validate this argument while handling the request
851
+					'validate_callback' => null,
852
+					'sanitize_callback' => null,
853
+				),
854
+				'having'   => array(
855
+					'required'          => false,
856
+					'default'           => null,
857
+					'type'              => 'object',
858
+					// because we accept an almost infinite list of possible where conditions, WP
859
+					// core validation and sanitization freaks out. We'll just validate this argument
860
+					// while handling the request
861
+					'validate_callback' => null,
862
+					'sanitize_callback' => null,
863
+				),
864
+				'caps'     => array(
865
+					'required' => false,
866
+					'default'  => EEM_Base::caps_read,
867
+					'type'     => 'string',
868
+					'enum'     => array(
869
+						EEM_Base::caps_read,
870
+						EEM_Base::caps_read_admin,
871
+						EEM_Base::caps_edit,
872
+						EEM_Base::caps_delete,
873
+					),
874
+				),
875
+			)
876
+		);
877
+	}
878
+
879
+
880
+	/**
881
+	 * Gets parameter information for a model regarding writing data
882
+	 *
883
+	 * @param string           $model_name
884
+	 * @param ModelVersionInfo $model_version_info
885
+	 * @param boolean          $create                                       whether this is for request to create (in
886
+	 *                                                                       which case we need all required params) or
887
+	 *                                                                       just to update (in which case we don't
888
+	 *                                                                       need those on every request)
889
+	 * @return array
890
+	 */
891
+	protected function _get_write_params(
892
+		$model_name,
893
+		ModelVersionInfo $model_version_info,
894
+		$create = false
895
+	) {
896
+		$model = EE_Registry::instance()->load_model($model_name);
897
+		$fields = $model_version_info->fieldsOnModelInThisVersion($model);
898
+		$args_info = array();
899
+		foreach ($fields as $field_name => $field_obj) {
900
+			if ($field_obj->is_auto_increment()) {
901
+				// totally ignore auto increment IDs
902
+				continue;
903
+			}
904
+			$arg_info = $field_obj->getSchema();
905
+			$required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
906
+			$arg_info['required'] = $required;
907
+			// remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
908
+			unset($arg_info['readonly']);
909
+			$schema_properties = $field_obj->getSchemaProperties();
910
+			if (isset($schema_properties['raw'])
911
+				&& $field_obj->getSchemaType() === 'object'
912
+			) {
913
+				// if there's a "raw" form of this argument, use those properties instead
914
+				$arg_info = array_replace(
915
+					$arg_info,
916
+					$schema_properties['raw']
917
+				);
918
+			}
919
+			$arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
920
+				$field_obj,
921
+				$field_obj->get_default_value(),
922
+				$model_version_info->requestedVersion()
923
+			);
924
+			// we do our own validation and sanitization within the controller
925
+			if (function_exists('rest_validate_value_from_schema')) {
926
+				$sanitize_callback = array(
927
+					'EED_Core_Rest_Api',
928
+					'default_sanitize_callback',
929
+				);
930
+			} else {
931
+				$sanitize_callback = null;
932
+			}
933
+			$arg_info['sanitize_callback'] = $sanitize_callback;
934
+			$args_info[ $field_name ] = $arg_info;
935
+			if ($field_obj instanceof EE_Datetime_Field) {
936
+				$gmt_arg_info = $arg_info;
937
+				$gmt_arg_info['description'] = sprintf(
938
+					esc_html__(
939
+						'%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
940
+						'event_espresso'
941
+					),
942
+					$field_obj->get_nicename(),
943
+					$field_name
944
+				);
945
+				$args_info[ $field_name . '_gmt' ] = $gmt_arg_info;
946
+			}
947
+		}
948
+		return $args_info;
949
+	}
950
+
951
+
952
+	/**
953
+	 * Replacement for WP API's 'rest_parse_request_arg'.
954
+	 * If the value is blank but not required, don't bother validating it.
955
+	 * Also, it uses our email validation instead of WP API's default.
956
+	 *
957
+	 * @param                 $value
958
+	 * @param WP_REST_Request $request
959
+	 * @param                 $param
960
+	 * @return bool|true|WP_Error
961
+	 * @throws InvalidArgumentException
962
+	 * @throws InvalidInterfaceException
963
+	 * @throws InvalidDataTypeException
964
+	 */
965
+	public static function default_sanitize_callback($value, WP_REST_Request $request, $param)
966
+	{
967
+		$attributes = $request->get_attributes();
968
+		if (! isset($attributes['args'][ $param ])
969
+			|| ! is_array($attributes['args'][ $param ])) {
970
+			$validation_result = true;
971
+		} else {
972
+			$args = $attributes['args'][ $param ];
973
+			if ((
974
+					$value === ''
975
+					|| $value === null
976
+				)
977
+				&& (! isset($args['required'])
978
+					|| $args['required'] === false
979
+				)
980
+			) {
981
+				// not required and not provided? that's cool
982
+				$validation_result = true;
983
+			} elseif (isset($args['format'])
984
+					  && $args['format'] === 'email'
985
+			) {
986
+				$validation_result = true;
987
+				if (! self::_validate_email($value)) {
988
+					$validation_result = new WP_Error(
989
+						'rest_invalid_param',
990
+						esc_html__(
991
+							'The email address is not valid or does not exist.',
992
+							'event_espresso'
993
+						)
994
+					);
995
+				}
996
+			} else {
997
+				$validation_result = rest_validate_value_from_schema($value, $args, $param);
998
+			}
999
+		}
1000
+		if (is_wp_error($validation_result)) {
1001
+			return $validation_result;
1002
+		}
1003
+		return rest_sanitize_request_arg($value, $request, $param);
1004
+	}
1005
+
1006
+
1007
+	/**
1008
+	 * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
1009
+	 *
1010
+	 * @param $email
1011
+	 * @return bool
1012
+	 * @throws InvalidArgumentException
1013
+	 * @throws InvalidInterfaceException
1014
+	 * @throws InvalidDataTypeException
1015
+	 */
1016
+	protected static function _validate_email($email)
1017
+	{
1018
+		try {
1019
+			EmailAddressFactory::create($email);
1020
+			return true;
1021
+		} catch (EmailValidationException $e) {
1022
+			return false;
1023
+		}
1024
+	}
1025
+
1026
+
1027
+	/**
1028
+	 * Gets routes for the config
1029
+	 *
1030
+	 * @return array @see _register_model_routes
1031
+	 * @deprecated since version 4.9.1
1032
+	 */
1033
+	protected function _register_config_routes()
1034
+	{
1035
+		$config_routes = array();
1036
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1037
+			$config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version(
1038
+				$version,
1039
+				$hidden_endpoint
1040
+			);
1041
+		}
1042
+		return $config_routes;
1043
+	}
1044
+
1045
+
1046
+	/**
1047
+	 * Gets routes for the config for the specified version
1048
+	 *
1049
+	 * @param string  $version
1050
+	 * @param boolean $hidden_endpoint
1051
+	 * @return array
1052
+	 */
1053
+	protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1054
+	{
1055
+		return array(
1056
+			'config'    => array(
1057
+				array(
1058
+					'callback'        => array(
1059
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1060
+						'handleRequest',
1061
+					),
1062
+					'methods'         => WP_REST_Server::READABLE,
1063
+					'hidden_endpoint' => $hidden_endpoint,
1064
+					'callback_args'   => array($version),
1065
+				),
1066
+			),
1067
+			'site_info' => array(
1068
+				array(
1069
+					'callback'        => array(
1070
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1071
+						'handleRequestSiteInfo',
1072
+					),
1073
+					'methods'         => WP_REST_Server::READABLE,
1074
+					'hidden_endpoint' => $hidden_endpoint,
1075
+					'callback_args'   => array($version),
1076
+				),
1077
+			),
1078
+		);
1079
+	}
1080
+
1081
+
1082
+	/**
1083
+	 * Gets the meta info routes
1084
+	 *
1085
+	 * @return array @see _register_model_routes
1086
+	 * @deprecated since version 4.9.1
1087
+	 */
1088
+	protected function _register_meta_routes()
1089
+	{
1090
+		$meta_routes = array();
1091
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1092
+			$meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version(
1093
+				$version,
1094
+				$hidden_endpoint
1095
+			);
1096
+		}
1097
+		return $meta_routes;
1098
+	}
1099
+
1100
+
1101
+	/**
1102
+	 * @param string  $version
1103
+	 * @param boolean $hidden_endpoint
1104
+	 * @return array
1105
+	 */
1106
+	protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1107
+	{
1108
+		return array(
1109
+			'resources' => array(
1110
+				array(
1111
+					'callback'        => array(
1112
+						'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1113
+						'handleRequestModelsMeta',
1114
+					),
1115
+					'methods'         => WP_REST_Server::READABLE,
1116
+					'hidden_endpoint' => $hidden_endpoint,
1117
+					'callback_args'   => array($version),
1118
+				),
1119
+			),
1120
+		);
1121
+	}
1122
+
1123
+
1124
+	/**
1125
+	 * Tries to hide old 4.6 endpoints from the
1126
+	 *
1127
+	 * @param array $route_data
1128
+	 * @return array
1129
+	 * @throws \EE_Error
1130
+	 */
1131
+	public static function hide_old_endpoints($route_data)
1132
+	{
1133
+		// allow API clients to override which endpoints get hidden, in case
1134
+		// they want to discover particular endpoints
1135
+		// also, we don't have access to the request so we have to just grab it from the superglobal
1136
+		$force_show_ee_namespace = ltrim(
1137
+			EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1138
+			'/'
1139
+		);
1140
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1141
+			foreach ($relative_urls as $resource_name => $endpoints) {
1142
+				foreach ($endpoints as $key => $endpoint) {
1143
+					// skip schema and other route options
1144
+					if (! is_numeric($key)) {
1145
+						continue;
1146
+					}
1147
+					// by default, hide "hidden_endpoint"s, unless the request indicates
1148
+					// to $force_show_ee_namespace, in which case only show that one
1149
+					// namespace's endpoints (and hide all others)
1150
+					if (($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1151
+						|| ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1152
+					) {
1153
+						$full_route = '/' . ltrim($namespace, '/');
1154
+						$full_route .= '/' . ltrim($resource_name, '/');
1155
+						unset($route_data[ $full_route ]);
1156
+					}
1157
+				}
1158
+			}
1159
+		}
1160
+		return $route_data;
1161
+	}
1162
+
1163
+
1164
+	/**
1165
+	 * Returns an array describing which versions of core support serving requests for.
1166
+	 * Keys are core versions' major and minor version, and values are the
1167
+	 * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1168
+	 * data by just removing a few models and fields from the responses. However, 4.15 might remove
1169
+	 * the answers table entirely, in which case it would be very difficult for
1170
+	 * it to serve 4.6-style responses.
1171
+	 * Versions of core that are missing from this array are unknowns.
1172
+	 * previous ver
1173
+	 *
1174
+	 * @return array
1175
+	 */
1176
+	public static function version_compatibilities()
1177
+	{
1178
+		return apply_filters(
1179
+			'FHEE__EED_Core_REST_API__version_compatibilities',
1180
+			array(
1181
+				'4.8.29' => '4.8.29',
1182
+				'4.8.33' => '4.8.29',
1183
+				'4.8.34' => '4.8.29',
1184
+				'4.8.36' => '4.8.29',
1185
+			)
1186
+		);
1187
+	}
1188
+
1189
+
1190
+	/**
1191
+	 * Gets the latest API version served. Eg if there
1192
+	 * are two versions served of the API, 4.8.29 and 4.8.32, and
1193
+	 * we are on core version 4.8.34, it will return the string "4.8.32"
1194
+	 *
1195
+	 * @return string
1196
+	 */
1197
+	public static function latest_rest_api_version()
1198
+	{
1199
+		$versions_served = \EED_Core_Rest_Api::versions_served();
1200
+		$versions_served_keys = array_keys($versions_served);
1201
+		return end($versions_served_keys);
1202
+	}
1203
+
1204
+
1205
+	/**
1206
+	 * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1207
+	 * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1208
+	 * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1209
+	 * We also indicate whether or not this version should be put in the index or not
1210
+	 *
1211
+	 * @return array keys are API version numbers (just major and minor numbers), and values
1212
+	 * are whether or not they should be hidden
1213
+	 */
1214
+	public static function versions_served()
1215
+	{
1216
+		$versions_served = array();
1217
+		$possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1218
+		$lowest_compatible_version = end($possibly_served_versions);
1219
+		reset($possibly_served_versions);
1220
+		$versions_served_historically = array_keys($possibly_served_versions);
1221
+		$latest_version = end($versions_served_historically);
1222
+		reset($versions_served_historically);
1223
+		// for each version of core we have ever served:
1224
+		foreach ($versions_served_historically as $key_versioned_endpoint) {
1225
+			// if it's not above the current core version, and it's compatible with the current version of core
1226
+
1227
+			if ($key_versioned_endpoint === $latest_version) {
1228
+				// don't hide the latest version in the index
1229
+				$versions_served[ $key_versioned_endpoint ] = false;
1230
+			} elseif (version_compare($key_versioned_endpoint, $lowest_compatible_version, '>=')
1231
+				&& version_compare($key_versioned_endpoint, EED_Core_Rest_Api::core_version(), '<')
1232
+			) {
1233
+				// include, but hide, previous versions which are still supported
1234
+				$versions_served[ $key_versioned_endpoint ] = true;
1235
+			} elseif (apply_filters(
1236
+				'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1237
+				false,
1238
+				$possibly_served_versions
1239
+			)) {
1240
+				// if a version is no longer supported, don't include it in index or list of versions served
1241
+				$versions_served[ $key_versioned_endpoint ] = true;
1242
+			}
1243
+		}
1244
+		return $versions_served;
1245
+	}
1246
+
1247
+
1248
+	/**
1249
+	 * Gets the major and minor version of EE core's version string
1250
+	 *
1251
+	 * @return string
1252
+	 */
1253
+	public static function core_version()
1254
+	{
1255
+		return apply_filters(
1256
+			'FHEE__EED_Core_REST_API__core_version',
1257
+			implode(
1258
+				'.',
1259
+				array_slice(
1260
+					explode(
1261
+						'.',
1262
+						espresso_version()
1263
+					),
1264
+					0,
1265
+					3
1266
+				)
1267
+			)
1268
+		);
1269
+	}
1270
+
1271
+
1272
+	/**
1273
+	 * Gets the default limit that should be used when querying for resources
1274
+	 *
1275
+	 * @return int
1276
+	 */
1277
+	public static function get_default_query_limit()
1278
+	{
1279
+		// we actually don't use a const because we want folks to always use
1280
+		// this method, not the const directly
1281
+		return apply_filters(
1282
+			'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1283
+			50
1284
+		);
1285
+	}
1286
+
1287
+
1288
+	/**
1289
+	 *
1290
+	 * @param string $version api version string (i.e. '4.8.36')
1291
+	 * @return array
1292
+	 */
1293
+	public static function getCollectionRoutesIndexedByModelName($version = '')
1294
+	{
1295
+		$version = empty($version) ? self::latest_rest_api_version() : $version;
1296
+		$model_names = self::model_names_with_plural_routes($version);
1297
+		$collection_routes = array();
1298
+		foreach ($model_names as $model_name => $model_class_name) {
1299
+			$collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/'
1300
+															. EEH_Inflector::pluralize_and_lower($model_name);
1301
+		}
1302
+		return $collection_routes;
1303
+	}
1304
+
1305
+
1306
+	/**
1307
+	 * Returns an array of primary key names indexed by model names.
1308
+	 * @param string $version
1309
+	 * @return array
1310
+	 */
1311
+	public static function getPrimaryKeyNamesIndexedByModelName($version = '')
1312
+	{
1313
+		$version = empty($version) ? self::latest_rest_api_version() : $version;
1314
+		$model_names = self::model_names_with_plural_routes($version);
1315
+		$primary_key_items = array();
1316
+		foreach ($model_names as $model_name => $model_class_name) {
1317
+			$primary_keys = $model_class_name::instance()->get_combined_primary_key_fields();
1318
+			foreach ($primary_keys as $primary_key_name => $primary_key_field) {
1319
+				if (count($primary_keys) > 1) {
1320
+					$primary_key_items[ strtolower($model_name) ][] = $primary_key_name;
1321
+				} else {
1322
+					$primary_key_items[ strtolower($model_name) ] = $primary_key_name;
1323
+				}
1324
+			}
1325
+		}
1326
+		return $primary_key_items;
1327
+	}
1328
+
1329
+	/**
1330
+	 * Determines the EE REST API debug mode is activated, or not.
1331
+	 * @since 4.9.76.p
1332
+	 * @return bool
1333
+	 */
1334
+	public static function debugMode()
1335
+	{
1336
+		static $debug_mode = null; // could be class prop
1337
+		if ($debug_mode === null) {
1338
+			$debug_mode = defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE;
1339
+		}
1340
+		return $debug_mode;
1341
+	}
1342
+
1343
+
1344
+
1345
+	/**
1346
+	 *    run - initial module setup
1347
+	 *
1348
+	 * @access    public
1349
+	 * @param  WP $WP
1350
+	 * @return    void
1351
+	 */
1352
+	public function run($WP)
1353
+	{
1354
+	}
1355 1355
 }
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
      */
124 124
     protected static function _set_hooks_for_changes()
125 125
     {
126
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api/changes'), false);
126
+        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES.'rest_api/changes'), false);
127 127
         foreach ($folder_contents as $classname_in_namespace => $filepath) {
128 128
             // ignore the base parent class
129 129
             // and legacy named classes
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
             ) {
133 133
                 continue;
134 134
             }
135
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
135
+            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\'.$classname_in_namespace;
136 136
             if (class_exists($full_classname)) {
137 137
                 $instance_of_class = new $full_classname;
138 138
                 if ($instance_of_class instanceof ChangesInBase) {
@@ -177,10 +177,10 @@  discard block
 block discarded – undo
177 177
                      * }
178 178
                      */
179 179
                     // skip route options
180
-                    if (! is_numeric($endpoint_key)) {
180
+                    if ( ! is_numeric($endpoint_key)) {
181 181
                         continue;
182 182
                     }
183
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
183
+                    if ( ! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
184 184
                         throw new EE_Error(
185 185
                             esc_html__(
186 186
                             // @codingStandardsIgnoreStart
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
                     }
202 202
                     if (isset($data_for_single_endpoint['callback_args'])) {
203 203
                         $callback_args = $data_for_single_endpoint['callback_args'];
204
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
204
+                        $single_endpoint_args['callback'] = function(\WP_REST_Request $request) use (
205 205
                             $callback,
206 206
                             $callback_args
207 207
                         ) {
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
                     $schema_route_data = $data_for_multiple_endpoints['schema'];
221 221
                     $schema_callback = $schema_route_data['schema_callback'];
222 222
                     $callback_args = $schema_route_data['callback_args'];
223
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
223
+                    $multiple_endpoint_args['schema'] = function() use ($schema_callback, $callback_args) {
224 224
                         return call_user_func_array(
225 225
                             $schema_callback,
226 226
                             $callback_args
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
     {
263 263
         // delete the saved EE REST API routes
264 264
         foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
265
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
265
+            delete_option(EED_Core_Rest_Api::saved_routes_option_names.$version);
266 266
         }
267 267
     }
268 268
 
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
     {
282 282
         $ee_routes = array();
283 283
         foreach (self::versions_served() as $version => $hidden_endpoints) {
284
-            $ee_routes[ self::ee_api_namespace . $version ] = self::_get_ee_route_data_for_version(
284
+            $ee_routes[self::ee_api_namespace.$version] = self::_get_ee_route_data_for_version(
285 285
                 $version,
286 286
                 $hidden_endpoints
287 287
             );
@@ -301,8 +301,8 @@  discard block
 block discarded – undo
301 301
      */
302 302
     protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
303 303
     {
304
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
305
-        if (! $ee_routes || EED_Core_Rest_Api::debugMode()) {
304
+        $ee_routes = get_option(self::saved_routes_option_names.$version, null);
305
+        if ( ! $ee_routes || EED_Core_Rest_Api::debugMode()) {
306 306
             $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
307 307
         }
308 308
         return $ee_routes;
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
                 $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
330 330
             )
331 331
         );
332
-        $option_name = self::saved_routes_option_names . $version;
332
+        $option_name = self::saved_routes_option_names.$version;
333 333
         if (get_option($option_name)) {
334 334
             update_option($option_name, $routes, true);
335 335
         } else {
@@ -374,8 +374,8 @@  discard block
 block discarded – undo
374 374
     {
375 375
         $model_routes = array();
376 376
         foreach (self::versions_served() as $version => $hidden_endpoint) {
377
-            $model_routes[ EED_Core_Rest_Api::ee_api_namespace
378
-                           . $version ] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
377
+            $model_routes[EED_Core_Rest_Api::ee_api_namespace
378
+                           . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
379 379
         }
380 380
         return $model_routes;
381 381
     }
@@ -444,13 +444,13 @@  discard block
 block discarded – undo
444 444
         foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
445 445
             $model = \EE_Registry::instance()->load_model($model_name);
446 446
             // if this isn't a valid model then let's skip iterate to the next item in the loop.
447
-            if (! $model instanceof EEM_Base) {
447
+            if ( ! $model instanceof EEM_Base) {
448 448
                 continue;
449 449
             }
450 450
             // yes we could just register one route for ALL models, but then they wouldn't show up in the index
451 451
             $plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
452 452
             $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
453
-            $model_routes[ $plural_model_route ] = array(
453
+            $model_routes[$plural_model_route] = array(
454 454
                 array(
455 455
                     'callback'        => array(
456 456
                         'EventEspresso\core\libraries\rest_api\controllers\model\Read',
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
                     'hidden_endpoint' => $hidden_endpoint,
462 462
                     'args'            => $this->_get_read_query_params($model, $version),
463 463
                     '_links'          => array(
464
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
464
+                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace.$version.$singular_model_route),
465 465
                     ),
466 466
                 ),
467 467
                 'schema' => array(
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
                     'callback_args'   => array($version, $model_name),
473 473
                 ),
474 474
             );
475
-            $model_routes[ $singular_model_route ] = array(
475
+            $model_routes[$singular_model_route] = array(
476 476
                 array(
477 477
                     'callback'        => array(
478 478
                         'EventEspresso\core\libraries\rest_api\controllers\model\Read',
@@ -489,7 +489,7 @@  discard block
 block discarded – undo
489 489
                 EED_Core_Rest_Api::should_have_write_endpoints($model),
490 490
                 $model
491 491
             )) {
492
-                $model_routes[ $plural_model_route ][] = array(
492
+                $model_routes[$plural_model_route][] = array(
493 493
                     'callback'        => array(
494 494
                         'EventEspresso\core\libraries\rest_api\controllers\model\Write',
495 495
                         'handleRequestInsert',
@@ -499,8 +499,8 @@  discard block
 block discarded – undo
499 499
                     'hidden_endpoint' => $hidden_endpoint,
500 500
                     'args'            => $this->_get_write_params($model_name, $model_version_info, true),
501 501
                 );
502
-                $model_routes[ $singular_model_route ] = array_merge(
503
-                    $model_routes[ $singular_model_route ],
502
+                $model_routes[$singular_model_route] = array_merge(
503
+                    $model_routes[$singular_model_route],
504 504
                     array(
505 505
                         array(
506 506
                             'callback'        => array(
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
                     '(?P<id>[^\/]+)',
532 532
                     $relation_obj
533 533
                 );
534
-                $model_routes[ $related_route ] = array(
534
+                $model_routes[$related_route] = array(
535 535
                     array(
536 536
                         'callback'        => array(
537 537
                             'EventEspresso\core\libraries\rest_api\controllers\model\Read',
@@ -544,8 +544,8 @@  discard block
 block discarded – undo
544 544
                     ),
545 545
                 );
546 546
 
547
-                $related_write_route = $related_route . '/' . '(?P<related_id>[^\/]+)';
548
-                $model_routes[ $related_write_route ] = array(
547
+                $related_write_route = $related_route.'/'.'(?P<related_id>[^\/]+)';
548
+                $model_routes[$related_write_route] = array(
549 549
                     array(
550 550
                         'callback'        => array(
551 551
                             'EventEspresso\core\libraries\rest_api\controllers\model\Write',
@@ -598,7 +598,7 @@  discard block
 block discarded – undo
598 598
      */
599 599
     public static function get_entity_route($model, $id)
600 600
     {
601
-        return EED_Core_Rest_Api::get_collection_route($model) . '/' . $id;
601
+        return EED_Core_Rest_Api::get_collection_route($model).'/'.$id;
602 602
     }
603 603
 
604 604
 
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
             $relation_obj->get_other_model()->get_this_model_name(),
619 619
             $relation_obj
620 620
         );
621
-        return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
621
+        return EED_Core_Rest_Api::get_entity_route($model, $id).'/'.$related_model_name_endpoint_part;
622 622
     }
623 623
 
624 624
 
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
      */
633 633
     public static function get_versioned_route_to($relative_route, $version = '4.8.36')
634 634
     {
635
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
635
+        return '/'.EED_Core_Rest_Api::ee_api_namespace.$version.'/'.$relative_route;
636 636
     }
637 637
 
638 638
 
@@ -646,7 +646,7 @@  discard block
 block discarded – undo
646 646
     {
647 647
         $routes = array();
648 648
         foreach (self::versions_served() as $version => $hidden_endpoint) {
649
-            $routes[ self::ee_api_namespace . $version ] = $this->_get_rpc_route_data_for_version(
649
+            $routes[self::ee_api_namespace.$version] = $this->_get_rpc_route_data_for_version(
650 650
                 $version,
651 651
                 $hidden_endpoint
652 652
             );
@@ -769,12 +769,12 @@  discard block
 block discarded – undo
769 769
     {
770 770
         // if they're related through a HABTM relation, check for any non-FKs
771 771
         $all_relation_settings = $source_model->relation_settings();
772
-        $relation_settings = $all_relation_settings[ $related_model->get_this_model_name() ];
772
+        $relation_settings = $all_relation_settings[$related_model->get_this_model_name()];
773 773
         $params = array();
774 774
         if ($relation_settings instanceof EE_HABTM_Relation && $relation_settings->hasNonKeyFields()) {
775 775
             foreach ($relation_settings->getNonKeyFields() as $field) {
776 776
                 /* @var $field EE_Model_Field_Base */
777
-                $params[ $field->get_name() ] = array(
777
+                $params[$field->get_name()] = array(
778 778
                     'required' => ! $field->is_nullable(),
779 779
                     'default' => ModelDataTranslator::prepareFieldValueForJson($field, $field->get_default_value(), $version),
780 780
                     'type' => $field->getSchemaType(),
@@ -799,7 +799,7 @@  discard block
 block discarded – undo
799 799
     {
800 800
         $default_orderby = array();
801 801
         foreach ($model->get_combined_primary_key_fields() as $key_field) {
802
-            $default_orderby[ $key_field->get_name() ] = 'ASC';
802
+            $default_orderby[$key_field->get_name()] = 'ASC';
803 803
         }
804 804
         return array_merge(
805 805
             $this->_get_response_selection_query_params($model, $version),
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
                     'type'              => array(
834 834
                         'object',
835 835
                         'string',
836
-                    ),// because we accept a variety of types, WP core validation and sanitization
836
+                    ), // because we accept a variety of types, WP core validation and sanitization
837 837
                     // freaks out. We'll just validate this argument while handling the request
838 838
                     'validate_callback' => null,
839 839
                     'sanitize_callback' => null,
@@ -931,7 +931,7 @@  discard block
 block discarded – undo
931 931
                 $sanitize_callback = null;
932 932
             }
933 933
             $arg_info['sanitize_callback'] = $sanitize_callback;
934
-            $args_info[ $field_name ] = $arg_info;
934
+            $args_info[$field_name] = $arg_info;
935 935
             if ($field_obj instanceof EE_Datetime_Field) {
936 936
                 $gmt_arg_info = $arg_info;
937 937
                 $gmt_arg_info['description'] = sprintf(
@@ -942,7 +942,7 @@  discard block
 block discarded – undo
942 942
                     $field_obj->get_nicename(),
943 943
                     $field_name
944 944
                 );
945
-                $args_info[ $field_name . '_gmt' ] = $gmt_arg_info;
945
+                $args_info[$field_name.'_gmt'] = $gmt_arg_info;
946 946
             }
947 947
         }
948 948
         return $args_info;
@@ -965,16 +965,16 @@  discard block
 block discarded – undo
965 965
     public static function default_sanitize_callback($value, WP_REST_Request $request, $param)
966 966
     {
967 967
         $attributes = $request->get_attributes();
968
-        if (! isset($attributes['args'][ $param ])
969
-            || ! is_array($attributes['args'][ $param ])) {
968
+        if ( ! isset($attributes['args'][$param])
969
+            || ! is_array($attributes['args'][$param])) {
970 970
             $validation_result = true;
971 971
         } else {
972
-            $args = $attributes['args'][ $param ];
972
+            $args = $attributes['args'][$param];
973 973
             if ((
974 974
                     $value === ''
975 975
                     || $value === null
976 976
                 )
977
-                && (! isset($args['required'])
977
+                && ( ! isset($args['required'])
978 978
                     || $args['required'] === false
979 979
                 )
980 980
             ) {
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
                       && $args['format'] === 'email'
985 985
             ) {
986 986
                 $validation_result = true;
987
-                if (! self::_validate_email($value)) {
987
+                if ( ! self::_validate_email($value)) {
988 988
                     $validation_result = new WP_Error(
989 989
                         'rest_invalid_param',
990 990
                         esc_html__(
@@ -1034,7 +1034,7 @@  discard block
 block discarded – undo
1034 1034
     {
1035 1035
         $config_routes = array();
1036 1036
         foreach (self::versions_served() as $version => $hidden_endpoint) {
1037
-            $config_routes[ self::ee_api_namespace . $version ] = $this->_get_config_route_data_for_version(
1037
+            $config_routes[self::ee_api_namespace.$version] = $this->_get_config_route_data_for_version(
1038 1038
                 $version,
1039 1039
                 $hidden_endpoint
1040 1040
             );
@@ -1089,7 +1089,7 @@  discard block
 block discarded – undo
1089 1089
     {
1090 1090
         $meta_routes = array();
1091 1091
         foreach (self::versions_served() as $version => $hidden_endpoint) {
1092
-            $meta_routes[ self::ee_api_namespace . $version ] = $this->_get_meta_route_data_for_version(
1092
+            $meta_routes[self::ee_api_namespace.$version] = $this->_get_meta_route_data_for_version(
1093 1093
                 $version,
1094 1094
                 $hidden_endpoint
1095 1095
             );
@@ -1141,7 +1141,7 @@  discard block
 block discarded – undo
1141 1141
             foreach ($relative_urls as $resource_name => $endpoints) {
1142 1142
                 foreach ($endpoints as $key => $endpoint) {
1143 1143
                     // skip schema and other route options
1144
-                    if (! is_numeric($key)) {
1144
+                    if ( ! is_numeric($key)) {
1145 1145
                         continue;
1146 1146
                     }
1147 1147
                     // by default, hide "hidden_endpoint"s, unless the request indicates
@@ -1150,9 +1150,9 @@  discard block
 block discarded – undo
1150 1150
                     if (($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1151 1151
                         || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1152 1152
                     ) {
1153
-                        $full_route = '/' . ltrim($namespace, '/');
1154
-                        $full_route .= '/' . ltrim($resource_name, '/');
1155
-                        unset($route_data[ $full_route ]);
1153
+                        $full_route = '/'.ltrim($namespace, '/');
1154
+                        $full_route .= '/'.ltrim($resource_name, '/');
1155
+                        unset($route_data[$full_route]);
1156 1156
                     }
1157 1157
                 }
1158 1158
             }
@@ -1226,19 +1226,19 @@  discard block
 block discarded – undo
1226 1226
 
1227 1227
             if ($key_versioned_endpoint === $latest_version) {
1228 1228
                 // don't hide the latest version in the index
1229
-                $versions_served[ $key_versioned_endpoint ] = false;
1229
+                $versions_served[$key_versioned_endpoint] = false;
1230 1230
             } elseif (version_compare($key_versioned_endpoint, $lowest_compatible_version, '>=')
1231 1231
                 && version_compare($key_versioned_endpoint, EED_Core_Rest_Api::core_version(), '<')
1232 1232
             ) {
1233 1233
                 // include, but hide, previous versions which are still supported
1234
-                $versions_served[ $key_versioned_endpoint ] = true;
1234
+                $versions_served[$key_versioned_endpoint] = true;
1235 1235
             } elseif (apply_filters(
1236 1236
                 'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1237 1237
                 false,
1238 1238
                 $possibly_served_versions
1239 1239
             )) {
1240 1240
                 // if a version is no longer supported, don't include it in index or list of versions served
1241
-                $versions_served[ $key_versioned_endpoint ] = true;
1241
+                $versions_served[$key_versioned_endpoint] = true;
1242 1242
             }
1243 1243
         }
1244 1244
         return $versions_served;
@@ -1296,7 +1296,7 @@  discard block
 block discarded – undo
1296 1296
         $model_names = self::model_names_with_plural_routes($version);
1297 1297
         $collection_routes = array();
1298 1298
         foreach ($model_names as $model_name => $model_class_name) {
1299
-            $collection_routes[ strtolower($model_name) ] = '/' . self::ee_api_namespace . $version . '/'
1299
+            $collection_routes[strtolower($model_name)] = '/'.self::ee_api_namespace.$version.'/'
1300 1300
                                                             . EEH_Inflector::pluralize_and_lower($model_name);
1301 1301
         }
1302 1302
         return $collection_routes;
@@ -1317,9 +1317,9 @@  discard block
 block discarded – undo
1317 1317
             $primary_keys = $model_class_name::instance()->get_combined_primary_key_fields();
1318 1318
             foreach ($primary_keys as $primary_key_name => $primary_key_field) {
1319 1319
                 if (count($primary_keys) > 1) {
1320
-                    $primary_key_items[ strtolower($model_name) ][] = $primary_key_name;
1320
+                    $primary_key_items[strtolower($model_name)][] = $primary_key_name;
1321 1321
                 } else {
1322
-                    $primary_key_items[ strtolower($model_name) ] = $primary_key_name;
1322
+                    $primary_key_items[strtolower($model_name)] = $primary_key_name;
1323 1323
                 }
1324 1324
             }
1325 1325
         }
Please login to merge, or discard this patch.
core/services/collections/iterators/CollectionFilterCallbackIterator.php 1 patch
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -9,51 +9,51 @@
 block discarded – undo
9 9
 class CollectionFilterCallbackIterator extends FilterIterator
10 10
 {
11 11
 
12
-    /**
13
-     * Used for determining whether the iterated object in the Collection is "valid" or not.
14
-     * @var Closure
15
-     */
16
-    private $acceptance_callback;
17
-
18
-
19
-    /**
20
-     * CollectionFilterCallbackIterator constructor.
21
-     *
22
-     * @param Collection $collection
23
-     * @param Closure    $acceptance_callback  The closure will receive an instance of whatever object is stored on the
24
-     *                                         collection when iterating over the collection and should return boolean.
25
-     */
26
-    public function __construct(Collection $collection, Closure $acceptance_callback)
27
-    {
28
-        $this->acceptance_callback = $acceptance_callback;
29
-        parent::__construct($collection);
30
-    }
31
-
32
-    /**
33
-     * Check whether the current element of the iterator is acceptable
34
-     *
35
-     * @link  http://php.net/manual/en/filteriterator.accept.php
36
-     * @return bool true if the current element is acceptable, otherwise false.
37
-     */
38
-    public function accept()
39
-    {
40
-        $acceptance_callback = $this->acceptance_callback;
41
-        return $acceptance_callback($this->getInnerIterator()->current());
42
-    }
43
-
44
-
45
-
46
-    /**
47
-     * Returns a filtered array of objects from the collection using the provided acceptance callback
48
-     * @return array
49
-     */
50
-    public function getFiltered()
51
-    {
52
-        $filtered_array = array();
53
-        $this->rewind();
54
-        foreach ($this as $filtered_object) {
55
-            $filtered_array[] = $filtered_object;
56
-        }
57
-        return $filtered_array;
58
-    }
12
+	/**
13
+	 * Used for determining whether the iterated object in the Collection is "valid" or not.
14
+	 * @var Closure
15
+	 */
16
+	private $acceptance_callback;
17
+
18
+
19
+	/**
20
+	 * CollectionFilterCallbackIterator constructor.
21
+	 *
22
+	 * @param Collection $collection
23
+	 * @param Closure    $acceptance_callback  The closure will receive an instance of whatever object is stored on the
24
+	 *                                         collection when iterating over the collection and should return boolean.
25
+	 */
26
+	public function __construct(Collection $collection, Closure $acceptance_callback)
27
+	{
28
+		$this->acceptance_callback = $acceptance_callback;
29
+		parent::__construct($collection);
30
+	}
31
+
32
+	/**
33
+	 * Check whether the current element of the iterator is acceptable
34
+	 *
35
+	 * @link  http://php.net/manual/en/filteriterator.accept.php
36
+	 * @return bool true if the current element is acceptable, otherwise false.
37
+	 */
38
+	public function accept()
39
+	{
40
+		$acceptance_callback = $this->acceptance_callback;
41
+		return $acceptance_callback($this->getInnerIterator()->current());
42
+	}
43
+
44
+
45
+
46
+	/**
47
+	 * Returns a filtered array of objects from the collection using the provided acceptance callback
48
+	 * @return array
49
+	 */
50
+	public function getFiltered()
51
+	{
52
+		$filtered_array = array();
53
+		$this->rewind();
54
+		foreach ($this as $filtered_object) {
55
+			$filtered_array[] = $filtered_object;
56
+		}
57
+		return $filtered_array;
58
+	}
59 59
 }
Please login to merge, or discard this patch.
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   +4526 added lines, -4526 removed lines patch added patch discarded remove patch
@@ -19,2626 +19,2626 @@  discard block
 block discarded – undo
19 19
 class Messages_Admin_Page extends EE_Admin_Page
20 20
 {
21 21
 
22
-    /**
23
-     * @type EE_Message_Resource_Manager $_message_resource_manager
24
-     */
25
-    protected $_message_resource_manager;
26
-
27
-    /**
28
-     * @type string $_active_message_type_name
29
-     */
30
-    protected $_active_message_type_name = '';
31
-
32
-    /**
33
-     * @type EE_messenger $_active_messenger
34
-     */
35
-    protected $_active_messenger;
36
-    protected $_activate_state;
37
-    protected $_activate_meta_box_type;
38
-    protected $_current_message_meta_box;
39
-    protected $_current_message_meta_box_object;
40
-    protected $_context_switcher;
41
-    protected $_shortcodes = array();
42
-    protected $_active_messengers = array();
43
-    protected $_active_message_types = array();
44
-
45
-    /**
46
-     * @var EE_Message_Template_Group $_message_template_group
47
-     */
48
-    protected $_message_template_group;
49
-    protected $_m_mt_settings = array();
50
-
51
-
52
-    /**
53
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
-     * IF there is no group then it gets automatically set to the Default template pack.
55
-     *
56
-     * @since 4.5.0
57
-     *
58
-     * @var EE_Messages_Template_Pack
59
-     */
60
-    protected $_template_pack;
61
-
62
-
63
-    /**
64
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
-     * group is.  If there is no group then it automatically gets set to default.
66
-     *
67
-     * @since 4.5.0
68
-     *
69
-     * @var string
70
-     */
71
-    protected $_variation;
72
-
73
-
74
-    /**
75
-     * @param bool $routing
76
-     * @throws EE_Error
77
-     */
78
-    public function __construct($routing = true)
79
-    {
80
-        // make sure messages autoloader is running
81
-        EED_Messages::set_autoloaders();
82
-        parent::__construct($routing);
83
-    }
84
-
85
-
86
-    protected function _init_page_props()
87
-    {
88
-        $this->page_slug = EE_MSG_PG_SLUG;
89
-        $this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
-        $this->_admin_base_url = EE_MSG_ADMIN_URL;
91
-        $this->_admin_base_path = EE_MSG_ADMIN;
92
-
93
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
-            : array();
95
-
96
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
-        $this->_load_message_resource_manager();
98
-    }
99
-
100
-
101
-    /**
102
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
-     *
104
-     * @throws EE_Error
105
-     * @throws InvalidDataTypeException
106
-     * @throws InvalidInterfaceException
107
-     * @throws InvalidArgumentException
108
-     * @throws ReflectionException
109
-     */
110
-    protected function _load_message_resource_manager()
111
-    {
112
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
-    }
114
-
115
-
116
-    /**
117
-     * @deprecated 4.9.9.rc.014
118
-     * @return array
119
-     * @throws EE_Error
120
-     * @throws InvalidArgumentException
121
-     * @throws InvalidDataTypeException
122
-     * @throws InvalidInterfaceException
123
-     */
124
-    public function get_messengers_for_list_table()
125
-    {
126
-        EE_Error::doing_it_wrong(
127
-            __METHOD__,
128
-            sprintf(
129
-                esc_html__(
130
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
-                    'event_espresso'
132
-                ),
133
-                'Messages_Admin_Page::get_messengers_select_input()'
134
-            ),
135
-            '4.9.9.rc.014'
136
-        );
137
-
138
-        $m_values = array();
139
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
-        // setup messengers for selects
141
-        $i = 1;
142
-        foreach ($active_messengers as $active_messenger) {
143
-            if ($active_messenger instanceof EE_Message) {
144
-                $m_values[ $i ]['id'] = $active_messenger->messenger();
145
-                $m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
-                $i++;
147
-            }
148
-        }
149
-
150
-        return $m_values;
151
-    }
152
-
153
-
154
-    /**
155
-     * @deprecated 4.9.9.rc.014
156
-     * @return array
157
-     * @throws EE_Error
158
-     * @throws InvalidArgumentException
159
-     * @throws InvalidDataTypeException
160
-     * @throws InvalidInterfaceException
161
-     */
162
-    public function get_message_types_for_list_table()
163
-    {
164
-        EE_Error::doing_it_wrong(
165
-            __METHOD__,
166
-            sprintf(
167
-                esc_html__(
168
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
-                    'event_espresso'
170
-                ),
171
-                'Messages_Admin_Page::get_message_types_select_input()'
172
-            ),
173
-            '4.9.9.rc.014'
174
-        );
175
-
176
-        $mt_values = array();
177
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
-        $i = 1;
179
-        foreach ($active_messages as $active_message) {
180
-            if ($active_message instanceof EE_Message) {
181
-                $mt_values[ $i ]['id'] = $active_message->message_type();
182
-                $mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
-                $i++;
184
-            }
185
-        }
186
-
187
-        return $mt_values;
188
-    }
189
-
190
-
191
-    /**
192
-     * @deprecated 4.9.9.rc.014
193
-     * @return array
194
-     * @throws EE_Error
195
-     * @throws InvalidArgumentException
196
-     * @throws InvalidDataTypeException
197
-     * @throws InvalidInterfaceException
198
-     */
199
-    public function get_contexts_for_message_types_for_list_table()
200
-    {
201
-        EE_Error::doing_it_wrong(
202
-            __METHOD__,
203
-            sprintf(
204
-                esc_html__(
205
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
-                    'event_espresso'
207
-                ),
208
-                'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
-            ),
210
-            '4.9.9.rc.014'
211
-        );
212
-
213
-        $contexts = array();
214
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
-        foreach ($active_message_contexts as $active_message) {
216
-            if ($active_message instanceof EE_Message) {
217
-                $message_type = $active_message->message_type_object();
218
-                if ($message_type instanceof EE_message_type) {
219
-                    $message_type_contexts = $message_type->get_contexts();
220
-                    foreach ($message_type_contexts as $context => $context_details) {
221
-                        $contexts[ $context ] = $context_details['label'];
222
-                    }
223
-                }
224
-            }
225
-        }
226
-
227
-        return $contexts;
228
-    }
229
-
230
-
231
-    /**
232
-     * Generate select input with provided messenger options array.
233
-     *
234
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
-     *                                 labels.
236
-     * @return string
237
-     * @throws EE_Error
238
-     */
239
-    public function get_messengers_select_input($messenger_options)
240
-    {
241
-        // if empty or just one value then just return an empty string
242
-        if (empty($messenger_options)
243
-            || ! is_array($messenger_options)
244
-            || count($messenger_options) === 1
245
-        ) {
246
-            return '';
247
-        }
248
-        // merge in default
249
-        $messenger_options = array_merge(
250
-            array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
-            $messenger_options
252
-        );
253
-        $input = new EE_Select_Input(
254
-            $messenger_options,
255
-            array(
256
-                'html_name'  => 'ee_messenger_filter_by',
257
-                'html_id'    => 'ee_messenger_filter_by',
258
-                'html_class' => 'wide',
259
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
-                    : 'none_selected',
262
-            )
263
-        );
264
-
265
-        return $input->get_html_for_input();
266
-    }
267
-
268
-
269
-    /**
270
-     * Generate select input with provided message type options array.
271
-     *
272
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
-     *                                    message type labels
274
-     * @return string
275
-     * @throws EE_Error
276
-     */
277
-    public function get_message_types_select_input($message_type_options)
278
-    {
279
-        // if empty or count of options is 1 then just return an empty string
280
-        if (empty($message_type_options)
281
-            || ! is_array($message_type_options)
282
-            || count($message_type_options) === 1
283
-        ) {
284
-            return '';
285
-        }
286
-        // merge in default
287
-        $message_type_options = array_merge(
288
-            array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
-            $message_type_options
290
-        );
291
-        $input = new EE_Select_Input(
292
-            $message_type_options,
293
-            array(
294
-                'html_name'  => 'ee_message_type_filter_by',
295
-                'html_id'    => 'ee_message_type_filter_by',
296
-                'html_class' => 'wide',
297
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
-                    : 'none_selected',
300
-            )
301
-        );
302
-
303
-        return $input->get_html_for_input();
304
-    }
305
-
306
-
307
-    /**
308
-     * Generate select input with provide message type contexts array.
309
-     *
310
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
-     *                               context label.
312
-     * @return string
313
-     * @throws EE_Error
314
-     */
315
-    public function get_contexts_for_message_types_select_input($context_options)
316
-    {
317
-        // if empty or count of options is one then just return empty string
318
-        if (empty($context_options)
319
-            || ! is_array($context_options)
320
-            || count($context_options) === 1
321
-        ) {
322
-            return '';
323
-        }
324
-        // merge in default
325
-        $context_options = array_merge(
326
-            array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
-            $context_options
328
-        );
329
-        $input = new EE_Select_Input(
330
-            $context_options,
331
-            array(
332
-                'html_name'  => 'ee_context_filter_by',
333
-                'html_id'    => 'ee_context_filter_by',
334
-                'html_class' => 'wide',
335
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
336
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
337
-                    : 'none_selected',
338
-            )
339
-        );
340
-
341
-        return $input->get_html_for_input();
342
-    }
343
-
344
-
345
-    protected function _ajax_hooks()
346
-    {
347
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
-        add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
-    }
354
-
355
-
356
-    protected function _define_page_props()
357
-    {
358
-        $this->_admin_page_title = $this->page_label;
359
-        $this->_labels = array(
360
-            'buttons'    => array(
361
-                'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
-                'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
-                'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
-            ),
365
-            'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
-        );
367
-    }
368
-
369
-
370
-    /**
371
-     *        an array for storing key => value pairs of request actions and their corresponding methods
372
-     *
373
-     * @access protected
374
-     * @return void
375
-     */
376
-    protected function _set_page_routes()
377
-    {
378
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
-            ? $this->_req_data['GRP_ID']
380
-            : 0;
381
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
-            ? $this->_req_data['id']
383
-            : $grp_id;
384
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
-            ? $this->_req_data['MSG_ID']
386
-            : 0;
387
-
388
-        $this->_page_routes = array(
389
-            'default'                          => array(
390
-                'func'       => '_message_queue_list_table',
391
-                'capability' => 'ee_read_global_messages',
392
-            ),
393
-            'global_mtps'                      => array(
394
-                'func'       => '_ee_default_messages_overview_list_table',
395
-                'capability' => 'ee_read_global_messages',
396
-            ),
397
-            'custom_mtps'                      => array(
398
-                'func'       => '_custom_mtps_preview',
399
-                'capability' => 'ee_read_messages',
400
-            ),
401
-            'add_new_message_template'         => array(
402
-                'func'       => '_add_message_template',
403
-                'capability' => 'ee_edit_messages',
404
-                'noheader'   => true,
405
-            ),
406
-            'edit_message_template'            => array(
407
-                'func'       => '_edit_message_template',
408
-                'capability' => 'ee_edit_message',
409
-                'obj_id'     => $grp_id,
410
-            ),
411
-            'preview_message'                  => array(
412
-                'func'               => '_preview_message',
413
-                'capability'         => 'ee_read_message',
414
-                'obj_id'             => $grp_id,
415
-                'noheader'           => true,
416
-                'headers_sent_route' => 'display_preview_message',
417
-            ),
418
-            'display_preview_message'          => array(
419
-                'func'       => '_display_preview_message',
420
-                'capability' => 'ee_read_message',
421
-                'obj_id'     => $grp_id,
422
-            ),
423
-            'insert_message_template'          => array(
424
-                'func'       => '_insert_or_update_message_template',
425
-                'capability' => 'ee_edit_messages',
426
-                'args'       => array('new_template' => true),
427
-                'noheader'   => true,
428
-            ),
429
-            'update_message_template'          => array(
430
-                'func'       => '_insert_or_update_message_template',
431
-                'capability' => 'ee_edit_message',
432
-                'obj_id'     => $grp_id,
433
-                'args'       => array('new_template' => false),
434
-                'noheader'   => true,
435
-            ),
436
-            'trash_message_template'           => array(
437
-                'func'       => '_trash_or_restore_message_template',
438
-                'capability' => 'ee_delete_message',
439
-                'obj_id'     => $grp_id,
440
-                'args'       => array('trash' => true, 'all' => true),
441
-                'noheader'   => true,
442
-            ),
443
-            'trash_message_template_context'   => array(
444
-                'func'       => '_trash_or_restore_message_template',
445
-                'capability' => 'ee_delete_message',
446
-                'obj_id'     => $grp_id,
447
-                'args'       => array('trash' => true),
448
-                'noheader'   => true,
449
-            ),
450
-            'restore_message_template'         => array(
451
-                'func'       => '_trash_or_restore_message_template',
452
-                'capability' => 'ee_delete_message',
453
-                'obj_id'     => $grp_id,
454
-                'args'       => array('trash' => false, 'all' => true),
455
-                'noheader'   => true,
456
-            ),
457
-            'restore_message_template_context' => array(
458
-                'func'       => '_trash_or_restore_message_template',
459
-                'capability' => 'ee_delete_message',
460
-                'obj_id'     => $grp_id,
461
-                'args'       => array('trash' => false),
462
-                'noheader'   => true,
463
-            ),
464
-            'delete_message_template'          => array(
465
-                'func'       => '_delete_message_template',
466
-                'capability' => 'ee_delete_message',
467
-                'obj_id'     => $grp_id,
468
-                'noheader'   => true,
469
-            ),
470
-            'reset_to_default'                 => array(
471
-                'func'       => '_reset_to_default_template',
472
-                'capability' => 'ee_edit_message',
473
-                'obj_id'     => $grp_id,
474
-                'noheader'   => true,
475
-            ),
476
-            'settings'                         => array(
477
-                'func'       => '_settings',
478
-                'capability' => 'manage_options',
479
-            ),
480
-            'update_global_settings'           => array(
481
-                'func'       => '_update_global_settings',
482
-                'capability' => 'manage_options',
483
-                'noheader'   => true,
484
-            ),
485
-            'generate_now'                     => array(
486
-                'func'       => '_generate_now',
487
-                'capability' => 'ee_send_message',
488
-                'noheader'   => true,
489
-            ),
490
-            'generate_and_send_now'            => array(
491
-                'func'       => '_generate_and_send_now',
492
-                'capability' => 'ee_send_message',
493
-                'noheader'   => true,
494
-            ),
495
-            'queue_for_resending'              => array(
496
-                'func'       => '_queue_for_resending',
497
-                'capability' => 'ee_send_message',
498
-                'noheader'   => true,
499
-            ),
500
-            'send_now'                         => array(
501
-                'func'       => '_send_now',
502
-                'capability' => 'ee_send_message',
503
-                'noheader'   => true,
504
-            ),
505
-            'delete_ee_message'                => array(
506
-                'func'       => '_delete_ee_messages',
507
-                'capability' => 'ee_delete_messages',
508
-                'noheader'   => true,
509
-            ),
510
-            'delete_ee_messages'               => array(
511
-                'func'       => '_delete_ee_messages',
512
-                'capability' => 'ee_delete_messages',
513
-                'noheader'   => true,
514
-                'obj_id'     => $msg_id,
515
-            ),
516
-        );
517
-    }
518
-
519
-
520
-    protected function _set_page_config()
521
-    {
522
-        $this->_page_config = array(
523
-            'default'                  => array(
524
-                'nav'           => array(
525
-                    'label' => esc_html__('Message Activity', 'event_espresso'),
526
-                    'order' => 10,
527
-                ),
528
-                'list_table'    => 'EE_Message_List_Table',
529
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
-                'require_nonce' => false,
531
-            ),
532
-            'global_mtps'              => array(
533
-                'nav'           => array(
534
-                    'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
-                    'order' => 20,
536
-                ),
537
-                'list_table'    => 'Messages_Template_List_Table',
538
-                'help_tabs'     => array(
539
-                    'messages_overview_help_tab'                                => array(
540
-                        'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
-                        'filename' => 'messages_overview',
542
-                    ),
543
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
544
-                        'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
-                        'filename' => 'messages_overview_table_column_headings',
546
-                    ),
547
-                    'messages_overview_messages_filters_help_tab'               => array(
548
-                        'title'    => esc_html__('Message Filters', 'event_espresso'),
549
-                        'filename' => 'messages_overview_filters',
550
-                    ),
551
-                    'messages_overview_messages_views_help_tab'                 => array(
552
-                        'title'    => esc_html__('Message Views', 'event_espresso'),
553
-                        'filename' => 'messages_overview_views',
554
-                    ),
555
-                    'message_overview_message_types_help_tab'                   => array(
556
-                        'title'    => esc_html__('Message Types', 'event_espresso'),
557
-                        'filename' => 'messages_overview_types',
558
-                    ),
559
-                    'messages_overview_messengers_help_tab'                     => array(
560
-                        'title'    => esc_html__('Messengers', 'event_espresso'),
561
-                        'filename' => 'messages_overview_messengers',
562
-                    ),
563
-                ),
564
-                'help_tour'     => array('Messages_Overview_Help_Tour'),
565
-                'require_nonce' => false,
566
-            ),
567
-            'custom_mtps'              => array(
568
-                'nav'           => array(
569
-                    'label' => esc_html__('Custom Message Templates', 'event_espresso'),
570
-                    'order' => 30,
571
-                ),
572
-                'help_tabs'     => array(),
573
-                'help_tour'     => array(),
574
-                'require_nonce' => false,
575
-            ),
576
-            'add_new_message_template' => array(
577
-                'nav'           => array(
578
-                    'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
579
-                    'order'      => 5,
580
-                    'persistent' => false,
581
-                ),
582
-                'require_nonce' => false,
583
-            ),
584
-            'edit_message_template'    => array(
585
-                'labels'        => array(
586
-                    'buttons'    => array(
587
-                        'reset' => esc_html__('Reset Templates', 'event_espresso'),
588
-                    ),
589
-                    'publishbox' => esc_html__('Update Actions', 'event_espresso'),
590
-                ),
591
-                'nav'           => array(
592
-                    'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
593
-                    'order'      => 5,
594
-                    'persistent' => false,
595
-                    'url'        => '',
596
-                ),
597
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
598
-                'has_metaboxes' => true,
599
-                'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
600
-                'help_tabs'     => array(
601
-                    'edit_message_template'            => array(
602
-                        'title'    => esc_html__('Message Template Editor', 'event_espresso'),
603
-                        'callback' => 'edit_message_template_help_tab',
604
-                    ),
605
-                    'message_templates_help_tab'       => array(
606
-                        'title'    => esc_html__('Message Templates', 'event_espresso'),
607
-                        'filename' => 'messages_templates',
608
-                    ),
609
-                    'message_template_shortcodes'      => array(
610
-                        'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
611
-                        'callback' => 'message_template_shortcodes_help_tab',
612
-                    ),
613
-                    'message_preview_help_tab'         => array(
614
-                        'title'    => esc_html__('Message Preview', 'event_espresso'),
615
-                        'filename' => 'messages_preview',
616
-                    ),
617
-                    'messages_overview_other_help_tab' => array(
618
-                        'title'    => esc_html__('Messages Other', 'event_espresso'),
619
-                        'filename' => 'messages_overview_other',
620
-                    ),
621
-                ),
622
-                'require_nonce' => false,
623
-            ),
624
-            'display_preview_message'  => array(
625
-                'nav'           => array(
626
-                    'label'      => esc_html__('Message Preview', 'event_espresso'),
627
-                    'order'      => 5,
628
-                    'url'        => '',
629
-                    'persistent' => false,
630
-                ),
631
-                'help_tabs'     => array(
632
-                    'preview_message' => array(
633
-                        'title'    => esc_html__('About Previews', 'event_espresso'),
634
-                        'callback' => 'preview_message_help_tab',
635
-                    ),
636
-                ),
637
-                'require_nonce' => false,
638
-            ),
639
-            'settings'                 => array(
640
-                'nav'           => array(
641
-                    'label' => esc_html__('Settings', 'event_espresso'),
642
-                    'order' => 40,
643
-                ),
644
-                'metaboxes'     => array('_messages_settings_metaboxes'),
645
-                'help_tabs'     => array(
646
-                    'messages_settings_help_tab'               => array(
647
-                        'title'    => esc_html__('Messages Settings', 'event_espresso'),
648
-                        'filename' => 'messages_settings',
649
-                    ),
650
-                    'messages_settings_message_types_help_tab' => array(
651
-                        'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
652
-                        'filename' => 'messages_settings_message_types',
653
-                    ),
654
-                    'messages_settings_messengers_help_tab'    => array(
655
-                        'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
656
-                        'filename' => 'messages_settings_messengers',
657
-                    ),
658
-                ),
659
-                'help_tour'     => array('Messages_Settings_Help_Tour'),
660
-                'require_nonce' => false,
661
-            ),
662
-        );
663
-    }
664
-
665
-
666
-    protected function _add_screen_options()
667
-    {
668
-        // todo
669
-    }
670
-
671
-
672
-    protected function _add_screen_options_global_mtps()
673
-    {
674
-        /**
675
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
676
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
677
-         */
678
-        $page_title = $this->_admin_page_title;
679
-        $this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
680
-        $this->_per_page_screen_option();
681
-        $this->_admin_page_title = $page_title;
682
-    }
683
-
684
-
685
-    protected function _add_screen_options_default()
686
-    {
687
-        $this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
688
-        $this->_per_page_screen_option();
689
-    }
690
-
691
-
692
-    // none of the below group are currently used for Messages
693
-    protected function _add_feature_pointers()
694
-    {
695
-    }
696
-
697
-    public function admin_init()
698
-    {
699
-    }
700
-
701
-    public function admin_notices()
702
-    {
703
-    }
704
-
705
-    public function admin_footer_scripts()
706
-    {
707
-    }
708
-
709
-
710
-    public function messages_help_tab()
711
-    {
712
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
713
-    }
714
-
715
-
716
-    public function messengers_help_tab()
717
-    {
718
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
719
-    }
720
-
721
-
722
-    public function message_types_help_tab()
723
-    {
724
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
725
-    }
726
-
727
-
728
-    public function messages_overview_help_tab()
729
-    {
730
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
731
-    }
732
-
733
-
734
-    public function message_templates_help_tab()
735
-    {
736
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
737
-    }
738
-
739
-
740
-    public function edit_message_template_help_tab()
741
-    {
742
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
743
-                        . esc_attr__('Editor Title', 'event_espresso')
744
-                        . '" />';
745
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
746
-                        . esc_attr__('Context Switcher and Preview', 'event_espresso')
747
-                        . '" />';
748
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
749
-                        . esc_attr__('Message Template Form Fields', 'event_espresso')
750
-                        . '" />';
751
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
752
-                        . esc_attr__('Shortcodes Metabox', 'event_espresso')
753
-                        . '" />';
754
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
755
-                        . esc_attr__('Publish Metabox', 'event_espresso')
756
-                        . '" />';
757
-        EEH_Template::display_template(
758
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
759
-            $args
760
-        );
761
-    }
762
-
763
-
764
-    public function message_template_shortcodes_help_tab()
765
-    {
766
-        $this->_set_shortcodes();
767
-        $args['shortcodes'] = $this->_shortcodes;
768
-        EEH_Template::display_template(
769
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
770
-            $args
771
-        );
772
-    }
773
-
774
-
775
-    public function preview_message_help_tab()
776
-    {
777
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
778
-    }
779
-
780
-
781
-    public function settings_help_tab()
782
-    {
783
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
784
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
785
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
786
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
787
-        $args['img3'] = '<div class="switch">'
788
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
789
-                        . ' type="checkbox" checked="checked">'
790
-                        . '<label for="ee-on-off-toggle-on"></label>'
791
-                        . '</div>';
792
-        $args['img4'] = '<div class="switch">'
793
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
794
-                        . ' type="checkbox">'
795
-                        . '<label for="ee-on-off-toggle-on"></label>'
796
-                        . '</div>';
797
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
798
-    }
799
-
800
-
801
-    public function load_scripts_styles()
802
-    {
803
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
804
-        wp_enqueue_style('espresso_ee_msg');
805
-
806
-        wp_register_script(
807
-            'ee-messages-settings',
808
-            EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
-            array('jquery-ui-droppable', 'ee-serialize-full-array'),
810
-            EVENT_ESPRESSO_VERSION,
811
-            true
812
-        );
813
-        wp_register_script(
814
-            'ee-msg-list-table-js',
815
-            EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
816
-            array('ee-dialog'),
817
-            EVENT_ESPRESSO_VERSION
818
-        );
819
-    }
820
-
821
-
822
-    public function load_scripts_styles_default()
823
-    {
824
-        wp_enqueue_script('ee-msg-list-table-js');
825
-    }
826
-
827
-
828
-    public function wp_editor_css($mce_css)
829
-    {
830
-        // if we're on the edit_message_template route
831
-        if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
832
-            $message_type_name = $this->_active_message_type_name;
833
-
834
-            // we're going to REPLACE the existing mce css
835
-            // we need to get the css file location from the active messenger
836
-            $mce_css = $this->_active_messenger->get_variation(
837
-                $this->_template_pack,
838
-                $message_type_name,
839
-                true,
840
-                'wpeditor',
841
-                $this->_variation
842
-            );
843
-        }
844
-
845
-        return $mce_css;
846
-    }
847
-
848
-
849
-    public function load_scripts_styles_edit_message_template()
850
-    {
851
-
852
-        $this->_set_shortcodes();
853
-
854
-        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
855
-            esc_html__(
856
-                'Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
857
-                'event_espresso'
858
-            ),
859
-            $this->_message_template_group->messenger_obj()->label['singular'],
860
-            $this->_message_template_group->message_type_obj()->label['singular']
861
-        );
862
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
863
-            'Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
864
-            'event_espresso'
865
-        );
866
-        EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
867
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
868
-            'event_espresso'
869
-        );
870
-
871
-        wp_register_script(
872
-            'ee_msgs_edit_js',
873
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
874
-            array('jquery'),
875
-            EVENT_ESPRESSO_VERSION
876
-        );
877
-
878
-        wp_enqueue_script('ee_admin_js');
879
-        wp_enqueue_script('ee_msgs_edit_js');
880
-
881
-        // add in special css for tiny_mce
882
-        add_filter('mce_css', array($this, 'wp_editor_css'));
883
-    }
884
-
885
-
886
-    public function load_scripts_styles_display_preview_message()
887
-    {
888
-
889
-        $this->_set_message_template_group();
890
-
891
-        if (isset($this->_req_data['messenger'])) {
892
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
893
-                $this->_req_data['messenger']
894
-            );
895
-        }
896
-
897
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
898
-
899
-
900
-        wp_enqueue_style(
901
-            'espresso_preview_css',
902
-            $this->_active_messenger->get_variation(
903
-                $this->_template_pack,
904
-                $message_type_name,
905
-                true,
906
-                'preview',
907
-                $this->_variation
908
-            )
909
-        );
910
-    }
911
-
912
-
913
-    public function load_scripts_styles_settings()
914
-    {
915
-        wp_register_style(
916
-            'ee-message-settings',
917
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
918
-            array(),
919
-            EVENT_ESPRESSO_VERSION
920
-        );
921
-        wp_enqueue_style('ee-text-links');
922
-        wp_enqueue_style('ee-message-settings');
923
-        wp_enqueue_script('ee-messages-settings');
924
-    }
925
-
926
-
927
-    /**
928
-     * set views array for List Table
929
-     */
930
-    public function _set_list_table_views_global_mtps()
931
-    {
932
-        $this->_views = array(
933
-            'in_use' => array(
934
-                'slug'  => 'in_use',
935
-                'label' => esc_html__('In Use', 'event_espresso'),
936
-                'count' => 0,
937
-            ),
938
-        );
939
-    }
940
-
941
-
942
-    /**
943
-     * Set views array for the Custom Template List Table
944
-     */
945
-    public function _set_list_table_views_custom_mtps()
946
-    {
947
-        $this->_set_list_table_views_global_mtps();
948
-        $this->_views['in_use']['bulk_action'] = array(
949
-            'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
950
-        );
951
-    }
952
-
953
-
954
-    /**
955
-     * set views array for message queue list table
956
-     *
957
-     * @throws InvalidDataTypeException
958
-     * @throws InvalidInterfaceException
959
-     * @throws InvalidArgumentException
960
-     * @throws EE_Error
961
-     * @throws ReflectionException
962
-     */
963
-    public function _set_list_table_views_default()
964
-    {
965
-        EE_Registry::instance()->load_helper('Template');
966
-
967
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
968
-            'ee_send_message',
969
-            'message_list_table_bulk_actions'
970
-        )
971
-            ? array(
972
-                'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
973
-                'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
974
-                'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
975
-                'send_now'              => esc_html__('Send Now', 'event_espresso'),
976
-            )
977
-            : array();
978
-
979
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
980
-            'ee_delete_messages',
981
-            'message_list_table_bulk_actions'
982
-        )
983
-            ? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
984
-            : array();
985
-
986
-
987
-        $this->_views = array(
988
-            'all' => array(
989
-                'slug'        => 'all',
990
-                'label'       => esc_html__('All', 'event_espresso'),
991
-                'count'       => 0,
992
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
993
-            ),
994
-        );
995
-
996
-
997
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
998
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
999
-                continue;
1000
-            }
1001
-            $status_bulk_actions = $common_bulk_actions;
1002
-            // unset bulk actions not applying to status
1003
-            if (! empty($status_bulk_actions)) {
1004
-                switch ($status) {
1005
-                    case EEM_Message::status_idle:
1006
-                    case EEM_Message::status_resend:
1007
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1008
-                        break;
1009
-
1010
-                    case EEM_Message::status_failed:
1011
-                    case EEM_Message::status_debug_only:
1012
-                    case EEM_Message::status_messenger_executing:
1013
-                        $status_bulk_actions = array();
1014
-                        break;
1015
-
1016
-                    case EEM_Message::status_incomplete:
1017
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1018
-                        break;
1019
-
1020
-                    case EEM_Message::status_retry:
1021
-                    case EEM_Message::status_sent:
1022
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1023
-                        break;
1024
-                }
1025
-            }
1026
-
1027
-            // skip adding messenger executing status to views because it will be included with the Failed view.
1028
-            if ($status === EEM_Message::status_messenger_executing) {
1029
-                continue;
1030
-            }
1031
-
1032
-            $this->_views[ strtolower($status) ] = array(
1033
-                'slug'        => strtolower($status),
1034
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1035
-                'count'       => 0,
1036
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1037
-            );
1038
-        }
1039
-    }
1040
-
1041
-
1042
-    protected function _ee_default_messages_overview_list_table()
1043
-    {
1044
-        $this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1045
-        $this->display_admin_list_table_page_with_no_sidebar();
1046
-    }
1047
-
1048
-
1049
-    protected function _message_queue_list_table()
1050
-    {
1051
-        $this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1052
-        $this->_template_args['per_column'] = 6;
1053
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1054
-        $this->_template_args['before_list_table'] = '<h3>'
1055
-                                                     . EEM_Message::instance()->get_pretty_label_for_results()
1056
-                                                     . '</h3>';
1057
-        $this->display_admin_list_table_page_with_no_sidebar();
1058
-    }
1059
-
1060
-
1061
-    protected function _message_legend_items()
1062
-    {
1063
-
1064
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
1065
-        $action_items = array();
1066
-
1067
-        foreach ($action_css_classes as $action_item => $action_details) {
1068
-            if ($action_item === 'see_notifications_for') {
1069
-                continue;
1070
-            }
1071
-            $action_items[ $action_item ] = array(
1072
-                'class' => $action_details['css_class'],
1073
-                'desc'  => $action_details['label'],
1074
-            );
1075
-        }
1076
-
1077
-        /** @type array $status_items status legend setup */
1078
-        $status_items = array(
1079
-            'sent_status'                => array(
1080
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1081
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1082
-            ),
1083
-            'idle_status'                => array(
1084
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1085
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1086
-            ),
1087
-            'failed_status'              => array(
1088
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1089
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1090
-            ),
1091
-            'messenger_executing_status' => array(
1092
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1093
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1094
-            ),
1095
-            'resend_status'              => array(
1096
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1097
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1098
-            ),
1099
-            'incomplete_status'          => array(
1100
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1101
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1102
-            ),
1103
-            'retry_status'               => array(
1104
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1105
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1106
-            ),
1107
-        );
1108
-        if (EEM_Message::debug()) {
1109
-            $status_items['debug_only_status'] = array(
1110
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1111
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1112
-            );
1113
-        }
1114
-
1115
-        return array_merge($action_items, $status_items);
1116
-    }
1117
-
1118
-
1119
-    protected function _custom_mtps_preview()
1120
-    {
1121
-        $this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1122
-        $this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1123
-                                               . ' alt="' . esc_attr__(
1124
-                                                   'Preview Custom Message Templates screenshot',
1125
-                                                   'event_espresso'
1126
-                                               ) . '" />';
1127
-        $this->_template_args['preview_text'] = '<strong>'
1128
-                                                . esc_html__(
1129
-                                                    'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1130
-                                                    'event_espresso'
1131
-                                                )
1132
-                                                . '</strong>';
1133
-
1134
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1135
-    }
1136
-
1137
-
1138
-    /**
1139
-     * get_message_templates
1140
-     * This gets all the message templates for listing on the overview list.
1141
-     *
1142
-     * @access public
1143
-     * @param int    $perpage the amount of templates groups to show per page
1144
-     * @param string $type    the current _view we're getting templates for
1145
-     * @param bool   $count   return count?
1146
-     * @param bool   $all     disregard any paging info (get all data);
1147
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1148
-     * @return array
1149
-     * @throws EE_Error
1150
-     * @throws InvalidArgumentException
1151
-     * @throws InvalidDataTypeException
1152
-     * @throws InvalidInterfaceException
1153
-     */
1154
-    public function get_message_templates(
1155
-        $perpage = 10,
1156
-        $type = 'in_use',
1157
-        $count = false,
1158
-        $all = false,
1159
-        $global = true
1160
-    ) {
1161
-
1162
-        $MTP = EEM_Message_Template_Group::instance();
1163
-
1164
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1165
-        $orderby = $this->_req_data['orderby'];
1166
-
1167
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1168
-            ? $this->_req_data['order']
1169
-            : 'ASC';
1170
-
1171
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1172
-            ? $this->_req_data['paged']
1173
-            : 1;
1174
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1175
-            ? $this->_req_data['perpage']
1176
-            : $perpage;
1177
-
1178
-        $offset = ($current_page - 1) * $per_page;
1179
-        $limit = $all ? null : array($offset, $per_page);
1180
-
1181
-
1182
-        // options will match what is in the _views array property
1183
-        switch ($type) {
1184
-            case 'in_use':
1185
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1186
-                break;
1187
-            default:
1188
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1189
-        }
1190
-
1191
-        return $templates;
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * filters etc might need a list of installed message_types
1197
-     *
1198
-     * @return array an array of message type objects
1199
-     */
1200
-    public function get_installed_message_types()
1201
-    {
1202
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1203
-        $installed = array();
1204
-
1205
-        foreach ($installed_message_types as $message_type) {
1206
-            $installed[ $message_type->name ] = $message_type;
1207
-        }
1208
-
1209
-        return $installed;
1210
-    }
1211
-
1212
-
1213
-    /**
1214
-     * _add_message_template
1215
-     *
1216
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1217
-     *
1218
-     * @param string $message_type
1219
-     * @param string $messenger
1220
-     * @param string $GRP_ID
1221
-     *
1222
-     * @throws EE_error
1223
-     */
1224
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1225
-    {
1226
-        // set values override any request data
1227
-        $message_type = ! empty($message_type) ? $message_type : '';
1228
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1229
-            ? $this->_req_data['message_type']
1230
-            : $message_type;
1231
-
1232
-        $messenger = ! empty($messenger) ? $messenger : '';
1233
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1234
-            ? $this->_req_data['messenger']
1235
-            : $messenger;
1236
-
1237
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1238
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1239
-
1240
-        // we need messenger and message type.  They should be coming from the event editor. If not here then return error
1241
-        if (empty($message_type) || empty($messenger)) {
1242
-            throw new EE_Error(
1243
-                esc_html__(
1244
-                    'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1245
-                    'event_espresso'
1246
-                )
1247
-            );
1248
-        }
1249
-
1250
-        // we need the GRP_ID for the template being used as the base for the new template
1251
-        if (empty($GRP_ID)) {
1252
-            throw new EE_Error(
1253
-                esc_html__(
1254
-                    'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1255
-                    'event_espresso'
1256
-                )
1257
-            );
1258
-        }
1259
-
1260
-        // let's just make sure the template gets generated!
1261
-
1262
-        // we need to reassign some variables for what the insert is expecting
1263
-        $this->_req_data['MTP_messenger'] = $messenger;
1264
-        $this->_req_data['MTP_message_type'] = $message_type;
1265
-        $this->_req_data['GRP_ID'] = $GRP_ID;
1266
-        $this->_insert_or_update_message_template(true);
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * public wrapper for the _add_message_template method
1272
-     *
1273
-     * @param string $message_type     message type slug
1274
-     * @param string $messenger        messenger slug
1275
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1276
-     *                                 off of.
1277
-     * @throws EE_error
1278
-     */
1279
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1280
-    {
1281
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1282
-    }
1283
-
1284
-
1285
-    /**
1286
-     * _edit_message_template
1287
-     *
1288
-     * @access protected
1289
-     * @return void
1290
-     * @throws InvalidIdentifierException
1291
-     * @throws DomainException
1292
-     * @throws EE_Error
1293
-     * @throws InvalidArgumentException
1294
-     * @throws ReflectionException
1295
-     * @throws InvalidDataTypeException
1296
-     * @throws InvalidInterfaceException
1297
-     */
1298
-    protected function _edit_message_template()
1299
-    {
1300
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1301
-        $template_fields = '';
1302
-        $sidebar_fields = '';
1303
-        // we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1304
-        // valid html in the templates.
1305
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1306
-
1307
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1308
-            ? absint($this->_req_data['id'])
1309
-            : false;
1310
-
1311
-        $this->_set_shortcodes(); // this also sets the _message_template property.
1312
-        $message_template_group = $this->_message_template_group;
1313
-        $c_label = $message_template_group->context_label();
1314
-        $c_config = $message_template_group->contexts_config();
1315
-
1316
-        reset($c_config);
1317
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1318
-            ? strtolower($this->_req_data['context'])
1319
-            : key($c_config);
1320
-
1321
-
1322
-        if (empty($GRP_ID)) {
1323
-            $action = 'insert_message_template';
1324
-            $edit_message_template_form_url = add_query_arg(
1325
-                array('action' => $action, 'noheader' => true),
1326
-                EE_MSG_ADMIN_URL
1327
-            );
1328
-        } else {
1329
-            $action = 'update_message_template';
1330
-            $edit_message_template_form_url = add_query_arg(
1331
-                array('action' => $action, 'noheader' => true),
1332
-                EE_MSG_ADMIN_URL
1333
-            );
1334
-        }
1335
-
1336
-        // set active messenger for this view
1337
-        $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1338
-            $message_template_group->messenger()
1339
-        );
1340
-        $this->_active_message_type_name = $message_template_group->message_type();
1341
-
1342
-
1343
-        // Do we have any validation errors?
1344
-        $validators = $this->_get_transient();
1345
-        $v_fields = ! empty($validators) ? array_keys($validators) : array();
1346
-
1347
-
1348
-        // we need to assemble the title from Various details
1349
-        $context_label = sprintf(
1350
-            esc_html__('(%s %s)', 'event_espresso'),
1351
-            $c_config[ $context ]['label'],
1352
-            ucwords($c_label['label'])
1353
-        );
1354
-
1355
-        $title = sprintf(
1356
-            esc_html__(' %s %s Template %s', 'event_espresso'),
1357
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1358
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1359
-            $context_label
1360
-        );
1361
-
1362
-        $this->_template_args['GRP_ID'] = $GRP_ID;
1363
-        $this->_template_args['message_template'] = $message_template_group;
1364
-        $this->_template_args['is_extra_fields'] = false;
1365
-
1366
-
1367
-        // let's get EEH_MSG_Template so we can get template form fields
1368
-        $template_field_structure = EEH_MSG_Template::get_fields(
1369
-            $message_template_group->messenger(),
1370
-            $message_template_group->message_type()
1371
-        );
1372
-
1373
-        if (! $template_field_structure) {
1374
-            $template_field_structure = false;
1375
-            $template_fields = esc_html__(
1376
-                'There was an error in assembling the fields for this display (you should see an error message)',
1377
-                'event_espresso'
1378
-            );
1379
-        }
1380
-
1381
-
1382
-        $message_templates = $message_template_group->context_templates();
1383
-
1384
-
1385
-        // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1386
-        // will get handled in the "extra" array.
1387
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1388
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1389
-                unset($template_field_structure[ $context ][ $reference_field ]);
1390
-            }
1391
-        }
1392
-
1393
-        // let's loop through the template_field_structure and actually assemble the input fields!
1394
-        if (! empty($template_field_structure)) {
1395
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1396
-                // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1397
-                // the extra array and reset them.
1398
-                if ($template_field === 'extra') {
1399
-                    $this->_template_args['is_extra_fields'] = true;
1400
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1401
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1402
-                        $content = $message_template instanceof EE_Message_Template
1403
-                            ? $message_template->get('MTP_content')
1404
-                            : '';
1405
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1406
-                            // let's verify if we need this extra field via the shortcodes parameter.
1407
-                            $continue = false;
1408
-                            if (isset($extra_array['shortcodes_required'])) {
1409
-                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1410
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1411
-                                        $continue = true;
1412
-                                    }
1413
-                                }
1414
-                                if ($continue) {
1415
-                                    continue;
1416
-                                }
1417
-                            }
1418
-
1419
-                            $field_id = $reference_field
1420
-                                        . '-'
1421
-                                        . $extra_field
1422
-                                        . '-content';
1423
-                            $template_form_fields[ $field_id ] = $extra_array;
1424
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1425
-                                                                         . $reference_field
1426
-                                                                         . '][content]['
1427
-                                                                         . $extra_field . ']';
1428
-                            $css_class = isset($extra_array['css_class'])
1429
-                                ? $extra_array['css_class']
1430
-                                : '';
1431
-
1432
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1433
-                                                                              && in_array($extra_field, $v_fields, true)
1434
-                                                                              &&
1435
-                                                                              (
1436
-                                                                                  is_array($validators[ $extra_field ])
1437
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1438
-                                                                              )
1439
-                                ? 'validate-error ' . $css_class
1440
-                                : $css_class;
1441
-
1442
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1443
-                                                                          && isset($content[ $extra_field ])
1444
-                                ? $content[ $extra_field ]
1445
-                                : '';
1446
-
1447
-                            // do we have a validation error?  if we do then let's use that value instead
1448
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1449
-                                ? $validators[ $extra_field ]['value']
1450
-                                : $template_form_fields[ $field_id ]['value'];
1451
-
1452
-
1453
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1454
-
1455
-                            // shortcode selector
1456
-                            $field_name_to_use = $extra_field === 'main'
1457
-                                ? 'content'
1458
-                                : $extra_field;
1459
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1460
-                                $field_name_to_use,
1461
-                                $field_id
1462
-                            );
1463
-
1464
-                            if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1465
-                                // we want to decode the entities
1466
-                                $template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1467
-                            }/**/
1468
-                        }
1469
-                        $templatefield_MTP_id = $reference_field . '-MTP_ID';
1470
-                        $templatefield_templatename_id = $reference_field . '-name';
1471
-
1472
-                        $template_form_fields[ $templatefield_MTP_id ] = array(
1473
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1474
-                            'label'      => null,
1475
-                            'input'      => 'hidden',
1476
-                            'type'       => 'int',
1477
-                            'required'   => false,
1478
-                            'validation' => false,
1479
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1480
-                            'css_class'  => '',
1481
-                            'format'     => '%d',
1482
-                            'db-col'     => 'MTP_ID',
1483
-                        );
1484
-
1485
-                        $template_form_fields[ $templatefield_templatename_id ] = array(
1486
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1487
-                            'label'      => null,
1488
-                            'input'      => 'hidden',
1489
-                            'type'       => 'string',
1490
-                            'required'   => false,
1491
-                            'validation' => true,
1492
-                            'value'      => $reference_field,
1493
-                            'css_class'  => '',
1494
-                            'format'     => '%s',
1495
-                            'db-col'     => 'MTP_template_field',
1496
-                        );
1497
-                    }
1498
-                    continue; // skip the next stuff, we got the necessary fields here for this dataset.
1499
-                } else {
1500
-                    $field_id = $template_field . '-content';
1501
-                    $template_form_fields[ $field_id ] = $field_setup_array;
1502
-                    $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1503
-                    $message_template = isset($message_templates[ $context ][ $template_field ])
1504
-                        ? $message_templates[ $context ][ $template_field ]
1505
-                        : null;
1506
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1507
-                                                                  && is_array($message_templates[ $context ])
1508
-                                                                  && $message_template instanceof EE_Message_Template
1509
-                        ? $message_template->get('MTP_content')
1510
-                        : '';
1511
-
1512
-                    // do we have a validator error for this field?  if we do then we'll use that value instead
1513
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1514
-                        ? $validators[ $template_field ]['value']
1515
-                        : $template_form_fields[ $field_id ]['value'];
1516
-
1517
-
1518
-                    $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1519
-                    $css_class = isset($field_setup_array['css_class'])
1520
-                        ? $field_setup_array['css_class']
1521
-                        : '';
1522
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1523
-                                                                      && in_array($template_field, $v_fields, true)
1524
-                                                                      && isset($validators[ $template_field ]['msg'])
1525
-                        ? 'validate-error ' . $css_class
1526
-                        : $css_class;
1527
-
1528
-                    // shortcode selector
1529
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1530
-                        $template_field,
1531
-                        $field_id
1532
-                    );
1533
-                }
1534
-
1535
-                // k took care of content field(s) now let's take care of others.
1536
-
1537
-                $templatefield_MTP_id = $template_field . '-MTP_ID';
1538
-                $templatefield_field_templatename_id = $template_field . '-name';
1539
-
1540
-                // foreach template field there are actually two form fields created
1541
-                $template_form_fields[ $templatefield_MTP_id ] = array(
1542
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1543
-                    'label'      => null,
1544
-                    'input'      => 'hidden',
1545
-                    'type'       => 'int',
1546
-                    'required'   => false,
1547
-                    'validation' => true,
1548
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1549
-                    'css_class'  => '',
1550
-                    'format'     => '%d',
1551
-                    'db-col'     => 'MTP_ID',
1552
-                );
1553
-
1554
-                $template_form_fields[ $templatefield_field_templatename_id ] = array(
1555
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1556
-                    'label'      => null,
1557
-                    'input'      => 'hidden',
1558
-                    'type'       => 'string',
1559
-                    'required'   => false,
1560
-                    'validation' => true,
1561
-                    'value'      => $template_field,
1562
-                    'css_class'  => '',
1563
-                    'format'     => '%s',
1564
-                    'db-col'     => 'MTP_template_field',
1565
-                );
1566
-            }
1567
-
1568
-            // add other fields
1569
-            $template_form_fields['ee-msg-current-context'] = array(
1570
-                'name'       => 'MTP_context',
1571
-                'label'      => null,
1572
-                'input'      => 'hidden',
1573
-                'type'       => 'string',
1574
-                'required'   => false,
1575
-                'validation' => true,
1576
-                'value'      => $context,
1577
-                'css_class'  => '',
1578
-                'format'     => '%s',
1579
-                'db-col'     => 'MTP_context',
1580
-            );
1581
-
1582
-            $template_form_fields['ee-msg-grp-id'] = array(
1583
-                'name'       => 'GRP_ID',
1584
-                'label'      => null,
1585
-                'input'      => 'hidden',
1586
-                'type'       => 'int',
1587
-                'required'   => false,
1588
-                'validation' => true,
1589
-                'value'      => $GRP_ID,
1590
-                'css_class'  => '',
1591
-                'format'     => '%d',
1592
-                'db-col'     => 'GRP_ID',
1593
-            );
1594
-
1595
-            $template_form_fields['ee-msg-messenger'] = array(
1596
-                'name'       => 'MTP_messenger',
1597
-                'label'      => null,
1598
-                'input'      => 'hidden',
1599
-                'type'       => 'string',
1600
-                'required'   => false,
1601
-                'validation' => true,
1602
-                'value'      => $message_template_group->messenger(),
1603
-                'css_class'  => '',
1604
-                'format'     => '%s',
1605
-                'db-col'     => 'MTP_messenger',
1606
-            );
1607
-
1608
-            $template_form_fields['ee-msg-message-type'] = array(
1609
-                'name'       => 'MTP_message_type',
1610
-                'label'      => null,
1611
-                'input'      => 'hidden',
1612
-                'type'       => 'string',
1613
-                'required'   => false,
1614
-                'validation' => true,
1615
-                'value'      => $message_template_group->message_type(),
1616
-                'css_class'  => '',
1617
-                'format'     => '%s',
1618
-                'db-col'     => 'MTP_message_type',
1619
-            );
1620
-
1621
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1622
-                'name'       => 'MTP_is_global',
1623
-                'label'      => esc_html__('Global Template', 'event_espresso'),
1624
-                'input'      => 'hidden',
1625
-                'type'       => 'int',
1626
-                'required'   => false,
1627
-                'validation' => true,
1628
-                'value'      => $message_template_group->get('MTP_is_global'),
1629
-                'css_class'  => '',
1630
-                'format'     => '%d',
1631
-                'db-col'     => 'MTP_is_global',
1632
-            );
1633
-
1634
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1635
-                'name'       => 'MTP_is_override',
1636
-                'label'      => esc_html__('Override all custom', 'event_espresso'),
1637
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1638
-                'type'       => 'int',
1639
-                'required'   => false,
1640
-                'validation' => true,
1641
-                'value'      => $message_template_group->get('MTP_is_override'),
1642
-                'css_class'  => '',
1643
-                'format'     => '%d',
1644
-                'db-col'     => 'MTP_is_override',
1645
-            );
1646
-
1647
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1648
-                'name'       => 'MTP_is_active',
1649
-                'label'      => esc_html__('Active Template', 'event_espresso'),
1650
-                'input'      => 'hidden',
1651
-                'type'       => 'int',
1652
-                'required'   => false,
1653
-                'validation' => true,
1654
-                'value'      => $message_template_group->is_active(),
1655
-                'css_class'  => '',
1656
-                'format'     => '%d',
1657
-                'db-col'     => 'MTP_is_active',
1658
-            );
1659
-
1660
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1661
-                'name'       => 'MTP_deleted',
1662
-                'label'      => null,
1663
-                'input'      => 'hidden',
1664
-                'type'       => 'int',
1665
-                'required'   => false,
1666
-                'validation' => true,
1667
-                'value'      => $message_template_group->get('MTP_deleted'),
1668
-                'css_class'  => '',
1669
-                'format'     => '%d',
1670
-                'db-col'     => 'MTP_deleted',
1671
-            );
1672
-            $sidebar_form_fields['ee-msg-author'] = array(
1673
-                'name'       => 'MTP_user_id',
1674
-                'label'      => esc_html__('Author', 'event_espresso'),
1675
-                'input'      => 'hidden',
1676
-                'type'       => 'int',
1677
-                'required'   => false,
1678
-                'validation' => false,
1679
-                'value'      => $message_template_group->user(),
1680
-                'format'     => '%d',
1681
-                'db-col'     => 'MTP_user_id',
1682
-            );
1683
-
1684
-            $sidebar_form_fields['ee-msg-route'] = array(
1685
-                'name'  => 'action',
1686
-                'input' => 'hidden',
1687
-                'type'  => 'string',
1688
-                'value' => $action,
1689
-            );
1690
-
1691
-            $sidebar_form_fields['ee-msg-id'] = array(
1692
-                'name'  => 'id',
1693
-                'input' => 'hidden',
1694
-                'type'  => 'int',
1695
-                'value' => $GRP_ID,
1696
-            );
1697
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1698
-                'name'  => $action . '_nonce',
1699
-                'input' => 'hidden',
1700
-                'type'  => 'string',
1701
-                'value' => wp_create_nonce($action . '_nonce'),
1702
-            );
1703
-
1704
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1705
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1706
-                    'name'  => 'template_switch',
1707
-                    'input' => 'hidden',
1708
-                    'type'  => 'int',
1709
-                    'value' => 1,
1710
-                );
1711
-            }
1712
-
1713
-
1714
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1715
-            $sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1716
-        } //end if ( !empty($template_field_structure) )
1717
-
1718
-        // set extra content for publish box
1719
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1720
-        $this->_set_publish_post_box_vars(
1721
-            'id',
1722
-            $GRP_ID,
1723
-            false,
1724
-            add_query_arg(
1725
-                array('action' => 'global_mtps'),
1726
-                $this->_admin_base_url
1727
-            )
1728
-        );
1729
-
1730
-        // add preview button
1731
-        $preview_url = parent::add_query_args_and_nonce(
1732
-            array(
1733
-                'message_type' => $message_template_group->message_type(),
1734
-                'messenger'    => $message_template_group->messenger(),
1735
-                'context'      => $context,
1736
-                'GRP_ID'       => $GRP_ID,
1737
-                'action'       => 'preview_message',
1738
-            ),
1739
-            $this->_admin_base_url
1740
-        );
1741
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1742
-                          . esc_html__('Preview', 'event_espresso')
1743
-                          . '</a>';
1744
-
1745
-
1746
-        // setup context switcher
1747
-        $context_switcher_args = array(
1748
-            'page'    => 'espresso_messages',
1749
-            'action'  => 'edit_message_template',
1750
-            'id'      => $GRP_ID,
1751
-            'context' => $context,
1752
-            'extra'   => $preview_button,
1753
-        );
1754
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1755
-
1756
-
1757
-        // main box
1758
-        $this->_template_args['template_fields'] = $template_fields;
1759
-        $this->_template_args['sidebar_box_id'] = 'details';
1760
-        $this->_template_args['action'] = $action;
1761
-        $this->_template_args['context'] = $context;
1762
-        $this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1763
-        $this->_template_args['learn_more_about_message_templates_link'] =
1764
-            $this->_learn_more_about_message_templates_link();
1765
-
1766
-
1767
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1768
-        $this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1769
-            $message_template_group,
1770
-            $context,
1771
-            $context_label
1772
-        );
1773
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1774
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1775
-
1776
-        $this->_template_path = $this->_template_args['GRP_ID']
1777
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1778
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1779
-
1780
-        // send along EE_Message_Template_Group object for further template use.
1781
-        $this->_template_args['MTP'] = $message_template_group;
1782
-
1783
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1784
-            $this->_template_path,
1785
-            $this->_template_args,
1786
-            true
1787
-        );
1788
-
1789
-
1790
-        // finally, let's set the admin_page title
1791
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1792
-
1793
-
1794
-        // we need to take care of setting the shortcodes property for use elsewhere.
1795
-        $this->_set_shortcodes();
1796
-
1797
-
1798
-        // final template wrapper
1799
-        $this->display_admin_page_with_sidebar();
1800
-    }
1801
-
1802
-
1803
-    public function filter_tinymce_init($mceInit, $editor_id)
1804
-    {
1805
-        return $mceInit;
1806
-    }
1807
-
1808
-
1809
-    public function add_context_switcher()
1810
-    {
1811
-        return $this->_context_switcher;
1812
-    }
1813
-
1814
-
1815
-    /**
1816
-     * Adds the activation/deactivation toggle for the message template context.
1817
-     *
1818
-     * @param EE_Message_Template_Group $message_template_group
1819
-     * @param string                    $context
1820
-     * @param string                    $context_label
1821
-     * @return string
1822
-     * @throws DomainException
1823
-     * @throws EE_Error
1824
-     * @throws InvalidIdentifierException
1825
-     */
1826
-    protected function add_active_context_element(
1827
-        EE_Message_Template_Group $message_template_group,
1828
-        $context,
1829
-        $context_label
1830
-    ) {
1831
-        $template_args = array(
1832
-            'context'                   => $context,
1833
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1834
-            'is_active'                 => $message_template_group->is_context_active($context),
1835
-            'on_off_action'             => $message_template_group->is_context_active($context)
1836
-                ? 'context-off'
1837
-                : 'context-on',
1838
-            'context_label'             => str_replace(array('(', ')'), '', $context_label),
1839
-            'message_template_group_id' => $message_template_group->ID(),
1840
-        );
1841
-        return EEH_Template::display_template(
1842
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1843
-            $template_args,
1844
-            true
1845
-        );
1846
-    }
1847
-
1848
-
1849
-    /**
1850
-     * Ajax callback for `toggle_context_template` ajax action.
1851
-     * Handles toggling the message context on or off.
1852
-     *
1853
-     * @throws EE_Error
1854
-     * @throws InvalidArgumentException
1855
-     * @throws InvalidDataTypeException
1856
-     * @throws InvalidIdentifierException
1857
-     * @throws InvalidInterfaceException
1858
-     */
1859
-    public function toggle_context_template()
1860
-    {
1861
-        $success = true;
1862
-        // check for required data
1863
-        if (! isset(
1864
-            $this->_req_data['message_template_group_id'],
1865
-            $this->_req_data['context'],
1866
-            $this->_req_data['status']
1867
-        )) {
1868
-            EE_Error::add_error(
1869
-                esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1870
-                __FILE__,
1871
-                __FUNCTION__,
1872
-                __LINE__
1873
-            );
1874
-            $success = false;
1875
-        }
1876
-
1877
-        $nonce = isset($this->_req_data['toggle_context_nonce'])
1878
-            ? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1879
-            : '';
1880
-        $nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1881
-        $this->_verify_nonce($nonce, $nonce_ref);
1882
-        $status = $this->_req_data['status'];
1883
-        if ($status !== 'off' && $status !== 'on') {
1884
-            EE_Error::add_error(
1885
-                sprintf(
1886
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1887
-                    $this->_req_data['status']
1888
-                ),
1889
-                __FILE__,
1890
-                __FUNCTION__,
1891
-                __LINE__
1892
-            );
1893
-            $success = false;
1894
-        }
1895
-        $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1896
-            $this->_req_data['message_template_group_id']
1897
-        );
1898
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1899
-            EE_Error::add_error(
1900
-                sprintf(
1901
-                    esc_html__(
1902
-                        'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1903
-                        'event_espresso'
1904
-                    ),
1905
-                    $this->_req_data['message_template_group_id'],
1906
-                    'EE_Message_Template_Group'
1907
-                ),
1908
-                __FILE__,
1909
-                __FUNCTION__,
1910
-                __LINE__
1911
-            );
1912
-            $success = false;
1913
-        }
1914
-        if ($success) {
1915
-            $success = $status === 'off'
1916
-                ? $message_template_group->deactivate_context($this->_req_data['context'])
1917
-                : $message_template_group->activate_context($this->_req_data['context']);
1918
-        }
1919
-        $this->_template_args['success'] = $success;
1920
-        $this->_return_json();
1921
-    }
1922
-
1923
-
1924
-    public function _add_form_element_before()
1925
-    {
1926
-        return '<form method="post" action="'
1927
-               . $this->_template_args["edit_message_template_form_url"]
1928
-               . '" id="ee-msg-edit-frm">';
1929
-    }
1930
-
1931
-    public function _add_form_element_after()
1932
-    {
1933
-        return '</form>';
1934
-    }
1935
-
1936
-
1937
-    /**
1938
-     * This executes switching the template pack for a message template.
1939
-     *
1940
-     * @since 4.5.0
1941
-     * @throws EE_Error
1942
-     * @throws InvalidDataTypeException
1943
-     * @throws InvalidInterfaceException
1944
-     * @throws InvalidArgumentException
1945
-     * @throws ReflectionException
1946
-     */
1947
-    public function switch_template_pack()
1948
-    {
1949
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1950
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1951
-
1952
-        // verify we have needed values.
1953
-        if (empty($GRP_ID) || empty($template_pack)) {
1954
-            $this->_template_args['error'] = true;
1955
-            EE_Error::add_error(
1956
-                esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1957
-                __FILE__,
1958
-                __FUNCTION__,
1959
-                __LINE__
1960
-            );
1961
-        } else {
1962
-            // get template, set the new template_pack and then reset to default
1963
-            /** @type EE_Message_Template_Group $message_template_group */
1964
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1965
-
1966
-            $message_template_group->set_template_pack_name($template_pack);
1967
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1968
-            $this->_req_data['mt'] = $message_template_group->message_type();
1969
-
1970
-            $query_args = $this->_reset_to_default_template();
1971
-
1972
-            if (empty($query_args['id'])) {
1973
-                EE_Error::add_error(
1974
-                    esc_html__(
1975
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1976
-                        'event_espresso'
1977
-                    ),
1978
-                    __FILE__,
1979
-                    __FUNCTION__,
1980
-                    __LINE__
1981
-                );
1982
-                $this->_template_args['error'] = true;
1983
-            } else {
1984
-                $template_label = $message_template_group->get_template_pack()->label;
1985
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1986
-                EE_Error::add_success(
1987
-                    sprintf(
1988
-                        esc_html__(
1989
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1990
-                            'event_espresso'
1991
-                        ),
1992
-                        $template_label,
1993
-                        $template_pack_labels->template_pack
1994
-                    )
1995
-                );
1996
-                // generate the redirect url for js.
1997
-                $url = self::add_query_args_and_nonce(
1998
-                    $query_args,
1999
-                    $this->_admin_base_url
2000
-                );
2001
-                $this->_template_args['data']['redirect_url'] = $url;
2002
-                $this->_template_args['success'] = true;
2003
-            }
2004
-
2005
-            $this->_return_json();
2006
-        }
2007
-    }
2008
-
2009
-
2010
-    /**
2011
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2012
-     * they want.
2013
-     *
2014
-     * @access protected
2015
-     * @return array|null
2016
-     * @throws EE_Error
2017
-     * @throws InvalidArgumentException
2018
-     * @throws InvalidDataTypeException
2019
-     * @throws InvalidInterfaceException
2020
-     */
2021
-    protected function _reset_to_default_template()
2022
-    {
2023
-
2024
-        $templates = array();
2025
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2026
-        // we need to make sure we've got the info we need.
2027
-        if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2028
-            EE_Error::add_error(
2029
-                esc_html__(
2030
-                    '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.',
2031
-                    'event_espresso'
2032
-                ),
2033
-                __FILE__,
2034
-                __FUNCTION__,
2035
-                __LINE__
2036
-            );
2037
-        }
2038
-
2039
-        // all templates will be reset to whatever the defaults are
2040
-        // for the global template matching the messenger and message type.
2041
-        $success = ! empty($GRP_ID) ? true : false;
2042
-
2043
-        if ($success) {
2044
-            // let's first determine if the incoming template is a global template,
2045
-            // if it isn't then we need to get the global template matching messenger and message type.
2046
-            // $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2047
-
2048
-
2049
-            // note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2050
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
2051
-
2052
-            if ($success) {
2053
-                // if successfully deleted, lets generate the new ones.
2054
-                // Note. We set GLOBAL to true, because resets on ANY template
2055
-                // will use the related global template defaults for regeneration.
2056
-                // This means that if a custom template is reset it resets to whatever the related global template is.
2057
-                // HOWEVER, we DO keep the template pack and template variation set
2058
-                // for the current custom template when resetting.
2059
-                $templates = $this->_generate_new_templates(
2060
-                    $this->_req_data['msgr'],
2061
-                    $this->_req_data['mt'],
2062
-                    $GRP_ID,
2063
-                    true
2064
-                );
2065
-            }
2066
-        }
2067
-
2068
-        // any error messages?
2069
-        if (! $success) {
2070
-            EE_Error::add_error(
2071
-                esc_html__(
2072
-                    'Something went wrong with deleting existing templates. Unable to reset to default',
2073
-                    'event_espresso'
2074
-                ),
2075
-                __FILE__,
2076
-                __FUNCTION__,
2077
-                __LINE__
2078
-            );
2079
-        }
2080
-
2081
-        // all good, let's add a success message!
2082
-        if ($success && ! empty($templates)) {
2083
-            // the info for the template we generated is the first element in the returned array
2084
-            // $templates = $templates[0];
2085
-            EE_Error::overwrite_success();
2086
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2087
-        }
2088
-
2089
-
2090
-        $query_args = array(
2091
-            'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2092
-            'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2093
-            'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2094
-        );
2095
-
2096
-        // if called via ajax then we return query args otherwise redirect
2097
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2098
-            return $query_args;
2099
-        } else {
2100
-            $this->_redirect_after_action(false, '', '', $query_args, true);
2101
-
2102
-            return null;
2103
-        }
2104
-    }
2105
-
2106
-
2107
-    /**
2108
-     * Retrieve and set the message preview for display.
2109
-     *
2110
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2111
-     * @return string
2112
-     * @throws ReflectionException
2113
-     * @throws EE_Error
2114
-     * @throws InvalidArgumentException
2115
-     * @throws InvalidDataTypeException
2116
-     * @throws InvalidInterfaceException
2117
-     */
2118
-    public function _preview_message($send = false)
2119
-    {
2120
-        // first make sure we've got the necessary parameters
2121
-        if (! isset(
2122
-            $this->_req_data['message_type'],
2123
-            $this->_req_data['messenger'],
2124
-            $this->_req_data['messenger'],
2125
-            $this->_req_data['GRP_ID']
2126
-        )) {
2127
-            EE_Error::add_error(
2128
-                esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2129
-                __FILE__,
2130
-                __FUNCTION__,
2131
-                __LINE__
2132
-            );
2133
-        }
2134
-
2135
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2136
-
2137
-
2138
-        // get the preview!
2139
-        $preview = EED_Messages::preview_message(
2140
-            $this->_req_data['message_type'],
2141
-            $this->_req_data['context'],
2142
-            $this->_req_data['messenger'],
2143
-            $send
2144
-        );
2145
-
2146
-        if ($send) {
2147
-            return $preview;
2148
-        }
2149
-
2150
-        // let's add a button to go back to the edit view
2151
-        $query_args = array(
2152
-            'id'      => $this->_req_data['GRP_ID'],
2153
-            'context' => $this->_req_data['context'],
2154
-            'action'  => 'edit_message_template',
2155
-        );
2156
-        $go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2157
-        $preview_button = '<a href="'
2158
-                          . $go_back_url
2159
-                          . '" class="button-secondary messages-preview-go-back-button">'
2160
-                          . esc_html__('Go Back to Edit', 'event_espresso')
2161
-                          . '</a>';
2162
-        $message_types = $this->get_installed_message_types();
2163
-        $active_messenger = $this->_message_resource_manager->get_active_messenger(
2164
-            $this->_req_data['messenger']
2165
-        );
2166
-        $active_messenger_label = $active_messenger instanceof EE_messenger
2167
-            ? ucwords($active_messenger->label['singular'])
2168
-            : esc_html__('Unknown Messenger', 'event_espresso');
2169
-        // let's provide a helpful title for context
2170
-        $preview_title = sprintf(
2171
-            esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2172
-            $active_messenger_label,
2173
-            ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2174
-        );
2175
-        if (empty($preview)) {
2176
-            $this->noEventsErrorMessage();
2177
-        }
2178
-        // setup display of preview.
2179
-        $this->_admin_page_title = $preview_title;
2180
-        $this->_template_args['admin_page_title'] = $preview_title;
2181
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2182
-        $this->_template_args['data']['force_json'] = true;
2183
-
2184
-        return '';
2185
-    }
2186
-
2187
-
2188
-    /**
2189
-     * Used to set an error if there are no events available for generating a preview/test send.
2190
-     *
2191
-     * @param bool $test_send  Whether the error should be generated for the context of a test send.
2192
-     */
2193
-    protected function noEventsErrorMessage($test_send = false)
2194
-    {
2195
-        $events_url = parent::add_query_args_and_nonce(
2196
-            array(
2197
-                'action' => 'default',
2198
-                'page'   => 'espresso_events',
2199
-            ),
2200
-            admin_url('admin.php')
2201
-        );
2202
-        $message = $test_send
2203
-            ? __(
2204
-                '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!',
2205
-                'event_espresso'
2206
-            )
2207
-            : __(
2208
-                '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!',
2209
-                'event_espresso'
2210
-            );
2211
-
2212
-        EE_Error::add_attention(
2213
-            sprintf(
2214
-                $message,
2215
-                "<a href='{$events_url}'>",
2216
-                '</a>'
2217
-            )
2218
-        );
2219
-    }
2220
-
2221
-
2222
-    /**
2223
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2224
-     * gets called automatically.
2225
-     *
2226
-     * @since 4.5.0
2227
-     *
2228
-     * @return string
2229
-     */
2230
-    protected function _display_preview_message()
2231
-    {
2232
-        $this->display_admin_page_with_no_sidebar();
2233
-    }
2234
-
2235
-
2236
-    /**
2237
-     * registers metaboxes that should show up on the "edit_message_template" page
2238
-     *
2239
-     * @access protected
2240
-     * @return void
2241
-     */
2242
-    protected function _register_edit_meta_boxes()
2243
-    {
2244
-        add_meta_box(
2245
-            'mtp_valid_shortcodes',
2246
-            esc_html__('Valid Shortcodes', 'event_espresso'),
2247
-            array($this, 'shortcode_meta_box'),
2248
-            $this->_current_screen->id,
2249
-            'side',
2250
-            'default'
2251
-        );
2252
-        add_meta_box(
2253
-            'mtp_extra_actions',
2254
-            esc_html__('Extra Actions', 'event_espresso'),
2255
-            array($this, 'extra_actions_meta_box'),
2256
-            $this->_current_screen->id,
2257
-            'side',
2258
-            'high'
2259
-        );
2260
-        add_meta_box(
2261
-            'mtp_templates',
2262
-            esc_html__('Template Styles', 'event_espresso'),
2263
-            array($this, 'template_pack_meta_box'),
2264
-            $this->_current_screen->id,
2265
-            'side',
2266
-            'high'
2267
-        );
2268
-    }
2269
-
2270
-
2271
-    /**
2272
-     * metabox content for all template pack and variation selection.
2273
-     *
2274
-     * @since 4.5.0
2275
-     * @return string
2276
-     * @throws DomainException
2277
-     * @throws EE_Error
2278
-     * @throws InvalidArgumentException
2279
-     * @throws ReflectionException
2280
-     * @throws InvalidDataTypeException
2281
-     * @throws InvalidInterfaceException
2282
-     */
2283
-    public function template_pack_meta_box()
2284
-    {
2285
-        $this->_set_message_template_group();
2286
-
2287
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
2288
-
2289
-        $tp_select_values = array();
2290
-
2291
-        foreach ($tp_collection as $tp) {
2292
-            // only include template packs that support this messenger and message type!
2293
-            $supports = $tp->get_supports();
2294
-            if (! isset($supports[ $this->_message_template_group->messenger() ])
2295
-                || ! in_array(
2296
-                    $this->_message_template_group->message_type(),
2297
-                    $supports[ $this->_message_template_group->messenger() ],
2298
-                    true
2299
-                )
2300
-            ) {
2301
-                // not supported
2302
-                continue;
2303
-            }
2304
-
2305
-            $tp_select_values[] = array(
2306
-                'text' => $tp->label,
2307
-                'id'   => $tp->dbref,
2308
-            );
2309
-        }
2310
-
2311
-        // if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2312
-        // the default template pack.  This still allows for the odd template pack to override.
2313
-        if (empty($tp_select_values)) {
2314
-            $tp_select_values[] = array(
2315
-                'text' => esc_html__('Default', 'event_espresso'),
2316
-                'id'   => 'default',
2317
-            );
2318
-        }
2319
-
2320
-        // setup variation select values for the currently selected template.
2321
-        $variations = $this->_message_template_group->get_template_pack()->get_variations(
2322
-            $this->_message_template_group->messenger(),
2323
-            $this->_message_template_group->message_type()
2324
-        );
2325
-        $variations_select_values = array();
2326
-        foreach ($variations as $variation => $label) {
2327
-            $variations_select_values[] = array(
2328
-                'text' => $label,
2329
-                'id'   => $variation,
2330
-            );
2331
-        }
2332
-
2333
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2334
-
2335
-        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2336
-            'MTP_template_pack',
2337
-            $tp_select_values,
2338
-            $this->_message_template_group->get_template_pack_name()
2339
-        );
2340
-        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
2341
-            'MTP_template_variation',
2342
-            $variations_select_values,
2343
-            $this->_message_template_group->get_template_pack_variation()
2344
-        );
2345
-        $template_args['template_pack_label'] = $template_pack_labels->template_pack;
2346
-        $template_args['template_variation_label'] = $template_pack_labels->template_variation;
2347
-        $template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2348
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2349
-
2350
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2351
-
2352
-        EEH_Template::display_template($template, $template_args);
2353
-    }
2354
-
2355
-
2356
-    /**
2357
-     * This meta box holds any extra actions related to Message Templates
2358
-     * For now, this includes Resetting templates to defaults and sending a test email.
2359
-     *
2360
-     * @access  public
2361
-     * @return void
2362
-     * @throws EE_Error
2363
-     */
2364
-    public function extra_actions_meta_box()
2365
-    {
2366
-        $template_form_fields = array();
2367
-
2368
-        $extra_args = array(
2369
-            'msgr'   => $this->_message_template_group->messenger(),
2370
-            'mt'     => $this->_message_template_group->message_type(),
2371
-            'GRP_ID' => $this->_message_template_group->GRP_ID(),
2372
-        );
2373
-        // first we need to see if there are any fields
2374
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2375
-
2376
-        if (! empty($fields)) {
2377
-            // yup there be fields
2378
-            foreach ($fields as $field => $config) {
2379
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2380
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2381
-                $default = isset($config['default']) ? $config['default'] : '';
2382
-                $default = isset($config['value']) ? $config['value'] : $default;
2383
-
2384
-                // if type is hidden and the value is empty
2385
-                // something may have gone wrong so let's correct with the defaults
2386
-                $fix = $config['input'] === 'hidden'
2387
-                       && isset($existing[ $field ])
2388
-                       && empty($existing[ $field ])
2389
-                    ? $default
2390
-                    : '';
2391
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2392
-                    ? $existing[ $field ]
2393
-                    : $fix;
2394
-
2395
-                $template_form_fields[ $field_id ] = array(
2396
-                    'name'       => 'test_settings_fld[' . $field . ']',
2397
-                    'label'      => $config['label'],
2398
-                    'input'      => $config['input'],
2399
-                    'type'       => $config['type'],
2400
-                    'required'   => $config['required'],
2401
-                    'validation' => $config['validation'],
2402
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2403
-                    'css_class'  => $config['css_class'],
2404
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2405
-                    'default'    => $default,
2406
-                    'format'     => $config['format'],
2407
-                );
2408
-            }
2409
-        }
2410
-
2411
-        $test_settings_fields = ! empty($template_form_fields)
2412
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2413
-            : '';
2414
-
2415
-        $test_settings_html = '';
2416
-        // print out $test_settings_fields
2417
-        if (! empty($test_settings_fields)) {
2418
-            echo $test_settings_fields;
2419
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2420
-            $test_settings_html .= 'name="test_button" value="';
2421
-            $test_settings_html .= esc_html__('Test Send', 'event_espresso');
2422
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2423
-        }
2424
-
2425
-        // and button
2426
-        $test_settings_html .= '<p>'
2427
-                               . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2428
-                               . '</p>';
2429
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2430
-        $test_settings_html .= $this->get_action_link_or_button(
2431
-            'reset_to_default',
2432
-            'reset',
2433
-            $extra_args,
2434
-            'button-primary reset-default-button'
2435
-        );
2436
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2437
-        echo $test_settings_html;
2438
-    }
2439
-
2440
-
2441
-    /**
2442
-     * This returns the shortcode selector skeleton for a given context and field.
2443
-     *
2444
-     * @since 4.9.rc.000
2445
-     * @param string $field           The name of the field retrieving shortcodes for.
2446
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2447
-     * @return string
2448
-     * @throws DomainException
2449
-     * @throws EE_Error
2450
-     * @throws InvalidArgumentException
2451
-     * @throws ReflectionException
2452
-     * @throws InvalidDataTypeException
2453
-     * @throws InvalidInterfaceException
2454
-     */
2455
-    protected function _get_shortcode_selector($field, $linked_input_id)
2456
-    {
2457
-        $template_args = array(
2458
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2459
-            'fieldname'       => $field,
2460
-            'linked_input_id' => $linked_input_id,
2461
-        );
2462
-
2463
-        return EEH_Template::display_template(
2464
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2465
-            $template_args,
2466
-            true
2467
-        );
2468
-    }
2469
-
2470
-
2471
-    /**
2472
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2473
-     * page)
2474
-     *
2475
-     * @access public
2476
-     * @return void
2477
-     * @throws EE_Error
2478
-     * @throws InvalidArgumentException
2479
-     * @throws ReflectionException
2480
-     * @throws InvalidDataTypeException
2481
-     * @throws InvalidInterfaceException
2482
-     */
2483
-    public function shortcode_meta_box()
2484
-    {
2485
-        $shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2486
-        // $messenger = $this->_message_template_group->messenger_obj();
2487
-        // now let's set the content depending on the status of the shortcodes array
2488
-        if (empty($shortcodes)) {
2489
-            $content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2490
-            echo $content;
2491
-        } else {
2492
-            // $alt = 0;
2493
-            ?>
22
+	/**
23
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
24
+	 */
25
+	protected $_message_resource_manager;
26
+
27
+	/**
28
+	 * @type string $_active_message_type_name
29
+	 */
30
+	protected $_active_message_type_name = '';
31
+
32
+	/**
33
+	 * @type EE_messenger $_active_messenger
34
+	 */
35
+	protected $_active_messenger;
36
+	protected $_activate_state;
37
+	protected $_activate_meta_box_type;
38
+	protected $_current_message_meta_box;
39
+	protected $_current_message_meta_box_object;
40
+	protected $_context_switcher;
41
+	protected $_shortcodes = array();
42
+	protected $_active_messengers = array();
43
+	protected $_active_message_types = array();
44
+
45
+	/**
46
+	 * @var EE_Message_Template_Group $_message_template_group
47
+	 */
48
+	protected $_message_template_group;
49
+	protected $_m_mt_settings = array();
50
+
51
+
52
+	/**
53
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
+	 * IF there is no group then it gets automatically set to the Default template pack.
55
+	 *
56
+	 * @since 4.5.0
57
+	 *
58
+	 * @var EE_Messages_Template_Pack
59
+	 */
60
+	protected $_template_pack;
61
+
62
+
63
+	/**
64
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
+	 * group is.  If there is no group then it automatically gets set to default.
66
+	 *
67
+	 * @since 4.5.0
68
+	 *
69
+	 * @var string
70
+	 */
71
+	protected $_variation;
72
+
73
+
74
+	/**
75
+	 * @param bool $routing
76
+	 * @throws EE_Error
77
+	 */
78
+	public function __construct($routing = true)
79
+	{
80
+		// make sure messages autoloader is running
81
+		EED_Messages::set_autoloaders();
82
+		parent::__construct($routing);
83
+	}
84
+
85
+
86
+	protected function _init_page_props()
87
+	{
88
+		$this->page_slug = EE_MSG_PG_SLUG;
89
+		$this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
+		$this->_admin_base_url = EE_MSG_ADMIN_URL;
91
+		$this->_admin_base_path = EE_MSG_ADMIN;
92
+
93
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
+			: array();
95
+
96
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
+		$this->_load_message_resource_manager();
98
+	}
99
+
100
+
101
+	/**
102
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
+	 *
104
+	 * @throws EE_Error
105
+	 * @throws InvalidDataTypeException
106
+	 * @throws InvalidInterfaceException
107
+	 * @throws InvalidArgumentException
108
+	 * @throws ReflectionException
109
+	 */
110
+	protected function _load_message_resource_manager()
111
+	{
112
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
+	}
114
+
115
+
116
+	/**
117
+	 * @deprecated 4.9.9.rc.014
118
+	 * @return array
119
+	 * @throws EE_Error
120
+	 * @throws InvalidArgumentException
121
+	 * @throws InvalidDataTypeException
122
+	 * @throws InvalidInterfaceException
123
+	 */
124
+	public function get_messengers_for_list_table()
125
+	{
126
+		EE_Error::doing_it_wrong(
127
+			__METHOD__,
128
+			sprintf(
129
+				esc_html__(
130
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
+					'event_espresso'
132
+				),
133
+				'Messages_Admin_Page::get_messengers_select_input()'
134
+			),
135
+			'4.9.9.rc.014'
136
+		);
137
+
138
+		$m_values = array();
139
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
+		// setup messengers for selects
141
+		$i = 1;
142
+		foreach ($active_messengers as $active_messenger) {
143
+			if ($active_messenger instanceof EE_Message) {
144
+				$m_values[ $i ]['id'] = $active_messenger->messenger();
145
+				$m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
+				$i++;
147
+			}
148
+		}
149
+
150
+		return $m_values;
151
+	}
152
+
153
+
154
+	/**
155
+	 * @deprecated 4.9.9.rc.014
156
+	 * @return array
157
+	 * @throws EE_Error
158
+	 * @throws InvalidArgumentException
159
+	 * @throws InvalidDataTypeException
160
+	 * @throws InvalidInterfaceException
161
+	 */
162
+	public function get_message_types_for_list_table()
163
+	{
164
+		EE_Error::doing_it_wrong(
165
+			__METHOD__,
166
+			sprintf(
167
+				esc_html__(
168
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
+					'event_espresso'
170
+				),
171
+				'Messages_Admin_Page::get_message_types_select_input()'
172
+			),
173
+			'4.9.9.rc.014'
174
+		);
175
+
176
+		$mt_values = array();
177
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
+		$i = 1;
179
+		foreach ($active_messages as $active_message) {
180
+			if ($active_message instanceof EE_Message) {
181
+				$mt_values[ $i ]['id'] = $active_message->message_type();
182
+				$mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
+				$i++;
184
+			}
185
+		}
186
+
187
+		return $mt_values;
188
+	}
189
+
190
+
191
+	/**
192
+	 * @deprecated 4.9.9.rc.014
193
+	 * @return array
194
+	 * @throws EE_Error
195
+	 * @throws InvalidArgumentException
196
+	 * @throws InvalidDataTypeException
197
+	 * @throws InvalidInterfaceException
198
+	 */
199
+	public function get_contexts_for_message_types_for_list_table()
200
+	{
201
+		EE_Error::doing_it_wrong(
202
+			__METHOD__,
203
+			sprintf(
204
+				esc_html__(
205
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
+					'event_espresso'
207
+				),
208
+				'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
+			),
210
+			'4.9.9.rc.014'
211
+		);
212
+
213
+		$contexts = array();
214
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
+		foreach ($active_message_contexts as $active_message) {
216
+			if ($active_message instanceof EE_Message) {
217
+				$message_type = $active_message->message_type_object();
218
+				if ($message_type instanceof EE_message_type) {
219
+					$message_type_contexts = $message_type->get_contexts();
220
+					foreach ($message_type_contexts as $context => $context_details) {
221
+						$contexts[ $context ] = $context_details['label'];
222
+					}
223
+				}
224
+			}
225
+		}
226
+
227
+		return $contexts;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Generate select input with provided messenger options array.
233
+	 *
234
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
+	 *                                 labels.
236
+	 * @return string
237
+	 * @throws EE_Error
238
+	 */
239
+	public function get_messengers_select_input($messenger_options)
240
+	{
241
+		// if empty or just one value then just return an empty string
242
+		if (empty($messenger_options)
243
+			|| ! is_array($messenger_options)
244
+			|| count($messenger_options) === 1
245
+		) {
246
+			return '';
247
+		}
248
+		// merge in default
249
+		$messenger_options = array_merge(
250
+			array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
+			$messenger_options
252
+		);
253
+		$input = new EE_Select_Input(
254
+			$messenger_options,
255
+			array(
256
+				'html_name'  => 'ee_messenger_filter_by',
257
+				'html_id'    => 'ee_messenger_filter_by',
258
+				'html_class' => 'wide',
259
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
+					: 'none_selected',
262
+			)
263
+		);
264
+
265
+		return $input->get_html_for_input();
266
+	}
267
+
268
+
269
+	/**
270
+	 * Generate select input with provided message type options array.
271
+	 *
272
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
+	 *                                    message type labels
274
+	 * @return string
275
+	 * @throws EE_Error
276
+	 */
277
+	public function get_message_types_select_input($message_type_options)
278
+	{
279
+		// if empty or count of options is 1 then just return an empty string
280
+		if (empty($message_type_options)
281
+			|| ! is_array($message_type_options)
282
+			|| count($message_type_options) === 1
283
+		) {
284
+			return '';
285
+		}
286
+		// merge in default
287
+		$message_type_options = array_merge(
288
+			array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
+			$message_type_options
290
+		);
291
+		$input = new EE_Select_Input(
292
+			$message_type_options,
293
+			array(
294
+				'html_name'  => 'ee_message_type_filter_by',
295
+				'html_id'    => 'ee_message_type_filter_by',
296
+				'html_class' => 'wide',
297
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
+					: 'none_selected',
300
+			)
301
+		);
302
+
303
+		return $input->get_html_for_input();
304
+	}
305
+
306
+
307
+	/**
308
+	 * Generate select input with provide message type contexts array.
309
+	 *
310
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
+	 *                               context label.
312
+	 * @return string
313
+	 * @throws EE_Error
314
+	 */
315
+	public function get_contexts_for_message_types_select_input($context_options)
316
+	{
317
+		// if empty or count of options is one then just return empty string
318
+		if (empty($context_options)
319
+			|| ! is_array($context_options)
320
+			|| count($context_options) === 1
321
+		) {
322
+			return '';
323
+		}
324
+		// merge in default
325
+		$context_options = array_merge(
326
+			array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
+			$context_options
328
+		);
329
+		$input = new EE_Select_Input(
330
+			$context_options,
331
+			array(
332
+				'html_name'  => 'ee_context_filter_by',
333
+				'html_id'    => 'ee_context_filter_by',
334
+				'html_class' => 'wide',
335
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
336
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
337
+					: 'none_selected',
338
+			)
339
+		);
340
+
341
+		return $input->get_html_for_input();
342
+	}
343
+
344
+
345
+	protected function _ajax_hooks()
346
+	{
347
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
+		add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
+	}
354
+
355
+
356
+	protected function _define_page_props()
357
+	{
358
+		$this->_admin_page_title = $this->page_label;
359
+		$this->_labels = array(
360
+			'buttons'    => array(
361
+				'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
+				'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
+				'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
+			),
365
+			'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
+		);
367
+	}
368
+
369
+
370
+	/**
371
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
372
+	 *
373
+	 * @access protected
374
+	 * @return void
375
+	 */
376
+	protected function _set_page_routes()
377
+	{
378
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
+			? $this->_req_data['GRP_ID']
380
+			: 0;
381
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
+			? $this->_req_data['id']
383
+			: $grp_id;
384
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
+			? $this->_req_data['MSG_ID']
386
+			: 0;
387
+
388
+		$this->_page_routes = array(
389
+			'default'                          => array(
390
+				'func'       => '_message_queue_list_table',
391
+				'capability' => 'ee_read_global_messages',
392
+			),
393
+			'global_mtps'                      => array(
394
+				'func'       => '_ee_default_messages_overview_list_table',
395
+				'capability' => 'ee_read_global_messages',
396
+			),
397
+			'custom_mtps'                      => array(
398
+				'func'       => '_custom_mtps_preview',
399
+				'capability' => 'ee_read_messages',
400
+			),
401
+			'add_new_message_template'         => array(
402
+				'func'       => '_add_message_template',
403
+				'capability' => 'ee_edit_messages',
404
+				'noheader'   => true,
405
+			),
406
+			'edit_message_template'            => array(
407
+				'func'       => '_edit_message_template',
408
+				'capability' => 'ee_edit_message',
409
+				'obj_id'     => $grp_id,
410
+			),
411
+			'preview_message'                  => array(
412
+				'func'               => '_preview_message',
413
+				'capability'         => 'ee_read_message',
414
+				'obj_id'             => $grp_id,
415
+				'noheader'           => true,
416
+				'headers_sent_route' => 'display_preview_message',
417
+			),
418
+			'display_preview_message'          => array(
419
+				'func'       => '_display_preview_message',
420
+				'capability' => 'ee_read_message',
421
+				'obj_id'     => $grp_id,
422
+			),
423
+			'insert_message_template'          => array(
424
+				'func'       => '_insert_or_update_message_template',
425
+				'capability' => 'ee_edit_messages',
426
+				'args'       => array('new_template' => true),
427
+				'noheader'   => true,
428
+			),
429
+			'update_message_template'          => array(
430
+				'func'       => '_insert_or_update_message_template',
431
+				'capability' => 'ee_edit_message',
432
+				'obj_id'     => $grp_id,
433
+				'args'       => array('new_template' => false),
434
+				'noheader'   => true,
435
+			),
436
+			'trash_message_template'           => array(
437
+				'func'       => '_trash_or_restore_message_template',
438
+				'capability' => 'ee_delete_message',
439
+				'obj_id'     => $grp_id,
440
+				'args'       => array('trash' => true, 'all' => true),
441
+				'noheader'   => true,
442
+			),
443
+			'trash_message_template_context'   => array(
444
+				'func'       => '_trash_or_restore_message_template',
445
+				'capability' => 'ee_delete_message',
446
+				'obj_id'     => $grp_id,
447
+				'args'       => array('trash' => true),
448
+				'noheader'   => true,
449
+			),
450
+			'restore_message_template'         => array(
451
+				'func'       => '_trash_or_restore_message_template',
452
+				'capability' => 'ee_delete_message',
453
+				'obj_id'     => $grp_id,
454
+				'args'       => array('trash' => false, 'all' => true),
455
+				'noheader'   => true,
456
+			),
457
+			'restore_message_template_context' => array(
458
+				'func'       => '_trash_or_restore_message_template',
459
+				'capability' => 'ee_delete_message',
460
+				'obj_id'     => $grp_id,
461
+				'args'       => array('trash' => false),
462
+				'noheader'   => true,
463
+			),
464
+			'delete_message_template'          => array(
465
+				'func'       => '_delete_message_template',
466
+				'capability' => 'ee_delete_message',
467
+				'obj_id'     => $grp_id,
468
+				'noheader'   => true,
469
+			),
470
+			'reset_to_default'                 => array(
471
+				'func'       => '_reset_to_default_template',
472
+				'capability' => 'ee_edit_message',
473
+				'obj_id'     => $grp_id,
474
+				'noheader'   => true,
475
+			),
476
+			'settings'                         => array(
477
+				'func'       => '_settings',
478
+				'capability' => 'manage_options',
479
+			),
480
+			'update_global_settings'           => array(
481
+				'func'       => '_update_global_settings',
482
+				'capability' => 'manage_options',
483
+				'noheader'   => true,
484
+			),
485
+			'generate_now'                     => array(
486
+				'func'       => '_generate_now',
487
+				'capability' => 'ee_send_message',
488
+				'noheader'   => true,
489
+			),
490
+			'generate_and_send_now'            => array(
491
+				'func'       => '_generate_and_send_now',
492
+				'capability' => 'ee_send_message',
493
+				'noheader'   => true,
494
+			),
495
+			'queue_for_resending'              => array(
496
+				'func'       => '_queue_for_resending',
497
+				'capability' => 'ee_send_message',
498
+				'noheader'   => true,
499
+			),
500
+			'send_now'                         => array(
501
+				'func'       => '_send_now',
502
+				'capability' => 'ee_send_message',
503
+				'noheader'   => true,
504
+			),
505
+			'delete_ee_message'                => array(
506
+				'func'       => '_delete_ee_messages',
507
+				'capability' => 'ee_delete_messages',
508
+				'noheader'   => true,
509
+			),
510
+			'delete_ee_messages'               => array(
511
+				'func'       => '_delete_ee_messages',
512
+				'capability' => 'ee_delete_messages',
513
+				'noheader'   => true,
514
+				'obj_id'     => $msg_id,
515
+			),
516
+		);
517
+	}
518
+
519
+
520
+	protected function _set_page_config()
521
+	{
522
+		$this->_page_config = array(
523
+			'default'                  => array(
524
+				'nav'           => array(
525
+					'label' => esc_html__('Message Activity', 'event_espresso'),
526
+					'order' => 10,
527
+				),
528
+				'list_table'    => 'EE_Message_List_Table',
529
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
+				'require_nonce' => false,
531
+			),
532
+			'global_mtps'              => array(
533
+				'nav'           => array(
534
+					'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
+					'order' => 20,
536
+				),
537
+				'list_table'    => 'Messages_Template_List_Table',
538
+				'help_tabs'     => array(
539
+					'messages_overview_help_tab'                                => array(
540
+						'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
+						'filename' => 'messages_overview',
542
+					),
543
+					'messages_overview_messages_table_column_headings_help_tab' => array(
544
+						'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
+						'filename' => 'messages_overview_table_column_headings',
546
+					),
547
+					'messages_overview_messages_filters_help_tab'               => array(
548
+						'title'    => esc_html__('Message Filters', 'event_espresso'),
549
+						'filename' => 'messages_overview_filters',
550
+					),
551
+					'messages_overview_messages_views_help_tab'                 => array(
552
+						'title'    => esc_html__('Message Views', 'event_espresso'),
553
+						'filename' => 'messages_overview_views',
554
+					),
555
+					'message_overview_message_types_help_tab'                   => array(
556
+						'title'    => esc_html__('Message Types', 'event_espresso'),
557
+						'filename' => 'messages_overview_types',
558
+					),
559
+					'messages_overview_messengers_help_tab'                     => array(
560
+						'title'    => esc_html__('Messengers', 'event_espresso'),
561
+						'filename' => 'messages_overview_messengers',
562
+					),
563
+				),
564
+				'help_tour'     => array('Messages_Overview_Help_Tour'),
565
+				'require_nonce' => false,
566
+			),
567
+			'custom_mtps'              => array(
568
+				'nav'           => array(
569
+					'label' => esc_html__('Custom Message Templates', 'event_espresso'),
570
+					'order' => 30,
571
+				),
572
+				'help_tabs'     => array(),
573
+				'help_tour'     => array(),
574
+				'require_nonce' => false,
575
+			),
576
+			'add_new_message_template' => array(
577
+				'nav'           => array(
578
+					'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
579
+					'order'      => 5,
580
+					'persistent' => false,
581
+				),
582
+				'require_nonce' => false,
583
+			),
584
+			'edit_message_template'    => array(
585
+				'labels'        => array(
586
+					'buttons'    => array(
587
+						'reset' => esc_html__('Reset Templates', 'event_espresso'),
588
+					),
589
+					'publishbox' => esc_html__('Update Actions', 'event_espresso'),
590
+				),
591
+				'nav'           => array(
592
+					'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
593
+					'order'      => 5,
594
+					'persistent' => false,
595
+					'url'        => '',
596
+				),
597
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
598
+				'has_metaboxes' => true,
599
+				'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
600
+				'help_tabs'     => array(
601
+					'edit_message_template'            => array(
602
+						'title'    => esc_html__('Message Template Editor', 'event_espresso'),
603
+						'callback' => 'edit_message_template_help_tab',
604
+					),
605
+					'message_templates_help_tab'       => array(
606
+						'title'    => esc_html__('Message Templates', 'event_espresso'),
607
+						'filename' => 'messages_templates',
608
+					),
609
+					'message_template_shortcodes'      => array(
610
+						'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
611
+						'callback' => 'message_template_shortcodes_help_tab',
612
+					),
613
+					'message_preview_help_tab'         => array(
614
+						'title'    => esc_html__('Message Preview', 'event_espresso'),
615
+						'filename' => 'messages_preview',
616
+					),
617
+					'messages_overview_other_help_tab' => array(
618
+						'title'    => esc_html__('Messages Other', 'event_espresso'),
619
+						'filename' => 'messages_overview_other',
620
+					),
621
+				),
622
+				'require_nonce' => false,
623
+			),
624
+			'display_preview_message'  => array(
625
+				'nav'           => array(
626
+					'label'      => esc_html__('Message Preview', 'event_espresso'),
627
+					'order'      => 5,
628
+					'url'        => '',
629
+					'persistent' => false,
630
+				),
631
+				'help_tabs'     => array(
632
+					'preview_message' => array(
633
+						'title'    => esc_html__('About Previews', 'event_espresso'),
634
+						'callback' => 'preview_message_help_tab',
635
+					),
636
+				),
637
+				'require_nonce' => false,
638
+			),
639
+			'settings'                 => array(
640
+				'nav'           => array(
641
+					'label' => esc_html__('Settings', 'event_espresso'),
642
+					'order' => 40,
643
+				),
644
+				'metaboxes'     => array('_messages_settings_metaboxes'),
645
+				'help_tabs'     => array(
646
+					'messages_settings_help_tab'               => array(
647
+						'title'    => esc_html__('Messages Settings', 'event_espresso'),
648
+						'filename' => 'messages_settings',
649
+					),
650
+					'messages_settings_message_types_help_tab' => array(
651
+						'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
652
+						'filename' => 'messages_settings_message_types',
653
+					),
654
+					'messages_settings_messengers_help_tab'    => array(
655
+						'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
656
+						'filename' => 'messages_settings_messengers',
657
+					),
658
+				),
659
+				'help_tour'     => array('Messages_Settings_Help_Tour'),
660
+				'require_nonce' => false,
661
+			),
662
+		);
663
+	}
664
+
665
+
666
+	protected function _add_screen_options()
667
+	{
668
+		// todo
669
+	}
670
+
671
+
672
+	protected function _add_screen_options_global_mtps()
673
+	{
674
+		/**
675
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
676
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
677
+		 */
678
+		$page_title = $this->_admin_page_title;
679
+		$this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
680
+		$this->_per_page_screen_option();
681
+		$this->_admin_page_title = $page_title;
682
+	}
683
+
684
+
685
+	protected function _add_screen_options_default()
686
+	{
687
+		$this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
688
+		$this->_per_page_screen_option();
689
+	}
690
+
691
+
692
+	// none of the below group are currently used for Messages
693
+	protected function _add_feature_pointers()
694
+	{
695
+	}
696
+
697
+	public function admin_init()
698
+	{
699
+	}
700
+
701
+	public function admin_notices()
702
+	{
703
+	}
704
+
705
+	public function admin_footer_scripts()
706
+	{
707
+	}
708
+
709
+
710
+	public function messages_help_tab()
711
+	{
712
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
713
+	}
714
+
715
+
716
+	public function messengers_help_tab()
717
+	{
718
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
719
+	}
720
+
721
+
722
+	public function message_types_help_tab()
723
+	{
724
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
725
+	}
726
+
727
+
728
+	public function messages_overview_help_tab()
729
+	{
730
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
731
+	}
732
+
733
+
734
+	public function message_templates_help_tab()
735
+	{
736
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
737
+	}
738
+
739
+
740
+	public function edit_message_template_help_tab()
741
+	{
742
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
743
+						. esc_attr__('Editor Title', 'event_espresso')
744
+						. '" />';
745
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
746
+						. esc_attr__('Context Switcher and Preview', 'event_espresso')
747
+						. '" />';
748
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
749
+						. esc_attr__('Message Template Form Fields', 'event_espresso')
750
+						. '" />';
751
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
752
+						. esc_attr__('Shortcodes Metabox', 'event_espresso')
753
+						. '" />';
754
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
755
+						. esc_attr__('Publish Metabox', 'event_espresso')
756
+						. '" />';
757
+		EEH_Template::display_template(
758
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
759
+			$args
760
+		);
761
+	}
762
+
763
+
764
+	public function message_template_shortcodes_help_tab()
765
+	{
766
+		$this->_set_shortcodes();
767
+		$args['shortcodes'] = $this->_shortcodes;
768
+		EEH_Template::display_template(
769
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
770
+			$args
771
+		);
772
+	}
773
+
774
+
775
+	public function preview_message_help_tab()
776
+	{
777
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
778
+	}
779
+
780
+
781
+	public function settings_help_tab()
782
+	{
783
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
784
+						. '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
785
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
786
+						. '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
787
+		$args['img3'] = '<div class="switch">'
788
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
789
+						. ' type="checkbox" checked="checked">'
790
+						. '<label for="ee-on-off-toggle-on"></label>'
791
+						. '</div>';
792
+		$args['img4'] = '<div class="switch">'
793
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
794
+						. ' type="checkbox">'
795
+						. '<label for="ee-on-off-toggle-on"></label>'
796
+						. '</div>';
797
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
798
+	}
799
+
800
+
801
+	public function load_scripts_styles()
802
+	{
803
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
804
+		wp_enqueue_style('espresso_ee_msg');
805
+
806
+		wp_register_script(
807
+			'ee-messages-settings',
808
+			EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
+			array('jquery-ui-droppable', 'ee-serialize-full-array'),
810
+			EVENT_ESPRESSO_VERSION,
811
+			true
812
+		);
813
+		wp_register_script(
814
+			'ee-msg-list-table-js',
815
+			EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
816
+			array('ee-dialog'),
817
+			EVENT_ESPRESSO_VERSION
818
+		);
819
+	}
820
+
821
+
822
+	public function load_scripts_styles_default()
823
+	{
824
+		wp_enqueue_script('ee-msg-list-table-js');
825
+	}
826
+
827
+
828
+	public function wp_editor_css($mce_css)
829
+	{
830
+		// if we're on the edit_message_template route
831
+		if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
832
+			$message_type_name = $this->_active_message_type_name;
833
+
834
+			// we're going to REPLACE the existing mce css
835
+			// we need to get the css file location from the active messenger
836
+			$mce_css = $this->_active_messenger->get_variation(
837
+				$this->_template_pack,
838
+				$message_type_name,
839
+				true,
840
+				'wpeditor',
841
+				$this->_variation
842
+			);
843
+		}
844
+
845
+		return $mce_css;
846
+	}
847
+
848
+
849
+	public function load_scripts_styles_edit_message_template()
850
+	{
851
+
852
+		$this->_set_shortcodes();
853
+
854
+		EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
855
+			esc_html__(
856
+				'Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
857
+				'event_espresso'
858
+			),
859
+			$this->_message_template_group->messenger_obj()->label['singular'],
860
+			$this->_message_template_group->message_type_obj()->label['singular']
861
+		);
862
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
863
+			'Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
864
+			'event_espresso'
865
+		);
866
+		EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
867
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
868
+			'event_espresso'
869
+		);
870
+
871
+		wp_register_script(
872
+			'ee_msgs_edit_js',
873
+			EE_MSG_ASSETS_URL . 'ee_message_editor.js',
874
+			array('jquery'),
875
+			EVENT_ESPRESSO_VERSION
876
+		);
877
+
878
+		wp_enqueue_script('ee_admin_js');
879
+		wp_enqueue_script('ee_msgs_edit_js');
880
+
881
+		// add in special css for tiny_mce
882
+		add_filter('mce_css', array($this, 'wp_editor_css'));
883
+	}
884
+
885
+
886
+	public function load_scripts_styles_display_preview_message()
887
+	{
888
+
889
+		$this->_set_message_template_group();
890
+
891
+		if (isset($this->_req_data['messenger'])) {
892
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
893
+				$this->_req_data['messenger']
894
+			);
895
+		}
896
+
897
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
898
+
899
+
900
+		wp_enqueue_style(
901
+			'espresso_preview_css',
902
+			$this->_active_messenger->get_variation(
903
+				$this->_template_pack,
904
+				$message_type_name,
905
+				true,
906
+				'preview',
907
+				$this->_variation
908
+			)
909
+		);
910
+	}
911
+
912
+
913
+	public function load_scripts_styles_settings()
914
+	{
915
+		wp_register_style(
916
+			'ee-message-settings',
917
+			EE_MSG_ASSETS_URL . 'ee_message_settings.css',
918
+			array(),
919
+			EVENT_ESPRESSO_VERSION
920
+		);
921
+		wp_enqueue_style('ee-text-links');
922
+		wp_enqueue_style('ee-message-settings');
923
+		wp_enqueue_script('ee-messages-settings');
924
+	}
925
+
926
+
927
+	/**
928
+	 * set views array for List Table
929
+	 */
930
+	public function _set_list_table_views_global_mtps()
931
+	{
932
+		$this->_views = array(
933
+			'in_use' => array(
934
+				'slug'  => 'in_use',
935
+				'label' => esc_html__('In Use', 'event_espresso'),
936
+				'count' => 0,
937
+			),
938
+		);
939
+	}
940
+
941
+
942
+	/**
943
+	 * Set views array for the Custom Template List Table
944
+	 */
945
+	public function _set_list_table_views_custom_mtps()
946
+	{
947
+		$this->_set_list_table_views_global_mtps();
948
+		$this->_views['in_use']['bulk_action'] = array(
949
+			'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
950
+		);
951
+	}
952
+
953
+
954
+	/**
955
+	 * set views array for message queue list table
956
+	 *
957
+	 * @throws InvalidDataTypeException
958
+	 * @throws InvalidInterfaceException
959
+	 * @throws InvalidArgumentException
960
+	 * @throws EE_Error
961
+	 * @throws ReflectionException
962
+	 */
963
+	public function _set_list_table_views_default()
964
+	{
965
+		EE_Registry::instance()->load_helper('Template');
966
+
967
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
968
+			'ee_send_message',
969
+			'message_list_table_bulk_actions'
970
+		)
971
+			? array(
972
+				'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
973
+				'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
974
+				'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
975
+				'send_now'              => esc_html__('Send Now', 'event_espresso'),
976
+			)
977
+			: array();
978
+
979
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
980
+			'ee_delete_messages',
981
+			'message_list_table_bulk_actions'
982
+		)
983
+			? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
984
+			: array();
985
+
986
+
987
+		$this->_views = array(
988
+			'all' => array(
989
+				'slug'        => 'all',
990
+				'label'       => esc_html__('All', 'event_espresso'),
991
+				'count'       => 0,
992
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
993
+			),
994
+		);
995
+
996
+
997
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
998
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
999
+				continue;
1000
+			}
1001
+			$status_bulk_actions = $common_bulk_actions;
1002
+			// unset bulk actions not applying to status
1003
+			if (! empty($status_bulk_actions)) {
1004
+				switch ($status) {
1005
+					case EEM_Message::status_idle:
1006
+					case EEM_Message::status_resend:
1007
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1008
+						break;
1009
+
1010
+					case EEM_Message::status_failed:
1011
+					case EEM_Message::status_debug_only:
1012
+					case EEM_Message::status_messenger_executing:
1013
+						$status_bulk_actions = array();
1014
+						break;
1015
+
1016
+					case EEM_Message::status_incomplete:
1017
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1018
+						break;
1019
+
1020
+					case EEM_Message::status_retry:
1021
+					case EEM_Message::status_sent:
1022
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1023
+						break;
1024
+				}
1025
+			}
1026
+
1027
+			// skip adding messenger executing status to views because it will be included with the Failed view.
1028
+			if ($status === EEM_Message::status_messenger_executing) {
1029
+				continue;
1030
+			}
1031
+
1032
+			$this->_views[ strtolower($status) ] = array(
1033
+				'slug'        => strtolower($status),
1034
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1035
+				'count'       => 0,
1036
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1037
+			);
1038
+		}
1039
+	}
1040
+
1041
+
1042
+	protected function _ee_default_messages_overview_list_table()
1043
+	{
1044
+		$this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1045
+		$this->display_admin_list_table_page_with_no_sidebar();
1046
+	}
1047
+
1048
+
1049
+	protected function _message_queue_list_table()
1050
+	{
1051
+		$this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1052
+		$this->_template_args['per_column'] = 6;
1053
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1054
+		$this->_template_args['before_list_table'] = '<h3>'
1055
+													 . EEM_Message::instance()->get_pretty_label_for_results()
1056
+													 . '</h3>';
1057
+		$this->display_admin_list_table_page_with_no_sidebar();
1058
+	}
1059
+
1060
+
1061
+	protected function _message_legend_items()
1062
+	{
1063
+
1064
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
1065
+		$action_items = array();
1066
+
1067
+		foreach ($action_css_classes as $action_item => $action_details) {
1068
+			if ($action_item === 'see_notifications_for') {
1069
+				continue;
1070
+			}
1071
+			$action_items[ $action_item ] = array(
1072
+				'class' => $action_details['css_class'],
1073
+				'desc'  => $action_details['label'],
1074
+			);
1075
+		}
1076
+
1077
+		/** @type array $status_items status legend setup */
1078
+		$status_items = array(
1079
+			'sent_status'                => array(
1080
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1081
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1082
+			),
1083
+			'idle_status'                => array(
1084
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1085
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1086
+			),
1087
+			'failed_status'              => array(
1088
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1089
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1090
+			),
1091
+			'messenger_executing_status' => array(
1092
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1093
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1094
+			),
1095
+			'resend_status'              => array(
1096
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1097
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1098
+			),
1099
+			'incomplete_status'          => array(
1100
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1101
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1102
+			),
1103
+			'retry_status'               => array(
1104
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1105
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1106
+			),
1107
+		);
1108
+		if (EEM_Message::debug()) {
1109
+			$status_items['debug_only_status'] = array(
1110
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1111
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1112
+			);
1113
+		}
1114
+
1115
+		return array_merge($action_items, $status_items);
1116
+	}
1117
+
1118
+
1119
+	protected function _custom_mtps_preview()
1120
+	{
1121
+		$this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1122
+		$this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1123
+											   . ' alt="' . esc_attr__(
1124
+												   'Preview Custom Message Templates screenshot',
1125
+												   'event_espresso'
1126
+											   ) . '" />';
1127
+		$this->_template_args['preview_text'] = '<strong>'
1128
+												. esc_html__(
1129
+													'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1130
+													'event_espresso'
1131
+												)
1132
+												. '</strong>';
1133
+
1134
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1135
+	}
1136
+
1137
+
1138
+	/**
1139
+	 * get_message_templates
1140
+	 * This gets all the message templates for listing on the overview list.
1141
+	 *
1142
+	 * @access public
1143
+	 * @param int    $perpage the amount of templates groups to show per page
1144
+	 * @param string $type    the current _view we're getting templates for
1145
+	 * @param bool   $count   return count?
1146
+	 * @param bool   $all     disregard any paging info (get all data);
1147
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1148
+	 * @return array
1149
+	 * @throws EE_Error
1150
+	 * @throws InvalidArgumentException
1151
+	 * @throws InvalidDataTypeException
1152
+	 * @throws InvalidInterfaceException
1153
+	 */
1154
+	public function get_message_templates(
1155
+		$perpage = 10,
1156
+		$type = 'in_use',
1157
+		$count = false,
1158
+		$all = false,
1159
+		$global = true
1160
+	) {
1161
+
1162
+		$MTP = EEM_Message_Template_Group::instance();
1163
+
1164
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1165
+		$orderby = $this->_req_data['orderby'];
1166
+
1167
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1168
+			? $this->_req_data['order']
1169
+			: 'ASC';
1170
+
1171
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1172
+			? $this->_req_data['paged']
1173
+			: 1;
1174
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1175
+			? $this->_req_data['perpage']
1176
+			: $perpage;
1177
+
1178
+		$offset = ($current_page - 1) * $per_page;
1179
+		$limit = $all ? null : array($offset, $per_page);
1180
+
1181
+
1182
+		// options will match what is in the _views array property
1183
+		switch ($type) {
1184
+			case 'in_use':
1185
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1186
+				break;
1187
+			default:
1188
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1189
+		}
1190
+
1191
+		return $templates;
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * filters etc might need a list of installed message_types
1197
+	 *
1198
+	 * @return array an array of message type objects
1199
+	 */
1200
+	public function get_installed_message_types()
1201
+	{
1202
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1203
+		$installed = array();
1204
+
1205
+		foreach ($installed_message_types as $message_type) {
1206
+			$installed[ $message_type->name ] = $message_type;
1207
+		}
1208
+
1209
+		return $installed;
1210
+	}
1211
+
1212
+
1213
+	/**
1214
+	 * _add_message_template
1215
+	 *
1216
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1217
+	 *
1218
+	 * @param string $message_type
1219
+	 * @param string $messenger
1220
+	 * @param string $GRP_ID
1221
+	 *
1222
+	 * @throws EE_error
1223
+	 */
1224
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1225
+	{
1226
+		// set values override any request data
1227
+		$message_type = ! empty($message_type) ? $message_type : '';
1228
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1229
+			? $this->_req_data['message_type']
1230
+			: $message_type;
1231
+
1232
+		$messenger = ! empty($messenger) ? $messenger : '';
1233
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1234
+			? $this->_req_data['messenger']
1235
+			: $messenger;
1236
+
1237
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1238
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1239
+
1240
+		// we need messenger and message type.  They should be coming from the event editor. If not here then return error
1241
+		if (empty($message_type) || empty($messenger)) {
1242
+			throw new EE_Error(
1243
+				esc_html__(
1244
+					'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1245
+					'event_espresso'
1246
+				)
1247
+			);
1248
+		}
1249
+
1250
+		// we need the GRP_ID for the template being used as the base for the new template
1251
+		if (empty($GRP_ID)) {
1252
+			throw new EE_Error(
1253
+				esc_html__(
1254
+					'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1255
+					'event_espresso'
1256
+				)
1257
+			);
1258
+		}
1259
+
1260
+		// let's just make sure the template gets generated!
1261
+
1262
+		// we need to reassign some variables for what the insert is expecting
1263
+		$this->_req_data['MTP_messenger'] = $messenger;
1264
+		$this->_req_data['MTP_message_type'] = $message_type;
1265
+		$this->_req_data['GRP_ID'] = $GRP_ID;
1266
+		$this->_insert_or_update_message_template(true);
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * public wrapper for the _add_message_template method
1272
+	 *
1273
+	 * @param string $message_type     message type slug
1274
+	 * @param string $messenger        messenger slug
1275
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1276
+	 *                                 off of.
1277
+	 * @throws EE_error
1278
+	 */
1279
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1280
+	{
1281
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1282
+	}
1283
+
1284
+
1285
+	/**
1286
+	 * _edit_message_template
1287
+	 *
1288
+	 * @access protected
1289
+	 * @return void
1290
+	 * @throws InvalidIdentifierException
1291
+	 * @throws DomainException
1292
+	 * @throws EE_Error
1293
+	 * @throws InvalidArgumentException
1294
+	 * @throws ReflectionException
1295
+	 * @throws InvalidDataTypeException
1296
+	 * @throws InvalidInterfaceException
1297
+	 */
1298
+	protected function _edit_message_template()
1299
+	{
1300
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1301
+		$template_fields = '';
1302
+		$sidebar_fields = '';
1303
+		// we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1304
+		// valid html in the templates.
1305
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1306
+
1307
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1308
+			? absint($this->_req_data['id'])
1309
+			: false;
1310
+
1311
+		$this->_set_shortcodes(); // this also sets the _message_template property.
1312
+		$message_template_group = $this->_message_template_group;
1313
+		$c_label = $message_template_group->context_label();
1314
+		$c_config = $message_template_group->contexts_config();
1315
+
1316
+		reset($c_config);
1317
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1318
+			? strtolower($this->_req_data['context'])
1319
+			: key($c_config);
1320
+
1321
+
1322
+		if (empty($GRP_ID)) {
1323
+			$action = 'insert_message_template';
1324
+			$edit_message_template_form_url = add_query_arg(
1325
+				array('action' => $action, 'noheader' => true),
1326
+				EE_MSG_ADMIN_URL
1327
+			);
1328
+		} else {
1329
+			$action = 'update_message_template';
1330
+			$edit_message_template_form_url = add_query_arg(
1331
+				array('action' => $action, 'noheader' => true),
1332
+				EE_MSG_ADMIN_URL
1333
+			);
1334
+		}
1335
+
1336
+		// set active messenger for this view
1337
+		$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1338
+			$message_template_group->messenger()
1339
+		);
1340
+		$this->_active_message_type_name = $message_template_group->message_type();
1341
+
1342
+
1343
+		// Do we have any validation errors?
1344
+		$validators = $this->_get_transient();
1345
+		$v_fields = ! empty($validators) ? array_keys($validators) : array();
1346
+
1347
+
1348
+		// we need to assemble the title from Various details
1349
+		$context_label = sprintf(
1350
+			esc_html__('(%s %s)', 'event_espresso'),
1351
+			$c_config[ $context ]['label'],
1352
+			ucwords($c_label['label'])
1353
+		);
1354
+
1355
+		$title = sprintf(
1356
+			esc_html__(' %s %s Template %s', 'event_espresso'),
1357
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1358
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1359
+			$context_label
1360
+		);
1361
+
1362
+		$this->_template_args['GRP_ID'] = $GRP_ID;
1363
+		$this->_template_args['message_template'] = $message_template_group;
1364
+		$this->_template_args['is_extra_fields'] = false;
1365
+
1366
+
1367
+		// let's get EEH_MSG_Template so we can get template form fields
1368
+		$template_field_structure = EEH_MSG_Template::get_fields(
1369
+			$message_template_group->messenger(),
1370
+			$message_template_group->message_type()
1371
+		);
1372
+
1373
+		if (! $template_field_structure) {
1374
+			$template_field_structure = false;
1375
+			$template_fields = esc_html__(
1376
+				'There was an error in assembling the fields for this display (you should see an error message)',
1377
+				'event_espresso'
1378
+			);
1379
+		}
1380
+
1381
+
1382
+		$message_templates = $message_template_group->context_templates();
1383
+
1384
+
1385
+		// if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1386
+		// will get handled in the "extra" array.
1387
+		if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1388
+			foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1389
+				unset($template_field_structure[ $context ][ $reference_field ]);
1390
+			}
1391
+		}
1392
+
1393
+		// let's loop through the template_field_structure and actually assemble the input fields!
1394
+		if (! empty($template_field_structure)) {
1395
+			foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1396
+				// if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1397
+				// the extra array and reset them.
1398
+				if ($template_field === 'extra') {
1399
+					$this->_template_args['is_extra_fields'] = true;
1400
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1401
+						$message_template = $message_templates[ $context ][ $reference_field ];
1402
+						$content = $message_template instanceof EE_Message_Template
1403
+							? $message_template->get('MTP_content')
1404
+							: '';
1405
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1406
+							// let's verify if we need this extra field via the shortcodes parameter.
1407
+							$continue = false;
1408
+							if (isset($extra_array['shortcodes_required'])) {
1409
+								foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1410
+									if (! array_key_exists($shortcode, $this->_shortcodes)) {
1411
+										$continue = true;
1412
+									}
1413
+								}
1414
+								if ($continue) {
1415
+									continue;
1416
+								}
1417
+							}
1418
+
1419
+							$field_id = $reference_field
1420
+										. '-'
1421
+										. $extra_field
1422
+										. '-content';
1423
+							$template_form_fields[ $field_id ] = $extra_array;
1424
+							$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1425
+																		 . $reference_field
1426
+																		 . '][content]['
1427
+																		 . $extra_field . ']';
1428
+							$css_class = isset($extra_array['css_class'])
1429
+								? $extra_array['css_class']
1430
+								: '';
1431
+
1432
+							$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1433
+																			  && in_array($extra_field, $v_fields, true)
1434
+																			  &&
1435
+																			  (
1436
+																				  is_array($validators[ $extra_field ])
1437
+																				  && isset($validators[ $extra_field ]['msg'])
1438
+																			  )
1439
+								? 'validate-error ' . $css_class
1440
+								: $css_class;
1441
+
1442
+							$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1443
+																		  && isset($content[ $extra_field ])
1444
+								? $content[ $extra_field ]
1445
+								: '';
1446
+
1447
+							// do we have a validation error?  if we do then let's use that value instead
1448
+							$template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1449
+								? $validators[ $extra_field ]['value']
1450
+								: $template_form_fields[ $field_id ]['value'];
1451
+
1452
+
1453
+							$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1454
+
1455
+							// shortcode selector
1456
+							$field_name_to_use = $extra_field === 'main'
1457
+								? 'content'
1458
+								: $extra_field;
1459
+							$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1460
+								$field_name_to_use,
1461
+								$field_id
1462
+							);
1463
+
1464
+							if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1465
+								// we want to decode the entities
1466
+								$template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1467
+							}/**/
1468
+						}
1469
+						$templatefield_MTP_id = $reference_field . '-MTP_ID';
1470
+						$templatefield_templatename_id = $reference_field . '-name';
1471
+
1472
+						$template_form_fields[ $templatefield_MTP_id ] = array(
1473
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1474
+							'label'      => null,
1475
+							'input'      => 'hidden',
1476
+							'type'       => 'int',
1477
+							'required'   => false,
1478
+							'validation' => false,
1479
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1480
+							'css_class'  => '',
1481
+							'format'     => '%d',
1482
+							'db-col'     => 'MTP_ID',
1483
+						);
1484
+
1485
+						$template_form_fields[ $templatefield_templatename_id ] = array(
1486
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1487
+							'label'      => null,
1488
+							'input'      => 'hidden',
1489
+							'type'       => 'string',
1490
+							'required'   => false,
1491
+							'validation' => true,
1492
+							'value'      => $reference_field,
1493
+							'css_class'  => '',
1494
+							'format'     => '%s',
1495
+							'db-col'     => 'MTP_template_field',
1496
+						);
1497
+					}
1498
+					continue; // skip the next stuff, we got the necessary fields here for this dataset.
1499
+				} else {
1500
+					$field_id = $template_field . '-content';
1501
+					$template_form_fields[ $field_id ] = $field_setup_array;
1502
+					$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1503
+					$message_template = isset($message_templates[ $context ][ $template_field ])
1504
+						? $message_templates[ $context ][ $template_field ]
1505
+						: null;
1506
+					$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1507
+																  && is_array($message_templates[ $context ])
1508
+																  && $message_template instanceof EE_Message_Template
1509
+						? $message_template->get('MTP_content')
1510
+						: '';
1511
+
1512
+					// do we have a validator error for this field?  if we do then we'll use that value instead
1513
+					$template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1514
+						? $validators[ $template_field ]['value']
1515
+						: $template_form_fields[ $field_id ]['value'];
1516
+
1517
+
1518
+					$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1519
+					$css_class = isset($field_setup_array['css_class'])
1520
+						? $field_setup_array['css_class']
1521
+						: '';
1522
+					$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1523
+																	  && in_array($template_field, $v_fields, true)
1524
+																	  && isset($validators[ $template_field ]['msg'])
1525
+						? 'validate-error ' . $css_class
1526
+						: $css_class;
1527
+
1528
+					// shortcode selector
1529
+					$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1530
+						$template_field,
1531
+						$field_id
1532
+					);
1533
+				}
1534
+
1535
+				// k took care of content field(s) now let's take care of others.
1536
+
1537
+				$templatefield_MTP_id = $template_field . '-MTP_ID';
1538
+				$templatefield_field_templatename_id = $template_field . '-name';
1539
+
1540
+				// foreach template field there are actually two form fields created
1541
+				$template_form_fields[ $templatefield_MTP_id ] = array(
1542
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1543
+					'label'      => null,
1544
+					'input'      => 'hidden',
1545
+					'type'       => 'int',
1546
+					'required'   => false,
1547
+					'validation' => true,
1548
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1549
+					'css_class'  => '',
1550
+					'format'     => '%d',
1551
+					'db-col'     => 'MTP_ID',
1552
+				);
1553
+
1554
+				$template_form_fields[ $templatefield_field_templatename_id ] = array(
1555
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1556
+					'label'      => null,
1557
+					'input'      => 'hidden',
1558
+					'type'       => 'string',
1559
+					'required'   => false,
1560
+					'validation' => true,
1561
+					'value'      => $template_field,
1562
+					'css_class'  => '',
1563
+					'format'     => '%s',
1564
+					'db-col'     => 'MTP_template_field',
1565
+				);
1566
+			}
1567
+
1568
+			// add other fields
1569
+			$template_form_fields['ee-msg-current-context'] = array(
1570
+				'name'       => 'MTP_context',
1571
+				'label'      => null,
1572
+				'input'      => 'hidden',
1573
+				'type'       => 'string',
1574
+				'required'   => false,
1575
+				'validation' => true,
1576
+				'value'      => $context,
1577
+				'css_class'  => '',
1578
+				'format'     => '%s',
1579
+				'db-col'     => 'MTP_context',
1580
+			);
1581
+
1582
+			$template_form_fields['ee-msg-grp-id'] = array(
1583
+				'name'       => 'GRP_ID',
1584
+				'label'      => null,
1585
+				'input'      => 'hidden',
1586
+				'type'       => 'int',
1587
+				'required'   => false,
1588
+				'validation' => true,
1589
+				'value'      => $GRP_ID,
1590
+				'css_class'  => '',
1591
+				'format'     => '%d',
1592
+				'db-col'     => 'GRP_ID',
1593
+			);
1594
+
1595
+			$template_form_fields['ee-msg-messenger'] = array(
1596
+				'name'       => 'MTP_messenger',
1597
+				'label'      => null,
1598
+				'input'      => 'hidden',
1599
+				'type'       => 'string',
1600
+				'required'   => false,
1601
+				'validation' => true,
1602
+				'value'      => $message_template_group->messenger(),
1603
+				'css_class'  => '',
1604
+				'format'     => '%s',
1605
+				'db-col'     => 'MTP_messenger',
1606
+			);
1607
+
1608
+			$template_form_fields['ee-msg-message-type'] = array(
1609
+				'name'       => 'MTP_message_type',
1610
+				'label'      => null,
1611
+				'input'      => 'hidden',
1612
+				'type'       => 'string',
1613
+				'required'   => false,
1614
+				'validation' => true,
1615
+				'value'      => $message_template_group->message_type(),
1616
+				'css_class'  => '',
1617
+				'format'     => '%s',
1618
+				'db-col'     => 'MTP_message_type',
1619
+			);
1620
+
1621
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1622
+				'name'       => 'MTP_is_global',
1623
+				'label'      => esc_html__('Global Template', 'event_espresso'),
1624
+				'input'      => 'hidden',
1625
+				'type'       => 'int',
1626
+				'required'   => false,
1627
+				'validation' => true,
1628
+				'value'      => $message_template_group->get('MTP_is_global'),
1629
+				'css_class'  => '',
1630
+				'format'     => '%d',
1631
+				'db-col'     => 'MTP_is_global',
1632
+			);
1633
+
1634
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1635
+				'name'       => 'MTP_is_override',
1636
+				'label'      => esc_html__('Override all custom', 'event_espresso'),
1637
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1638
+				'type'       => 'int',
1639
+				'required'   => false,
1640
+				'validation' => true,
1641
+				'value'      => $message_template_group->get('MTP_is_override'),
1642
+				'css_class'  => '',
1643
+				'format'     => '%d',
1644
+				'db-col'     => 'MTP_is_override',
1645
+			);
1646
+
1647
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1648
+				'name'       => 'MTP_is_active',
1649
+				'label'      => esc_html__('Active Template', 'event_espresso'),
1650
+				'input'      => 'hidden',
1651
+				'type'       => 'int',
1652
+				'required'   => false,
1653
+				'validation' => true,
1654
+				'value'      => $message_template_group->is_active(),
1655
+				'css_class'  => '',
1656
+				'format'     => '%d',
1657
+				'db-col'     => 'MTP_is_active',
1658
+			);
1659
+
1660
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1661
+				'name'       => 'MTP_deleted',
1662
+				'label'      => null,
1663
+				'input'      => 'hidden',
1664
+				'type'       => 'int',
1665
+				'required'   => false,
1666
+				'validation' => true,
1667
+				'value'      => $message_template_group->get('MTP_deleted'),
1668
+				'css_class'  => '',
1669
+				'format'     => '%d',
1670
+				'db-col'     => 'MTP_deleted',
1671
+			);
1672
+			$sidebar_form_fields['ee-msg-author'] = array(
1673
+				'name'       => 'MTP_user_id',
1674
+				'label'      => esc_html__('Author', 'event_espresso'),
1675
+				'input'      => 'hidden',
1676
+				'type'       => 'int',
1677
+				'required'   => false,
1678
+				'validation' => false,
1679
+				'value'      => $message_template_group->user(),
1680
+				'format'     => '%d',
1681
+				'db-col'     => 'MTP_user_id',
1682
+			);
1683
+
1684
+			$sidebar_form_fields['ee-msg-route'] = array(
1685
+				'name'  => 'action',
1686
+				'input' => 'hidden',
1687
+				'type'  => 'string',
1688
+				'value' => $action,
1689
+			);
1690
+
1691
+			$sidebar_form_fields['ee-msg-id'] = array(
1692
+				'name'  => 'id',
1693
+				'input' => 'hidden',
1694
+				'type'  => 'int',
1695
+				'value' => $GRP_ID,
1696
+			);
1697
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1698
+				'name'  => $action . '_nonce',
1699
+				'input' => 'hidden',
1700
+				'type'  => 'string',
1701
+				'value' => wp_create_nonce($action . '_nonce'),
1702
+			);
1703
+
1704
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1705
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1706
+					'name'  => 'template_switch',
1707
+					'input' => 'hidden',
1708
+					'type'  => 'int',
1709
+					'value' => 1,
1710
+				);
1711
+			}
1712
+
1713
+
1714
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1715
+			$sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1716
+		} //end if ( !empty($template_field_structure) )
1717
+
1718
+		// set extra content for publish box
1719
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1720
+		$this->_set_publish_post_box_vars(
1721
+			'id',
1722
+			$GRP_ID,
1723
+			false,
1724
+			add_query_arg(
1725
+				array('action' => 'global_mtps'),
1726
+				$this->_admin_base_url
1727
+			)
1728
+		);
1729
+
1730
+		// add preview button
1731
+		$preview_url = parent::add_query_args_and_nonce(
1732
+			array(
1733
+				'message_type' => $message_template_group->message_type(),
1734
+				'messenger'    => $message_template_group->messenger(),
1735
+				'context'      => $context,
1736
+				'GRP_ID'       => $GRP_ID,
1737
+				'action'       => 'preview_message',
1738
+			),
1739
+			$this->_admin_base_url
1740
+		);
1741
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1742
+						  . esc_html__('Preview', 'event_espresso')
1743
+						  . '</a>';
1744
+
1745
+
1746
+		// setup context switcher
1747
+		$context_switcher_args = array(
1748
+			'page'    => 'espresso_messages',
1749
+			'action'  => 'edit_message_template',
1750
+			'id'      => $GRP_ID,
1751
+			'context' => $context,
1752
+			'extra'   => $preview_button,
1753
+		);
1754
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1755
+
1756
+
1757
+		// main box
1758
+		$this->_template_args['template_fields'] = $template_fields;
1759
+		$this->_template_args['sidebar_box_id'] = 'details';
1760
+		$this->_template_args['action'] = $action;
1761
+		$this->_template_args['context'] = $context;
1762
+		$this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1763
+		$this->_template_args['learn_more_about_message_templates_link'] =
1764
+			$this->_learn_more_about_message_templates_link();
1765
+
1766
+
1767
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1768
+		$this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1769
+			$message_template_group,
1770
+			$context,
1771
+			$context_label
1772
+		);
1773
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1774
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1775
+
1776
+		$this->_template_path = $this->_template_args['GRP_ID']
1777
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1778
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1779
+
1780
+		// send along EE_Message_Template_Group object for further template use.
1781
+		$this->_template_args['MTP'] = $message_template_group;
1782
+
1783
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1784
+			$this->_template_path,
1785
+			$this->_template_args,
1786
+			true
1787
+		);
1788
+
1789
+
1790
+		// finally, let's set the admin_page title
1791
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1792
+
1793
+
1794
+		// we need to take care of setting the shortcodes property for use elsewhere.
1795
+		$this->_set_shortcodes();
1796
+
1797
+
1798
+		// final template wrapper
1799
+		$this->display_admin_page_with_sidebar();
1800
+	}
1801
+
1802
+
1803
+	public function filter_tinymce_init($mceInit, $editor_id)
1804
+	{
1805
+		return $mceInit;
1806
+	}
1807
+
1808
+
1809
+	public function add_context_switcher()
1810
+	{
1811
+		return $this->_context_switcher;
1812
+	}
1813
+
1814
+
1815
+	/**
1816
+	 * Adds the activation/deactivation toggle for the message template context.
1817
+	 *
1818
+	 * @param EE_Message_Template_Group $message_template_group
1819
+	 * @param string                    $context
1820
+	 * @param string                    $context_label
1821
+	 * @return string
1822
+	 * @throws DomainException
1823
+	 * @throws EE_Error
1824
+	 * @throws InvalidIdentifierException
1825
+	 */
1826
+	protected function add_active_context_element(
1827
+		EE_Message_Template_Group $message_template_group,
1828
+		$context,
1829
+		$context_label
1830
+	) {
1831
+		$template_args = array(
1832
+			'context'                   => $context,
1833
+			'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1834
+			'is_active'                 => $message_template_group->is_context_active($context),
1835
+			'on_off_action'             => $message_template_group->is_context_active($context)
1836
+				? 'context-off'
1837
+				: 'context-on',
1838
+			'context_label'             => str_replace(array('(', ')'), '', $context_label),
1839
+			'message_template_group_id' => $message_template_group->ID(),
1840
+		);
1841
+		return EEH_Template::display_template(
1842
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1843
+			$template_args,
1844
+			true
1845
+		);
1846
+	}
1847
+
1848
+
1849
+	/**
1850
+	 * Ajax callback for `toggle_context_template` ajax action.
1851
+	 * Handles toggling the message context on or off.
1852
+	 *
1853
+	 * @throws EE_Error
1854
+	 * @throws InvalidArgumentException
1855
+	 * @throws InvalidDataTypeException
1856
+	 * @throws InvalidIdentifierException
1857
+	 * @throws InvalidInterfaceException
1858
+	 */
1859
+	public function toggle_context_template()
1860
+	{
1861
+		$success = true;
1862
+		// check for required data
1863
+		if (! isset(
1864
+			$this->_req_data['message_template_group_id'],
1865
+			$this->_req_data['context'],
1866
+			$this->_req_data['status']
1867
+		)) {
1868
+			EE_Error::add_error(
1869
+				esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1870
+				__FILE__,
1871
+				__FUNCTION__,
1872
+				__LINE__
1873
+			);
1874
+			$success = false;
1875
+		}
1876
+
1877
+		$nonce = isset($this->_req_data['toggle_context_nonce'])
1878
+			? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1879
+			: '';
1880
+		$nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1881
+		$this->_verify_nonce($nonce, $nonce_ref);
1882
+		$status = $this->_req_data['status'];
1883
+		if ($status !== 'off' && $status !== 'on') {
1884
+			EE_Error::add_error(
1885
+				sprintf(
1886
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1887
+					$this->_req_data['status']
1888
+				),
1889
+				__FILE__,
1890
+				__FUNCTION__,
1891
+				__LINE__
1892
+			);
1893
+			$success = false;
1894
+		}
1895
+		$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1896
+			$this->_req_data['message_template_group_id']
1897
+		);
1898
+		if (! $message_template_group instanceof EE_Message_Template_Group) {
1899
+			EE_Error::add_error(
1900
+				sprintf(
1901
+					esc_html__(
1902
+						'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1903
+						'event_espresso'
1904
+					),
1905
+					$this->_req_data['message_template_group_id'],
1906
+					'EE_Message_Template_Group'
1907
+				),
1908
+				__FILE__,
1909
+				__FUNCTION__,
1910
+				__LINE__
1911
+			);
1912
+			$success = false;
1913
+		}
1914
+		if ($success) {
1915
+			$success = $status === 'off'
1916
+				? $message_template_group->deactivate_context($this->_req_data['context'])
1917
+				: $message_template_group->activate_context($this->_req_data['context']);
1918
+		}
1919
+		$this->_template_args['success'] = $success;
1920
+		$this->_return_json();
1921
+	}
1922
+
1923
+
1924
+	public function _add_form_element_before()
1925
+	{
1926
+		return '<form method="post" action="'
1927
+			   . $this->_template_args["edit_message_template_form_url"]
1928
+			   . '" id="ee-msg-edit-frm">';
1929
+	}
1930
+
1931
+	public function _add_form_element_after()
1932
+	{
1933
+		return '</form>';
1934
+	}
1935
+
1936
+
1937
+	/**
1938
+	 * This executes switching the template pack for a message template.
1939
+	 *
1940
+	 * @since 4.5.0
1941
+	 * @throws EE_Error
1942
+	 * @throws InvalidDataTypeException
1943
+	 * @throws InvalidInterfaceException
1944
+	 * @throws InvalidArgumentException
1945
+	 * @throws ReflectionException
1946
+	 */
1947
+	public function switch_template_pack()
1948
+	{
1949
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1950
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1951
+
1952
+		// verify we have needed values.
1953
+		if (empty($GRP_ID) || empty($template_pack)) {
1954
+			$this->_template_args['error'] = true;
1955
+			EE_Error::add_error(
1956
+				esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1957
+				__FILE__,
1958
+				__FUNCTION__,
1959
+				__LINE__
1960
+			);
1961
+		} else {
1962
+			// get template, set the new template_pack and then reset to default
1963
+			/** @type EE_Message_Template_Group $message_template_group */
1964
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1965
+
1966
+			$message_template_group->set_template_pack_name($template_pack);
1967
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1968
+			$this->_req_data['mt'] = $message_template_group->message_type();
1969
+
1970
+			$query_args = $this->_reset_to_default_template();
1971
+
1972
+			if (empty($query_args['id'])) {
1973
+				EE_Error::add_error(
1974
+					esc_html__(
1975
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1976
+						'event_espresso'
1977
+					),
1978
+					__FILE__,
1979
+					__FUNCTION__,
1980
+					__LINE__
1981
+				);
1982
+				$this->_template_args['error'] = true;
1983
+			} else {
1984
+				$template_label = $message_template_group->get_template_pack()->label;
1985
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1986
+				EE_Error::add_success(
1987
+					sprintf(
1988
+						esc_html__(
1989
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1990
+							'event_espresso'
1991
+						),
1992
+						$template_label,
1993
+						$template_pack_labels->template_pack
1994
+					)
1995
+				);
1996
+				// generate the redirect url for js.
1997
+				$url = self::add_query_args_and_nonce(
1998
+					$query_args,
1999
+					$this->_admin_base_url
2000
+				);
2001
+				$this->_template_args['data']['redirect_url'] = $url;
2002
+				$this->_template_args['success'] = true;
2003
+			}
2004
+
2005
+			$this->_return_json();
2006
+		}
2007
+	}
2008
+
2009
+
2010
+	/**
2011
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2012
+	 * they want.
2013
+	 *
2014
+	 * @access protected
2015
+	 * @return array|null
2016
+	 * @throws EE_Error
2017
+	 * @throws InvalidArgumentException
2018
+	 * @throws InvalidDataTypeException
2019
+	 * @throws InvalidInterfaceException
2020
+	 */
2021
+	protected function _reset_to_default_template()
2022
+	{
2023
+
2024
+		$templates = array();
2025
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2026
+		// we need to make sure we've got the info we need.
2027
+		if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2028
+			EE_Error::add_error(
2029
+				esc_html__(
2030
+					'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.',
2031
+					'event_espresso'
2032
+				),
2033
+				__FILE__,
2034
+				__FUNCTION__,
2035
+				__LINE__
2036
+			);
2037
+		}
2038
+
2039
+		// all templates will be reset to whatever the defaults are
2040
+		// for the global template matching the messenger and message type.
2041
+		$success = ! empty($GRP_ID) ? true : false;
2042
+
2043
+		if ($success) {
2044
+			// let's first determine if the incoming template is a global template,
2045
+			// if it isn't then we need to get the global template matching messenger and message type.
2046
+			// $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2047
+
2048
+
2049
+			// note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2050
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
2051
+
2052
+			if ($success) {
2053
+				// if successfully deleted, lets generate the new ones.
2054
+				// Note. We set GLOBAL to true, because resets on ANY template
2055
+				// will use the related global template defaults for regeneration.
2056
+				// This means that if a custom template is reset it resets to whatever the related global template is.
2057
+				// HOWEVER, we DO keep the template pack and template variation set
2058
+				// for the current custom template when resetting.
2059
+				$templates = $this->_generate_new_templates(
2060
+					$this->_req_data['msgr'],
2061
+					$this->_req_data['mt'],
2062
+					$GRP_ID,
2063
+					true
2064
+				);
2065
+			}
2066
+		}
2067
+
2068
+		// any error messages?
2069
+		if (! $success) {
2070
+			EE_Error::add_error(
2071
+				esc_html__(
2072
+					'Something went wrong with deleting existing templates. Unable to reset to default',
2073
+					'event_espresso'
2074
+				),
2075
+				__FILE__,
2076
+				__FUNCTION__,
2077
+				__LINE__
2078
+			);
2079
+		}
2080
+
2081
+		// all good, let's add a success message!
2082
+		if ($success && ! empty($templates)) {
2083
+			// the info for the template we generated is the first element in the returned array
2084
+			// $templates = $templates[0];
2085
+			EE_Error::overwrite_success();
2086
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2087
+		}
2088
+
2089
+
2090
+		$query_args = array(
2091
+			'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2092
+			'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2093
+			'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2094
+		);
2095
+
2096
+		// if called via ajax then we return query args otherwise redirect
2097
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2098
+			return $query_args;
2099
+		} else {
2100
+			$this->_redirect_after_action(false, '', '', $query_args, true);
2101
+
2102
+			return null;
2103
+		}
2104
+	}
2105
+
2106
+
2107
+	/**
2108
+	 * Retrieve and set the message preview for display.
2109
+	 *
2110
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2111
+	 * @return string
2112
+	 * @throws ReflectionException
2113
+	 * @throws EE_Error
2114
+	 * @throws InvalidArgumentException
2115
+	 * @throws InvalidDataTypeException
2116
+	 * @throws InvalidInterfaceException
2117
+	 */
2118
+	public function _preview_message($send = false)
2119
+	{
2120
+		// first make sure we've got the necessary parameters
2121
+		if (! isset(
2122
+			$this->_req_data['message_type'],
2123
+			$this->_req_data['messenger'],
2124
+			$this->_req_data['messenger'],
2125
+			$this->_req_data['GRP_ID']
2126
+		)) {
2127
+			EE_Error::add_error(
2128
+				esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2129
+				__FILE__,
2130
+				__FUNCTION__,
2131
+				__LINE__
2132
+			);
2133
+		}
2134
+
2135
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2136
+
2137
+
2138
+		// get the preview!
2139
+		$preview = EED_Messages::preview_message(
2140
+			$this->_req_data['message_type'],
2141
+			$this->_req_data['context'],
2142
+			$this->_req_data['messenger'],
2143
+			$send
2144
+		);
2145
+
2146
+		if ($send) {
2147
+			return $preview;
2148
+		}
2149
+
2150
+		// let's add a button to go back to the edit view
2151
+		$query_args = array(
2152
+			'id'      => $this->_req_data['GRP_ID'],
2153
+			'context' => $this->_req_data['context'],
2154
+			'action'  => 'edit_message_template',
2155
+		);
2156
+		$go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2157
+		$preview_button = '<a href="'
2158
+						  . $go_back_url
2159
+						  . '" class="button-secondary messages-preview-go-back-button">'
2160
+						  . esc_html__('Go Back to Edit', 'event_espresso')
2161
+						  . '</a>';
2162
+		$message_types = $this->get_installed_message_types();
2163
+		$active_messenger = $this->_message_resource_manager->get_active_messenger(
2164
+			$this->_req_data['messenger']
2165
+		);
2166
+		$active_messenger_label = $active_messenger instanceof EE_messenger
2167
+			? ucwords($active_messenger->label['singular'])
2168
+			: esc_html__('Unknown Messenger', 'event_espresso');
2169
+		// let's provide a helpful title for context
2170
+		$preview_title = sprintf(
2171
+			esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2172
+			$active_messenger_label,
2173
+			ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2174
+		);
2175
+		if (empty($preview)) {
2176
+			$this->noEventsErrorMessage();
2177
+		}
2178
+		// setup display of preview.
2179
+		$this->_admin_page_title = $preview_title;
2180
+		$this->_template_args['admin_page_title'] = $preview_title;
2181
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2182
+		$this->_template_args['data']['force_json'] = true;
2183
+
2184
+		return '';
2185
+	}
2186
+
2187
+
2188
+	/**
2189
+	 * Used to set an error if there are no events available for generating a preview/test send.
2190
+	 *
2191
+	 * @param bool $test_send  Whether the error should be generated for the context of a test send.
2192
+	 */
2193
+	protected function noEventsErrorMessage($test_send = false)
2194
+	{
2195
+		$events_url = parent::add_query_args_and_nonce(
2196
+			array(
2197
+				'action' => 'default',
2198
+				'page'   => 'espresso_events',
2199
+			),
2200
+			admin_url('admin.php')
2201
+		);
2202
+		$message = $test_send
2203
+			? __(
2204
+				'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!',
2205
+				'event_espresso'
2206
+			)
2207
+			: __(
2208
+				'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!',
2209
+				'event_espresso'
2210
+			);
2211
+
2212
+		EE_Error::add_attention(
2213
+			sprintf(
2214
+				$message,
2215
+				"<a href='{$events_url}'>",
2216
+				'</a>'
2217
+			)
2218
+		);
2219
+	}
2220
+
2221
+
2222
+	/**
2223
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2224
+	 * gets called automatically.
2225
+	 *
2226
+	 * @since 4.5.0
2227
+	 *
2228
+	 * @return string
2229
+	 */
2230
+	protected function _display_preview_message()
2231
+	{
2232
+		$this->display_admin_page_with_no_sidebar();
2233
+	}
2234
+
2235
+
2236
+	/**
2237
+	 * registers metaboxes that should show up on the "edit_message_template" page
2238
+	 *
2239
+	 * @access protected
2240
+	 * @return void
2241
+	 */
2242
+	protected function _register_edit_meta_boxes()
2243
+	{
2244
+		add_meta_box(
2245
+			'mtp_valid_shortcodes',
2246
+			esc_html__('Valid Shortcodes', 'event_espresso'),
2247
+			array($this, 'shortcode_meta_box'),
2248
+			$this->_current_screen->id,
2249
+			'side',
2250
+			'default'
2251
+		);
2252
+		add_meta_box(
2253
+			'mtp_extra_actions',
2254
+			esc_html__('Extra Actions', 'event_espresso'),
2255
+			array($this, 'extra_actions_meta_box'),
2256
+			$this->_current_screen->id,
2257
+			'side',
2258
+			'high'
2259
+		);
2260
+		add_meta_box(
2261
+			'mtp_templates',
2262
+			esc_html__('Template Styles', 'event_espresso'),
2263
+			array($this, 'template_pack_meta_box'),
2264
+			$this->_current_screen->id,
2265
+			'side',
2266
+			'high'
2267
+		);
2268
+	}
2269
+
2270
+
2271
+	/**
2272
+	 * metabox content for all template pack and variation selection.
2273
+	 *
2274
+	 * @since 4.5.0
2275
+	 * @return string
2276
+	 * @throws DomainException
2277
+	 * @throws EE_Error
2278
+	 * @throws InvalidArgumentException
2279
+	 * @throws ReflectionException
2280
+	 * @throws InvalidDataTypeException
2281
+	 * @throws InvalidInterfaceException
2282
+	 */
2283
+	public function template_pack_meta_box()
2284
+	{
2285
+		$this->_set_message_template_group();
2286
+
2287
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
2288
+
2289
+		$tp_select_values = array();
2290
+
2291
+		foreach ($tp_collection as $tp) {
2292
+			// only include template packs that support this messenger and message type!
2293
+			$supports = $tp->get_supports();
2294
+			if (! isset($supports[ $this->_message_template_group->messenger() ])
2295
+				|| ! in_array(
2296
+					$this->_message_template_group->message_type(),
2297
+					$supports[ $this->_message_template_group->messenger() ],
2298
+					true
2299
+				)
2300
+			) {
2301
+				// not supported
2302
+				continue;
2303
+			}
2304
+
2305
+			$tp_select_values[] = array(
2306
+				'text' => $tp->label,
2307
+				'id'   => $tp->dbref,
2308
+			);
2309
+		}
2310
+
2311
+		// if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2312
+		// the default template pack.  This still allows for the odd template pack to override.
2313
+		if (empty($tp_select_values)) {
2314
+			$tp_select_values[] = array(
2315
+				'text' => esc_html__('Default', 'event_espresso'),
2316
+				'id'   => 'default',
2317
+			);
2318
+		}
2319
+
2320
+		// setup variation select values for the currently selected template.
2321
+		$variations = $this->_message_template_group->get_template_pack()->get_variations(
2322
+			$this->_message_template_group->messenger(),
2323
+			$this->_message_template_group->message_type()
2324
+		);
2325
+		$variations_select_values = array();
2326
+		foreach ($variations as $variation => $label) {
2327
+			$variations_select_values[] = array(
2328
+				'text' => $label,
2329
+				'id'   => $variation,
2330
+			);
2331
+		}
2332
+
2333
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2334
+
2335
+		$template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2336
+			'MTP_template_pack',
2337
+			$tp_select_values,
2338
+			$this->_message_template_group->get_template_pack_name()
2339
+		);
2340
+		$template_args['variations_selector'] = EEH_Form_Fields::select_input(
2341
+			'MTP_template_variation',
2342
+			$variations_select_values,
2343
+			$this->_message_template_group->get_template_pack_variation()
2344
+		);
2345
+		$template_args['template_pack_label'] = $template_pack_labels->template_pack;
2346
+		$template_args['template_variation_label'] = $template_pack_labels->template_variation;
2347
+		$template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2348
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2349
+
2350
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2351
+
2352
+		EEH_Template::display_template($template, $template_args);
2353
+	}
2354
+
2355
+
2356
+	/**
2357
+	 * This meta box holds any extra actions related to Message Templates
2358
+	 * For now, this includes Resetting templates to defaults and sending a test email.
2359
+	 *
2360
+	 * @access  public
2361
+	 * @return void
2362
+	 * @throws EE_Error
2363
+	 */
2364
+	public function extra_actions_meta_box()
2365
+	{
2366
+		$template_form_fields = array();
2367
+
2368
+		$extra_args = array(
2369
+			'msgr'   => $this->_message_template_group->messenger(),
2370
+			'mt'     => $this->_message_template_group->message_type(),
2371
+			'GRP_ID' => $this->_message_template_group->GRP_ID(),
2372
+		);
2373
+		// first we need to see if there are any fields
2374
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2375
+
2376
+		if (! empty($fields)) {
2377
+			// yup there be fields
2378
+			foreach ($fields as $field => $config) {
2379
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2380
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2381
+				$default = isset($config['default']) ? $config['default'] : '';
2382
+				$default = isset($config['value']) ? $config['value'] : $default;
2383
+
2384
+				// if type is hidden and the value is empty
2385
+				// something may have gone wrong so let's correct with the defaults
2386
+				$fix = $config['input'] === 'hidden'
2387
+					   && isset($existing[ $field ])
2388
+					   && empty($existing[ $field ])
2389
+					? $default
2390
+					: '';
2391
+				$existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2392
+					? $existing[ $field ]
2393
+					: $fix;
2394
+
2395
+				$template_form_fields[ $field_id ] = array(
2396
+					'name'       => 'test_settings_fld[' . $field . ']',
2397
+					'label'      => $config['label'],
2398
+					'input'      => $config['input'],
2399
+					'type'       => $config['type'],
2400
+					'required'   => $config['required'],
2401
+					'validation' => $config['validation'],
2402
+					'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2403
+					'css_class'  => $config['css_class'],
2404
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2405
+					'default'    => $default,
2406
+					'format'     => $config['format'],
2407
+				);
2408
+			}
2409
+		}
2410
+
2411
+		$test_settings_fields = ! empty($template_form_fields)
2412
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2413
+			: '';
2414
+
2415
+		$test_settings_html = '';
2416
+		// print out $test_settings_fields
2417
+		if (! empty($test_settings_fields)) {
2418
+			echo $test_settings_fields;
2419
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2420
+			$test_settings_html .= 'name="test_button" value="';
2421
+			$test_settings_html .= esc_html__('Test Send', 'event_espresso');
2422
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2423
+		}
2424
+
2425
+		// and button
2426
+		$test_settings_html .= '<p>'
2427
+							   . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2428
+							   . '</p>';
2429
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2430
+		$test_settings_html .= $this->get_action_link_or_button(
2431
+			'reset_to_default',
2432
+			'reset',
2433
+			$extra_args,
2434
+			'button-primary reset-default-button'
2435
+		);
2436
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2437
+		echo $test_settings_html;
2438
+	}
2439
+
2440
+
2441
+	/**
2442
+	 * This returns the shortcode selector skeleton for a given context and field.
2443
+	 *
2444
+	 * @since 4.9.rc.000
2445
+	 * @param string $field           The name of the field retrieving shortcodes for.
2446
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2447
+	 * @return string
2448
+	 * @throws DomainException
2449
+	 * @throws EE_Error
2450
+	 * @throws InvalidArgumentException
2451
+	 * @throws ReflectionException
2452
+	 * @throws InvalidDataTypeException
2453
+	 * @throws InvalidInterfaceException
2454
+	 */
2455
+	protected function _get_shortcode_selector($field, $linked_input_id)
2456
+	{
2457
+		$template_args = array(
2458
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2459
+			'fieldname'       => $field,
2460
+			'linked_input_id' => $linked_input_id,
2461
+		);
2462
+
2463
+		return EEH_Template::display_template(
2464
+			EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2465
+			$template_args,
2466
+			true
2467
+		);
2468
+	}
2469
+
2470
+
2471
+	/**
2472
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2473
+	 * page)
2474
+	 *
2475
+	 * @access public
2476
+	 * @return void
2477
+	 * @throws EE_Error
2478
+	 * @throws InvalidArgumentException
2479
+	 * @throws ReflectionException
2480
+	 * @throws InvalidDataTypeException
2481
+	 * @throws InvalidInterfaceException
2482
+	 */
2483
+	public function shortcode_meta_box()
2484
+	{
2485
+		$shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2486
+		// $messenger = $this->_message_template_group->messenger_obj();
2487
+		// now let's set the content depending on the status of the shortcodes array
2488
+		if (empty($shortcodes)) {
2489
+			$content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2490
+			echo $content;
2491
+		} else {
2492
+			// $alt = 0;
2493
+			?>
2494 2494
             <div style="float:right; margin-top:10px"><?php
2495
-                            echo $this->_get_help_tab_link('message_template_shortcodes');
2496
-                            ?></div>
2495
+							echo $this->_get_help_tab_link('message_template_shortcodes');
2496
+							?></div>
2497 2497
             <p class="small-text"><?php
2498
-                                  printf(
2499
-                                      esc_html__(
2500
-                                          'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2501
-                                          'event_espresso'
2502
-                                      ),
2503
-                                      '<span class="dashicons dashicons-menu"></span>'
2504
-                                  );
2505
-                                ?>
2498
+								  printf(
2499
+									  esc_html__(
2500
+										  'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2501
+										  'event_espresso'
2502
+									  ),
2503
+									  '<span class="dashicons dashicons-menu"></span>'
2504
+								  );
2505
+								?>
2506 2506
             </p>
2507 2507
             <?php
2508
-        }
2509
-    }
2510
-
2511
-
2512
-    /**
2513
-     * used to set the $_shortcodes property for when its needed elsewhere.
2514
-     *
2515
-     * @access protected
2516
-     * @return void
2517
-     * @throws EE_Error
2518
-     * @throws InvalidArgumentException
2519
-     * @throws ReflectionException
2520
-     * @throws InvalidDataTypeException
2521
-     * @throws InvalidInterfaceException
2522
-     */
2523
-    protected function _set_shortcodes()
2524
-    {
2525
-
2526
-        // no need to run this if the property is already set
2527
-        if (! empty($this->_shortcodes)) {
2528
-            return;
2529
-        }
2530
-
2531
-        $this->_shortcodes = $this->_get_shortcodes();
2532
-    }
2533
-
2534
-
2535
-    /**
2536
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2537
-     * property)
2538
-     *
2539
-     * @access  protected
2540
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2541
-     *                         for. Defaults to all (for the given context)
2542
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2543
-     * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2544
-     *                         true just an array of shortcode/label pairs.
2545
-     * @throws EE_Error
2546
-     * @throws InvalidArgumentException
2547
-     * @throws ReflectionException
2548
-     * @throws InvalidDataTypeException
2549
-     * @throws InvalidInterfaceException
2550
-     */
2551
-    protected function _get_shortcodes($fields = array(), $merged = true)
2552
-    {
2553
-        $this->_set_message_template_group();
2554
-
2555
-        // we need the messenger and message template to retrieve the valid shortcodes array.
2556
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2557
-            ? absint($this->_req_data['id'])
2558
-            : false;
2559
-        $context = isset($this->_req_data['context'])
2560
-            ? $this->_req_data['context']
2561
-            : key($this->_message_template_group->contexts_config());
2562
-
2563
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2564
-    }
2565
-
2566
-
2567
-    /**
2568
-     * This sets the _message_template property (containing the called message_template object)
2569
-     *
2570
-     * @access protected
2571
-     * @return void
2572
-     * @throws EE_Error
2573
-     * @throws InvalidArgumentException
2574
-     * @throws ReflectionException
2575
-     * @throws InvalidDataTypeException
2576
-     * @throws InvalidInterfaceException
2577
-     */
2578
-    protected function _set_message_template_group()
2579
-    {
2580
-
2581
-        if (! empty($this->_message_template_group)) {
2582
-            return;
2583
-        } //get out if this is already set.
2584
-
2585
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2586
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2587
-
2588
-        // let's get the message templates
2589
-        $MTP = EEM_Message_Template_Group::instance();
2590
-
2591
-        if (empty($GRP_ID)) {
2592
-            $this->_message_template_group = $MTP->create_default_object();
2593
-        } else {
2594
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2595
-        }
2596
-
2597
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2598
-        $this->_variation = $this->_message_template_group->get_template_pack_variation();
2599
-    }
2600
-
2601
-
2602
-    /**
2603
-     * sets up a context switcher for edit forms
2604
-     *
2605
-     * @access  protected
2606
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2607
-     * @param array                      $args                  various things the context switcher needs.
2608
-     * @throws EE_Error
2609
-     */
2610
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2611
-    {
2612
-        $context_details = $template_group_object->contexts_config();
2613
-        $context_label = $template_group_object->context_label();
2614
-        ob_start();
2615
-        ?>
2508
+		}
2509
+	}
2510
+
2511
+
2512
+	/**
2513
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2514
+	 *
2515
+	 * @access protected
2516
+	 * @return void
2517
+	 * @throws EE_Error
2518
+	 * @throws InvalidArgumentException
2519
+	 * @throws ReflectionException
2520
+	 * @throws InvalidDataTypeException
2521
+	 * @throws InvalidInterfaceException
2522
+	 */
2523
+	protected function _set_shortcodes()
2524
+	{
2525
+
2526
+		// no need to run this if the property is already set
2527
+		if (! empty($this->_shortcodes)) {
2528
+			return;
2529
+		}
2530
+
2531
+		$this->_shortcodes = $this->_get_shortcodes();
2532
+	}
2533
+
2534
+
2535
+	/**
2536
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2537
+	 * property)
2538
+	 *
2539
+	 * @access  protected
2540
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2541
+	 *                         for. Defaults to all (for the given context)
2542
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2543
+	 * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2544
+	 *                         true just an array of shortcode/label pairs.
2545
+	 * @throws EE_Error
2546
+	 * @throws InvalidArgumentException
2547
+	 * @throws ReflectionException
2548
+	 * @throws InvalidDataTypeException
2549
+	 * @throws InvalidInterfaceException
2550
+	 */
2551
+	protected function _get_shortcodes($fields = array(), $merged = true)
2552
+	{
2553
+		$this->_set_message_template_group();
2554
+
2555
+		// we need the messenger and message template to retrieve the valid shortcodes array.
2556
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2557
+			? absint($this->_req_data['id'])
2558
+			: false;
2559
+		$context = isset($this->_req_data['context'])
2560
+			? $this->_req_data['context']
2561
+			: key($this->_message_template_group->contexts_config());
2562
+
2563
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2564
+	}
2565
+
2566
+
2567
+	/**
2568
+	 * This sets the _message_template property (containing the called message_template object)
2569
+	 *
2570
+	 * @access protected
2571
+	 * @return void
2572
+	 * @throws EE_Error
2573
+	 * @throws InvalidArgumentException
2574
+	 * @throws ReflectionException
2575
+	 * @throws InvalidDataTypeException
2576
+	 * @throws InvalidInterfaceException
2577
+	 */
2578
+	protected function _set_message_template_group()
2579
+	{
2580
+
2581
+		if (! empty($this->_message_template_group)) {
2582
+			return;
2583
+		} //get out if this is already set.
2584
+
2585
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2586
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2587
+
2588
+		// let's get the message templates
2589
+		$MTP = EEM_Message_Template_Group::instance();
2590
+
2591
+		if (empty($GRP_ID)) {
2592
+			$this->_message_template_group = $MTP->create_default_object();
2593
+		} else {
2594
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2595
+		}
2596
+
2597
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2598
+		$this->_variation = $this->_message_template_group->get_template_pack_variation();
2599
+	}
2600
+
2601
+
2602
+	/**
2603
+	 * sets up a context switcher for edit forms
2604
+	 *
2605
+	 * @access  protected
2606
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2607
+	 * @param array                      $args                  various things the context switcher needs.
2608
+	 * @throws EE_Error
2609
+	 */
2610
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2611
+	{
2612
+		$context_details = $template_group_object->contexts_config();
2613
+		$context_label = $template_group_object->context_label();
2614
+		ob_start();
2615
+		?>
2616 2616
         <div class="ee-msg-switcher-container">
2617 2617
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2618 2618
                 <?php
2619
-                foreach ($args as $name => $value) {
2620
-                    if ($name === 'context' || empty($value) || $name === 'extra') {
2621
-                        continue;
2622
-                    }
2623
-                    ?>
2619
+				foreach ($args as $name => $value) {
2620
+					if ($name === 'context' || empty($value) || $name === 'extra') {
2621
+						continue;
2622
+					}
2623
+					?>
2624 2624
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2625 2625
                     <?php
2626
-                }
2627
-                // setup nonce_url
2628
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2629
-                ?>
2626
+				}
2627
+				// setup nonce_url
2628
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2629
+				?>
2630 2630
                 <select name="context">
2631 2631
                     <?php
2632
-                    $context_templates = $template_group_object->context_templates();
2633
-                    if (is_array($context_templates)) :
2634
-                        foreach ($context_templates as $context => $template_fields) :
2635
-                            $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2636
-                            ?>
2632
+					$context_templates = $template_group_object->context_templates();
2633
+					if (is_array($context_templates)) :
2634
+						foreach ($context_templates as $context => $template_fields) :
2635
+							$checked = ($context === $args['context']) ? 'selected="selected"' : '';
2636
+							?>
2637 2637
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2638 2638
                                 <?php echo $context_details[ $context ]['label']; ?>
2639 2639
                             </option>
2640 2640
                         <?php endforeach;
2641
-                    endif; ?>
2641
+					endif; ?>
2642 2642
                 </select>
2643 2643
                 <?php $button_text = sprintf(__('Switch %s', 'event_espresso'), ucwords($context_label['label'])); ?>
2644 2644
                 <input id="submit-msg-context-switcher-sbmt" class="button-secondary" type="submit"
@@ -2647,1925 +2647,1925 @@  discard block
 block discarded – undo
2647 2647
             <?php echo $args['extra']; ?>
2648 2648
         </div> <!-- end .ee-msg-switcher-container -->
2649 2649
         <?php
2650
-        $output = ob_get_contents();
2651
-        ob_clean();
2652
-        $this->_context_switcher = $output;
2653
-    }
2654
-
2655
-
2656
-    /**
2657
-     * utility for sanitizing new values coming in.
2658
-     * Note: this is only used when updating a context.
2659
-     *
2660
-     * @access protected
2661
-     *
2662
-     * @param int $index This helps us know which template field to select from the request array.
2663
-     *
2664
-     * @return array
2665
-     */
2666
-    protected function _set_message_template_column_values($index)
2667
-    {
2668
-        if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2669
-            foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2670
-                $this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2671
-            }
2672
-        }
2673
-
2674
-
2675
-        $set_column_values = array(
2676
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2677
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2678
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2679
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2680
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2681
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2682
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2683
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2684
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2685
-                ? absint($this->_req_data['MTP_is_global'])
2686
-                : 0,
2687
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2688
-                ? absint($this->_req_data['MTP_is_override'])
2689
-                : 0,
2690
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2691
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2692
-        );
2693
-
2694
-
2695
-        return $set_column_values;
2696
-    }
2697
-
2698
-
2699
-    protected function _insert_or_update_message_template($new = false)
2700
-    {
2701
-
2702
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2703
-        $success = 0;
2704
-        $override = false;
2705
-
2706
-        // setup notices description
2707
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2708
-
2709
-        // need the message type and messenger objects to be able to use the labels for the notices
2710
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2711
-        $messenger_label = $messenger_object instanceof EE_messenger
2712
-            ? ucwords($messenger_object->label['singular'])
2713
-            : '';
2714
-
2715
-        $message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2716
-            ? $this->_req_data['MTP_message_type']
2717
-            : '';
2718
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2719
-
2720
-        $message_type_label = $message_type_object instanceof EE_message_type
2721
-            ? ucwords($message_type_object->label['singular'])
2722
-            : '';
2723
-
2724
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2725
-            ? $this->_req_data['MTP_context']
2726
-            : '';
2727
-        $context = ucwords(str_replace('_', ' ', $context_slug));
2728
-
2729
-        $item_desc = $messenger_label && $message_type_label
2730
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2731
-            : '';
2732
-        $item_desc .= 'Message Template';
2733
-        $query_args = array();
2734
-        $edit_array = array();
2735
-        $action_desc = '';
2736
-
2737
-        // if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2738
-        // user to edit.
2739
-        if ($new) {
2740
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2741
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2742
-                if (empty($edit_array)) {
2743
-                    $success = 0;
2744
-                } else {
2745
-                    $success = 1;
2746
-                    $edit_array = $edit_array[0];
2747
-                    $query_args = array(
2748
-                        'id'      => $edit_array['GRP_ID'],
2749
-                        'context' => $edit_array['MTP_context'],
2750
-                        'action'  => 'edit_message_template',
2751
-                    );
2752
-                }
2753
-            }
2754
-            $action_desc = 'created';
2755
-        } else {
2756
-            $MTPG = EEM_Message_Template_Group::instance();
2757
-            $MTP = EEM_Message_Template::instance();
2758
-
2759
-
2760
-            // run update for each template field in displayed context
2761
-            if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2762
-                EE_Error::add_error(
2763
-                    esc_html__(
2764
-                        'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2765
-                        'event_espresso'
2766
-                    ),
2767
-                    __FILE__,
2768
-                    __FUNCTION__,
2769
-                    __LINE__
2770
-                );
2771
-                $success = 0;
2772
-            } else {
2773
-                // first validate all fields!
2774
-                // this filter allows client code to add its own validation to the template fields as well.
2775
-                // returning an empty array means everything passed validation.
2776
-                // errors in validation should be represented in an array with the following shape:
2777
-                // array(
2778
-                //   'fieldname' => array(
2779
-                //          'msg' => 'error message'
2780
-                //          'value' => 'value for field producing error'
2781
-                // )
2782
-                $custom_validation = (array) apply_filters(
2783
-                    'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2784
-                    array(),
2785
-                    $this->_req_data['MTP_template_fields'],
2786
-                    $context_slug,
2787
-                    $messenger_slug,
2788
-                    $message_type_slug
2789
-                );
2790
-
2791
-                $system_validation = $MTPG->validate(
2792
-                    $this->_req_data['MTP_template_fields'],
2793
-                    $context_slug,
2794
-                    $messenger_slug,
2795
-                    $message_type_slug
2796
-                );
2797
-
2798
-                $system_validation = ! is_array($system_validation) && $system_validation ? array()
2799
-                    : $system_validation;
2800
-                $validates = array_merge($custom_validation, $system_validation);
2801
-
2802
-                // if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2803
-                // appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2804
-                //  WE need to make sure there is no actual error messages in validates.
2805
-                if (is_array($validates) && ! empty($validates)) {
2806
-                    // add the transient so when the form loads we know which fields to highlight
2807
-                    $this->_add_transient('edit_message_template', $validates);
2808
-
2809
-                    $success = 0;
2810
-
2811
-                    // setup notices
2812
-                    foreach ($validates as $field => $error) {
2813
-                        if (isset($error['msg'])) {
2814
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2815
-                        }
2816
-                    }
2817
-                } else {
2818
-                    $set_column_values = array();
2819
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2820
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2821
-
2822
-                        $where_cols_n_values = array(
2823
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2824
-                        );
2825
-                        // if they aren't allowed to use all JS, restrict them to just posty-y tags
2826
-                        if (! current_user_can('unfiltered_html')) {
2827
-                            if (is_array($set_column_values['MTP_content'])) {
2828
-                                foreach ($set_column_values['MTP_content'] as $key => $value) {
2829
-                                    // remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2830
-                                    // only removes slashes from double-quotes, so attributes using single quotes always
2831
-                                    // appear invalid.) But currently the models expect slashed data, so after wp_kses
2832
-                                    // runs we need to re-slash the data. Sheesh. See
2833
-                                    // https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2834
-                                    $set_column_values['MTP_content'][ $key ] = addslashes(
2835
-                                        wp_kses(
2836
-                                            stripslashes($value),
2837
-                                            wp_kses_allowed_html('post')
2838
-                                        )
2839
-                                    );
2840
-                                }
2841
-                            } else {
2842
-                                $set_column_values['MTP_content'] = wp_kses(
2843
-                                    $set_column_values['MTP_content'],
2844
-                                    wp_kses_allowed_html('post')
2845
-                                );
2846
-                            }
2847
-                        }
2848
-                        $message_template_fields = array(
2849
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2850
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2851
-                            'MTP_context'        => $set_column_values['MTP_context'],
2852
-                            'MTP_content'        => $set_column_values['MTP_content'],
2853
-                        );
2854
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2855
-                            if ($updated === false) {
2856
-                                EE_Error::add_error(
2857
-                                    sprintf(
2858
-                                        esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2859
-                                        $template_field
2860
-                                    ),
2861
-                                    __FILE__,
2862
-                                    __FUNCTION__,
2863
-                                    __LINE__
2864
-                                );
2865
-                            } else {
2866
-                                $success = 1;
2867
-                            }
2868
-                        } else {
2869
-                            // only do this logic if we don't have a MTP_ID for this field
2870
-                            if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2871
-                                // this has already been through the template field validator and sanitized, so it will be
2872
-                                // safe to insert this field.  Why insert?  This typically happens when we introduce a new
2873
-                                // message template field in a messenger/message type and existing users don't have the
2874
-                                // default setup for it.
2875
-                                // @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2876
-                                $updated = $MTP->insert($message_template_fields);
2877
-                                if (! $updated || is_wp_error($updated)) {
2878
-                                    EE_Error::add_error(
2879
-                                        sprintf(
2880
-                                            esc_html__('%s field could not be updated.', 'event_espresso'),
2881
-                                            $template_field
2882
-                                        ),
2883
-                                        __FILE__,
2884
-                                        __FUNCTION__,
2885
-                                        __LINE__
2886
-                                    );
2887
-                                    $success = 0;
2888
-                                } else {
2889
-                                    $success = 1;
2890
-                                }
2891
-                            }
2892
-                        }
2893
-                        $action_desc = 'updated';
2894
-                    }
2895
-
2896
-                    // we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2897
-                    $mtpg_fields = array(
2898
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2899
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2900
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2901
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2902
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2903
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2904
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2905
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2906
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2907
-                            : '',
2908
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2909
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2910
-                            : '',
2911
-                    );
2912
-
2913
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2914
-                    $updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2915
-
2916
-                    if ($updated === false) {
2917
-                        EE_Error::add_error(
2918
-                            sprintf(
2919
-                                esc_html__(
2920
-                                    'The Message Template Group (%d) was NOT updated for some reason',
2921
-                                    'event_espresso'
2922
-                                ),
2923
-                                $set_column_values['GRP_ID']
2924
-                            ),
2925
-                            __FILE__,
2926
-                            __FUNCTION__,
2927
-                            __LINE__
2928
-                        );
2929
-                    } else {
2930
-                        // k now we need to ensure the template_pack and template_variation fields are set.
2931
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2932
-                            ? $this->_req_data['MTP_template_pack']
2933
-                            : 'default';
2934
-
2935
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2936
-                            ? $this->_req_data['MTP_template_variation']
2937
-                            : 'default';
2938
-
2939
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2940
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2941
-                            $mtpg_obj->set_template_pack_name($template_pack);
2942
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2943
-                        }
2944
-                        $success = 1;
2945
-                    }
2946
-                }
2947
-            }
2948
-        }
2949
-
2950
-        // we return things differently if doing ajax
2951
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2952
-            $this->_template_args['success'] = $success;
2953
-            $this->_template_args['error'] = ! $success ? true : false;
2954
-            $this->_template_args['content'] = '';
2955
-            $this->_template_args['data'] = array(
2956
-                'grpID'        => $edit_array['GRP_ID'],
2957
-                'templateName' => $edit_array['template_name'],
2958
-            );
2959
-            if ($success) {
2960
-                EE_Error::overwrite_success();
2961
-                EE_Error::add_success(
2962
-                    esc_html__(
2963
-                        '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.',
2964
-                        'event_espresso'
2965
-                    )
2966
-                );
2967
-            }
2968
-
2969
-            $this->_return_json();
2970
-        }
2971
-
2972
-
2973
-        // was a test send triggered?
2974
-        if (isset($this->_req_data['test_button'])) {
2975
-            EE_Error::overwrite_success();
2976
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2977
-            $override = true;
2978
-        }
2979
-
2980
-        if (empty($query_args)) {
2981
-            $query_args = array(
2982
-                'id'      => $this->_req_data['GRP_ID'],
2983
-                'context' => $context_slug,
2984
-                'action'  => 'edit_message_template',
2985
-            );
2986
-        }
2987
-
2988
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2989
-    }
2990
-
2991
-
2992
-    /**
2993
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
2994
-     *
2995
-     * @param  string $context      what context being tested
2996
-     * @param  string $messenger    messenger being tested
2997
-     * @param  string $message_type message type being tested
2998
-     * @throws EE_Error
2999
-     * @throws InvalidArgumentException
3000
-     * @throws InvalidDataTypeException
3001
-     * @throws InvalidInterfaceException
3002
-     */
3003
-    protected function _do_test_send($context, $messenger, $message_type)
3004
-    {
3005
-        // set things up for preview
3006
-        $this->_req_data['messenger'] = $messenger;
3007
-        $this->_req_data['message_type'] = $message_type;
3008
-        $this->_req_data['context'] = $context;
3009
-        $this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
3010
-        $active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
3011
-
3012
-        // let's save any existing fields that might be required by the messenger
3013
-        if (isset($this->_req_data['test_settings_fld'])
3014
-            && $active_messenger instanceof EE_messenger
3015
-            && apply_filters(
3016
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3017
-                true,
3018
-                $this->_req_data['test_settings_fld'],
3019
-                $active_messenger
3020
-            )
3021
-        ) {
3022
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
3023
-        }
3024
-
3025
-        /**
3026
-         * Use filter to add additional controls on whether message can send or not
3027
-         */
3028
-        if (apply_filters(
3029
-            'FHEE__Messages_Admin_Page__do_test_send__can_send',
3030
-            true,
3031
-            $context,
3032
-            $this->_req_data,
3033
-            $messenger,
3034
-            $message_type
3035
-        )) {
3036
-            if (EEM_Event::instance()->count() > 0) {
3037
-                $success = $this->_preview_message(true);
3038
-                if ($success) {
3039
-                    EE_Error::add_success(__('Test message sent', 'event_espresso'));
3040
-                } else {
3041
-                    EE_Error::add_error(
3042
-                        esc_html__('The test message was not sent', 'event_espresso'),
3043
-                        __FILE__,
3044
-                        __FUNCTION__,
3045
-                        __LINE__
3046
-                    );
3047
-                }
3048
-            } else {
3049
-                $this->noEventsErrorMessage(true);
3050
-            }
3051
-        }
3052
-    }
3053
-
3054
-
3055
-    /**
3056
-     * _generate_new_templates
3057
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3058
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3059
-     * for the event.
3060
-     *
3061
-     *
3062
-     * @param  string $messenger     the messenger we are generating templates for
3063
-     * @param array   $message_types array of message types that the templates are generated for.
3064
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3065
-     *                               indicate the message_template_group being used as the base.
3066
-     *
3067
-     * @param bool    $global
3068
-     *
3069
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
3070
-     *                               encountering problems.
3071
-     * @throws EE_Error
3072
-     */
3073
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3074
-    {
3075
-
3076
-        // if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3077
-        // just don't generate any templates.
3078
-        if (empty($message_types)) {
3079
-            return true;
3080
-        }
3081
-
3082
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3083
-    }
3084
-
3085
-
3086
-    /**
3087
-     * [_trash_or_restore_message_template]
3088
-     *
3089
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3090
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3091
-     *                        an individual context (FALSE).
3092
-     * @return void
3093
-     * @throws EE_Error
3094
-     * @throws InvalidArgumentException
3095
-     * @throws InvalidDataTypeException
3096
-     * @throws InvalidInterfaceException
3097
-     */
3098
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
3099
-    {
3100
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3101
-        $MTP = EEM_Message_Template_Group::instance();
3102
-
3103
-        $success = 1;
3104
-
3105
-        // incoming GRP_IDs
3106
-        if ($all) {
3107
-            // Checkboxes
3108
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3109
-                // if array has more than one element then success message should be plural.
3110
-                // todo: what about nonce?
3111
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3112
-
3113
-                // cycle through checkboxes
3114
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3115
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3116
-                    if (! $trashed_or_restored) {
3117
-                        $success = 0;
3118
-                    }
3119
-                }
3120
-            } else {
3121
-                // grab single GRP_ID and handle
3122
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3123
-                if (! empty($GRP_ID)) {
3124
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3125
-                    if (! $trashed_or_restored) {
3126
-                        $success = 0;
3127
-                    }
3128
-                } else {
3129
-                    $success = 0;
3130
-                }
3131
-            }
3132
-        }
3133
-
3134
-        $action_desc = $trash
3135
-            ? esc_html__('moved to the trash', 'event_espresso')
3136
-            : esc_html__('restored', 'event_espresso');
3137
-
3138
-        $action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3139
-
3140
-        $item_desc = $all ? _n(
3141
-            'Message Template Group',
3142
-            'Message Template Groups',
3143
-            $success,
3144
-            'event_espresso'
3145
-        ) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3146
-
3147
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3148
-            'template',
3149
-            'templates',
3150
-            $success,
3151
-            'event_espresso'
3152
-        ) : $item_desc;
3153
-
3154
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
3155
-    }
3156
-
3157
-
3158
-    /**
3159
-     * [_delete_message_template]
3160
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3161
-     *
3162
-     * @return void
3163
-     * @throws EE_Error
3164
-     * @throws InvalidArgumentException
3165
-     * @throws InvalidDataTypeException
3166
-     * @throws InvalidInterfaceException
3167
-     */
3168
-    protected function _delete_message_template()
3169
-    {
3170
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3171
-
3172
-        // checkboxes
3173
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3174
-            // if array has more than one element then success message should be plural
3175
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3176
-
3177
-            // cycle through bulk action checkboxes
3178
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3179
-                $success = $this->_delete_mtp_permanently($GRP_ID);
3180
-            }
3181
-        } else {
3182
-            // grab single grp_id and delete
3183
-            $GRP_ID = absint($this->_req_data['id']);
3184
-            $success = $this->_delete_mtp_permanently($GRP_ID);
3185
-        }
3186
-
3187
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3188
-    }
3189
-
3190
-
3191
-    /**
3192
-     * helper for permanently deleting a mtP group and all related message_templates
3193
-     *
3194
-     * @param  int  $GRP_ID        The group being deleted
3195
-     * @param  bool $include_group whether to delete the Message Template Group as well.
3196
-     * @return bool boolean to indicate the success of the deletes or not.
3197
-     * @throws EE_Error
3198
-     * @throws InvalidArgumentException
3199
-     * @throws InvalidDataTypeException
3200
-     * @throws InvalidInterfaceException
3201
-     */
3202
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3203
-    {
3204
-        $success = 1;
3205
-        $MTPG = EEM_Message_Template_Group::instance();
3206
-        // first let's GET this group
3207
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
3208
-        // then delete permanently all the related Message Templates
3209
-        $deleted = $MTG->delete_related_permanently('Message_Template');
3210
-
3211
-        if ($deleted === 0) {
3212
-            $success = 0;
3213
-        }
3214
-
3215
-        // now delete permanently this particular group
3216
-
3217
-        if ($include_group && ! $MTG->delete_permanently()) {
3218
-            $success = 0;
3219
-        }
3220
-
3221
-        return $success;
3222
-    }
3223
-
3224
-
3225
-    /**
3226
-     *    _learn_more_about_message_templates_link
3227
-     *
3228
-     * @access protected
3229
-     * @return string
3230
-     */
3231
-    protected function _learn_more_about_message_templates_link()
3232
-    {
3233
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3234
-               . esc_html__('learn more about how message templates works', 'event_espresso')
3235
-               . '</a>';
3236
-    }
3237
-
3238
-
3239
-    /**
3240
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3241
-     * ajax and other routes.
3242
-     *
3243
-     * @return void
3244
-     * @throws DomainException
3245
-     */
3246
-    protected function _settings()
3247
-    {
3248
-
3249
-
3250
-        $this->_set_m_mt_settings();
3251
-
3252
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3253
-            ? $this->_req_data['selected_messenger']
3254
-            : 'email';
3255
-
3256
-        // let's setup the messenger tabs
3257
-        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3258
-            $this->_m_mt_settings['messenger_tabs'],
3259
-            'messenger_links',
3260
-            '|',
3261
-            $selected_messenger
3262
-        );
3263
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3264
-        $this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3265
-
3266
-        $this->display_admin_page_with_sidebar();
3267
-    }
3268
-
3269
-
3270
-    /**
3271
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3272
-     *
3273
-     * @access protected
3274
-     * @return void
3275
-     * @throws DomainException
3276
-     */
3277
-    protected function _set_m_mt_settings()
3278
-    {
3279
-        // first if this is already set then lets get out no need to regenerate data.
3280
-        if (! empty($this->_m_mt_settings)) {
3281
-            return;
3282
-        }
3283
-
3284
-        // get all installed messengers and message_types
3285
-        /** @type EE_messenger[] $messengers */
3286
-        $messengers = $this->_message_resource_manager->installed_messengers();
3287
-        /** @type EE_message_type[] $message_types */
3288
-        $message_types = $this->_message_resource_manager->installed_message_types();
3289
-
3290
-
3291
-        // assemble the array for the _tab_text_links helper
3292
-
3293
-        foreach ($messengers as $messenger) {
3294
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3295
-                'label' => ucwords($messenger->label['singular']),
3296
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3297
-                    ? 'messenger-active'
3298
-                    : '',
3299
-                'href'  => $messenger->name,
3300
-                'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3301
-                'slug'  => $messenger->name,
3302
-                'obj'   => $messenger,
3303
-            );
3304
-
3305
-
3306
-            $message_types_for_messenger = $messenger->get_valid_message_types();
3307
-
3308
-            foreach ($message_types as $message_type) {
3309
-                // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3310
-                // it shouldn't show in either the inactive OR active metabox.
3311
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3312
-                    continue;
3313
-                }
3314
-
3315
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3316
-                    $messenger->name,
3317
-                    $message_type->name
3318
-                )
3319
-                    ? 'active'
3320
-                    : 'inactive';
3321
-
3322
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3323
-                    'label'    => ucwords($message_type->label['singular']),
3324
-                    'class'    => 'message-type-' . $a_or_i,
3325
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3326
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3327
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3328
-                    'title'    => $a_or_i === 'active'
3329
-                        ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3330
-                        : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3331
-                    'content'  => $a_or_i === 'active'
3332
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
3333
-                        : $this->_message_type_settings_content($message_type, $messenger),
3334
-                    'slug'     => $message_type->name,
3335
-                    'active'   => $a_or_i === 'active',
3336
-                    'obj'      => $message_type,
3337
-                );
3338
-            }
3339
-        }
3340
-    }
3341
-
3342
-
3343
-    /**
3344
-     * This just prepares the content for the message type settings
3345
-     *
3346
-     * @param  EE_message_type $message_type The message type object
3347
-     * @param  EE_messenger    $messenger    The messenger object
3348
-     * @param  boolean         $active       Whether the message type is active or not
3349
-     * @return string html output for the content
3350
-     * @throws DomainException
3351
-     */
3352
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
3353
-    {
3354
-        // get message type fields
3355
-        $fields = $message_type->get_admin_settings_fields();
3356
-        $settings_template_args['template_form_fields'] = '';
3357
-
3358
-        if (! empty($fields) && $active) {
3359
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3360
-            foreach ($fields as $fldname => $fldprops) {
3361
-                $field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3362
-                $template_form_field[ $field_id ] = array(
3363
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3364
-                    'label'      => $fldprops['label'],
3365
-                    'input'      => $fldprops['field_type'],
3366
-                    'type'       => $fldprops['value_type'],
3367
-                    'required'   => $fldprops['required'],
3368
-                    'validation' => $fldprops['validation'],
3369
-                    'value'      => isset($existing_settings[ $fldname ])
3370
-                        ? $existing_settings[ $fldname ]
3371
-                        : $fldprops['default'],
3372
-                    'options'    => isset($fldprops['options'])
3373
-                        ? $fldprops['options']
3374
-                        : array(),
3375
-                    'default'    => isset($existing_settings[ $fldname ])
3376
-                        ? $existing_settings[ $fldname ]
3377
-                        : $fldprops['default'],
3378
-                    'css_class'  => 'no-drag',
3379
-                    'format'     => $fldprops['format'],
3380
-                );
3381
-            }
3382
-
3383
-
3384
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3385
-                ? $this->_generate_admin_form_fields(
3386
-                    $template_form_field,
3387
-                    'string',
3388
-                    'ee_mt_activate_form'
3389
-                )
3390
-                : '';
3391
-        }
3392
-
3393
-        $settings_template_args['description'] = $message_type->description;
3394
-        // we also need some hidden fields
3395
-        $settings_template_args['hidden_fields'] = array(
3396
-            'message_type_settings[messenger]'    => array(
3397
-                'type'  => 'hidden',
3398
-                'value' => $messenger->name,
3399
-            ),
3400
-            'message_type_settings[message_type]' => array(
3401
-                'type'  => 'hidden',
3402
-                'value' => $message_type->name,
3403
-            ),
3404
-            'type'                                => array(
3405
-                'type'  => 'hidden',
3406
-                'value' => 'message_type',
3407
-            ),
3408
-        );
3409
-
3410
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3411
-            $settings_template_args['hidden_fields'],
3412
-            'array'
3413
-        );
3414
-        $settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3415
-            ? ' hidden'
3416
-            : '';
3417
-
3418
-
3419
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3420
-        $content = EEH_Template::display_template($template, $settings_template_args, true);
3421
-
3422
-        return $content;
3423
-    }
3424
-
3425
-
3426
-    /**
3427
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
3428
-     *
3429
-     * @access protected
3430
-     * @return void
3431
-     * @throws DomainException
3432
-     */
3433
-    protected function _messages_settings_metaboxes()
3434
-    {
3435
-        $this->_set_m_mt_settings();
3436
-        $m_boxes = $mt_boxes = array();
3437
-        $m_template_args = $mt_template_args = array();
3438
-
3439
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3440
-            ? $this->_req_data['selected_messenger']
3441
-            : 'email';
3442
-
3443
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
3444
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3445
-                $hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3446
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3447
-                // messenger meta boxes
3448
-                $active = $selected_messenger === $messenger;
3449
-                $active_mt_tabs = isset(
3450
-                    $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3451
-                )
3452
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3453
-                    : '';
3454
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3455
-                    esc_html__('%s Settings', 'event_espresso'),
3456
-                    $tab_array['label']
3457
-                );
3458
-                $m_template_args[ $messenger . '_a_box' ] = array(
3459
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3460
-                    'inactive_message_types' => isset(
3461
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3462
-                    )
3463
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3464
-                        : '',
3465
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3466
-                    'hidden'                 => $active ? '' : ' hidden',
3467
-                    'hide_on_message'        => $hide_on_message,
3468
-                    'messenger'              => $messenger,
3469
-                    'active'                 => $active,
3470
-                );
3471
-                // message type meta boxes
3472
-                // (which is really just the inactive container for each messenger
3473
-                // showing inactive message types for that messenger)
3474
-                $mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3475
-                $mt_template_args[ $messenger . '_i_box' ] = array(
3476
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3477
-                    'inactive_message_types' => isset(
3478
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3479
-                    )
3480
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3481
-                        : '',
3482
-                    'hidden'                 => $active ? '' : ' hidden',
3483
-                    'hide_on_message'        => $hide_on_message,
3484
-                    'hide_off_message'       => $hide_off_message,
3485
-                    'messenger'              => $messenger,
3486
-                    'active'                 => $active,
3487
-                );
3488
-            }
3489
-        }
3490
-
3491
-
3492
-        // register messenger metaboxes
3493
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3494
-        foreach ($m_boxes as $box => $label) {
3495
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3496
-            $msgr = str_replace('_a_box', '', $box);
3497
-            add_meta_box(
3498
-                'espresso_' . $msgr . '_settings',
3499
-                $label,
3500
-                function ($post, $metabox) {
3501
-                    echo EEH_Template::display_template(
3502
-                        $metabox["args"]["template_path"],
3503
-                        $metabox["args"]["template_args"],
3504
-                        true
3505
-                    );
3506
-                },
3507
-                $this->_current_screen->id,
3508
-                'normal',
3509
-                'high',
3510
-                $callback_args
3511
-            );
3512
-        }
3513
-
3514
-        // register message type metaboxes
3515
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3516
-        foreach ($mt_boxes as $box => $label) {
3517
-            $callback_args = array(
3518
-                'template_path' => $mt_template_path,
3519
-                'template_args' => $mt_template_args[ $box ],
3520
-            );
3521
-            $mt = str_replace('_i_box', '', $box);
3522
-            add_meta_box(
3523
-                'espresso_' . $mt . '_inactive_mts',
3524
-                $label,
3525
-                function ($post, $metabox) {
3526
-                    echo EEH_Template::display_template(
3527
-                        $metabox["args"]["template_path"],
3528
-                        $metabox["args"]["template_args"],
3529
-                        true
3530
-                    );
3531
-                },
3532
-                $this->_current_screen->id,
3533
-                'side',
3534
-                'high',
3535
-                $callback_args
3536
-            );
3537
-        }
3538
-
3539
-        // register metabox for global messages settings but only when on the main site.  On single site installs this
3540
-        // will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3541
-        if (is_main_site()) {
3542
-            add_meta_box(
3543
-                'espresso_global_message_settings',
3544
-                esc_html__('Global Message Settings', 'event_espresso'),
3545
-                array($this, 'global_messages_settings_metabox_content'),
3546
-                $this->_current_screen->id,
3547
-                'normal',
3548
-                'low',
3549
-                array()
3550
-            );
3551
-        }
3552
-    }
3553
-
3554
-
3555
-    /**
3556
-     *  This generates the content for the global messages settings metabox.
3557
-     *
3558
-     * @return string
3559
-     * @throws EE_Error
3560
-     * @throws InvalidArgumentException
3561
-     * @throws ReflectionException
3562
-     * @throws InvalidDataTypeException
3563
-     * @throws InvalidInterfaceException
3564
-     */
3565
-    public function global_messages_settings_metabox_content()
3566
-    {
3567
-        $form = $this->_generate_global_settings_form();
3568
-        echo $form->form_open(
3569
-            $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3570
-            'POST'
3571
-        )
3572
-             . $form->get_html()
3573
-             . $form->form_close();
3574
-    }
3575
-
3576
-
3577
-    /**
3578
-     * This generates and returns the form object for the global messages settings.
3579
-     *
3580
-     * @return EE_Form_Section_Proper
3581
-     * @throws EE_Error
3582
-     * @throws InvalidArgumentException
3583
-     * @throws ReflectionException
3584
-     * @throws InvalidDataTypeException
3585
-     * @throws InvalidInterfaceException
3586
-     */
3587
-    protected function _generate_global_settings_form()
3588
-    {
3589
-        EE_Registry::instance()->load_helper('HTML');
3590
-        /** @var EE_Network_Core_Config $network_config */
3591
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3592
-
3593
-        return new EE_Form_Section_Proper(
3594
-            array(
3595
-                'name'            => 'global_messages_settings',
3596
-                'html_id'         => 'global_messages_settings',
3597
-                'html_class'      => 'form-table',
3598
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3599
-                'subsections'     => apply_filters(
3600
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3601
-                    array(
3602
-                        'do_messages_on_same_request' => new EE_Select_Input(
3603
-                            array(
3604
-                                true  => esc_html__("On the same request", "event_espresso"),
3605
-                                false => esc_html__("On a separate request", "event_espresso"),
3606
-                            ),
3607
-                            array(
3608
-                                'default'         => $network_config->do_messages_on_same_request,
3609
-                                'html_label_text' => esc_html__(
3610
-                                    'Generate and send all messages:',
3611
-                                    'event_espresso'
3612
-                                ),
3613
-                                'html_help_text'  => esc_html__(
3614
-                                    '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.',
3615
-                                    'event_espresso'
3616
-                                ),
3617
-                            )
3618
-                        ),
3619
-                        'delete_threshold'            => new EE_Select_Input(
3620
-                            array(
3621
-                                0  => esc_html__('Forever', 'event_espresso'),
3622
-                                3  => esc_html__('3 Months', 'event_espresso'),
3623
-                                6  => esc_html__('6 Months', 'event_espresso'),
3624
-                                9  => esc_html__('9 Months', 'event_espresso'),
3625
-                                12 => esc_html__('12 Months', 'event_espresso'),
3626
-                                24 => esc_html__('24 Months', 'event_espresso'),
3627
-                                36 => esc_html__('36 Months', 'event_espresso'),
3628
-                            ),
3629
-                            array(
3630
-                                'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3631
-                                'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3632
-                                'html_help_text'  => esc_html__(
3633
-                                    'You can control how long a record of processed messages is kept via this option.',
3634
-                                    'event_espresso'
3635
-                                ),
3636
-                            )
3637
-                        ),
3638
-                        'update_settings'             => new EE_Submit_Input(
3639
-                            array(
3640
-                                'default'         => esc_html__('Update', 'event_espresso'),
3641
-                                'html_label_text' => '&nbsp',
3642
-                            )
3643
-                        ),
3644
-                    )
3645
-                ),
3646
-            )
3647
-        );
3648
-    }
3649
-
3650
-
3651
-    /**
3652
-     * This handles updating the global settings set on the admin page.
3653
-     *
3654
-     * @throws EE_Error
3655
-     * @throws InvalidDataTypeException
3656
-     * @throws InvalidInterfaceException
3657
-     * @throws InvalidArgumentException
3658
-     * @throws ReflectionException
3659
-     */
3660
-    protected function _update_global_settings()
3661
-    {
3662
-        /** @var EE_Network_Core_Config $network_config */
3663
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3664
-        $messages_config = EE_Registry::instance()->CFG->messages;
3665
-        $form = $this->_generate_global_settings_form();
3666
-        if ($form->was_submitted()) {
3667
-            $form->receive_form_submission();
3668
-            if ($form->is_valid()) {
3669
-                $valid_data = $form->valid_data();
3670
-                foreach ($valid_data as $property => $value) {
3671
-                    $setter = 'set_' . $property;
3672
-                    if (method_exists($network_config, $setter)) {
3673
-                        $network_config->{$setter}($value);
3674
-                    } elseif (property_exists($network_config, $property)
3675
-                        && $network_config->{$property} !== $value
3676
-                    ) {
3677
-                        $network_config->{$property} = $value;
3678
-                    } elseif (property_exists($messages_config, $property)
3679
-                        && $messages_config->{$property} !== $value
3680
-                    ) {
3681
-                        $messages_config->{$property} = $value;
3682
-                    }
3683
-                }
3684
-                // only update if the form submission was valid!
3685
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3686
-                EE_Registry::instance()->CFG->update_espresso_config();
3687
-                EE_Error::overwrite_success();
3688
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3689
-            }
3690
-        }
3691
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3692
-    }
3693
-
3694
-
3695
-    /**
3696
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3697
-     *
3698
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3699
-     * @return string html formatted tabs
3700
-     * @throws DomainException
3701
-     */
3702
-    protected function _get_mt_tabs($tab_array)
3703
-    {
3704
-        $tab_array = (array) $tab_array;
3705
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3706
-        $tabs = '';
3707
-
3708
-        foreach ($tab_array as $tab) {
3709
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3710
-        }
3711
-
3712
-        return $tabs;
3713
-    }
3714
-
3715
-
3716
-    /**
3717
-     * This prepares the content of the messenger meta box admin settings
3718
-     *
3719
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3720
-     * @return string html formatted content
3721
-     * @throws DomainException
3722
-     */
3723
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3724
-    {
3725
-
3726
-        $fields = $messenger->get_admin_settings_fields();
3727
-        $settings_template_args['template_form_fields'] = '';
3728
-
3729
-        // is $messenger active?
3730
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3731
-
3732
-
3733
-        if (! empty($fields)) {
3734
-            $existing_settings = $messenger->get_existing_admin_settings();
3735
-
3736
-            foreach ($fields as $fldname => $fldprops) {
3737
-                $field_id = $messenger->name . '-' . $fldname;
3738
-                $template_form_field[ $field_id ] = array(
3739
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3740
-                    'label'      => $fldprops['label'],
3741
-                    'input'      => $fldprops['field_type'],
3742
-                    'type'       => $fldprops['value_type'],
3743
-                    'required'   => $fldprops['required'],
3744
-                    'validation' => $fldprops['validation'],
3745
-                    'value'      => isset($existing_settings[ $field_id ])
3746
-                        ? $existing_settings[ $field_id ]
3747
-                        : $fldprops['default'],
3748
-                    'css_class'  => '',
3749
-                    'format'     => $fldprops['format'],
3750
-                );
3751
-            }
3752
-
3753
-
3754
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3755
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3756
-                : '';
3757
-        }
3758
-
3759
-        // we also need some hidden fields
3760
-        $settings_template_args['hidden_fields'] = array(
3761
-            'messenger_settings[messenger]' => array(
3762
-                'type'  => 'hidden',
3763
-                'value' => $messenger->name,
3764
-            ),
3765
-            'type'                          => array(
3766
-                'type'  => 'hidden',
3767
-                'value' => 'messenger',
3768
-            ),
3769
-        );
3770
-
3771
-        // make sure any active message types that are existing are included in the hidden fields
3772
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3773
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3774
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3775
-                    'type'  => 'hidden',
3776
-                    'value' => $mt,
3777
-                );
3778
-            }
3779
-        }
3780
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3781
-            $settings_template_args['hidden_fields'],
3782
-            'array'
3783
-        );
3784
-        $active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3785
-
3786
-        $settings_template_args['messenger'] = $messenger->name;
3787
-        $settings_template_args['description'] = $messenger->description;
3788
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3789
-
3790
-
3791
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3792
-            $messenger->name
3793
-        )
3794
-            ? $settings_template_args['show_hide_edit_form']
3795
-            : ' hidden';
3796
-
3797
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3798
-            ? ' hidden'
3799
-            : $settings_template_args['show_hide_edit_form'];
3800
-
3801
-
3802
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3803
-        $settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3804
-        $settings_template_args['on_off_status'] = $active ? true : false;
3805
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3806
-        $content = EEH_Template::display_template(
3807
-            $template,
3808
-            $settings_template_args,
3809
-            true
3810
-        );
3811
-
3812
-        return $content;
3813
-    }
3814
-
3815
-
3816
-    /**
3817
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3818
-     *
3819
-     * @throws DomainException
3820
-     * @throws EE_Error
3821
-     * @throws InvalidDataTypeException
3822
-     * @throws InvalidInterfaceException
3823
-     * @throws InvalidArgumentException
3824
-     * @throws ReflectionException
3825
-     */
3826
-    public function activate_messenger_toggle()
3827
-    {
3828
-        $success = true;
3829
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3830
-        // let's check that we have required data
3831
-        if (! isset($this->_req_data['messenger'])) {
3832
-            EE_Error::add_error(
3833
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3834
-                __FILE__,
3835
-                __FUNCTION__,
3836
-                __LINE__
3837
-            );
3838
-            $success = false;
3839
-        }
3840
-
3841
-        // do a nonce check here since we're not arriving via a normal route
3842
-        $nonce = isset($this->_req_data['activate_nonce'])
3843
-            ? sanitize_text_field($this->_req_data['activate_nonce'])
3844
-            : '';
3845
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3846
-
3847
-        $this->_verify_nonce($nonce, $nonce_ref);
3848
-
3849
-
3850
-        if (! isset($this->_req_data['status'])) {
3851
-            EE_Error::add_error(
3852
-                esc_html__(
3853
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3854
-                    'event_espresso'
3855
-                ),
3856
-                __FILE__,
3857
-                __FUNCTION__,
3858
-                __LINE__
3859
-            );
3860
-            $success = false;
3861
-        }
3862
-
3863
-        // do check to verify we have a valid status.
3864
-        $status = $this->_req_data['status'];
3865
-
3866
-        if ($status !== 'off' && $status !== 'on') {
3867
-            EE_Error::add_error(
3868
-                sprintf(
3869
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3870
-                    $this->_req_data['status']
3871
-                ),
3872
-                __FILE__,
3873
-                __FUNCTION__,
3874
-                __LINE__
3875
-            );
3876
-            $success = false;
3877
-        }
3878
-
3879
-        if ($success) {
3880
-            // made it here?  Stop dawdling then!!
3881
-            $success = $status === 'off'
3882
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3883
-                : $this->_activate_messenger($this->_req_data['messenger']);
3884
-        }
3885
-
3886
-        $this->_template_args['success'] = $success;
3887
-
3888
-        // no special instructions so let's just do the json return (which should automatically do all the special stuff).
3889
-        $this->_return_json();
3890
-    }
3891
-
3892
-
3893
-    /**
3894
-     * used by ajax from the messages settings page to activate|deactivate a message type
3895
-     *
3896
-     * @throws DomainException
3897
-     * @throws EE_Error
3898
-     * @throws ReflectionException
3899
-     * @throws InvalidDataTypeException
3900
-     * @throws InvalidInterfaceException
3901
-     * @throws InvalidArgumentException
3902
-     */
3903
-    public function activate_mt_toggle()
3904
-    {
3905
-        $success = true;
3906
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3907
-
3908
-        // let's make sure we have the necessary data
3909
-        if (! isset($this->_req_data['message_type'])) {
3910
-            EE_Error::add_error(
3911
-                esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3912
-                __FILE__,
3913
-                __FUNCTION__,
3914
-                __LINE__
3915
-            );
3916
-            $success = false;
3917
-        }
3918
-
3919
-        if (! isset($this->_req_data['messenger'])) {
3920
-            EE_Error::add_error(
3921
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3922
-                __FILE__,
3923
-                __FUNCTION__,
3924
-                __LINE__
3925
-            );
3926
-            $success = false;
3927
-        }
3928
-
3929
-        if (! isset($this->_req_data['status'])) {
3930
-            EE_Error::add_error(
3931
-                esc_html__(
3932
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3933
-                    'event_espresso'
3934
-                ),
3935
-                __FILE__,
3936
-                __FUNCTION__,
3937
-                __LINE__
3938
-            );
3939
-            $success = false;
3940
-        }
3941
-
3942
-
3943
-        // do check to verify we have a valid status.
3944
-        $status = $this->_req_data['status'];
3945
-
3946
-        if ($status !== 'activate' && $status !== 'deactivate') {
3947
-            EE_Error::add_error(
3948
-                sprintf(
3949
-                    esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3950
-                    $this->_req_data['status']
3951
-                ),
3952
-                __FILE__,
3953
-                __FUNCTION__,
3954
-                __LINE__
3955
-            );
3956
-            $success = false;
3957
-        }
3958
-
3959
-
3960
-        // do a nonce check here since we're not arriving via a normal route
3961
-        $nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3962
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3963
-
3964
-        $this->_verify_nonce($nonce, $nonce_ref);
3965
-
3966
-        if ($success) {
3967
-            // made it here? um, what are you waiting for then?
3968
-            $success = $status === 'deactivate'
3969
-                ? $this->_deactivate_message_type_for_messenger(
3970
-                    $this->_req_data['messenger'],
3971
-                    $this->_req_data['message_type']
3972
-                )
3973
-                : $this->_activate_message_type_for_messenger(
3974
-                    $this->_req_data['messenger'],
3975
-                    $this->_req_data['message_type']
3976
-                );
3977
-        }
3978
-
3979
-        $this->_template_args['success'] = $success;
3980
-        $this->_return_json();
3981
-    }
3982
-
3983
-
3984
-    /**
3985
-     * Takes care of processing activating a messenger and preparing the appropriate response.
3986
-     *
3987
-     * @param string $messenger_name The name of the messenger being activated
3988
-     * @return bool
3989
-     * @throws DomainException
3990
-     * @throws EE_Error
3991
-     * @throws InvalidArgumentException
3992
-     * @throws ReflectionException
3993
-     * @throws InvalidDataTypeException
3994
-     * @throws InvalidInterfaceException
3995
-     */
3996
-    protected function _activate_messenger($messenger_name)
3997
-    {
3998
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3999
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4000
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger
4001
-            ? $active_messenger->get_default_message_types()
4002
-            : array();
4003
-
4004
-        // ensure is active
4005
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
4006
-
4007
-        // set response_data for reload
4008
-        foreach ($message_types_to_activate as $message_type_name) {
4009
-            /** @var EE_message_type $message_type */
4010
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4011
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4012
-                $messenger_name,
4013
-                $message_type_name
4014
-            )
4015
-                && $message_type instanceof EE_message_type
4016
-            ) {
4017
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
4018
-                if ($message_type->get_admin_settings_fields()) {
4019
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
4020
-                }
4021
-            }
4022
-        }
4023
-
4024
-        // add success message for activating messenger
4025
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4026
-    }
4027
-
4028
-
4029
-    /**
4030
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
4031
-     *
4032
-     * @param string $messenger_name The name of the messenger being activated
4033
-     * @return bool
4034
-     * @throws DomainException
4035
-     * @throws EE_Error
4036
-     * @throws InvalidArgumentException
4037
-     * @throws ReflectionException
4038
-     * @throws InvalidDataTypeException
4039
-     * @throws InvalidInterfaceException
4040
-     */
4041
-    protected function _deactivate_messenger($messenger_name)
4042
-    {
4043
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4044
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4045
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
4046
-
4047
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4048
-    }
4049
-
4050
-
4051
-    /**
4052
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4053
-     *
4054
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
4055
-     * @param string $message_type_name The name of the message type being activated for the messenger
4056
-     * @return bool
4057
-     * @throws DomainException
4058
-     * @throws EE_Error
4059
-     * @throws InvalidArgumentException
4060
-     * @throws ReflectionException
4061
-     * @throws InvalidDataTypeException
4062
-     * @throws InvalidInterfaceException
4063
-     */
4064
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4065
-    {
4066
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4067
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4068
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4069
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4070
-
4071
-        // ensure is active
4072
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
4073
-
4074
-        // set response for load
4075
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4076
-            $messenger_name,
4077
-            $message_type_name
4078
-        )
4079
-        ) {
4080
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
4081
-            if ($message_type_to_activate->get_admin_settings_fields()) {
4082
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
4083
-            }
4084
-        }
4085
-
4086
-        return $this->_setup_response_message_for_activating_messenger_with_message_types(
4087
-            $active_messenger,
4088
-            $message_type_to_activate
4089
-        );
4090
-    }
4091
-
4092
-
4093
-    /**
4094
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4095
-     *
4096
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4097
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
4098
-     * @return bool
4099
-     * @throws DomainException
4100
-     * @throws EE_Error
4101
-     * @throws InvalidArgumentException
4102
-     * @throws ReflectionException
4103
-     * @throws InvalidDataTypeException
4104
-     * @throws InvalidInterfaceException
4105
-     */
4106
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4107
-    {
4108
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4109
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4110
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4111
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4112
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4113
-
4114
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4115
-            $active_messenger,
4116
-            $message_type_to_deactivate
4117
-        );
4118
-    }
4119
-
4120
-
4121
-    /**
4122
-     * This just initializes the defaults for activating messenger and message type responses.
4123
-     */
4124
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
4125
-    {
4126
-        $this->_template_args['data']['active_mts'] = array();
4127
-        $this->_template_args['data']['mt_reload'] = array();
4128
-    }
4129
-
4130
-
4131
-    /**
4132
-     * Setup appropriate response for activating a messenger and/or message types
4133
-     *
4134
-     * @param EE_messenger         $messenger
4135
-     * @param EE_message_type|null $message_type
4136
-     * @return bool
4137
-     * @throws DomainException
4138
-     * @throws EE_Error
4139
-     * @throws InvalidArgumentException
4140
-     * @throws ReflectionException
4141
-     * @throws InvalidDataTypeException
4142
-     * @throws InvalidInterfaceException
4143
-     */
4144
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
4145
-        $messenger,
4146
-        EE_Message_Type $message_type = null
4147
-    ) {
4148
-        // if $messenger isn't a valid messenger object then get out.
4149
-        if (! $messenger instanceof EE_Messenger) {
4150
-            EE_Error::add_error(
4151
-                esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4152
-                __FILE__,
4153
-                __FUNCTION__,
4154
-                __LINE__
4155
-            );
4156
-
4157
-            return false;
4158
-        }
4159
-        // activated
4160
-        if ($this->_template_args['data']['active_mts']) {
4161
-            EE_Error::overwrite_success();
4162
-            // activated a message type with the messenger
4163
-            if ($message_type instanceof EE_message_type) {
4164
-                EE_Error::add_success(
4165
-                    sprintf(
4166
-                        esc_html__(
4167
-                            '%s message type has been successfully activated with the %s messenger',
4168
-                            'event_espresso'
4169
-                        ),
4170
-                        ucwords($message_type->label['singular']),
4171
-                        ucwords($messenger->label['singular'])
4172
-                    )
4173
-                );
4174
-
4175
-                // if message type was invoice then let's make sure we activate the invoice payment method.
4176
-                if ($message_type->name === 'invoice') {
4177
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
4178
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4179
-                    if ($pm instanceof EE_Payment_Method) {
4180
-                        EE_Error::add_attention(
4181
-                            esc_html__(
4182
-                                '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.',
4183
-                                'event_espresso'
4184
-                            )
4185
-                        );
4186
-                    }
4187
-                }
4188
-                // just toggles the entire messenger
4189
-            } else {
4190
-                EE_Error::add_success(
4191
-                    sprintf(
4192
-                        esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4193
-                        ucwords($messenger->label['singular'])
4194
-                    )
4195
-                );
4196
-            }
4197
-
4198
-            return true;
4199
-
4200
-            // possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4201
-            // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4202
-            // in which case we just give a success message for the messenger being successfully activated.
4203
-        } else {
4204
-            if (! $messenger->get_default_message_types()) {
4205
-                // messenger doesn't have any default message types so still a success.
4206
-                EE_Error::add_success(
4207
-                    sprintf(
4208
-                        esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4209
-                        ucwords($messenger->label['singular'])
4210
-                    )
4211
-                );
4212
-
4213
-                return true;
4214
-            } else {
4215
-                EE_Error::add_error(
4216
-                    $message_type instanceof EE_message_type
4217
-                        ? sprintf(
4218
-                            esc_html__(
4219
-                                '%s message type was not successfully activated with the %s messenger',
4220
-                                'event_espresso'
4221
-                            ),
4222
-                            ucwords($message_type->label['singular']),
4223
-                            ucwords($messenger->label['singular'])
4224
-                        )
4225
-                        : sprintf(
4226
-                            esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4227
-                            ucwords($messenger->label['singular'])
4228
-                        ),
4229
-                    __FILE__,
4230
-                    __FUNCTION__,
4231
-                    __LINE__
4232
-                );
4233
-
4234
-                return false;
4235
-            }
4236
-        }
4237
-    }
4238
-
4239
-
4240
-    /**
4241
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
4242
-     *
4243
-     * @param EE_messenger         $messenger
4244
-     * @param EE_message_type|null $message_type
4245
-     * @return bool
4246
-     * @throws DomainException
4247
-     * @throws EE_Error
4248
-     * @throws InvalidArgumentException
4249
-     * @throws ReflectionException
4250
-     * @throws InvalidDataTypeException
4251
-     * @throws InvalidInterfaceException
4252
-     */
4253
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4254
-        $messenger,
4255
-        EE_message_type $message_type = null
4256
-    ) {
4257
-        EE_Error::overwrite_success();
4258
-
4259
-        // if $messenger isn't a valid messenger object then get out.
4260
-        if (! $messenger instanceof EE_Messenger) {
4261
-            EE_Error::add_error(
4262
-                esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4263
-                __FILE__,
4264
-                __FUNCTION__,
4265
-                __LINE__
4266
-            );
4267
-
4268
-            return false;
4269
-        }
4270
-
4271
-        if ($message_type instanceof EE_message_type) {
4272
-            $message_type_name = $message_type->name;
4273
-            EE_Error::add_success(
4274
-                sprintf(
4275
-                    esc_html__(
4276
-                        '%s message type has been successfully deactivated for the %s messenger.',
4277
-                        'event_espresso'
4278
-                    ),
4279
-                    ucwords($message_type->label['singular']),
4280
-                    ucwords($messenger->label['singular'])
4281
-                )
4282
-            );
4283
-        } else {
4284
-            $message_type_name = '';
4285
-            EE_Error::add_success(
4286
-                sprintf(
4287
-                    esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4288
-                    ucwords($messenger->label['singular'])
4289
-                )
4290
-            );
4291
-        }
4292
-
4293
-        // if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4294
-        if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4295
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
4296
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4297
-            if ($count_updated > 0) {
4298
-                $msg = $message_type_name === 'invoice'
4299
-                    ? esc_html__(
4300
-                        '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.',
4301
-                        'event_espresso'
4302
-                    )
4303
-                    : esc_html__(
4304
-                        '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.',
4305
-                        'event_espresso'
4306
-                    );
4307
-                EE_Error::add_attention($msg);
4308
-            }
4309
-        }
4310
-
4311
-        return true;
4312
-    }
4313
-
4314
-
4315
-    /**
4316
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4317
-     *
4318
-     * @throws DomainException
4319
-     */
4320
-    public function update_mt_form()
4321
-    {
4322
-        if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4323
-            EE_Error::add_error(
4324
-                esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4325
-                __FILE__,
4326
-                __FUNCTION__,
4327
-                __LINE__
4328
-            );
4329
-            $this->_return_json();
4330
-        }
4331
-
4332
-        $message_types = $this->get_installed_message_types();
4333
-
4334
-        $message_type = $message_types[ $this->_req_data['message_type'] ];
4335
-        $messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4336
-
4337
-        $content = $this->_message_type_settings_content(
4338
-            $message_type,
4339
-            $messenger,
4340
-            true
4341
-        );
4342
-        $this->_template_args['success'] = true;
4343
-        $this->_template_args['content'] = $content;
4344
-        $this->_return_json();
4345
-    }
4346
-
4347
-
4348
-    /**
4349
-     * this handles saving the settings for a messenger or message type
4350
-     *
4351
-     */
4352
-    public function save_settings()
4353
-    {
4354
-        if (! isset($this->_req_data['type'])) {
4355
-            EE_Error::add_error(
4356
-                esc_html__(
4357
-                    'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4358
-                    'event_espresso'
4359
-                ),
4360
-                __FILE__,
4361
-                __FUNCTION__,
4362
-                __LINE__
4363
-            );
4364
-            $this->_template_args['error'] = true;
4365
-            $this->_return_json();
4366
-        }
4367
-
4368
-
4369
-        if ($this->_req_data['type'] === 'messenger') {
4370
-            // this should be an array.
4371
-            $settings = $this->_req_data['messenger_settings'];
4372
-            $messenger = $settings['messenger'];
4373
-            // let's setup the settings data
4374
-            foreach ($settings as $key => $value) {
4375
-                switch ($key) {
4376
-                    case 'messenger':
4377
-                        unset($settings['messenger']);
4378
-                        break;
4379
-                    case 'message_types':
4380
-                        unset($settings['message_types']);
4381
-                        break;
4382
-                    default:
4383
-                        $settings[ $key ] = $value;
4384
-                        break;
4385
-                }
4386
-            }
4387
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4388
-        } elseif ($this->_req_data['type'] === 'message_type') {
4389
-            $settings = $this->_req_data['message_type_settings'];
4390
-            $messenger = $settings['messenger'];
4391
-            $message_type = $settings['message_type'];
4392
-
4393
-            foreach ($settings as $key => $value) {
4394
-                switch ($key) {
4395
-                    case 'messenger':
4396
-                        unset($settings['messenger']);
4397
-                        break;
4398
-                    case 'message_type':
4399
-                        unset($settings['message_type']);
4400
-                        break;
4401
-                    default:
4402
-                        $settings[ $key ] = $value;
4403
-                        break;
4404
-                }
4405
-            }
4406
-
4407
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4408
-        }
4409
-
4410
-        // okay we should have the data all setup.  Now we just update!
4411
-        $success = $this->_message_resource_manager->update_active_messengers_option();
4412
-
4413
-        if ($success) {
4414
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
4415
-        } else {
4416
-            EE_Error::add_error(
4417
-                esc_html__(
4418
-                    'Settings did not get updated',
4419
-                    'event_espresso'
4420
-                ),
4421
-                __FILE__,
4422
-                __FUNCTION__,
4423
-                __LINE__
4424
-            );
4425
-        }
4426
-
4427
-        $this->_template_args['success'] = $success;
4428
-        $this->_return_json();
4429
-    }
4430
-
4431
-
4432
-
4433
-
4434
-    /**  EE MESSAGE PROCESSING ACTIONS **/
4435
-
4436
-
4437
-    /**
4438
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4439
-     * However, this does not send immediately, it just queues for sending.
4440
-     *
4441
-     * @since 4.9.0
4442
-     * @throws EE_Error
4443
-     * @throws InvalidDataTypeException
4444
-     * @throws InvalidInterfaceException
4445
-     * @throws InvalidArgumentException
4446
-     * @throws ReflectionException
4447
-     */
4448
-    protected function _generate_now()
4449
-    {
4450
-        EED_Messages::generate_now($this->_get_msg_ids_from_request());
4451
-        $this->_redirect_after_action(false, '', '', array(), true);
4452
-    }
4453
-
4454
-
4455
-    /**
4456
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4457
-     * are EEM_Message::status_resend or EEM_Message::status_idle
4458
-     *
4459
-     * @since 4.9.0
4460
-     * @throws EE_Error
4461
-     * @throws InvalidDataTypeException
4462
-     * @throws InvalidInterfaceException
4463
-     * @throws InvalidArgumentException
4464
-     * @throws ReflectionException
4465
-     */
4466
-    protected function _generate_and_send_now()
4467
-    {
4468
-        EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4469
-        $this->_redirect_after_action(false, '', '', array(), true);
4470
-    }
4471
-
4472
-
4473
-    /**
4474
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4475
-     *
4476
-     * @since 4.9.0
4477
-     * @throws EE_Error
4478
-     * @throws InvalidDataTypeException
4479
-     * @throws InvalidInterfaceException
4480
-     * @throws InvalidArgumentException
4481
-     * @throws ReflectionException
4482
-     */
4483
-    protected function _queue_for_resending()
4484
-    {
4485
-        EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4486
-        $this->_redirect_after_action(false, '', '', array(), true);
4487
-    }
4488
-
4489
-
4490
-    /**
4491
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4492
-     *
4493
-     * @since 4.9.0
4494
-     * @throws EE_Error
4495
-     * @throws InvalidDataTypeException
4496
-     * @throws InvalidInterfaceException
4497
-     * @throws InvalidArgumentException
4498
-     * @throws ReflectionException
4499
-     */
4500
-    protected function _send_now()
4501
-    {
4502
-        EED_Messages::send_now($this->_get_msg_ids_from_request());
4503
-        $this->_redirect_after_action(false, '', '', array(), true);
4504
-    }
4505
-
4506
-
4507
-    /**
4508
-     * Deletes EE_messages for IDs in the request.
4509
-     *
4510
-     * @since 4.9.0
4511
-     * @throws EE_Error
4512
-     * @throws InvalidDataTypeException
4513
-     * @throws InvalidInterfaceException
4514
-     * @throws InvalidArgumentException
4515
-     */
4516
-    protected function _delete_ee_messages()
4517
-    {
4518
-        $msg_ids = $this->_get_msg_ids_from_request();
4519
-        $deleted_count = 0;
4520
-        foreach ($msg_ids as $msg_id) {
4521
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4522
-                $deleted_count++;
4523
-            }
4524
-        }
4525
-        if ($deleted_count) {
4526
-            EE_Error::add_success(
4527
-                esc_html(
4528
-                    _n(
4529
-                        'Message successfully deleted',
4530
-                        'Messages successfully deleted',
4531
-                        $deleted_count,
4532
-                        'event_espresso'
4533
-                    )
4534
-                )
4535
-            );
4536
-            $this->_redirect_after_action(
4537
-                false,
4538
-                '',
4539
-                '',
4540
-                array(),
4541
-                true
4542
-            );
4543
-        } else {
4544
-            EE_Error::add_error(
4545
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4546
-                __FILE__,
4547
-                __FUNCTION__,
4548
-                __LINE__
4549
-            );
4550
-            $this->_redirect_after_action(false, '', '', array(), true);
4551
-        }
4552
-    }
4553
-
4554
-
4555
-    /**
4556
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4557
-     *
4558
-     * @since 4.9.0
4559
-     * @return array
4560
-     */
4561
-    protected function _get_msg_ids_from_request()
4562
-    {
4563
-        if (! isset($this->_req_data['MSG_ID'])) {
4564
-            return array();
4565
-        }
4566
-
4567
-        return is_array($this->_req_data['MSG_ID'])
4568
-            ? array_keys($this->_req_data['MSG_ID'])
4569
-            : array($this->_req_data['MSG_ID']);
4570
-    }
2650
+		$output = ob_get_contents();
2651
+		ob_clean();
2652
+		$this->_context_switcher = $output;
2653
+	}
2654
+
2655
+
2656
+	/**
2657
+	 * utility for sanitizing new values coming in.
2658
+	 * Note: this is only used when updating a context.
2659
+	 *
2660
+	 * @access protected
2661
+	 *
2662
+	 * @param int $index This helps us know which template field to select from the request array.
2663
+	 *
2664
+	 * @return array
2665
+	 */
2666
+	protected function _set_message_template_column_values($index)
2667
+	{
2668
+		if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2669
+			foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2670
+				$this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2671
+			}
2672
+		}
2673
+
2674
+
2675
+		$set_column_values = array(
2676
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2677
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2678
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2679
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2680
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2681
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2682
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2683
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2684
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2685
+				? absint($this->_req_data['MTP_is_global'])
2686
+				: 0,
2687
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2688
+				? absint($this->_req_data['MTP_is_override'])
2689
+				: 0,
2690
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2691
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2692
+		);
2693
+
2694
+
2695
+		return $set_column_values;
2696
+	}
2697
+
2698
+
2699
+	protected function _insert_or_update_message_template($new = false)
2700
+	{
2701
+
2702
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2703
+		$success = 0;
2704
+		$override = false;
2705
+
2706
+		// setup notices description
2707
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2708
+
2709
+		// need the message type and messenger objects to be able to use the labels for the notices
2710
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2711
+		$messenger_label = $messenger_object instanceof EE_messenger
2712
+			? ucwords($messenger_object->label['singular'])
2713
+			: '';
2714
+
2715
+		$message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2716
+			? $this->_req_data['MTP_message_type']
2717
+			: '';
2718
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2719
+
2720
+		$message_type_label = $message_type_object instanceof EE_message_type
2721
+			? ucwords($message_type_object->label['singular'])
2722
+			: '';
2723
+
2724
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2725
+			? $this->_req_data['MTP_context']
2726
+			: '';
2727
+		$context = ucwords(str_replace('_', ' ', $context_slug));
2728
+
2729
+		$item_desc = $messenger_label && $message_type_label
2730
+			? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2731
+			: '';
2732
+		$item_desc .= 'Message Template';
2733
+		$query_args = array();
2734
+		$edit_array = array();
2735
+		$action_desc = '';
2736
+
2737
+		// if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2738
+		// user to edit.
2739
+		if ($new) {
2740
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2741
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2742
+				if (empty($edit_array)) {
2743
+					$success = 0;
2744
+				} else {
2745
+					$success = 1;
2746
+					$edit_array = $edit_array[0];
2747
+					$query_args = array(
2748
+						'id'      => $edit_array['GRP_ID'],
2749
+						'context' => $edit_array['MTP_context'],
2750
+						'action'  => 'edit_message_template',
2751
+					);
2752
+				}
2753
+			}
2754
+			$action_desc = 'created';
2755
+		} else {
2756
+			$MTPG = EEM_Message_Template_Group::instance();
2757
+			$MTP = EEM_Message_Template::instance();
2758
+
2759
+
2760
+			// run update for each template field in displayed context
2761
+			if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2762
+				EE_Error::add_error(
2763
+					esc_html__(
2764
+						'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2765
+						'event_espresso'
2766
+					),
2767
+					__FILE__,
2768
+					__FUNCTION__,
2769
+					__LINE__
2770
+				);
2771
+				$success = 0;
2772
+			} else {
2773
+				// first validate all fields!
2774
+				// this filter allows client code to add its own validation to the template fields as well.
2775
+				// returning an empty array means everything passed validation.
2776
+				// errors in validation should be represented in an array with the following shape:
2777
+				// array(
2778
+				//   'fieldname' => array(
2779
+				//          'msg' => 'error message'
2780
+				//          'value' => 'value for field producing error'
2781
+				// )
2782
+				$custom_validation = (array) apply_filters(
2783
+					'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2784
+					array(),
2785
+					$this->_req_data['MTP_template_fields'],
2786
+					$context_slug,
2787
+					$messenger_slug,
2788
+					$message_type_slug
2789
+				);
2790
+
2791
+				$system_validation = $MTPG->validate(
2792
+					$this->_req_data['MTP_template_fields'],
2793
+					$context_slug,
2794
+					$messenger_slug,
2795
+					$message_type_slug
2796
+				);
2797
+
2798
+				$system_validation = ! is_array($system_validation) && $system_validation ? array()
2799
+					: $system_validation;
2800
+				$validates = array_merge($custom_validation, $system_validation);
2801
+
2802
+				// if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2803
+				// appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2804
+				//  WE need to make sure there is no actual error messages in validates.
2805
+				if (is_array($validates) && ! empty($validates)) {
2806
+					// add the transient so when the form loads we know which fields to highlight
2807
+					$this->_add_transient('edit_message_template', $validates);
2808
+
2809
+					$success = 0;
2810
+
2811
+					// setup notices
2812
+					foreach ($validates as $field => $error) {
2813
+						if (isset($error['msg'])) {
2814
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2815
+						}
2816
+					}
2817
+				} else {
2818
+					$set_column_values = array();
2819
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2820
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2821
+
2822
+						$where_cols_n_values = array(
2823
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2824
+						);
2825
+						// if they aren't allowed to use all JS, restrict them to just posty-y tags
2826
+						if (! current_user_can('unfiltered_html')) {
2827
+							if (is_array($set_column_values['MTP_content'])) {
2828
+								foreach ($set_column_values['MTP_content'] as $key => $value) {
2829
+									// remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2830
+									// only removes slashes from double-quotes, so attributes using single quotes always
2831
+									// appear invalid.) But currently the models expect slashed data, so after wp_kses
2832
+									// runs we need to re-slash the data. Sheesh. See
2833
+									// https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2834
+									$set_column_values['MTP_content'][ $key ] = addslashes(
2835
+										wp_kses(
2836
+											stripslashes($value),
2837
+											wp_kses_allowed_html('post')
2838
+										)
2839
+									);
2840
+								}
2841
+							} else {
2842
+								$set_column_values['MTP_content'] = wp_kses(
2843
+									$set_column_values['MTP_content'],
2844
+									wp_kses_allowed_html('post')
2845
+								);
2846
+							}
2847
+						}
2848
+						$message_template_fields = array(
2849
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2850
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2851
+							'MTP_context'        => $set_column_values['MTP_context'],
2852
+							'MTP_content'        => $set_column_values['MTP_content'],
2853
+						);
2854
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2855
+							if ($updated === false) {
2856
+								EE_Error::add_error(
2857
+									sprintf(
2858
+										esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2859
+										$template_field
2860
+									),
2861
+									__FILE__,
2862
+									__FUNCTION__,
2863
+									__LINE__
2864
+								);
2865
+							} else {
2866
+								$success = 1;
2867
+							}
2868
+						} else {
2869
+							// only do this logic if we don't have a MTP_ID for this field
2870
+							if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2871
+								// this has already been through the template field validator and sanitized, so it will be
2872
+								// safe to insert this field.  Why insert?  This typically happens when we introduce a new
2873
+								// message template field in a messenger/message type and existing users don't have the
2874
+								// default setup for it.
2875
+								// @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2876
+								$updated = $MTP->insert($message_template_fields);
2877
+								if (! $updated || is_wp_error($updated)) {
2878
+									EE_Error::add_error(
2879
+										sprintf(
2880
+											esc_html__('%s field could not be updated.', 'event_espresso'),
2881
+											$template_field
2882
+										),
2883
+										__FILE__,
2884
+										__FUNCTION__,
2885
+										__LINE__
2886
+									);
2887
+									$success = 0;
2888
+								} else {
2889
+									$success = 1;
2890
+								}
2891
+							}
2892
+						}
2893
+						$action_desc = 'updated';
2894
+					}
2895
+
2896
+					// we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2897
+					$mtpg_fields = array(
2898
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2899
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2900
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2901
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2902
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2903
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2904
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2905
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2906
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2907
+							: '',
2908
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2909
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2910
+							: '',
2911
+					);
2912
+
2913
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2914
+					$updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2915
+
2916
+					if ($updated === false) {
2917
+						EE_Error::add_error(
2918
+							sprintf(
2919
+								esc_html__(
2920
+									'The Message Template Group (%d) was NOT updated for some reason',
2921
+									'event_espresso'
2922
+								),
2923
+								$set_column_values['GRP_ID']
2924
+							),
2925
+							__FILE__,
2926
+							__FUNCTION__,
2927
+							__LINE__
2928
+						);
2929
+					} else {
2930
+						// k now we need to ensure the template_pack and template_variation fields are set.
2931
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2932
+							? $this->_req_data['MTP_template_pack']
2933
+							: 'default';
2934
+
2935
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2936
+							? $this->_req_data['MTP_template_variation']
2937
+							: 'default';
2938
+
2939
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2940
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2941
+							$mtpg_obj->set_template_pack_name($template_pack);
2942
+							$mtpg_obj->set_template_pack_variation($template_variation);
2943
+						}
2944
+						$success = 1;
2945
+					}
2946
+				}
2947
+			}
2948
+		}
2949
+
2950
+		// we return things differently if doing ajax
2951
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2952
+			$this->_template_args['success'] = $success;
2953
+			$this->_template_args['error'] = ! $success ? true : false;
2954
+			$this->_template_args['content'] = '';
2955
+			$this->_template_args['data'] = array(
2956
+				'grpID'        => $edit_array['GRP_ID'],
2957
+				'templateName' => $edit_array['template_name'],
2958
+			);
2959
+			if ($success) {
2960
+				EE_Error::overwrite_success();
2961
+				EE_Error::add_success(
2962
+					esc_html__(
2963
+						'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.',
2964
+						'event_espresso'
2965
+					)
2966
+				);
2967
+			}
2968
+
2969
+			$this->_return_json();
2970
+		}
2971
+
2972
+
2973
+		// was a test send triggered?
2974
+		if (isset($this->_req_data['test_button'])) {
2975
+			EE_Error::overwrite_success();
2976
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2977
+			$override = true;
2978
+		}
2979
+
2980
+		if (empty($query_args)) {
2981
+			$query_args = array(
2982
+				'id'      => $this->_req_data['GRP_ID'],
2983
+				'context' => $context_slug,
2984
+				'action'  => 'edit_message_template',
2985
+			);
2986
+		}
2987
+
2988
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2989
+	}
2990
+
2991
+
2992
+	/**
2993
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
2994
+	 *
2995
+	 * @param  string $context      what context being tested
2996
+	 * @param  string $messenger    messenger being tested
2997
+	 * @param  string $message_type message type being tested
2998
+	 * @throws EE_Error
2999
+	 * @throws InvalidArgumentException
3000
+	 * @throws InvalidDataTypeException
3001
+	 * @throws InvalidInterfaceException
3002
+	 */
3003
+	protected function _do_test_send($context, $messenger, $message_type)
3004
+	{
3005
+		// set things up for preview
3006
+		$this->_req_data['messenger'] = $messenger;
3007
+		$this->_req_data['message_type'] = $message_type;
3008
+		$this->_req_data['context'] = $context;
3009
+		$this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
3010
+		$active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
3011
+
3012
+		// let's save any existing fields that might be required by the messenger
3013
+		if (isset($this->_req_data['test_settings_fld'])
3014
+			&& $active_messenger instanceof EE_messenger
3015
+			&& apply_filters(
3016
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3017
+				true,
3018
+				$this->_req_data['test_settings_fld'],
3019
+				$active_messenger
3020
+			)
3021
+		) {
3022
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
3023
+		}
3024
+
3025
+		/**
3026
+		 * Use filter to add additional controls on whether message can send or not
3027
+		 */
3028
+		if (apply_filters(
3029
+			'FHEE__Messages_Admin_Page__do_test_send__can_send',
3030
+			true,
3031
+			$context,
3032
+			$this->_req_data,
3033
+			$messenger,
3034
+			$message_type
3035
+		)) {
3036
+			if (EEM_Event::instance()->count() > 0) {
3037
+				$success = $this->_preview_message(true);
3038
+				if ($success) {
3039
+					EE_Error::add_success(__('Test message sent', 'event_espresso'));
3040
+				} else {
3041
+					EE_Error::add_error(
3042
+						esc_html__('The test message was not sent', 'event_espresso'),
3043
+						__FILE__,
3044
+						__FUNCTION__,
3045
+						__LINE__
3046
+					);
3047
+				}
3048
+			} else {
3049
+				$this->noEventsErrorMessage(true);
3050
+			}
3051
+		}
3052
+	}
3053
+
3054
+
3055
+	/**
3056
+	 * _generate_new_templates
3057
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3058
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3059
+	 * for the event.
3060
+	 *
3061
+	 *
3062
+	 * @param  string $messenger     the messenger we are generating templates for
3063
+	 * @param array   $message_types array of message types that the templates are generated for.
3064
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3065
+	 *                               indicate the message_template_group being used as the base.
3066
+	 *
3067
+	 * @param bool    $global
3068
+	 *
3069
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
3070
+	 *                               encountering problems.
3071
+	 * @throws EE_Error
3072
+	 */
3073
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3074
+	{
3075
+
3076
+		// if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3077
+		// just don't generate any templates.
3078
+		if (empty($message_types)) {
3079
+			return true;
3080
+		}
3081
+
3082
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3083
+	}
3084
+
3085
+
3086
+	/**
3087
+	 * [_trash_or_restore_message_template]
3088
+	 *
3089
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3090
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3091
+	 *                        an individual context (FALSE).
3092
+	 * @return void
3093
+	 * @throws EE_Error
3094
+	 * @throws InvalidArgumentException
3095
+	 * @throws InvalidDataTypeException
3096
+	 * @throws InvalidInterfaceException
3097
+	 */
3098
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
3099
+	{
3100
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3101
+		$MTP = EEM_Message_Template_Group::instance();
3102
+
3103
+		$success = 1;
3104
+
3105
+		// incoming GRP_IDs
3106
+		if ($all) {
3107
+			// Checkboxes
3108
+			if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3109
+				// if array has more than one element then success message should be plural.
3110
+				// todo: what about nonce?
3111
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3112
+
3113
+				// cycle through checkboxes
3114
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3115
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3116
+					if (! $trashed_or_restored) {
3117
+						$success = 0;
3118
+					}
3119
+				}
3120
+			} else {
3121
+				// grab single GRP_ID and handle
3122
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3123
+				if (! empty($GRP_ID)) {
3124
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3125
+					if (! $trashed_or_restored) {
3126
+						$success = 0;
3127
+					}
3128
+				} else {
3129
+					$success = 0;
3130
+				}
3131
+			}
3132
+		}
3133
+
3134
+		$action_desc = $trash
3135
+			? esc_html__('moved to the trash', 'event_espresso')
3136
+			: esc_html__('restored', 'event_espresso');
3137
+
3138
+		$action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3139
+
3140
+		$item_desc = $all ? _n(
3141
+			'Message Template Group',
3142
+			'Message Template Groups',
3143
+			$success,
3144
+			'event_espresso'
3145
+		) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3146
+
3147
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3148
+			'template',
3149
+			'templates',
3150
+			$success,
3151
+			'event_espresso'
3152
+		) : $item_desc;
3153
+
3154
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
3155
+	}
3156
+
3157
+
3158
+	/**
3159
+	 * [_delete_message_template]
3160
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3161
+	 *
3162
+	 * @return void
3163
+	 * @throws EE_Error
3164
+	 * @throws InvalidArgumentException
3165
+	 * @throws InvalidDataTypeException
3166
+	 * @throws InvalidInterfaceException
3167
+	 */
3168
+	protected function _delete_message_template()
3169
+	{
3170
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3171
+
3172
+		// checkboxes
3173
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3174
+			// if array has more than one element then success message should be plural
3175
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3176
+
3177
+			// cycle through bulk action checkboxes
3178
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3179
+				$success = $this->_delete_mtp_permanently($GRP_ID);
3180
+			}
3181
+		} else {
3182
+			// grab single grp_id and delete
3183
+			$GRP_ID = absint($this->_req_data['id']);
3184
+			$success = $this->_delete_mtp_permanently($GRP_ID);
3185
+		}
3186
+
3187
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3188
+	}
3189
+
3190
+
3191
+	/**
3192
+	 * helper for permanently deleting a mtP group and all related message_templates
3193
+	 *
3194
+	 * @param  int  $GRP_ID        The group being deleted
3195
+	 * @param  bool $include_group whether to delete the Message Template Group as well.
3196
+	 * @return bool boolean to indicate the success of the deletes or not.
3197
+	 * @throws EE_Error
3198
+	 * @throws InvalidArgumentException
3199
+	 * @throws InvalidDataTypeException
3200
+	 * @throws InvalidInterfaceException
3201
+	 */
3202
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3203
+	{
3204
+		$success = 1;
3205
+		$MTPG = EEM_Message_Template_Group::instance();
3206
+		// first let's GET this group
3207
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
3208
+		// then delete permanently all the related Message Templates
3209
+		$deleted = $MTG->delete_related_permanently('Message_Template');
3210
+
3211
+		if ($deleted === 0) {
3212
+			$success = 0;
3213
+		}
3214
+
3215
+		// now delete permanently this particular group
3216
+
3217
+		if ($include_group && ! $MTG->delete_permanently()) {
3218
+			$success = 0;
3219
+		}
3220
+
3221
+		return $success;
3222
+	}
3223
+
3224
+
3225
+	/**
3226
+	 *    _learn_more_about_message_templates_link
3227
+	 *
3228
+	 * @access protected
3229
+	 * @return string
3230
+	 */
3231
+	protected function _learn_more_about_message_templates_link()
3232
+	{
3233
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3234
+			   . esc_html__('learn more about how message templates works', 'event_espresso')
3235
+			   . '</a>';
3236
+	}
3237
+
3238
+
3239
+	/**
3240
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3241
+	 * ajax and other routes.
3242
+	 *
3243
+	 * @return void
3244
+	 * @throws DomainException
3245
+	 */
3246
+	protected function _settings()
3247
+	{
3248
+
3249
+
3250
+		$this->_set_m_mt_settings();
3251
+
3252
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3253
+			? $this->_req_data['selected_messenger']
3254
+			: 'email';
3255
+
3256
+		// let's setup the messenger tabs
3257
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3258
+			$this->_m_mt_settings['messenger_tabs'],
3259
+			'messenger_links',
3260
+			'|',
3261
+			$selected_messenger
3262
+		);
3263
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3264
+		$this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3265
+
3266
+		$this->display_admin_page_with_sidebar();
3267
+	}
3268
+
3269
+
3270
+	/**
3271
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3272
+	 *
3273
+	 * @access protected
3274
+	 * @return void
3275
+	 * @throws DomainException
3276
+	 */
3277
+	protected function _set_m_mt_settings()
3278
+	{
3279
+		// first if this is already set then lets get out no need to regenerate data.
3280
+		if (! empty($this->_m_mt_settings)) {
3281
+			return;
3282
+		}
3283
+
3284
+		// get all installed messengers and message_types
3285
+		/** @type EE_messenger[] $messengers */
3286
+		$messengers = $this->_message_resource_manager->installed_messengers();
3287
+		/** @type EE_message_type[] $message_types */
3288
+		$message_types = $this->_message_resource_manager->installed_message_types();
3289
+
3290
+
3291
+		// assemble the array for the _tab_text_links helper
3292
+
3293
+		foreach ($messengers as $messenger) {
3294
+			$this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3295
+				'label' => ucwords($messenger->label['singular']),
3296
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3297
+					? 'messenger-active'
3298
+					: '',
3299
+				'href'  => $messenger->name,
3300
+				'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3301
+				'slug'  => $messenger->name,
3302
+				'obj'   => $messenger,
3303
+			);
3304
+
3305
+
3306
+			$message_types_for_messenger = $messenger->get_valid_message_types();
3307
+
3308
+			foreach ($message_types as $message_type) {
3309
+				// first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3310
+				// it shouldn't show in either the inactive OR active metabox.
3311
+				if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3312
+					continue;
3313
+				}
3314
+
3315
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3316
+					$messenger->name,
3317
+					$message_type->name
3318
+				)
3319
+					? 'active'
3320
+					: 'inactive';
3321
+
3322
+				$this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3323
+					'label'    => ucwords($message_type->label['singular']),
3324
+					'class'    => 'message-type-' . $a_or_i,
3325
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3326
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3327
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3328
+					'title'    => $a_or_i === 'active'
3329
+						? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3330
+						: esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3331
+					'content'  => $a_or_i === 'active'
3332
+						? $this->_message_type_settings_content($message_type, $messenger, true)
3333
+						: $this->_message_type_settings_content($message_type, $messenger),
3334
+					'slug'     => $message_type->name,
3335
+					'active'   => $a_or_i === 'active',
3336
+					'obj'      => $message_type,
3337
+				);
3338
+			}
3339
+		}
3340
+	}
3341
+
3342
+
3343
+	/**
3344
+	 * This just prepares the content for the message type settings
3345
+	 *
3346
+	 * @param  EE_message_type $message_type The message type object
3347
+	 * @param  EE_messenger    $messenger    The messenger object
3348
+	 * @param  boolean         $active       Whether the message type is active or not
3349
+	 * @return string html output for the content
3350
+	 * @throws DomainException
3351
+	 */
3352
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
3353
+	{
3354
+		// get message type fields
3355
+		$fields = $message_type->get_admin_settings_fields();
3356
+		$settings_template_args['template_form_fields'] = '';
3357
+
3358
+		if (! empty($fields) && $active) {
3359
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3360
+			foreach ($fields as $fldname => $fldprops) {
3361
+				$field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3362
+				$template_form_field[ $field_id ] = array(
3363
+					'name'       => 'message_type_settings[' . $fldname . ']',
3364
+					'label'      => $fldprops['label'],
3365
+					'input'      => $fldprops['field_type'],
3366
+					'type'       => $fldprops['value_type'],
3367
+					'required'   => $fldprops['required'],
3368
+					'validation' => $fldprops['validation'],
3369
+					'value'      => isset($existing_settings[ $fldname ])
3370
+						? $existing_settings[ $fldname ]
3371
+						: $fldprops['default'],
3372
+					'options'    => isset($fldprops['options'])
3373
+						? $fldprops['options']
3374
+						: array(),
3375
+					'default'    => isset($existing_settings[ $fldname ])
3376
+						? $existing_settings[ $fldname ]
3377
+						: $fldprops['default'],
3378
+					'css_class'  => 'no-drag',
3379
+					'format'     => $fldprops['format'],
3380
+				);
3381
+			}
3382
+
3383
+
3384
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3385
+				? $this->_generate_admin_form_fields(
3386
+					$template_form_field,
3387
+					'string',
3388
+					'ee_mt_activate_form'
3389
+				)
3390
+				: '';
3391
+		}
3392
+
3393
+		$settings_template_args['description'] = $message_type->description;
3394
+		// we also need some hidden fields
3395
+		$settings_template_args['hidden_fields'] = array(
3396
+			'message_type_settings[messenger]'    => array(
3397
+				'type'  => 'hidden',
3398
+				'value' => $messenger->name,
3399
+			),
3400
+			'message_type_settings[message_type]' => array(
3401
+				'type'  => 'hidden',
3402
+				'value' => $message_type->name,
3403
+			),
3404
+			'type'                                => array(
3405
+				'type'  => 'hidden',
3406
+				'value' => 'message_type',
3407
+			),
3408
+		);
3409
+
3410
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3411
+			$settings_template_args['hidden_fields'],
3412
+			'array'
3413
+		);
3414
+		$settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3415
+			? ' hidden'
3416
+			: '';
3417
+
3418
+
3419
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3420
+		$content = EEH_Template::display_template($template, $settings_template_args, true);
3421
+
3422
+		return $content;
3423
+	}
3424
+
3425
+
3426
+	/**
3427
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
3428
+	 *
3429
+	 * @access protected
3430
+	 * @return void
3431
+	 * @throws DomainException
3432
+	 */
3433
+	protected function _messages_settings_metaboxes()
3434
+	{
3435
+		$this->_set_m_mt_settings();
3436
+		$m_boxes = $mt_boxes = array();
3437
+		$m_template_args = $mt_template_args = array();
3438
+
3439
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3440
+			? $this->_req_data['selected_messenger']
3441
+			: 'email';
3442
+
3443
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
3444
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3445
+				$hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3446
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3447
+				// messenger meta boxes
3448
+				$active = $selected_messenger === $messenger;
3449
+				$active_mt_tabs = isset(
3450
+					$this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3451
+				)
3452
+					? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3453
+					: '';
3454
+				$m_boxes[ $messenger . '_a_box' ] = sprintf(
3455
+					esc_html__('%s Settings', 'event_espresso'),
3456
+					$tab_array['label']
3457
+				);
3458
+				$m_template_args[ $messenger . '_a_box' ] = array(
3459
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3460
+					'inactive_message_types' => isset(
3461
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3462
+					)
3463
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3464
+						: '',
3465
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3466
+					'hidden'                 => $active ? '' : ' hidden',
3467
+					'hide_on_message'        => $hide_on_message,
3468
+					'messenger'              => $messenger,
3469
+					'active'                 => $active,
3470
+				);
3471
+				// message type meta boxes
3472
+				// (which is really just the inactive container for each messenger
3473
+				// showing inactive message types for that messenger)
3474
+				$mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3475
+				$mt_template_args[ $messenger . '_i_box' ] = array(
3476
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3477
+					'inactive_message_types' => isset(
3478
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3479
+					)
3480
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3481
+						: '',
3482
+					'hidden'                 => $active ? '' : ' hidden',
3483
+					'hide_on_message'        => $hide_on_message,
3484
+					'hide_off_message'       => $hide_off_message,
3485
+					'messenger'              => $messenger,
3486
+					'active'                 => $active,
3487
+				);
3488
+			}
3489
+		}
3490
+
3491
+
3492
+		// register messenger metaboxes
3493
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3494
+		foreach ($m_boxes as $box => $label) {
3495
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3496
+			$msgr = str_replace('_a_box', '', $box);
3497
+			add_meta_box(
3498
+				'espresso_' . $msgr . '_settings',
3499
+				$label,
3500
+				function ($post, $metabox) {
3501
+					echo EEH_Template::display_template(
3502
+						$metabox["args"]["template_path"],
3503
+						$metabox["args"]["template_args"],
3504
+						true
3505
+					);
3506
+				},
3507
+				$this->_current_screen->id,
3508
+				'normal',
3509
+				'high',
3510
+				$callback_args
3511
+			);
3512
+		}
3513
+
3514
+		// register message type metaboxes
3515
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3516
+		foreach ($mt_boxes as $box => $label) {
3517
+			$callback_args = array(
3518
+				'template_path' => $mt_template_path,
3519
+				'template_args' => $mt_template_args[ $box ],
3520
+			);
3521
+			$mt = str_replace('_i_box', '', $box);
3522
+			add_meta_box(
3523
+				'espresso_' . $mt . '_inactive_mts',
3524
+				$label,
3525
+				function ($post, $metabox) {
3526
+					echo EEH_Template::display_template(
3527
+						$metabox["args"]["template_path"],
3528
+						$metabox["args"]["template_args"],
3529
+						true
3530
+					);
3531
+				},
3532
+				$this->_current_screen->id,
3533
+				'side',
3534
+				'high',
3535
+				$callback_args
3536
+			);
3537
+		}
3538
+
3539
+		// register metabox for global messages settings but only when on the main site.  On single site installs this
3540
+		// will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3541
+		if (is_main_site()) {
3542
+			add_meta_box(
3543
+				'espresso_global_message_settings',
3544
+				esc_html__('Global Message Settings', 'event_espresso'),
3545
+				array($this, 'global_messages_settings_metabox_content'),
3546
+				$this->_current_screen->id,
3547
+				'normal',
3548
+				'low',
3549
+				array()
3550
+			);
3551
+		}
3552
+	}
3553
+
3554
+
3555
+	/**
3556
+	 *  This generates the content for the global messages settings metabox.
3557
+	 *
3558
+	 * @return string
3559
+	 * @throws EE_Error
3560
+	 * @throws InvalidArgumentException
3561
+	 * @throws ReflectionException
3562
+	 * @throws InvalidDataTypeException
3563
+	 * @throws InvalidInterfaceException
3564
+	 */
3565
+	public function global_messages_settings_metabox_content()
3566
+	{
3567
+		$form = $this->_generate_global_settings_form();
3568
+		echo $form->form_open(
3569
+			$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3570
+			'POST'
3571
+		)
3572
+			 . $form->get_html()
3573
+			 . $form->form_close();
3574
+	}
3575
+
3576
+
3577
+	/**
3578
+	 * This generates and returns the form object for the global messages settings.
3579
+	 *
3580
+	 * @return EE_Form_Section_Proper
3581
+	 * @throws EE_Error
3582
+	 * @throws InvalidArgumentException
3583
+	 * @throws ReflectionException
3584
+	 * @throws InvalidDataTypeException
3585
+	 * @throws InvalidInterfaceException
3586
+	 */
3587
+	protected function _generate_global_settings_form()
3588
+	{
3589
+		EE_Registry::instance()->load_helper('HTML');
3590
+		/** @var EE_Network_Core_Config $network_config */
3591
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3592
+
3593
+		return new EE_Form_Section_Proper(
3594
+			array(
3595
+				'name'            => 'global_messages_settings',
3596
+				'html_id'         => 'global_messages_settings',
3597
+				'html_class'      => 'form-table',
3598
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3599
+				'subsections'     => apply_filters(
3600
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3601
+					array(
3602
+						'do_messages_on_same_request' => new EE_Select_Input(
3603
+							array(
3604
+								true  => esc_html__("On the same request", "event_espresso"),
3605
+								false => esc_html__("On a separate request", "event_espresso"),
3606
+							),
3607
+							array(
3608
+								'default'         => $network_config->do_messages_on_same_request,
3609
+								'html_label_text' => esc_html__(
3610
+									'Generate and send all messages:',
3611
+									'event_espresso'
3612
+								),
3613
+								'html_help_text'  => esc_html__(
3614
+									'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.',
3615
+									'event_espresso'
3616
+								),
3617
+							)
3618
+						),
3619
+						'delete_threshold'            => new EE_Select_Input(
3620
+							array(
3621
+								0  => esc_html__('Forever', 'event_espresso'),
3622
+								3  => esc_html__('3 Months', 'event_espresso'),
3623
+								6  => esc_html__('6 Months', 'event_espresso'),
3624
+								9  => esc_html__('9 Months', 'event_espresso'),
3625
+								12 => esc_html__('12 Months', 'event_espresso'),
3626
+								24 => esc_html__('24 Months', 'event_espresso'),
3627
+								36 => esc_html__('36 Months', 'event_espresso'),
3628
+							),
3629
+							array(
3630
+								'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3631
+								'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3632
+								'html_help_text'  => esc_html__(
3633
+									'You can control how long a record of processed messages is kept via this option.',
3634
+									'event_espresso'
3635
+								),
3636
+							)
3637
+						),
3638
+						'update_settings'             => new EE_Submit_Input(
3639
+							array(
3640
+								'default'         => esc_html__('Update', 'event_espresso'),
3641
+								'html_label_text' => '&nbsp',
3642
+							)
3643
+						),
3644
+					)
3645
+				),
3646
+			)
3647
+		);
3648
+	}
3649
+
3650
+
3651
+	/**
3652
+	 * This handles updating the global settings set on the admin page.
3653
+	 *
3654
+	 * @throws EE_Error
3655
+	 * @throws InvalidDataTypeException
3656
+	 * @throws InvalidInterfaceException
3657
+	 * @throws InvalidArgumentException
3658
+	 * @throws ReflectionException
3659
+	 */
3660
+	protected function _update_global_settings()
3661
+	{
3662
+		/** @var EE_Network_Core_Config $network_config */
3663
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3664
+		$messages_config = EE_Registry::instance()->CFG->messages;
3665
+		$form = $this->_generate_global_settings_form();
3666
+		if ($form->was_submitted()) {
3667
+			$form->receive_form_submission();
3668
+			if ($form->is_valid()) {
3669
+				$valid_data = $form->valid_data();
3670
+				foreach ($valid_data as $property => $value) {
3671
+					$setter = 'set_' . $property;
3672
+					if (method_exists($network_config, $setter)) {
3673
+						$network_config->{$setter}($value);
3674
+					} elseif (property_exists($network_config, $property)
3675
+						&& $network_config->{$property} !== $value
3676
+					) {
3677
+						$network_config->{$property} = $value;
3678
+					} elseif (property_exists($messages_config, $property)
3679
+						&& $messages_config->{$property} !== $value
3680
+					) {
3681
+						$messages_config->{$property} = $value;
3682
+					}
3683
+				}
3684
+				// only update if the form submission was valid!
3685
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3686
+				EE_Registry::instance()->CFG->update_espresso_config();
3687
+				EE_Error::overwrite_success();
3688
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3689
+			}
3690
+		}
3691
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3692
+	}
3693
+
3694
+
3695
+	/**
3696
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3697
+	 *
3698
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3699
+	 * @return string html formatted tabs
3700
+	 * @throws DomainException
3701
+	 */
3702
+	protected function _get_mt_tabs($tab_array)
3703
+	{
3704
+		$tab_array = (array) $tab_array;
3705
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3706
+		$tabs = '';
3707
+
3708
+		foreach ($tab_array as $tab) {
3709
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3710
+		}
3711
+
3712
+		return $tabs;
3713
+	}
3714
+
3715
+
3716
+	/**
3717
+	 * This prepares the content of the messenger meta box admin settings
3718
+	 *
3719
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3720
+	 * @return string html formatted content
3721
+	 * @throws DomainException
3722
+	 */
3723
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3724
+	{
3725
+
3726
+		$fields = $messenger->get_admin_settings_fields();
3727
+		$settings_template_args['template_form_fields'] = '';
3728
+
3729
+		// is $messenger active?
3730
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3731
+
3732
+
3733
+		if (! empty($fields)) {
3734
+			$existing_settings = $messenger->get_existing_admin_settings();
3735
+
3736
+			foreach ($fields as $fldname => $fldprops) {
3737
+				$field_id = $messenger->name . '-' . $fldname;
3738
+				$template_form_field[ $field_id ] = array(
3739
+					'name'       => 'messenger_settings[' . $field_id . ']',
3740
+					'label'      => $fldprops['label'],
3741
+					'input'      => $fldprops['field_type'],
3742
+					'type'       => $fldprops['value_type'],
3743
+					'required'   => $fldprops['required'],
3744
+					'validation' => $fldprops['validation'],
3745
+					'value'      => isset($existing_settings[ $field_id ])
3746
+						? $existing_settings[ $field_id ]
3747
+						: $fldprops['default'],
3748
+					'css_class'  => '',
3749
+					'format'     => $fldprops['format'],
3750
+				);
3751
+			}
3752
+
3753
+
3754
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3755
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3756
+				: '';
3757
+		}
3758
+
3759
+		// we also need some hidden fields
3760
+		$settings_template_args['hidden_fields'] = array(
3761
+			'messenger_settings[messenger]' => array(
3762
+				'type'  => 'hidden',
3763
+				'value' => $messenger->name,
3764
+			),
3765
+			'type'                          => array(
3766
+				'type'  => 'hidden',
3767
+				'value' => 'messenger',
3768
+			),
3769
+		);
3770
+
3771
+		// make sure any active message types that are existing are included in the hidden fields
3772
+		if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3773
+			foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3774
+				$settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3775
+					'type'  => 'hidden',
3776
+					'value' => $mt,
3777
+				);
3778
+			}
3779
+		}
3780
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3781
+			$settings_template_args['hidden_fields'],
3782
+			'array'
3783
+		);
3784
+		$active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3785
+
3786
+		$settings_template_args['messenger'] = $messenger->name;
3787
+		$settings_template_args['description'] = $messenger->description;
3788
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3789
+
3790
+
3791
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3792
+			$messenger->name
3793
+		)
3794
+			? $settings_template_args['show_hide_edit_form']
3795
+			: ' hidden';
3796
+
3797
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3798
+			? ' hidden'
3799
+			: $settings_template_args['show_hide_edit_form'];
3800
+
3801
+
3802
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3803
+		$settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3804
+		$settings_template_args['on_off_status'] = $active ? true : false;
3805
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3806
+		$content = EEH_Template::display_template(
3807
+			$template,
3808
+			$settings_template_args,
3809
+			true
3810
+		);
3811
+
3812
+		return $content;
3813
+	}
3814
+
3815
+
3816
+	/**
3817
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3818
+	 *
3819
+	 * @throws DomainException
3820
+	 * @throws EE_Error
3821
+	 * @throws InvalidDataTypeException
3822
+	 * @throws InvalidInterfaceException
3823
+	 * @throws InvalidArgumentException
3824
+	 * @throws ReflectionException
3825
+	 */
3826
+	public function activate_messenger_toggle()
3827
+	{
3828
+		$success = true;
3829
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3830
+		// let's check that we have required data
3831
+		if (! isset($this->_req_data['messenger'])) {
3832
+			EE_Error::add_error(
3833
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3834
+				__FILE__,
3835
+				__FUNCTION__,
3836
+				__LINE__
3837
+			);
3838
+			$success = false;
3839
+		}
3840
+
3841
+		// do a nonce check here since we're not arriving via a normal route
3842
+		$nonce = isset($this->_req_data['activate_nonce'])
3843
+			? sanitize_text_field($this->_req_data['activate_nonce'])
3844
+			: '';
3845
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3846
+
3847
+		$this->_verify_nonce($nonce, $nonce_ref);
3848
+
3849
+
3850
+		if (! isset($this->_req_data['status'])) {
3851
+			EE_Error::add_error(
3852
+				esc_html__(
3853
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3854
+					'event_espresso'
3855
+				),
3856
+				__FILE__,
3857
+				__FUNCTION__,
3858
+				__LINE__
3859
+			);
3860
+			$success = false;
3861
+		}
3862
+
3863
+		// do check to verify we have a valid status.
3864
+		$status = $this->_req_data['status'];
3865
+
3866
+		if ($status !== 'off' && $status !== 'on') {
3867
+			EE_Error::add_error(
3868
+				sprintf(
3869
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3870
+					$this->_req_data['status']
3871
+				),
3872
+				__FILE__,
3873
+				__FUNCTION__,
3874
+				__LINE__
3875
+			);
3876
+			$success = false;
3877
+		}
3878
+
3879
+		if ($success) {
3880
+			// made it here?  Stop dawdling then!!
3881
+			$success = $status === 'off'
3882
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3883
+				: $this->_activate_messenger($this->_req_data['messenger']);
3884
+		}
3885
+
3886
+		$this->_template_args['success'] = $success;
3887
+
3888
+		// no special instructions so let's just do the json return (which should automatically do all the special stuff).
3889
+		$this->_return_json();
3890
+	}
3891
+
3892
+
3893
+	/**
3894
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3895
+	 *
3896
+	 * @throws DomainException
3897
+	 * @throws EE_Error
3898
+	 * @throws ReflectionException
3899
+	 * @throws InvalidDataTypeException
3900
+	 * @throws InvalidInterfaceException
3901
+	 * @throws InvalidArgumentException
3902
+	 */
3903
+	public function activate_mt_toggle()
3904
+	{
3905
+		$success = true;
3906
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3907
+
3908
+		// let's make sure we have the necessary data
3909
+		if (! isset($this->_req_data['message_type'])) {
3910
+			EE_Error::add_error(
3911
+				esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3912
+				__FILE__,
3913
+				__FUNCTION__,
3914
+				__LINE__
3915
+			);
3916
+			$success = false;
3917
+		}
3918
+
3919
+		if (! isset($this->_req_data['messenger'])) {
3920
+			EE_Error::add_error(
3921
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3922
+				__FILE__,
3923
+				__FUNCTION__,
3924
+				__LINE__
3925
+			);
3926
+			$success = false;
3927
+		}
3928
+
3929
+		if (! isset($this->_req_data['status'])) {
3930
+			EE_Error::add_error(
3931
+				esc_html__(
3932
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3933
+					'event_espresso'
3934
+				),
3935
+				__FILE__,
3936
+				__FUNCTION__,
3937
+				__LINE__
3938
+			);
3939
+			$success = false;
3940
+		}
3941
+
3942
+
3943
+		// do check to verify we have a valid status.
3944
+		$status = $this->_req_data['status'];
3945
+
3946
+		if ($status !== 'activate' && $status !== 'deactivate') {
3947
+			EE_Error::add_error(
3948
+				sprintf(
3949
+					esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3950
+					$this->_req_data['status']
3951
+				),
3952
+				__FILE__,
3953
+				__FUNCTION__,
3954
+				__LINE__
3955
+			);
3956
+			$success = false;
3957
+		}
3958
+
3959
+
3960
+		// do a nonce check here since we're not arriving via a normal route
3961
+		$nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3962
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3963
+
3964
+		$this->_verify_nonce($nonce, $nonce_ref);
3965
+
3966
+		if ($success) {
3967
+			// made it here? um, what are you waiting for then?
3968
+			$success = $status === 'deactivate'
3969
+				? $this->_deactivate_message_type_for_messenger(
3970
+					$this->_req_data['messenger'],
3971
+					$this->_req_data['message_type']
3972
+				)
3973
+				: $this->_activate_message_type_for_messenger(
3974
+					$this->_req_data['messenger'],
3975
+					$this->_req_data['message_type']
3976
+				);
3977
+		}
3978
+
3979
+		$this->_template_args['success'] = $success;
3980
+		$this->_return_json();
3981
+	}
3982
+
3983
+
3984
+	/**
3985
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
3986
+	 *
3987
+	 * @param string $messenger_name The name of the messenger being activated
3988
+	 * @return bool
3989
+	 * @throws DomainException
3990
+	 * @throws EE_Error
3991
+	 * @throws InvalidArgumentException
3992
+	 * @throws ReflectionException
3993
+	 * @throws InvalidDataTypeException
3994
+	 * @throws InvalidInterfaceException
3995
+	 */
3996
+	protected function _activate_messenger($messenger_name)
3997
+	{
3998
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3999
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4000
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger
4001
+			? $active_messenger->get_default_message_types()
4002
+			: array();
4003
+
4004
+		// ensure is active
4005
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
4006
+
4007
+		// set response_data for reload
4008
+		foreach ($message_types_to_activate as $message_type_name) {
4009
+			/** @var EE_message_type $message_type */
4010
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4011
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4012
+				$messenger_name,
4013
+				$message_type_name
4014
+			)
4015
+				&& $message_type instanceof EE_message_type
4016
+			) {
4017
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
4018
+				if ($message_type->get_admin_settings_fields()) {
4019
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
4020
+				}
4021
+			}
4022
+		}
4023
+
4024
+		// add success message for activating messenger
4025
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4026
+	}
4027
+
4028
+
4029
+	/**
4030
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
4031
+	 *
4032
+	 * @param string $messenger_name The name of the messenger being activated
4033
+	 * @return bool
4034
+	 * @throws DomainException
4035
+	 * @throws EE_Error
4036
+	 * @throws InvalidArgumentException
4037
+	 * @throws ReflectionException
4038
+	 * @throws InvalidDataTypeException
4039
+	 * @throws InvalidInterfaceException
4040
+	 */
4041
+	protected function _deactivate_messenger($messenger_name)
4042
+	{
4043
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4044
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4045
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
4046
+
4047
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4048
+	}
4049
+
4050
+
4051
+	/**
4052
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4053
+	 *
4054
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
4055
+	 * @param string $message_type_name The name of the message type being activated for the messenger
4056
+	 * @return bool
4057
+	 * @throws DomainException
4058
+	 * @throws EE_Error
4059
+	 * @throws InvalidArgumentException
4060
+	 * @throws ReflectionException
4061
+	 * @throws InvalidDataTypeException
4062
+	 * @throws InvalidInterfaceException
4063
+	 */
4064
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4065
+	{
4066
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4067
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4068
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4069
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4070
+
4071
+		// ensure is active
4072
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
4073
+
4074
+		// set response for load
4075
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4076
+			$messenger_name,
4077
+			$message_type_name
4078
+		)
4079
+		) {
4080
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
4081
+			if ($message_type_to_activate->get_admin_settings_fields()) {
4082
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
4083
+			}
4084
+		}
4085
+
4086
+		return $this->_setup_response_message_for_activating_messenger_with_message_types(
4087
+			$active_messenger,
4088
+			$message_type_to_activate
4089
+		);
4090
+	}
4091
+
4092
+
4093
+	/**
4094
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4095
+	 *
4096
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4097
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
4098
+	 * @return bool
4099
+	 * @throws DomainException
4100
+	 * @throws EE_Error
4101
+	 * @throws InvalidArgumentException
4102
+	 * @throws ReflectionException
4103
+	 * @throws InvalidDataTypeException
4104
+	 * @throws InvalidInterfaceException
4105
+	 */
4106
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4107
+	{
4108
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4109
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4110
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4111
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4112
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4113
+
4114
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4115
+			$active_messenger,
4116
+			$message_type_to_deactivate
4117
+		);
4118
+	}
4119
+
4120
+
4121
+	/**
4122
+	 * This just initializes the defaults for activating messenger and message type responses.
4123
+	 */
4124
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
4125
+	{
4126
+		$this->_template_args['data']['active_mts'] = array();
4127
+		$this->_template_args['data']['mt_reload'] = array();
4128
+	}
4129
+
4130
+
4131
+	/**
4132
+	 * Setup appropriate response for activating a messenger and/or message types
4133
+	 *
4134
+	 * @param EE_messenger         $messenger
4135
+	 * @param EE_message_type|null $message_type
4136
+	 * @return bool
4137
+	 * @throws DomainException
4138
+	 * @throws EE_Error
4139
+	 * @throws InvalidArgumentException
4140
+	 * @throws ReflectionException
4141
+	 * @throws InvalidDataTypeException
4142
+	 * @throws InvalidInterfaceException
4143
+	 */
4144
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
4145
+		$messenger,
4146
+		EE_Message_Type $message_type = null
4147
+	) {
4148
+		// if $messenger isn't a valid messenger object then get out.
4149
+		if (! $messenger instanceof EE_Messenger) {
4150
+			EE_Error::add_error(
4151
+				esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4152
+				__FILE__,
4153
+				__FUNCTION__,
4154
+				__LINE__
4155
+			);
4156
+
4157
+			return false;
4158
+		}
4159
+		// activated
4160
+		if ($this->_template_args['data']['active_mts']) {
4161
+			EE_Error::overwrite_success();
4162
+			// activated a message type with the messenger
4163
+			if ($message_type instanceof EE_message_type) {
4164
+				EE_Error::add_success(
4165
+					sprintf(
4166
+						esc_html__(
4167
+							'%s message type has been successfully activated with the %s messenger',
4168
+							'event_espresso'
4169
+						),
4170
+						ucwords($message_type->label['singular']),
4171
+						ucwords($messenger->label['singular'])
4172
+					)
4173
+				);
4174
+
4175
+				// if message type was invoice then let's make sure we activate the invoice payment method.
4176
+				if ($message_type->name === 'invoice') {
4177
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
4178
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4179
+					if ($pm instanceof EE_Payment_Method) {
4180
+						EE_Error::add_attention(
4181
+							esc_html__(
4182
+								'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.',
4183
+								'event_espresso'
4184
+							)
4185
+						);
4186
+					}
4187
+				}
4188
+				// just toggles the entire messenger
4189
+			} else {
4190
+				EE_Error::add_success(
4191
+					sprintf(
4192
+						esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4193
+						ucwords($messenger->label['singular'])
4194
+					)
4195
+				);
4196
+			}
4197
+
4198
+			return true;
4199
+
4200
+			// possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4201
+			// message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4202
+			// in which case we just give a success message for the messenger being successfully activated.
4203
+		} else {
4204
+			if (! $messenger->get_default_message_types()) {
4205
+				// messenger doesn't have any default message types so still a success.
4206
+				EE_Error::add_success(
4207
+					sprintf(
4208
+						esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4209
+						ucwords($messenger->label['singular'])
4210
+					)
4211
+				);
4212
+
4213
+				return true;
4214
+			} else {
4215
+				EE_Error::add_error(
4216
+					$message_type instanceof EE_message_type
4217
+						? sprintf(
4218
+							esc_html__(
4219
+								'%s message type was not successfully activated with the %s messenger',
4220
+								'event_espresso'
4221
+							),
4222
+							ucwords($message_type->label['singular']),
4223
+							ucwords($messenger->label['singular'])
4224
+						)
4225
+						: sprintf(
4226
+							esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4227
+							ucwords($messenger->label['singular'])
4228
+						),
4229
+					__FILE__,
4230
+					__FUNCTION__,
4231
+					__LINE__
4232
+				);
4233
+
4234
+				return false;
4235
+			}
4236
+		}
4237
+	}
4238
+
4239
+
4240
+	/**
4241
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
4242
+	 *
4243
+	 * @param EE_messenger         $messenger
4244
+	 * @param EE_message_type|null $message_type
4245
+	 * @return bool
4246
+	 * @throws DomainException
4247
+	 * @throws EE_Error
4248
+	 * @throws InvalidArgumentException
4249
+	 * @throws ReflectionException
4250
+	 * @throws InvalidDataTypeException
4251
+	 * @throws InvalidInterfaceException
4252
+	 */
4253
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4254
+		$messenger,
4255
+		EE_message_type $message_type = null
4256
+	) {
4257
+		EE_Error::overwrite_success();
4258
+
4259
+		// if $messenger isn't a valid messenger object then get out.
4260
+		if (! $messenger instanceof EE_Messenger) {
4261
+			EE_Error::add_error(
4262
+				esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4263
+				__FILE__,
4264
+				__FUNCTION__,
4265
+				__LINE__
4266
+			);
4267
+
4268
+			return false;
4269
+		}
4270
+
4271
+		if ($message_type instanceof EE_message_type) {
4272
+			$message_type_name = $message_type->name;
4273
+			EE_Error::add_success(
4274
+				sprintf(
4275
+					esc_html__(
4276
+						'%s message type has been successfully deactivated for the %s messenger.',
4277
+						'event_espresso'
4278
+					),
4279
+					ucwords($message_type->label['singular']),
4280
+					ucwords($messenger->label['singular'])
4281
+				)
4282
+			);
4283
+		} else {
4284
+			$message_type_name = '';
4285
+			EE_Error::add_success(
4286
+				sprintf(
4287
+					esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4288
+					ucwords($messenger->label['singular'])
4289
+				)
4290
+			);
4291
+		}
4292
+
4293
+		// if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4294
+		if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4295
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
4296
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4297
+			if ($count_updated > 0) {
4298
+				$msg = $message_type_name === 'invoice'
4299
+					? esc_html__(
4300
+						'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.',
4301
+						'event_espresso'
4302
+					)
4303
+					: esc_html__(
4304
+						'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.',
4305
+						'event_espresso'
4306
+					);
4307
+				EE_Error::add_attention($msg);
4308
+			}
4309
+		}
4310
+
4311
+		return true;
4312
+	}
4313
+
4314
+
4315
+	/**
4316
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4317
+	 *
4318
+	 * @throws DomainException
4319
+	 */
4320
+	public function update_mt_form()
4321
+	{
4322
+		if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4323
+			EE_Error::add_error(
4324
+				esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4325
+				__FILE__,
4326
+				__FUNCTION__,
4327
+				__LINE__
4328
+			);
4329
+			$this->_return_json();
4330
+		}
4331
+
4332
+		$message_types = $this->get_installed_message_types();
4333
+
4334
+		$message_type = $message_types[ $this->_req_data['message_type'] ];
4335
+		$messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4336
+
4337
+		$content = $this->_message_type_settings_content(
4338
+			$message_type,
4339
+			$messenger,
4340
+			true
4341
+		);
4342
+		$this->_template_args['success'] = true;
4343
+		$this->_template_args['content'] = $content;
4344
+		$this->_return_json();
4345
+	}
4346
+
4347
+
4348
+	/**
4349
+	 * this handles saving the settings for a messenger or message type
4350
+	 *
4351
+	 */
4352
+	public function save_settings()
4353
+	{
4354
+		if (! isset($this->_req_data['type'])) {
4355
+			EE_Error::add_error(
4356
+				esc_html__(
4357
+					'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4358
+					'event_espresso'
4359
+				),
4360
+				__FILE__,
4361
+				__FUNCTION__,
4362
+				__LINE__
4363
+			);
4364
+			$this->_template_args['error'] = true;
4365
+			$this->_return_json();
4366
+		}
4367
+
4368
+
4369
+		if ($this->_req_data['type'] === 'messenger') {
4370
+			// this should be an array.
4371
+			$settings = $this->_req_data['messenger_settings'];
4372
+			$messenger = $settings['messenger'];
4373
+			// let's setup the settings data
4374
+			foreach ($settings as $key => $value) {
4375
+				switch ($key) {
4376
+					case 'messenger':
4377
+						unset($settings['messenger']);
4378
+						break;
4379
+					case 'message_types':
4380
+						unset($settings['message_types']);
4381
+						break;
4382
+					default:
4383
+						$settings[ $key ] = $value;
4384
+						break;
4385
+				}
4386
+			}
4387
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4388
+		} elseif ($this->_req_data['type'] === 'message_type') {
4389
+			$settings = $this->_req_data['message_type_settings'];
4390
+			$messenger = $settings['messenger'];
4391
+			$message_type = $settings['message_type'];
4392
+
4393
+			foreach ($settings as $key => $value) {
4394
+				switch ($key) {
4395
+					case 'messenger':
4396
+						unset($settings['messenger']);
4397
+						break;
4398
+					case 'message_type':
4399
+						unset($settings['message_type']);
4400
+						break;
4401
+					default:
4402
+						$settings[ $key ] = $value;
4403
+						break;
4404
+				}
4405
+			}
4406
+
4407
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4408
+		}
4409
+
4410
+		// okay we should have the data all setup.  Now we just update!
4411
+		$success = $this->_message_resource_manager->update_active_messengers_option();
4412
+
4413
+		if ($success) {
4414
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
4415
+		} else {
4416
+			EE_Error::add_error(
4417
+				esc_html__(
4418
+					'Settings did not get updated',
4419
+					'event_espresso'
4420
+				),
4421
+				__FILE__,
4422
+				__FUNCTION__,
4423
+				__LINE__
4424
+			);
4425
+		}
4426
+
4427
+		$this->_template_args['success'] = $success;
4428
+		$this->_return_json();
4429
+	}
4430
+
4431
+
4432
+
4433
+
4434
+	/**  EE MESSAGE PROCESSING ACTIONS **/
4435
+
4436
+
4437
+	/**
4438
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4439
+	 * However, this does not send immediately, it just queues for sending.
4440
+	 *
4441
+	 * @since 4.9.0
4442
+	 * @throws EE_Error
4443
+	 * @throws InvalidDataTypeException
4444
+	 * @throws InvalidInterfaceException
4445
+	 * @throws InvalidArgumentException
4446
+	 * @throws ReflectionException
4447
+	 */
4448
+	protected function _generate_now()
4449
+	{
4450
+		EED_Messages::generate_now($this->_get_msg_ids_from_request());
4451
+		$this->_redirect_after_action(false, '', '', array(), true);
4452
+	}
4453
+
4454
+
4455
+	/**
4456
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4457
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
4458
+	 *
4459
+	 * @since 4.9.0
4460
+	 * @throws EE_Error
4461
+	 * @throws InvalidDataTypeException
4462
+	 * @throws InvalidInterfaceException
4463
+	 * @throws InvalidArgumentException
4464
+	 * @throws ReflectionException
4465
+	 */
4466
+	protected function _generate_and_send_now()
4467
+	{
4468
+		EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4469
+		$this->_redirect_after_action(false, '', '', array(), true);
4470
+	}
4471
+
4472
+
4473
+	/**
4474
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4475
+	 *
4476
+	 * @since 4.9.0
4477
+	 * @throws EE_Error
4478
+	 * @throws InvalidDataTypeException
4479
+	 * @throws InvalidInterfaceException
4480
+	 * @throws InvalidArgumentException
4481
+	 * @throws ReflectionException
4482
+	 */
4483
+	protected function _queue_for_resending()
4484
+	{
4485
+		EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4486
+		$this->_redirect_after_action(false, '', '', array(), true);
4487
+	}
4488
+
4489
+
4490
+	/**
4491
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4492
+	 *
4493
+	 * @since 4.9.0
4494
+	 * @throws EE_Error
4495
+	 * @throws InvalidDataTypeException
4496
+	 * @throws InvalidInterfaceException
4497
+	 * @throws InvalidArgumentException
4498
+	 * @throws ReflectionException
4499
+	 */
4500
+	protected function _send_now()
4501
+	{
4502
+		EED_Messages::send_now($this->_get_msg_ids_from_request());
4503
+		$this->_redirect_after_action(false, '', '', array(), true);
4504
+	}
4505
+
4506
+
4507
+	/**
4508
+	 * Deletes EE_messages for IDs in the request.
4509
+	 *
4510
+	 * @since 4.9.0
4511
+	 * @throws EE_Error
4512
+	 * @throws InvalidDataTypeException
4513
+	 * @throws InvalidInterfaceException
4514
+	 * @throws InvalidArgumentException
4515
+	 */
4516
+	protected function _delete_ee_messages()
4517
+	{
4518
+		$msg_ids = $this->_get_msg_ids_from_request();
4519
+		$deleted_count = 0;
4520
+		foreach ($msg_ids as $msg_id) {
4521
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4522
+				$deleted_count++;
4523
+			}
4524
+		}
4525
+		if ($deleted_count) {
4526
+			EE_Error::add_success(
4527
+				esc_html(
4528
+					_n(
4529
+						'Message successfully deleted',
4530
+						'Messages successfully deleted',
4531
+						$deleted_count,
4532
+						'event_espresso'
4533
+					)
4534
+				)
4535
+			);
4536
+			$this->_redirect_after_action(
4537
+				false,
4538
+				'',
4539
+				'',
4540
+				array(),
4541
+				true
4542
+			);
4543
+		} else {
4544
+			EE_Error::add_error(
4545
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4546
+				__FILE__,
4547
+				__FUNCTION__,
4548
+				__LINE__
4549
+			);
4550
+			$this->_redirect_after_action(false, '', '', array(), true);
4551
+		}
4552
+	}
4553
+
4554
+
4555
+	/**
4556
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4557
+	 *
4558
+	 * @since 4.9.0
4559
+	 * @return array
4560
+	 */
4561
+	protected function _get_msg_ids_from_request()
4562
+	{
4563
+		if (! isset($this->_req_data['MSG_ID'])) {
4564
+			return array();
4565
+		}
4566
+
4567
+		return is_array($this->_req_data['MSG_ID'])
4568
+			? array_keys($this->_req_data['MSG_ID'])
4569
+			: array($this->_req_data['MSG_ID']);
4570
+	}
4571 4571
 }
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
             'sent_status'                => array(
1080
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1080
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_sent,
1081 1081
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, 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
             'failed_status'              => array(
1088
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1088
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_failed,
1089 1089
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, 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
             'resend_status'              => array(
1096
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1096
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_resend,
1097 1097
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1098 1098
             ),
1099 1099
             'incomplete_status'          => array(
1100
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1100
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_incomplete,
1101 1101
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1102 1102
             ),
1103 1103
             'retry_status'               => array(
1104
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1104
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_retry,
1105 1105
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, 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;
@@ -1348,7 +1348,7 @@  discard block
 block discarded – undo
1348 1348
         // we need to assemble the title from Various details
1349 1349
         $context_label = sprintf(
1350 1350
             esc_html__('(%s %s)', 'event_espresso'),
1351
-            $c_config[ $context ]['label'],
1351
+            $c_config[$context]['label'],
1352 1352
             ucwords($c_label['label'])
1353 1353
         );
1354 1354
 
@@ -1370,7 +1370,7 @@  discard block
 block discarded – undo
1370 1370
             $message_template_group->message_type()
1371 1371
         );
1372 1372
 
1373
-        if (! $template_field_structure) {
1373
+        if ( ! $template_field_structure) {
1374 1374
             $template_field_structure = false;
1375 1375
             $template_fields = esc_html__(
1376 1376
                 'There was an error in assembling the fields for this display (you should see an error message)',
@@ -1384,21 +1384,21 @@  discard block
 block discarded – undo
1384 1384
 
1385 1385
         // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1386 1386
         // will get handled in the "extra" array.
1387
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1388
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1389
-                unset($template_field_structure[ $context ][ $reference_field ]);
1387
+        if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1388
+            foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1389
+                unset($template_field_structure[$context][$reference_field]);
1390 1390
             }
1391 1391
         }
1392 1392
 
1393 1393
         // let's loop through the template_field_structure and actually assemble the input fields!
1394
-        if (! empty($template_field_structure)) {
1395
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1394
+        if ( ! empty($template_field_structure)) {
1395
+            foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1396 1396
                 // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1397 1397
                 // the extra array and reset them.
1398 1398
                 if ($template_field === 'extra') {
1399 1399
                     $this->_template_args['is_extra_fields'] = true;
1400 1400
                     foreach ($field_setup_array as $reference_field => $new_fields_array) {
1401
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1401
+                        $message_template = $message_templates[$context][$reference_field];
1402 1402
                         $content = $message_template instanceof EE_Message_Template
1403 1403
                             ? $message_template->get('MTP_content')
1404 1404
                             : '';
@@ -1407,7 +1407,7 @@  discard block
 block discarded – undo
1407 1407
                             $continue = false;
1408 1408
                             if (isset($extra_array['shortcodes_required'])) {
1409 1409
                                 foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1410
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1410
+                                    if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1411 1411
                                         $continue = true;
1412 1412
                                     }
1413 1413
                                 }
@@ -1420,57 +1420,57 @@  discard block
 block discarded – undo
1420 1420
                                         . '-'
1421 1421
                                         . $extra_field
1422 1422
                                         . '-content';
1423
-                            $template_form_fields[ $field_id ] = $extra_array;
1424
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1423
+                            $template_form_fields[$field_id] = $extra_array;
1424
+                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields['
1425 1425
                                                                          . $reference_field
1426 1426
                                                                          . '][content]['
1427
-                                                                         . $extra_field . ']';
1427
+                                                                         . $extra_field.']';
1428 1428
                             $css_class = isset($extra_array['css_class'])
1429 1429
                                 ? $extra_array['css_class']
1430 1430
                                 : '';
1431 1431
 
1432
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1432
+                            $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1433 1433
                                                                               && in_array($extra_field, $v_fields, true)
1434 1434
                                                                               &&
1435 1435
                                                                               (
1436
-                                                                                  is_array($validators[ $extra_field ])
1437
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1436
+                                                                                  is_array($validators[$extra_field])
1437
+                                                                                  && isset($validators[$extra_field]['msg'])
1438 1438
                                                                               )
1439
-                                ? 'validate-error ' . $css_class
1439
+                                ? 'validate-error '.$css_class
1440 1440
                                 : $css_class;
1441 1441
 
1442
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1443
-                                                                          && isset($content[ $extra_field ])
1444
-                                ? $content[ $extra_field ]
1442
+                            $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1443
+                                                                          && isset($content[$extra_field])
1444
+                                ? $content[$extra_field]
1445 1445
                                 : '';
1446 1446
 
1447 1447
                             // do we have a validation error?  if we do then let's use that value instead
1448
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1449
-                                ? $validators[ $extra_field ]['value']
1450
-                                : $template_form_fields[ $field_id ]['value'];
1448
+                            $template_form_fields[$field_id]['value'] = isset($validators[$extra_field])
1449
+                                ? $validators[$extra_field]['value']
1450
+                                : $template_form_fields[$field_id]['value'];
1451 1451
 
1452 1452
 
1453
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1453
+                            $template_form_fields[$field_id]['db-col'] = 'MTP_content';
1454 1454
 
1455 1455
                             // shortcode selector
1456 1456
                             $field_name_to_use = $extra_field === 'main'
1457 1457
                                 ? 'content'
1458 1458
                                 : $extra_field;
1459
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1459
+                            $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1460 1460
                                 $field_name_to_use,
1461 1461
                                 $field_id
1462 1462
                             );
1463 1463
 
1464 1464
                             if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1465 1465
                                 // we want to decode the entities
1466
-                                $template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1466
+                                $template_form_fields[$field_id]['value'] = $template_form_fields[$field_id]['value'];
1467 1467
                             }/**/
1468 1468
                         }
1469
-                        $templatefield_MTP_id = $reference_field . '-MTP_ID';
1470
-                        $templatefield_templatename_id = $reference_field . '-name';
1469
+                        $templatefield_MTP_id = $reference_field.'-MTP_ID';
1470
+                        $templatefield_templatename_id = $reference_field.'-name';
1471 1471
 
1472
-                        $template_form_fields[ $templatefield_MTP_id ] = array(
1473
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1472
+                        $template_form_fields[$templatefield_MTP_id] = array(
1473
+                            'name'       => 'MTP_template_fields['.$reference_field.'][MTP_ID]',
1474 1474
                             'label'      => null,
1475 1475
                             'input'      => 'hidden',
1476 1476
                             'type'       => 'int',
@@ -1482,8 +1482,8 @@  discard block
 block discarded – undo
1482 1482
                             'db-col'     => 'MTP_ID',
1483 1483
                         );
1484 1484
 
1485
-                        $template_form_fields[ $templatefield_templatename_id ] = array(
1486
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1485
+                        $template_form_fields[$templatefield_templatename_id] = array(
1486
+                            'name'       => 'MTP_template_fields['.$reference_field.'][name]',
1487 1487
                             'label'      => null,
1488 1488
                             'input'      => 'hidden',
1489 1489
                             'type'       => 'string',
@@ -1497,36 +1497,36 @@  discard block
 block discarded – undo
1497 1497
                     }
1498 1498
                     continue; // skip the next stuff, we got the necessary fields here for this dataset.
1499 1499
                 } else {
1500
-                    $field_id = $template_field . '-content';
1501
-                    $template_form_fields[ $field_id ] = $field_setup_array;
1502
-                    $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1503
-                    $message_template = isset($message_templates[ $context ][ $template_field ])
1504
-                        ? $message_templates[ $context ][ $template_field ]
1500
+                    $field_id = $template_field.'-content';
1501
+                    $template_form_fields[$field_id] = $field_setup_array;
1502
+                    $template_form_fields[$field_id]['name'] = 'MTP_template_fields['.$template_field.'][content]';
1503
+                    $message_template = isset($message_templates[$context][$template_field])
1504
+                        ? $message_templates[$context][$template_field]
1505 1505
                         : null;
1506
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1507
-                                                                  && is_array($message_templates[ $context ])
1506
+                    $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1507
+                                                                  && is_array($message_templates[$context])
1508 1508
                                                                   && $message_template instanceof EE_Message_Template
1509 1509
                         ? $message_template->get('MTP_content')
1510 1510
                         : '';
1511 1511
 
1512 1512
                     // do we have a validator error for this field?  if we do then we'll use that value instead
1513
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1514
-                        ? $validators[ $template_field ]['value']
1515
-                        : $template_form_fields[ $field_id ]['value'];
1513
+                    $template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1514
+                        ? $validators[$template_field]['value']
1515
+                        : $template_form_fields[$field_id]['value'];
1516 1516
 
1517 1517
 
1518
-                    $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1518
+                    $template_form_fields[$field_id]['db-col'] = 'MTP_content';
1519 1519
                     $css_class = isset($field_setup_array['css_class'])
1520 1520
                         ? $field_setup_array['css_class']
1521 1521
                         : '';
1522
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1522
+                    $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1523 1523
                                                                       && in_array($template_field, $v_fields, true)
1524
-                                                                      && isset($validators[ $template_field ]['msg'])
1525
-                        ? 'validate-error ' . $css_class
1524
+                                                                      && isset($validators[$template_field]['msg'])
1525
+                        ? 'validate-error '.$css_class
1526 1526
                         : $css_class;
1527 1527
 
1528 1528
                     // shortcode selector
1529
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1529
+                    $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1530 1530
                         $template_field,
1531 1531
                         $field_id
1532 1532
                     );
@@ -1534,12 +1534,12 @@  discard block
 block discarded – undo
1534 1534
 
1535 1535
                 // k took care of content field(s) now let's take care of others.
1536 1536
 
1537
-                $templatefield_MTP_id = $template_field . '-MTP_ID';
1538
-                $templatefield_field_templatename_id = $template_field . '-name';
1537
+                $templatefield_MTP_id = $template_field.'-MTP_ID';
1538
+                $templatefield_field_templatename_id = $template_field.'-name';
1539 1539
 
1540 1540
                 // foreach template field there are actually two form fields created
1541
-                $template_form_fields[ $templatefield_MTP_id ] = array(
1542
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1541
+                $template_form_fields[$templatefield_MTP_id] = array(
1542
+                    'name'       => 'MTP_template_fields['.$template_field.'][MTP_ID]',
1543 1543
                     'label'      => null,
1544 1544
                     'input'      => 'hidden',
1545 1545
                     'type'       => 'int',
@@ -1551,8 +1551,8 @@  discard block
 block discarded – undo
1551 1551
                     'db-col'     => 'MTP_ID',
1552 1552
                 );
1553 1553
 
1554
-                $template_form_fields[ $templatefield_field_templatename_id ] = array(
1555
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1554
+                $template_form_fields[$templatefield_field_templatename_id] = array(
1555
+                    'name'       => 'MTP_template_fields['.$template_field.'][name]',
1556 1556
                     'label'      => null,
1557 1557
                     'input'      => 'hidden',
1558 1558
                     'type'       => 'string',
@@ -1695,10 +1695,10 @@  discard block
 block discarded – undo
1695 1695
                 'value' => $GRP_ID,
1696 1696
             );
1697 1697
             $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1698
-                'name'  => $action . '_nonce',
1698
+                'name'  => $action.'_nonce',
1699 1699
                 'input' => 'hidden',
1700 1700
                 'type'  => 'string',
1701
-                'value' => wp_create_nonce($action . '_nonce'),
1701
+                'value' => wp_create_nonce($action.'_nonce'),
1702 1702
             );
1703 1703
 
1704 1704
             if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
@@ -1738,7 +1738,7 @@  discard block
 block discarded – undo
1738 1738
             ),
1739 1739
             $this->_admin_base_url
1740 1740
         );
1741
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1741
+        $preview_button = '<a href="'.$preview_url.'" class="button-secondary messages-preview-button">'
1742 1742
                           . esc_html__('Preview', 'event_espresso')
1743 1743
                           . '</a>';
1744 1744
 
@@ -1775,7 +1775,7 @@  discard block
 block discarded – undo
1775 1775
 
1776 1776
         $this->_template_path = $this->_template_args['GRP_ID']
1777 1777
             ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1778
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1778
+            : EE_MSG_TEMPLATE_PATH.'ee_msg_details_main_add_meta_box.template.php';
1779 1779
 
1780 1780
         // send along EE_Message_Template_Group object for further template use.
1781 1781
         $this->_template_args['MTP'] = $message_template_group;
@@ -1830,7 +1830,7 @@  discard block
 block discarded – undo
1830 1830
     ) {
1831 1831
         $template_args = array(
1832 1832
             'context'                   => $context,
1833
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1833
+            'nonce'                     => wp_create_nonce('activate_'.$context.'_toggle_nonce'),
1834 1834
             'is_active'                 => $message_template_group->is_context_active($context),
1835 1835
             'on_off_action'             => $message_template_group->is_context_active($context)
1836 1836
                 ? 'context-off'
@@ -1839,7 +1839,7 @@  discard block
 block discarded – undo
1839 1839
             'message_template_group_id' => $message_template_group->ID(),
1840 1840
         );
1841 1841
         return EEH_Template::display_template(
1842
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1842
+            EE_MSG_TEMPLATE_PATH.'ee_msg_editor_active_context_element.template.php',
1843 1843
             $template_args,
1844 1844
             true
1845 1845
         );
@@ -1860,7 +1860,7 @@  discard block
 block discarded – undo
1860 1860
     {
1861 1861
         $success = true;
1862 1862
         // check for required data
1863
-        if (! isset(
1863
+        if ( ! isset(
1864 1864
             $this->_req_data['message_template_group_id'],
1865 1865
             $this->_req_data['context'],
1866 1866
             $this->_req_data['status']
@@ -1877,7 +1877,7 @@  discard block
 block discarded – undo
1877 1877
         $nonce = isset($this->_req_data['toggle_context_nonce'])
1878 1878
             ? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1879 1879
             : '';
1880
-        $nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1880
+        $nonce_ref = 'activate_'.$this->_req_data['context'].'_toggle_nonce';
1881 1881
         $this->_verify_nonce($nonce, $nonce_ref);
1882 1882
         $status = $this->_req_data['status'];
1883 1883
         if ($status !== 'off' && $status !== 'on') {
@@ -1895,7 +1895,7 @@  discard block
 block discarded – undo
1895 1895
         $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1896 1896
             $this->_req_data['message_template_group_id']
1897 1897
         );
1898
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1898
+        if ( ! $message_template_group instanceof EE_Message_Template_Group) {
1899 1899
             EE_Error::add_error(
1900 1900
                 sprintf(
1901 1901
                     esc_html__(
@@ -2024,7 +2024,7 @@  discard block
 block discarded – undo
2024 2024
         $templates = array();
2025 2025
         $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2026 2026
         // we need to make sure we've got the info we need.
2027
-        if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2027
+        if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2028 2028
             EE_Error::add_error(
2029 2029
                 esc_html__(
2030 2030
                     '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.',
@@ -2066,7 +2066,7 @@  discard block
 block discarded – undo
2066 2066
         }
2067 2067
 
2068 2068
         // any error messages?
2069
-        if (! $success) {
2069
+        if ( ! $success) {
2070 2070
             EE_Error::add_error(
2071 2071
                 esc_html__(
2072 2072
                     'Something went wrong with deleting existing templates. Unable to reset to default',
@@ -2118,7 +2118,7 @@  discard block
 block discarded – undo
2118 2118
     public function _preview_message($send = false)
2119 2119
     {
2120 2120
         // first make sure we've got the necessary parameters
2121
-        if (! isset(
2121
+        if ( ! isset(
2122 2122
             $this->_req_data['message_type'],
2123 2123
             $this->_req_data['messenger'],
2124 2124
             $this->_req_data['messenger'],
@@ -2170,7 +2170,7 @@  discard block
 block discarded – undo
2170 2170
         $preview_title = sprintf(
2171 2171
             esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2172 2172
             $active_messenger_label,
2173
-            ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2173
+            ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
2174 2174
         );
2175 2175
         if (empty($preview)) {
2176 2176
             $this->noEventsErrorMessage();
@@ -2178,7 +2178,7 @@  discard block
 block discarded – undo
2178 2178
         // setup display of preview.
2179 2179
         $this->_admin_page_title = $preview_title;
2180 2180
         $this->_template_args['admin_page_title'] = $preview_title;
2181
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2181
+        $this->_template_args['admin_page_content'] = $preview_button.'<br />'.$preview;
2182 2182
         $this->_template_args['data']['force_json'] = true;
2183 2183
 
2184 2184
         return '';
@@ -2291,10 +2291,10 @@  discard block
 block discarded – undo
2291 2291
         foreach ($tp_collection as $tp) {
2292 2292
             // only include template packs that support this messenger and message type!
2293 2293
             $supports = $tp->get_supports();
2294
-            if (! isset($supports[ $this->_message_template_group->messenger() ])
2294
+            if ( ! isset($supports[$this->_message_template_group->messenger()])
2295 2295
                 || ! in_array(
2296 2296
                     $this->_message_template_group->message_type(),
2297
-                    $supports[ $this->_message_template_group->messenger() ],
2297
+                    $supports[$this->_message_template_group->messenger()],
2298 2298
                     true
2299 2299
                 )
2300 2300
             ) {
@@ -2347,7 +2347,7 @@  discard block
 block discarded – undo
2347 2347
         $template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2348 2348
         $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2349 2349
 
2350
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2350
+        $template = EE_MSG_TEMPLATE_PATH.'template_pack_and_variations_metabox.template.php';
2351 2351
 
2352 2352
         EEH_Template::display_template($template, $template_args);
2353 2353
     }
@@ -2373,10 +2373,10 @@  discard block
 block discarded – undo
2373 2373
         // first we need to see if there are any fields
2374 2374
         $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2375 2375
 
2376
-        if (! empty($fields)) {
2376
+        if ( ! empty($fields)) {
2377 2377
             // yup there be fields
2378 2378
             foreach ($fields as $field => $config) {
2379
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2379
+                $field_id = $this->_message_template_group->messenger().'_'.$field;
2380 2380
                 $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2381 2381
                 $default = isset($config['default']) ? $config['default'] : '';
2382 2382
                 $default = isset($config['value']) ? $config['value'] : $default;
@@ -2384,22 +2384,22 @@  discard block
 block discarded – undo
2384 2384
                 // if type is hidden and the value is empty
2385 2385
                 // something may have gone wrong so let's correct with the defaults
2386 2386
                 $fix = $config['input'] === 'hidden'
2387
-                       && isset($existing[ $field ])
2388
-                       && empty($existing[ $field ])
2387
+                       && isset($existing[$field])
2388
+                       && empty($existing[$field])
2389 2389
                     ? $default
2390 2390
                     : '';
2391
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2392
-                    ? $existing[ $field ]
2391
+                $existing[$field] = isset($existing[$field]) && empty($fix)
2392
+                    ? $existing[$field]
2393 2393
                     : $fix;
2394 2394
 
2395
-                $template_form_fields[ $field_id ] = array(
2396
-                    'name'       => 'test_settings_fld[' . $field . ']',
2395
+                $template_form_fields[$field_id] = array(
2396
+                    'name'       => 'test_settings_fld['.$field.']',
2397 2397
                     'label'      => $config['label'],
2398 2398
                     'input'      => $config['input'],
2399 2399
                     'type'       => $config['type'],
2400 2400
                     'required'   => $config['required'],
2401 2401
                     'validation' => $config['validation'],
2402
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2402
+                    'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2403 2403
                     'css_class'  => $config['css_class'],
2404 2404
                     'options'    => isset($config['options']) ? $config['options'] : array(),
2405 2405
                     'default'    => $default,
@@ -2414,7 +2414,7 @@  discard block
 block discarded – undo
2414 2414
 
2415 2415
         $test_settings_html = '';
2416 2416
         // print out $test_settings_fields
2417
-        if (! empty($test_settings_fields)) {
2417
+        if ( ! empty($test_settings_fields)) {
2418 2418
             echo $test_settings_fields;
2419 2419
             $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2420 2420
             $test_settings_html .= 'name="test_button" value="';
@@ -2461,7 +2461,7 @@  discard block
 block discarded – undo
2461 2461
         );
2462 2462
 
2463 2463
         return EEH_Template::display_template(
2464
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2464
+            EE_MSG_TEMPLATE_PATH.'shortcode_selector_skeleton.template.php',
2465 2465
             $template_args,
2466 2466
             true
2467 2467
         );
@@ -2486,7 +2486,7 @@  discard block
 block discarded – undo
2486 2486
         // $messenger = $this->_message_template_group->messenger_obj();
2487 2487
         // now let's set the content depending on the status of the shortcodes array
2488 2488
         if (empty($shortcodes)) {
2489
-            $content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2489
+            $content = '<p>'.esc_html__('There are no valid shortcodes available', 'event_espresso').'</p>';
2490 2490
             echo $content;
2491 2491
         } else {
2492 2492
             // $alt = 0;
@@ -2524,7 +2524,7 @@  discard block
 block discarded – undo
2524 2524
     {
2525 2525
 
2526 2526
         // no need to run this if the property is already set
2527
-        if (! empty($this->_shortcodes)) {
2527
+        if ( ! empty($this->_shortcodes)) {
2528 2528
             return;
2529 2529
         }
2530 2530
 
@@ -2578,7 +2578,7 @@  discard block
 block discarded – undo
2578 2578
     protected function _set_message_template_group()
2579 2579
     {
2580 2580
 
2581
-        if (! empty($this->_message_template_group)) {
2581
+        if ( ! empty($this->_message_template_group)) {
2582 2582
             return;
2583 2583
         } //get out if this is already set.
2584 2584
 
@@ -2625,7 +2625,7 @@  discard block
 block discarded – undo
2625 2625
                     <?php
2626 2626
                 }
2627 2627
                 // setup nonce_url
2628
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2628
+                wp_nonce_field($args['action'].'_nonce', $args['action'].'_nonce', false);
2629 2629
                 ?>
2630 2630
                 <select name="context">
2631 2631
                     <?php
@@ -2635,7 +2635,7 @@  discard block
 block discarded – undo
2635 2635
                             $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2636 2636
                             ?>
2637 2637
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2638
-                                <?php echo $context_details[ $context ]['label']; ?>
2638
+                                <?php echo $context_details[$context]['label']; ?>
2639 2639
                             </option>
2640 2640
                         <?php endforeach;
2641 2641
                     endif; ?>
@@ -2665,22 +2665,22 @@  discard block
 block discarded – undo
2665 2665
      */
2666 2666
     protected function _set_message_template_column_values($index)
2667 2667
     {
2668
-        if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2669
-            foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2670
-                $this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2668
+        if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2669
+            foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2670
+                $this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2671 2671
             }
2672 2672
         }
2673 2673
 
2674 2674
 
2675 2675
         $set_column_values = array(
2676
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2676
+            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2677 2677
             'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2678 2678
             'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2679 2679
             'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2680 2680
             'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2681
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2681
+            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2682 2682
             'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2683
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2683
+            'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2684 2684
             'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2685 2685
                 ? absint($this->_req_data['MTP_is_global'])
2686 2686
                 : 0,
@@ -2727,7 +2727,7 @@  discard block
 block discarded – undo
2727 2727
         $context = ucwords(str_replace('_', ' ', $context_slug));
2728 2728
 
2729 2729
         $item_desc = $messenger_label && $message_type_label
2730
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2730
+            ? $messenger_label.' '.$message_type_label.' '.$context.' '
2731 2731
             : '';
2732 2732
         $item_desc .= 'Message Template';
2733 2733
         $query_args = array();
@@ -2758,7 +2758,7 @@  discard block
 block discarded – undo
2758 2758
 
2759 2759
 
2760 2760
             // run update for each template field in displayed context
2761
-            if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2761
+            if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2762 2762
                 EE_Error::add_error(
2763 2763
                     esc_html__(
2764 2764
                         'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
@@ -2820,10 +2820,10 @@  discard block
 block discarded – undo
2820 2820
                         $set_column_values = $this->_set_message_template_column_values($template_field);
2821 2821
 
2822 2822
                         $where_cols_n_values = array(
2823
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2823
+                            'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID'],
2824 2824
                         );
2825 2825
                         // if they aren't allowed to use all JS, restrict them to just posty-y tags
2826
-                        if (! current_user_can('unfiltered_html')) {
2826
+                        if ( ! current_user_can('unfiltered_html')) {
2827 2827
                             if (is_array($set_column_values['MTP_content'])) {
2828 2828
                                 foreach ($set_column_values['MTP_content'] as $key => $value) {
2829 2829
                                     // remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
@@ -2831,7 +2831,7 @@  discard block
 block discarded – undo
2831 2831
                                     // appear invalid.) But currently the models expect slashed data, so after wp_kses
2832 2832
                                     // runs we need to re-slash the data. Sheesh. See
2833 2833
                                     // https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2834
-                                    $set_column_values['MTP_content'][ $key ] = addslashes(
2834
+                                    $set_column_values['MTP_content'][$key] = addslashes(
2835 2835
                                         wp_kses(
2836 2836
                                             stripslashes($value),
2837 2837
                                             wp_kses_allowed_html('post')
@@ -2867,14 +2867,14 @@  discard block
 block discarded – undo
2867 2867
                             }
2868 2868
                         } else {
2869 2869
                             // only do this logic if we don't have a MTP_ID for this field
2870
-                            if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2870
+                            if (empty($this->_req_data['MTP_template_fields'][$template_field]['MTP_ID'])) {
2871 2871
                                 // this has already been through the template field validator and sanitized, so it will be
2872 2872
                                 // safe to insert this field.  Why insert?  This typically happens when we introduce a new
2873 2873
                                 // message template field in a messenger/message type and existing users don't have the
2874 2874
                                 // default setup for it.
2875 2875
                                 // @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2876 2876
                                 $updated = $MTP->insert($message_template_fields);
2877
-                                if (! $updated || is_wp_error($updated)) {
2877
+                                if ( ! $updated || is_wp_error($updated)) {
2878 2878
                                     EE_Error::add_error(
2879 2879
                                         sprintf(
2880 2880
                                             esc_html__('%s field could not be updated.', 'event_espresso'),
@@ -3105,7 +3105,7 @@  discard block
 block discarded – undo
3105 3105
         // incoming GRP_IDs
3106 3106
         if ($all) {
3107 3107
             // Checkboxes
3108
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3108
+            if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3109 3109
                 // if array has more than one element then success message should be plural.
3110 3110
                 // todo: what about nonce?
3111 3111
                 $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
@@ -3113,16 +3113,16 @@  discard block
 block discarded – undo
3113 3113
                 // cycle through checkboxes
3114 3114
                 while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3115 3115
                     $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3116
-                    if (! $trashed_or_restored) {
3116
+                    if ( ! $trashed_or_restored) {
3117 3117
                         $success = 0;
3118 3118
                     }
3119 3119
                 }
3120 3120
             } else {
3121 3121
                 // grab single GRP_ID and handle
3122 3122
                 $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3123
-                if (! empty($GRP_ID)) {
3123
+                if ( ! empty($GRP_ID)) {
3124 3124
                     $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3125
-                    if (! $trashed_or_restored) {
3125
+                    if ( ! $trashed_or_restored) {
3126 3126
                         $success = 0;
3127 3127
                     }
3128 3128
                 } else {
@@ -3170,7 +3170,7 @@  discard block
 block discarded – undo
3170 3170
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3171 3171
 
3172 3172
         // checkboxes
3173
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3173
+        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3174 3174
             // if array has more than one element then success message should be plural
3175 3175
             $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3176 3176
 
@@ -3277,7 +3277,7 @@  discard block
 block discarded – undo
3277 3277
     protected function _set_m_mt_settings()
3278 3278
     {
3279 3279
         // first if this is already set then lets get out no need to regenerate data.
3280
-        if (! empty($this->_m_mt_settings)) {
3280
+        if ( ! empty($this->_m_mt_settings)) {
3281 3281
             return;
3282 3282
         }
3283 3283
 
@@ -3291,7 +3291,7 @@  discard block
 block discarded – undo
3291 3291
         // assemble the array for the _tab_text_links helper
3292 3292
 
3293 3293
         foreach ($messengers as $messenger) {
3294
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3294
+            $this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
3295 3295
                 'label' => ucwords($messenger->label['singular']),
3296 3296
                 'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3297 3297
                     ? 'messenger-active'
@@ -3308,7 +3308,7 @@  discard block
 block discarded – undo
3308 3308
             foreach ($message_types as $message_type) {
3309 3309
                 // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3310 3310
                 // it shouldn't show in either the inactive OR active metabox.
3311
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3311
+                if ( ! in_array($message_type->name, $message_types_for_messenger, true)) {
3312 3312
                     continue;
3313 3313
                 }
3314 3314
 
@@ -3319,12 +3319,12 @@  discard block
 block discarded – undo
3319 3319
                     ? 'active'
3320 3320
                     : 'inactive';
3321 3321
 
3322
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3322
+                $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
3323 3323
                     'label'    => ucwords($message_type->label['singular']),
3324
-                    'class'    => 'message-type-' . $a_or_i,
3325
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3326
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3327
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3324
+                    'class'    => 'message-type-'.$a_or_i,
3325
+                    'slug_id'  => $message_type->name.'-messagetype-'.$messenger->name,
3326
+                    'mt_nonce' => wp_create_nonce($message_type->name.'_nonce'),
3327
+                    'href'     => 'espresso_'.$message_type->name.'_message_type_settings',
3328 3328
                     'title'    => $a_or_i === 'active'
3329 3329
                         ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3330 3330
                         : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
@@ -3355,25 +3355,25 @@  discard block
 block discarded – undo
3355 3355
         $fields = $message_type->get_admin_settings_fields();
3356 3356
         $settings_template_args['template_form_fields'] = '';
3357 3357
 
3358
-        if (! empty($fields) && $active) {
3358
+        if ( ! empty($fields) && $active) {
3359 3359
             $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3360 3360
             foreach ($fields as $fldname => $fldprops) {
3361
-                $field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3362
-                $template_form_field[ $field_id ] = array(
3363
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3361
+                $field_id = $messenger->name.'-'.$message_type->name.'-'.$fldname;
3362
+                $template_form_field[$field_id] = array(
3363
+                    'name'       => 'message_type_settings['.$fldname.']',
3364 3364
                     'label'      => $fldprops['label'],
3365 3365
                     'input'      => $fldprops['field_type'],
3366 3366
                     'type'       => $fldprops['value_type'],
3367 3367
                     'required'   => $fldprops['required'],
3368 3368
                     'validation' => $fldprops['validation'],
3369
-                    'value'      => isset($existing_settings[ $fldname ])
3370
-                        ? $existing_settings[ $fldname ]
3369
+                    'value'      => isset($existing_settings[$fldname])
3370
+                        ? $existing_settings[$fldname]
3371 3371
                         : $fldprops['default'],
3372 3372
                     'options'    => isset($fldprops['options'])
3373 3373
                         ? $fldprops['options']
3374 3374
                         : array(),
3375
-                    'default'    => isset($existing_settings[ $fldname ])
3376
-                        ? $existing_settings[ $fldname ]
3375
+                    'default'    => isset($existing_settings[$fldname])
3376
+                        ? $existing_settings[$fldname]
3377 3377
                         : $fldprops['default'],
3378 3378
                     'css_class'  => 'no-drag',
3379 3379
                     'format'     => $fldprops['format'],
@@ -3416,7 +3416,7 @@  discard block
 block discarded – undo
3416 3416
             : '';
3417 3417
 
3418 3418
 
3419
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3419
+        $template = EE_MSG_TEMPLATE_PATH.'ee_msg_mt_settings_content.template.php';
3420 3420
         $content = EEH_Template::display_template($template, $settings_template_args, true);
3421 3421
 
3422 3422
         return $content;
@@ -3447,20 +3447,20 @@  discard block
 block discarded – undo
3447 3447
                 // messenger meta boxes
3448 3448
                 $active = $selected_messenger === $messenger;
3449 3449
                 $active_mt_tabs = isset(
3450
-                    $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3450
+                    $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
3451 3451
                 )
3452
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3452
+                    ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
3453 3453
                     : '';
3454
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3454
+                $m_boxes[$messenger.'_a_box'] = sprintf(
3455 3455
                     esc_html__('%s Settings', 'event_espresso'),
3456 3456
                     $tab_array['label']
3457 3457
                 );
3458
-                $m_template_args[ $messenger . '_a_box' ] = array(
3458
+                $m_template_args[$messenger.'_a_box'] = array(
3459 3459
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3460 3460
                     'inactive_message_types' => isset(
3461
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3461
+                        $this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
3462 3462
                     )
3463
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3463
+                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
3464 3464
                         : '',
3465 3465
                     'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3466 3466
                     'hidden'                 => $active ? '' : ' hidden',
@@ -3471,13 +3471,13 @@  discard block
 block discarded – undo
3471 3471
                 // message type meta boxes
3472 3472
                 // (which is really just the inactive container for each messenger
3473 3473
                 // showing inactive message types for that messenger)
3474
-                $mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3475
-                $mt_template_args[ $messenger . '_i_box' ] = array(
3474
+                $mt_boxes[$messenger.'_i_box'] = esc_html__('Inactive Message Types', 'event_espresso');
3475
+                $mt_template_args[$messenger.'_i_box'] = array(
3476 3476
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3477 3477
                     'inactive_message_types' => isset(
3478
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3478
+                        $this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
3479 3479
                     )
3480
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3480
+                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
3481 3481
                         : '',
3482 3482
                     'hidden'                 => $active ? '' : ' hidden',
3483 3483
                     'hide_on_message'        => $hide_on_message,
@@ -3490,14 +3490,14 @@  discard block
 block discarded – undo
3490 3490
 
3491 3491
 
3492 3492
         // register messenger metaboxes
3493
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3493
+        $m_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_mt_meta_box.template.php';
3494 3494
         foreach ($m_boxes as $box => $label) {
3495
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3495
+            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
3496 3496
             $msgr = str_replace('_a_box', '', $box);
3497 3497
             add_meta_box(
3498
-                'espresso_' . $msgr . '_settings',
3498
+                'espresso_'.$msgr.'_settings',
3499 3499
                 $label,
3500
-                function ($post, $metabox) {
3500
+                function($post, $metabox) {
3501 3501
                     echo EEH_Template::display_template(
3502 3502
                         $metabox["args"]["template_path"],
3503 3503
                         $metabox["args"]["template_args"],
@@ -3512,17 +3512,17 @@  discard block
 block discarded – undo
3512 3512
         }
3513 3513
 
3514 3514
         // register message type metaboxes
3515
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3515
+        $mt_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_meta_box.template.php';
3516 3516
         foreach ($mt_boxes as $box => $label) {
3517 3517
             $callback_args = array(
3518 3518
                 'template_path' => $mt_template_path,
3519
-                'template_args' => $mt_template_args[ $box ],
3519
+                'template_args' => $mt_template_args[$box],
3520 3520
             );
3521 3521
             $mt = str_replace('_i_box', '', $box);
3522 3522
             add_meta_box(
3523
-                'espresso_' . $mt . '_inactive_mts',
3523
+                'espresso_'.$mt.'_inactive_mts',
3524 3524
                 $label,
3525
-                function ($post, $metabox) {
3525
+                function($post, $metabox) {
3526 3526
                     echo EEH_Template::display_template(
3527 3527
                         $metabox["args"]["template_path"],
3528 3528
                         $metabox["args"]["template_args"],
@@ -3668,7 +3668,7 @@  discard block
 block discarded – undo
3668 3668
             if ($form->is_valid()) {
3669 3669
                 $valid_data = $form->valid_data();
3670 3670
                 foreach ($valid_data as $property => $value) {
3671
-                    $setter = 'set_' . $property;
3671
+                    $setter = 'set_'.$property;
3672 3672
                     if (method_exists($network_config, $setter)) {
3673 3673
                         $network_config->{$setter}($value);
3674 3674
                     } elseif (property_exists($network_config, $property)
@@ -3702,7 +3702,7 @@  discard block
 block discarded – undo
3702 3702
     protected function _get_mt_tabs($tab_array)
3703 3703
     {
3704 3704
         $tab_array = (array) $tab_array;
3705
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3705
+        $template = EE_MSG_TEMPLATE_PATH.'ee_msg_details_mt_settings_tab_item.template.php';
3706 3706
         $tabs = '';
3707 3707
 
3708 3708
         foreach ($tab_array as $tab) {
@@ -3730,20 +3730,20 @@  discard block
 block discarded – undo
3730 3730
         $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3731 3731
 
3732 3732
 
3733
-        if (! empty($fields)) {
3733
+        if ( ! empty($fields)) {
3734 3734
             $existing_settings = $messenger->get_existing_admin_settings();
3735 3735
 
3736 3736
             foreach ($fields as $fldname => $fldprops) {
3737
-                $field_id = $messenger->name . '-' . $fldname;
3738
-                $template_form_field[ $field_id ] = array(
3739
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3737
+                $field_id = $messenger->name.'-'.$fldname;
3738
+                $template_form_field[$field_id] = array(
3739
+                    'name'       => 'messenger_settings['.$field_id.']',
3740 3740
                     'label'      => $fldprops['label'],
3741 3741
                     'input'      => $fldprops['field_type'],
3742 3742
                     'type'       => $fldprops['value_type'],
3743 3743
                     'required'   => $fldprops['required'],
3744 3744
                     'validation' => $fldprops['validation'],
3745
-                    'value'      => isset($existing_settings[ $field_id ])
3746
-                        ? $existing_settings[ $field_id ]
3745
+                    'value'      => isset($existing_settings[$field_id])
3746
+                        ? $existing_settings[$field_id]
3747 3747
                         : $fldprops['default'],
3748 3748
                     'css_class'  => '',
3749 3749
                     'format'     => $fldprops['format'],
@@ -3769,9 +3769,9 @@  discard block
 block discarded – undo
3769 3769
         );
3770 3770
 
3771 3771
         // make sure any active message types that are existing are included in the hidden fields
3772
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3773
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3774
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3772
+        if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3773
+            foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3774
+                $settings_template_args['hidden_fields']['messenger_settings[message_types]['.$mt.']'] = array(
3775 3775
                     'type'  => 'hidden',
3776 3776
                     'value' => $mt,
3777 3777
                 );
@@ -3800,9 +3800,9 @@  discard block
 block discarded – undo
3800 3800
 
3801 3801
 
3802 3802
         $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3803
-        $settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3803
+        $settings_template_args['nonce'] = wp_create_nonce('activate_'.$messenger->name.'_toggle_nonce');
3804 3804
         $settings_template_args['on_off_status'] = $active ? true : false;
3805
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3805
+        $template = EE_MSG_TEMPLATE_PATH.'ee_msg_m_settings_content.template.php';
3806 3806
         $content = EEH_Template::display_template(
3807 3807
             $template,
3808 3808
             $settings_template_args,
@@ -3828,7 +3828,7 @@  discard block
 block discarded – undo
3828 3828
         $success = true;
3829 3829
         $this->_prep_default_response_for_messenger_or_message_type_toggle();
3830 3830
         // let's check that we have required data
3831
-        if (! isset($this->_req_data['messenger'])) {
3831
+        if ( ! isset($this->_req_data['messenger'])) {
3832 3832
             EE_Error::add_error(
3833 3833
                 esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3834 3834
                 __FILE__,
@@ -3842,12 +3842,12 @@  discard block
 block discarded – undo
3842 3842
         $nonce = isset($this->_req_data['activate_nonce'])
3843 3843
             ? sanitize_text_field($this->_req_data['activate_nonce'])
3844 3844
             : '';
3845
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3845
+        $nonce_ref = 'activate_'.$this->_req_data['messenger'].'_toggle_nonce';
3846 3846
 
3847 3847
         $this->_verify_nonce($nonce, $nonce_ref);
3848 3848
 
3849 3849
 
3850
-        if (! isset($this->_req_data['status'])) {
3850
+        if ( ! isset($this->_req_data['status'])) {
3851 3851
             EE_Error::add_error(
3852 3852
                 esc_html__(
3853 3853
                     'Messenger status needed to know whether activation or deactivation is happening. No status is given',
@@ -3906,7 +3906,7 @@  discard block
 block discarded – undo
3906 3906
         $this->_prep_default_response_for_messenger_or_message_type_toggle();
3907 3907
 
3908 3908
         // let's make sure we have the necessary data
3909
-        if (! isset($this->_req_data['message_type'])) {
3909
+        if ( ! isset($this->_req_data['message_type'])) {
3910 3910
             EE_Error::add_error(
3911 3911
                 esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3912 3912
                 __FILE__,
@@ -3916,7 +3916,7 @@  discard block
 block discarded – undo
3916 3916
             $success = false;
3917 3917
         }
3918 3918
 
3919
-        if (! isset($this->_req_data['messenger'])) {
3919
+        if ( ! isset($this->_req_data['messenger'])) {
3920 3920
             EE_Error::add_error(
3921 3921
                 esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3922 3922
                 __FILE__,
@@ -3926,7 +3926,7 @@  discard block
 block discarded – undo
3926 3926
             $success = false;
3927 3927
         }
3928 3928
 
3929
-        if (! isset($this->_req_data['status'])) {
3929
+        if ( ! isset($this->_req_data['status'])) {
3930 3930
             EE_Error::add_error(
3931 3931
                 esc_html__(
3932 3932
                     'Messenger status needed to know whether activation or deactivation is happening. No status is given',
@@ -3959,7 +3959,7 @@  discard block
 block discarded – undo
3959 3959
 
3960 3960
         // do a nonce check here since we're not arriving via a normal route
3961 3961
         $nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3962
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3962
+        $nonce_ref = $this->_req_data['message_type'].'_nonce';
3963 3963
 
3964 3964
         $this->_verify_nonce($nonce, $nonce_ref);
3965 3965
 
@@ -4146,7 +4146,7 @@  discard block
 block discarded – undo
4146 4146
         EE_Message_Type $message_type = null
4147 4147
     ) {
4148 4148
         // if $messenger isn't a valid messenger object then get out.
4149
-        if (! $messenger instanceof EE_Messenger) {
4149
+        if ( ! $messenger instanceof EE_Messenger) {
4150 4150
             EE_Error::add_error(
4151 4151
                 esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4152 4152
                 __FILE__,
@@ -4201,7 +4201,7 @@  discard block
 block discarded – undo
4201 4201
             // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4202 4202
             // in which case we just give a success message for the messenger being successfully activated.
4203 4203
         } else {
4204
-            if (! $messenger->get_default_message_types()) {
4204
+            if ( ! $messenger->get_default_message_types()) {
4205 4205
                 // messenger doesn't have any default message types so still a success.
4206 4206
                 EE_Error::add_success(
4207 4207
                     sprintf(
@@ -4257,7 +4257,7 @@  discard block
 block discarded – undo
4257 4257
         EE_Error::overwrite_success();
4258 4258
 
4259 4259
         // if $messenger isn't a valid messenger object then get out.
4260
-        if (! $messenger instanceof EE_Messenger) {
4260
+        if ( ! $messenger instanceof EE_Messenger) {
4261 4261
             EE_Error::add_error(
4262 4262
                 esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4263 4263
                 __FILE__,
@@ -4319,7 +4319,7 @@  discard block
 block discarded – undo
4319 4319
      */
4320 4320
     public function update_mt_form()
4321 4321
     {
4322
-        if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4322
+        if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4323 4323
             EE_Error::add_error(
4324 4324
                 esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4325 4325
                 __FILE__,
@@ -4331,7 +4331,7 @@  discard block
 block discarded – undo
4331 4331
 
4332 4332
         $message_types = $this->get_installed_message_types();
4333 4333
 
4334
-        $message_type = $message_types[ $this->_req_data['message_type'] ];
4334
+        $message_type = $message_types[$this->_req_data['message_type']];
4335 4335
         $messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4336 4336
 
4337 4337
         $content = $this->_message_type_settings_content(
@@ -4351,7 +4351,7 @@  discard block
 block discarded – undo
4351 4351
      */
4352 4352
     public function save_settings()
4353 4353
     {
4354
-        if (! isset($this->_req_data['type'])) {
4354
+        if ( ! isset($this->_req_data['type'])) {
4355 4355
             EE_Error::add_error(
4356 4356
                 esc_html__(
4357 4357
                     'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
@@ -4380,7 +4380,7 @@  discard block
 block discarded – undo
4380 4380
                         unset($settings['message_types']);
4381 4381
                         break;
4382 4382
                     default:
4383
-                        $settings[ $key ] = $value;
4383
+                        $settings[$key] = $value;
4384 4384
                         break;
4385 4385
                 }
4386 4386
             }
@@ -4399,7 +4399,7 @@  discard block
 block discarded – undo
4399 4399
                         unset($settings['message_type']);
4400 4400
                         break;
4401 4401
                     default:
4402
-                        $settings[ $key ] = $value;
4402
+                        $settings[$key] = $value;
4403 4403
                         break;
4404 4404
                 }
4405 4405
             }
@@ -4560,7 +4560,7 @@  discard block
 block discarded – undo
4560 4560
      */
4561 4561
     protected function _get_msg_ids_from_request()
4562 4562
     {
4563
-        if (! isset($this->_req_data['MSG_ID'])) {
4563
+        if ( ! isset($this->_req_data['MSG_ID'])) {
4564 4564
             return array();
4565 4565
         }
4566 4566
 
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.