Completed
Branch FET-11170-model-use-money-enti... (00bce3)
by
unknown
58:42 queued 45:24
created
core/EE_Registry.core.php 1 patch
Indentation   +1579 added lines, -1579 removed lines patch added patch discarded remove patch
@@ -23,1585 +23,1585 @@
 block discarded – undo
23 23
 class EE_Registry implements ResettableInterface
24 24
 {
25 25
 
26
-    /**
27
-     * @var EE_Registry $_instance
28
-     */
29
-    private static $_instance;
30
-
31
-    /**
32
-     * @var EE_Dependency_Map $_dependency_map
33
-     */
34
-    protected $_dependency_map;
35
-
36
-    /**
37
-     * @var array $_class_abbreviations
38
-     */
39
-    protected $_class_abbreviations = array();
40
-
41
-    /**
42
-     * @var CommandBusInterface $BUS
43
-     */
44
-    public $BUS;
45
-
46
-    /**
47
-     * @var EE_Cart $CART
48
-     */
49
-    public $CART;
50
-
51
-    /**
52
-     * @var EE_Config $CFG
53
-     */
54
-    public $CFG;
55
-
56
-    /**
57
-     * @var EE_Network_Config $NET_CFG
58
-     */
59
-    public $NET_CFG;
60
-
61
-    /**
62
-     * StdClass object for storing library classes in
63
-     *
64
-     * @var StdClass $LIB
65
-     */
66
-    public $LIB;
67
-
68
-    /**
69
-     * @var EE_Request_Handler $REQ
70
-     */
71
-    public $REQ;
72
-
73
-    /**
74
-     * @var EE_Session $SSN
75
-     */
76
-    public $SSN;
77
-
78
-    /**
79
-     * @since 4.5.0
80
-     * @var EE_Capabilities $CAP
81
-     */
82
-    public $CAP;
83
-
84
-    /**
85
-     * @since 4.9.0
86
-     * @var EE_Message_Resource_Manager $MRM
87
-     */
88
-    public $MRM;
89
-
90
-
91
-    /**
92
-     * @var Registry $AssetsRegistry
93
-     */
94
-    public $AssetsRegistry;
95
-
96
-    /**
97
-     * StdClass object for holding addons which have registered themselves to work with EE core
98
-     *
99
-     * @var EE_Addon[] $addons
100
-     */
101
-    public $addons;
102
-
103
-    /**
104
-     * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
105
-     *
106
-     * @var EEM_Base[] $models
107
-     */
108
-    public $models = array();
109
-
110
-    /**
111
-     * @var EED_Module[] $modules
112
-     */
113
-    public $modules;
114
-
115
-    /**
116
-     * @var EES_Shortcode[] $shortcodes
117
-     */
118
-    public $shortcodes;
119
-
120
-    /**
121
-     * @var WP_Widget[] $widgets
122
-     */
123
-    public $widgets;
124
-
125
-    /**
126
-     * this is an array of all implemented model names (i.e. not the parent abstract models, or models
127
-     * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
128
-     * Keys are model "short names" (eg "Event") as used in model relations, and values are
129
-     * classnames (eg "EEM_Event")
130
-     *
131
-     * @var array $non_abstract_db_models
132
-     */
133
-    public $non_abstract_db_models = array();
134
-
135
-
136
-    /**
137
-     * internationalization for JS strings
138
-     *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
139
-     *    in js file:  var translatedString = eei18n.string_key;
140
-     *
141
-     * @var array $i18n_js_strings
142
-     */
143
-    public static $i18n_js_strings = array();
144
-
145
-
146
-    /**
147
-     * $main_file - path to espresso.php
148
-     *
149
-     * @var array $main_file
150
-     */
151
-    public $main_file;
152
-
153
-    /**
154
-     * array of ReflectionClass objects where the key is the class name
155
-     *
156
-     * @var ReflectionClass[] $_reflectors
157
-     */
158
-    public $_reflectors;
159
-
160
-    /**
161
-     * boolean flag to indicate whether or not to load/save dependencies from/to the cache
162
-     *
163
-     * @var boolean $_cache_on
164
-     */
165
-    protected $_cache_on = true;
166
-
167
-
168
-
169
-    /**
170
-     * @singleton method used to instantiate class object
171
-     * @param  EE_Dependency_Map $dependency_map
172
-     * @return EE_Registry instance
173
-     * @throws InvalidArgumentException
174
-     * @throws InvalidInterfaceException
175
-     * @throws InvalidDataTypeException
176
-     */
177
-    public static function instance(EE_Dependency_Map $dependency_map = null)
178
-    {
179
-        // check if class object is instantiated
180
-        if (! self::$_instance instanceof EE_Registry) {
181
-            self::$_instance = new self($dependency_map);
182
-        }
183
-        return self::$_instance;
184
-    }
185
-
186
-
187
-
188
-    /**
189
-     * protected constructor to prevent direct creation
190
-     *
191
-     * @Constructor
192
-     * @param  EE_Dependency_Map $dependency_map
193
-     * @throws InvalidDataTypeException
194
-     * @throws InvalidInterfaceException
195
-     * @throws InvalidArgumentException
196
-     */
197
-    protected function __construct(EE_Dependency_Map $dependency_map)
198
-    {
199
-        $this->_dependency_map = $dependency_map;
200
-        // $registry_container = new RegistryContainer();
201
-        $this->LIB = new RegistryContainer();
202
-        $this->addons = new RegistryContainer();
203
-        $this->modules = new RegistryContainer();
204
-        $this->shortcodes = new RegistryContainer();
205
-        $this->widgets = new RegistryContainer();
206
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
207
-    }
208
-
209
-
210
-
211
-    /**
212
-     * initialize
213
-     *
214
-     * @throws EE_Error
215
-     * @throws ReflectionException
216
-     */
217
-    public function initialize()
218
-    {
219
-        $this->_class_abbreviations = apply_filters(
220
-            'FHEE__EE_Registry____construct___class_abbreviations',
221
-            array(
222
-                'EE_Config'                                       => 'CFG',
223
-                'EE_Session'                                      => 'SSN',
224
-                'EE_Capabilities'                                 => 'CAP',
225
-                'EE_Cart'                                         => 'CART',
226
-                'EE_Network_Config'                               => 'NET_CFG',
227
-                'EE_Request_Handler'                              => 'REQ',
228
-                'EE_Message_Resource_Manager'                     => 'MRM',
229
-                'EventEspresso\core\services\commands\CommandBus' => 'BUS',
230
-                'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
231
-            )
232
-        );
233
-        $this->load_core('Base', array(), true);
234
-        // add our request and response objects to the cache
235
-        $request_loader = $this->_dependency_map->class_loader('EE_Request');
236
-        $this->_set_cached_class(
237
-            $request_loader(),
238
-            'EE_Request'
239
-        );
240
-        $response_loader = $this->_dependency_map->class_loader('EE_Response');
241
-        $this->_set_cached_class(
242
-            $response_loader(),
243
-            'EE_Response'
244
-        );
245
-        add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
246
-    }
247
-
248
-
249
-
250
-    /**
251
-     * @return void
252
-     */
253
-    public function init()
254
-    {
255
-        // Get current page protocol
256
-        $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
257
-        // Output admin-ajax.php URL with same protocol as current page
258
-        self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
259
-        self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
260
-    }
261
-
262
-
263
-
264
-    /**
265
-     * localize_i18n_js_strings
266
-     *
267
-     * @return string
268
-     */
269
-    public static function localize_i18n_js_strings()
270
-    {
271
-        $i18n_js_strings = (array)self::$i18n_js_strings;
272
-        foreach ($i18n_js_strings as $key => $value) {
273
-            if (is_scalar($value)) {
274
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
275
-            }
276
-        }
277
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
278
-    }
279
-
280
-
281
-
282
-    /**
283
-     * @param mixed string | EED_Module $module
284
-     * @throws EE_Error
285
-     * @throws ReflectionException
286
-     */
287
-    public function add_module($module)
288
-    {
289
-        if ($module instanceof EED_Module) {
290
-            $module_class = get_class($module);
291
-            $this->modules->{$module_class} = $module;
292
-        } else {
293
-            if ( ! class_exists('EE_Module_Request_Router', false)) {
294
-                $this->load_core('Module_Request_Router');
295
-            }
296
-            EE_Module_Request_Router::module_factory($module);
297
-        }
298
-    }
299
-
300
-
301
-
302
-    /**
303
-     * @param string $module_name
304
-     * @return mixed EED_Module | NULL
305
-     */
306
-    public function get_module($module_name = '')
307
-    {
308
-        return isset($this->modules->{$module_name})
309
-            ? $this->modules->{$module_name}
310
-            : null;
311
-    }
312
-
313
-
314
-
315
-    /**
316
-     * loads core classes - must be singletons
317
-     *
318
-     * @param string $class_name - simple class name ie: session
319
-     * @param mixed  $arguments
320
-     * @param bool   $load_only
321
-     * @return mixed
322
-     * @throws EE_Error
323
-     * @throws ReflectionException
324
-     */
325
-    public function load_core($class_name, $arguments = array(), $load_only = false)
326
-    {
327
-        $core_paths = apply_filters(
328
-            'FHEE__EE_Registry__load_core__core_paths',
329
-            array(
330
-                EE_CORE,
331
-                EE_ADMIN,
332
-                EE_CPTS,
333
-                EE_CORE . 'data_migration_scripts' . DS,
334
-                EE_CORE . 'capabilities' . DS,
335
-                EE_CORE . 'request_stack' . DS,
336
-                EE_CORE . 'middleware' . DS,
337
-            )
338
-        );
339
-        // retrieve instantiated class
340
-        return $this->_load(
341
-            $core_paths,
342
-            'EE_',
343
-            $class_name,
344
-            'core',
345
-            $arguments,
346
-            false,
347
-            true,
348
-            $load_only
349
-        );
350
-    }
351
-
352
-
353
-
354
-    /**
355
-     * loads service classes
356
-     *
357
-     * @param string $class_name - simple class name ie: session
358
-     * @param mixed  $arguments
359
-     * @param bool   $load_only
360
-     * @return mixed
361
-     * @throws EE_Error
362
-     * @throws ReflectionException
363
-     */
364
-    public function load_service($class_name, $arguments = array(), $load_only = false)
365
-    {
366
-        $service_paths = apply_filters(
367
-            'FHEE__EE_Registry__load_service__service_paths',
368
-            array(
369
-                EE_CORE . 'services' . DS,
370
-            )
371
-        );
372
-        // retrieve instantiated class
373
-        return $this->_load(
374
-            $service_paths,
375
-            'EE_',
376
-            $class_name,
377
-            'class',
378
-            $arguments,
379
-            false,
380
-            true,
381
-            $load_only
382
-        );
383
-    }
384
-
385
-
386
-
387
-    /**
388
-     * loads data_migration_scripts
389
-     *
390
-     * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
391
-     * @param mixed  $arguments
392
-     * @return EE_Data_Migration_Script_Base|mixed
393
-     * @throws EE_Error
394
-     * @throws ReflectionException
395
-     */
396
-    public function load_dms($class_name, $arguments = array())
397
-    {
398
-        // retrieve instantiated class
399
-        return $this->_load(
400
-            EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
401
-            'EE_DMS_',
402
-            $class_name,
403
-            'dms',
404
-            $arguments,
405
-            false,
406
-            false
407
-        );
408
-    }
409
-
410
-
411
-
412
-    /**
413
-     * loads object creating classes - must be singletons
414
-     *
415
-     * @param string $class_name - simple class name ie: attendee
416
-     * @param mixed  $arguments  - an array of arguments to pass to the class
417
-     * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
418
-     *                           instantiate
419
-     * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
420
-     *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
421
-     * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
422
-     *                           (default)
423
-     * @return EE_Base_Class | bool
424
-     * @throws EE_Error
425
-     * @throws ReflectionException
426
-     */
427
-    public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
428
-    {
429
-        $paths = apply_filters(
430
-            'FHEE__EE_Registry__load_class__paths', array(
431
-            EE_CORE,
432
-            EE_CLASSES,
433
-            EE_BUSINESS,
434
-        )
435
-        );
436
-        // retrieve instantiated class
437
-        return $this->_load(
438
-            $paths,
439
-            'EE_',
440
-            $class_name,
441
-            'class',
442
-            $arguments,
443
-            $from_db,
444
-            $cache,
445
-            $load_only
446
-        );
447
-    }
448
-
449
-
450
-
451
-    /**
452
-     * loads helper classes - must be singletons
453
-     *
454
-     * @param string $class_name - simple class name ie: price
455
-     * @param mixed  $arguments
456
-     * @param bool   $load_only
457
-     * @return EEH_Base | bool
458
-     * @throws EE_Error
459
-     * @throws ReflectionException
460
-     */
461
-    public function load_helper($class_name, $arguments = array(), $load_only = true)
462
-    {
463
-        // todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
464
-        $helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
465
-        // retrieve instantiated class
466
-        return $this->_load(
467
-            $helper_paths,
468
-            'EEH_',
469
-            $class_name,
470
-            'helper',
471
-            $arguments,
472
-            false,
473
-            true,
474
-            $load_only
475
-        );
476
-    }
477
-
478
-
479
-
480
-    /**
481
-     * loads core classes - must be singletons
482
-     *
483
-     * @param string $class_name - simple class name ie: session
484
-     * @param mixed  $arguments
485
-     * @param bool   $load_only
486
-     * @param bool   $cache      whether to cache the object or not.
487
-     * @return mixed
488
-     * @throws EE_Error
489
-     * @throws ReflectionException
490
-     */
491
-    public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
492
-    {
493
-        $paths = array(
494
-            EE_LIBRARIES,
495
-            EE_LIBRARIES . 'messages' . DS,
496
-            EE_LIBRARIES . 'shortcodes' . DS,
497
-            EE_LIBRARIES . 'qtips' . DS,
498
-            EE_LIBRARIES . 'payment_methods' . DS,
499
-        );
500
-        // retrieve instantiated class
501
-        return $this->_load(
502
-            $paths,
503
-            'EE_',
504
-            $class_name,
505
-            'lib',
506
-            $arguments,
507
-            false,
508
-            $cache,
509
-            $load_only
510
-        );
511
-    }
512
-
513
-
514
-
515
-    /**
516
-     * loads model classes - must be singletons
517
-     *
518
-     * @param string $class_name - simple class name ie: price
519
-     * @param mixed  $arguments
520
-     * @param bool   $load_only
521
-     * @return EEM_Base | bool
522
-     * @throws EE_Error
523
-     * @throws ReflectionException
524
-     */
525
-    public function load_model($class_name, $arguments = array(), $load_only = false)
526
-    {
527
-        $paths = apply_filters(
528
-            'FHEE__EE_Registry__load_model__paths', array(
529
-            EE_MODELS,
530
-            EE_CORE,
531
-        )
532
-        );
533
-        // retrieve instantiated class
534
-        return $this->_load(
535
-            $paths,
536
-            'EEM_',
537
-            $class_name,
538
-            'model',
539
-            $arguments,
540
-            false,
541
-            true,
542
-            $load_only
543
-        );
544
-    }
545
-
546
-
547
-
548
-    /**
549
-     * loads model classes - must be singletons
550
-     *
551
-     * @param string $class_name - simple class name ie: price
552
-     * @param mixed  $arguments
553
-     * @param bool   $load_only
554
-     * @return mixed | bool
555
-     * @throws EE_Error
556
-     * @throws ReflectionException
557
-     */
558
-    public function load_model_class($class_name, $arguments = array(), $load_only = true)
559
-    {
560
-        $paths = array(
561
-            EE_MODELS . 'fields' . DS,
562
-            EE_MODELS . 'helpers' . DS,
563
-            EE_MODELS . 'relations' . DS,
564
-            EE_MODELS . 'strategies' . DS,
565
-        );
566
-        // retrieve instantiated class
567
-        return $this->_load(
568
-            $paths,
569
-            'EE_',
570
-            $class_name,
571
-            '',
572
-            $arguments,
573
-            false,
574
-            true,
575
-            $load_only
576
-        );
577
-    }
578
-
579
-
580
-
581
-    /**
582
-     * Determines if $model_name is the name of an actual EE model.
583
-     *
584
-     * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
585
-     * @return boolean
586
-     */
587
-    public function is_model_name($model_name)
588
-    {
589
-        return isset($this->models[$model_name]);
590
-    }
591
-
592
-
593
-
594
-    /**
595
-     * generic class loader
596
-     *
597
-     * @param string $path_to_file - directory path to file location, not including filename
598
-     * @param string $file_name    - file name  ie:  my_file.php, including extension
599
-     * @param string $type         - file type - core? class? helper? model?
600
-     * @param mixed  $arguments
601
-     * @param bool   $load_only
602
-     * @return mixed
603
-     * @throws EE_Error
604
-     * @throws ReflectionException
605
-     */
606
-    public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
607
-    {
608
-        // retrieve instantiated class
609
-        return $this->_load(
610
-            $path_to_file,
611
-            '',
612
-            $file_name,
613
-            $type,
614
-            $arguments,
615
-            false,
616
-            true,
617
-            $load_only
618
-        );
619
-    }
620
-
621
-
622
-
623
-    /**
624
-     * @param string $path_to_file - directory path to file location, not including filename
625
-     * @param string $class_name   - full class name  ie:  My_Class
626
-     * @param string $type         - file type - core? class? helper? model?
627
-     * @param mixed  $arguments
628
-     * @param bool   $load_only
629
-     * @return bool|EE_Addon|object
630
-     * @throws EE_Error
631
-     * @throws ReflectionException
632
-     */
633
-    public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
634
-    {
635
-        // retrieve instantiated class
636
-        return $this->_load(
637
-            $path_to_file,
638
-            'addon',
639
-            $class_name,
640
-            $type,
641
-            $arguments,
642
-            false,
643
-            true,
644
-            $load_only
645
-        );
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     * instantiates, caches, and automatically resolves dependencies
652
-     * for classes that use a Fully Qualified Class Name.
653
-     * if the class is not capable of being loaded using PSR-4 autoloading,
654
-     * then you need to use one of the existing load_*() methods
655
-     * which can resolve the classname and filepath from the passed arguments
656
-     *
657
-     * @param bool|string $class_name   Fully Qualified Class Name
658
-     * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
659
-     * @param bool        $cache        whether to cache the instantiated object for reuse
660
-     * @param bool        $from_db      some classes are instantiated from the db
661
-     *                                  and thus call a different method to instantiate
662
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
663
-     * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
664
-     * @return bool|null|mixed          null = failure to load or instantiate class object.
665
-     *                                  object = class loaded and instantiated successfully.
666
-     *                                  bool = fail or success when $load_only is true
667
-     * @throws EE_Error
668
-     * @throws ReflectionException
669
-     */
670
-    public function create(
671
-        $class_name = false,
672
-        $arguments = array(),
673
-        $cache = false,
674
-        $from_db = false,
675
-        $load_only = false,
676
-        $addon = false
677
-    ) {
678
-        $class_name = ltrim($class_name, '\\');
679
-        $class_name = $this->_dependency_map->get_alias($class_name);
680
-        $class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
681
-        // if a non-FQCN was passed, then verifyClassExists() might return an object
682
-        // or it could return null if the class just could not be found anywhere
683
-        if ($class_exists instanceof $class_name || $class_exists === null){
684
-            // either way, return the results
685
-            return $class_exists;
686
-        }
687
-        $class_name = $class_exists;
688
-        // if we're only loading the class and it already exists, then let's just return true immediately
689
-        if ($load_only) {
690
-            return true;
691
-        }
692
-        $addon = $addon
693
-            ? 'addon'
694
-            : '';
695
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
696
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
697
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
698
-        if ($this->_cache_on && $cache && ! $load_only) {
699
-            // return object if it's already cached
700
-            $cached_class = $this->_get_cached_class($class_name, $addon);
701
-            if ($cached_class !== null) {
702
-                return $cached_class;
703
-            }
704
-        }
705
-        // obtain the loader method from the dependency map
706
-        $loader = $this->_dependency_map->class_loader($class_name);
707
-        // instantiate the requested object
708
-        if ($loader instanceof Closure) {
709
-            $class_obj = $loader($arguments);
710
-        } else if ($loader && method_exists($this, $loader)) {
711
-            $class_obj = $this->{$loader}($class_name, $arguments);
712
-        } else {
713
-            $class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
714
-        }
715
-        if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
716
-            // save it for later... kinda like gum  { : $
717
-            $this->_set_cached_class($class_obj, $class_name, $addon, $from_db);
718
-        }
719
-        $this->_cache_on = true;
720
-        return $class_obj;
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
727
-     *
728
-     * @param string $class_name
729
-     * @param array  $arguments
730
-     * @param int    $attempt
731
-     * @return mixed
732
-     */
733
-    private function loadOrVerifyClassExists($class_name, array $arguments, $attempt = 1) {
734
-        if (is_object($class_name) || class_exists($class_name)) {
735
-            return $class_name;
736
-        }
737
-        switch ($attempt) {
738
-            case 1:
739
-                // if it's a FQCN then maybe the class is registered with a preceding \
740
-                $class_name = strpos($class_name, '\\') !== false
741
-                    ? '\\' . ltrim($class_name, '\\')
742
-                    : $class_name;
743
-                break;
744
-            case 2:
745
-                //
746
-                $loader = $this->_dependency_map->class_loader($class_name);
747
-                if ($loader && method_exists($this, $loader)) {
748
-                    return $this->{$loader}($class_name, $arguments);
749
-                }
750
-                break;
751
-            case 3:
752
-            default;
753
-                return null;
754
-        }
755
-        $attempt++;
756
-        return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
757
-    }
758
-
759
-
760
-
761
-    /**
762
-     * instantiates, caches, and injects dependencies for classes
763
-     *
764
-     * @param array       $file_paths   an array of paths to folders to look in
765
-     * @param string      $class_prefix EE  or EEM or... ???
766
-     * @param bool|string $class_name   $class name
767
-     * @param string      $type         file type - core? class? helper? model?
768
-     * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
769
-     * @param bool        $from_db      some classes are instantiated from the db
770
-     *                                  and thus call a different method to instantiate
771
-     * @param bool        $cache        whether to cache the instantiated object for reuse
772
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
773
-     * @return bool|null|object null = failure to load or instantiate class object.
774
-     *                                  object = class loaded and instantiated successfully.
775
-     *                                  bool = fail or success when $load_only is true
776
-     * @throws EE_Error
777
-     * @throws ReflectionException
778
-     */
779
-    protected function _load(
780
-        $file_paths = array(),
781
-        $class_prefix = 'EE_',
782
-        $class_name = false,
783
-        $type = 'class',
784
-        $arguments = array(),
785
-        $from_db = false,
786
-        $cache = true,
787
-        $load_only = false
788
-    ) {
789
-        $class_name = ltrim($class_name, '\\');
790
-        // strip php file extension
791
-        $class_name = str_replace('.php', '', trim($class_name));
792
-        // does the class have a prefix ?
793
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
794
-            // make sure $class_prefix is uppercase
795
-            $class_prefix = strtoupper(trim($class_prefix));
796
-            // add class prefix ONCE!!!
797
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
798
-        }
799
-        $class_name = $this->_dependency_map->get_alias($class_name);
800
-        $class_exists = class_exists($class_name, false);
801
-        // if we're only loading the class and it already exists, then let's just return true immediately
802
-        if ($load_only && $class_exists) {
803
-            return true;
804
-        }
805
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
806
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
807
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
808
-        if ($this->_cache_on && $cache && ! $load_only) {
809
-            // return object if it's already cached
810
-            $cached_class = $this->_get_cached_class($class_name, $class_prefix);
811
-            if ($cached_class !== null) {
812
-                return $cached_class;
813
-            }
814
-        }
815
-        // if the class doesn't already exist.. then we need to try and find the file and load it
816
-        if (! $class_exists) {
817
-            // get full path to file
818
-            $path = $this->_resolve_path($class_name, $type, $file_paths);
819
-            // load the file
820
-            $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
821
-            // if loading failed, or we are only loading a file but NOT instantiating an object
822
-            if (! $loaded || $load_only) {
823
-                // return boolean if only loading, or null if an object was expected
824
-                return $load_only
825
-                    ? $loaded
826
-                    : null;
827
-            }
828
-        }
829
-        // instantiate the requested object
830
-        $class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
831
-        if ($this->_cache_on && $cache) {
832
-            // save it for later... kinda like gum  { : $
833
-            $this->_set_cached_class($class_obj, $class_name, $class_prefix, $from_db);
834
-        }
835
-        $this->_cache_on = true;
836
-        return $class_obj;
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * @param string $class_name
843
-     * @param string $default have to specify something, but not anything that will conflict
844
-     * @return mixed|string
845
-     */
846
-    protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
847
-    {
848
-        return isset($this->_class_abbreviations[$class_name])
849
-            ? $this->_class_abbreviations[$class_name]
850
-            : $default;
851
-    }
852
-
853
-    /**
854
-     * attempts to find a cached version of the requested class
855
-     * by looking in the following places:
856
-     *        $this->{$class_abbreviation}            ie:    $this->CART
857
-     *        $this->{$class_name}                        ie:    $this->Some_Class
858
-     *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
859
-     *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
860
-     *
861
-     * @param string $class_name
862
-     * @param string $class_prefix
863
-     * @return mixed
864
-     */
865
-    protected function _get_cached_class($class_name, $class_prefix = '')
866
-    {
867
-        if ($class_name === 'EE_Registry') {
868
-            return $this;
869
-        }
870
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
871
-        $class_name = str_replace('\\', '_', $class_name);
872
-        // check if class has already been loaded, and return it if it has been
873
-        if (isset($this->{$class_abbreviation})) {
874
-            return $this->{$class_abbreviation};
875
-        }
876
-        if (isset ($this->{$class_name})) {
877
-            return $this->{$class_name};
878
-        }
879
-        if (isset ($this->LIB->{$class_name})) {
880
-            return $this->LIB->{$class_name};
881
-        }
882
-        if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
883
-            return $this->addons->{$class_name};
884
-        }
885
-        return null;
886
-    }
887
-
888
-
889
-
890
-    /**
891
-     * removes a cached version of the requested class
892
-     *
893
-     * @param string  $class_name
894
-     * @param boolean $addon
895
-     * @return boolean
896
-     */
897
-    public function clear_cached_class($class_name, $addon = false)
898
-    {
899
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
900
-        $class_name = str_replace('\\', '_', $class_name);
901
-        // check if class has already been loaded, and return it if it has been
902
-        if (isset($this->{$class_abbreviation})) {
903
-            $this->{$class_abbreviation} = null;
904
-            return true;
905
-        }
906
-        if (isset($this->{$class_name})) {
907
-            $this->{$class_name} = null;
908
-            return true;
909
-        }
910
-        if (isset($this->LIB->{$class_name})) {
911
-            unset($this->LIB->{$class_name});
912
-            return true;
913
-        }
914
-        if ($addon && isset($this->addons->{$class_name})) {
915
-            unset($this->addons->{$class_name});
916
-            return true;
917
-        }
918
-        return false;
919
-    }
920
-
921
-
922
-
923
-    /**
924
-     * attempts to find a full valid filepath for the requested class.
925
-     * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
926
-     * then returns that path if the target file has been found and is readable
927
-     *
928
-     * @param string $class_name
929
-     * @param string $type
930
-     * @param array  $file_paths
931
-     * @return string | bool
932
-     */
933
-    protected function _resolve_path($class_name, $type = '', $file_paths = array())
934
-    {
935
-        // make sure $file_paths is an array
936
-        $file_paths = is_array($file_paths)
937
-            ? $file_paths
938
-            : array($file_paths);
939
-        // cycle thru paths
940
-        foreach ($file_paths as $key => $file_path) {
941
-            // convert all separators to proper DS, if no filepath, then use EE_CLASSES
942
-            $file_path = $file_path
943
-                ? str_replace(array('/', '\\'), DS, $file_path)
944
-                : EE_CLASSES;
945
-            // prep file type
946
-            $type = ! empty($type)
947
-                ? trim($type, '.') . '.'
948
-                : '';
949
-            // build full file path
950
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
951
-            //does the file exist and can be read ?
952
-            if (is_readable($file_paths[$key])) {
953
-                return $file_paths[$key];
954
-            }
955
-        }
956
-        return false;
957
-    }
958
-
959
-
960
-
961
-    /**
962
-     * basically just performs a require_once()
963
-     * but with some error handling
964
-     *
965
-     * @param  string $path
966
-     * @param  string $class_name
967
-     * @param  string $type
968
-     * @param  array  $file_paths
969
-     * @return bool
970
-     * @throws EE_Error
971
-     * @throws ReflectionException
972
-     */
973
-    protected function _require_file($path, $class_name, $type = '', $file_paths = array())
974
-    {
975
-        $this->resolve_legacy_class_parent($class_name);
976
-        // don't give up! you gotta...
977
-        try {
978
-            //does the file exist and can it be read ?
979
-            if (! $path) {
980
-                // just in case the file has already been autoloaded,
981
-                // but discrepancies in the naming schema are preventing it from
982
-                // being loaded via one of the EE_Registry::load_*() methods,
983
-                // then let's try one last hail mary before throwing an exception
984
-                // and call class_exists() again, but with autoloading turned ON
985
-                if(class_exists($class_name)) {
986
-                    return true;
987
-                }
988
-                // so sorry, can't find the file
989
-                throw new EE_Error (
990
-                    sprintf(
991
-                        esc_html__(
992
-                            'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
993
-                            'event_espresso'
994
-                        ),
995
-                        trim($type, '.'),
996
-                        $class_name,
997
-                        '<br />' . implode(',<br />', $file_paths)
998
-                    )
999
-                );
1000
-            }
1001
-            // get the file
1002
-            require_once($path);
1003
-            // if the class isn't already declared somewhere
1004
-            if (class_exists($class_name, false) === false) {
1005
-                // so sorry, not a class
1006
-                throw new EE_Error(
1007
-                    sprintf(
1008
-                        esc_html__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
1009
-                        $type,
1010
-                        $path,
1011
-                        $class_name
1012
-                    )
1013
-                );
1014
-            }
1015
-        } catch (EE_Error $e) {
1016
-            $e->get_error();
1017
-            return false;
1018
-        }
1019
-        return true;
1020
-    }
1021
-
1022
-
1023
-
1024
-    /**
1025
-     * Some of our legacy classes that extended a parent class would simply use a require() statement
1026
-     * before their class declaration in order to ensure that the parent class was loaded.
1027
-     * This is not ideal, but it's nearly impossible to determine the parent class of a non-namespaced class,
1028
-     * without triggering a fatal error because the parent class has yet to be loaded and therefore doesn't exist.
1029
-     *
1030
-     * @param string $class_name
1031
-     */
1032
-    protected function resolve_legacy_class_parent($class_name = '')
1033
-    {
1034
-        try {
1035
-            $legacy_parent_class_map = array(
1036
-                'EE_Payment_Processor' => 'core/business/EE_Processor_Base.class.php'
1037
-            );
1038
-            if(isset($legacy_parent_class_map[$class_name])) {
1039
-                require_once EE_PLUGIN_DIR_PATH . $legacy_parent_class_map[$class_name];
1040
-            }
1041
-        } catch (Exception $exception) {
1042
-        }
1043
-    }
1044
-
1045
-
1046
-
1047
-    /**
1048
-     * _create_object
1049
-     * Attempts to instantiate the requested class via any of the
1050
-     * commonly used instantiation methods employed throughout EE.
1051
-     * The priority for instantiation is as follows:
1052
-     *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1053
-     *        - model objects via their 'new_instance_from_db' method
1054
-     *        - model objects via their 'new_instance' method
1055
-     *        - "singleton" classes" via their 'instance' method
1056
-     *    - standard instantiable classes via their __constructor
1057
-     * Prior to instantiation, if the classname exists in the dependency_map,
1058
-     * then the constructor for the requested class will be examined to determine
1059
-     * if any dependencies exist, and if they can be injected.
1060
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1061
-     *
1062
-     * @param string $class_name
1063
-     * @param array  $arguments
1064
-     * @param string $type
1065
-     * @param bool   $from_db
1066
-     * @return null|object
1067
-     * @throws EE_Error
1068
-     * @throws ReflectionException
1069
-     */
1070
-    protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
1071
-    {
1072
-        // create reflection
1073
-        $reflector = $this->get_ReflectionClass($class_name);
1074
-        // make sure arguments are an array
1075
-        $arguments = is_array($arguments)
1076
-            ? $arguments
1077
-            : array($arguments);
1078
-        // and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1079
-        // else wrap it in an additional array so that it doesn't get split into multiple parameters
1080
-        $arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1081
-            ? $arguments
1082
-            : array($arguments);
1083
-        // attempt to inject dependencies ?
1084
-        if ($this->_dependency_map->has($class_name)) {
1085
-            $arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1086
-        }
1087
-        // instantiate the class if possible
1088
-        if ($reflector->isAbstract()) {
1089
-            // nothing to instantiate, loading file was enough
1090
-            // does not throw an exception so $instantiation_mode is unused
1091
-            // $instantiation_mode = "1) no constructor abstract class";
1092
-            return true;
1093
-        }
1094
-        if (empty($arguments) && $reflector->getConstructor() === null && $reflector->isInstantiable()) {
1095
-            // no constructor = static methods only... nothing to instantiate, loading file was enough
1096
-            // $instantiation_mode = "2) no constructor but instantiable";
1097
-            return $reflector->newInstance();
1098
-        }
1099
-        if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1100
-            // $instantiation_mode = "3) new_instance_from_db()";
1101
-            return call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
1102
-        }
1103
-        if (method_exists($class_name, 'new_instance')) {
1104
-            // $instantiation_mode = "4) new_instance()";
1105
-            return call_user_func_array(array($class_name, 'new_instance'), $arguments);
1106
-        }
1107
-        if (method_exists($class_name, 'instance')) {
1108
-            // $instantiation_mode = "5) instance()";
1109
-            return call_user_func_array(array($class_name, 'instance'), $arguments);
1110
-        }
1111
-        if ($reflector->isInstantiable()) {
1112
-            // $instantiation_mode = "6) constructor";
1113
-            return $reflector->newInstanceArgs($arguments);
1114
-        }
1115
-        // heh ? something's not right !
1116
-        throw new EE_Error(
1117
-            sprintf(
1118
-                __('The %s file %s could not be instantiated.', 'event_espresso'),
1119
-                $type,
1120
-                $class_name
1121
-            )
1122
-        );
1123
-    }
1124
-
1125
-
1126
-
1127
-    /**
1128
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1129
-     * @param array $array
1130
-     * @return bool
1131
-     */
1132
-    protected function _array_is_numerically_and_sequentially_indexed(array $array)
1133
-    {
1134
-        return ! empty($array)
1135
-            ? array_keys($array) === range(0, count($array) - 1)
1136
-            : true;
1137
-    }
1138
-
1139
-
1140
-
1141
-    /**
1142
-     * getReflectionClass
1143
-     * checks if a ReflectionClass object has already been generated for a class
1144
-     * and returns that instead of creating a new one
1145
-     *
1146
-     * @param string $class_name
1147
-     * @return ReflectionClass
1148
-     * @throws ReflectionException
1149
-     */
1150
-    public function get_ReflectionClass($class_name)
1151
-    {
1152
-        if (
1153
-            ! isset($this->_reflectors[$class_name])
1154
-            || ! $this->_reflectors[$class_name] instanceof ReflectionClass
1155
-        ) {
1156
-            $this->_reflectors[$class_name] = new ReflectionClass($class_name);
1157
-        }
1158
-        return $this->_reflectors[$class_name];
1159
-    }
1160
-
1161
-
1162
-
1163
-    /**
1164
-     * _resolve_dependencies
1165
-     * examines the constructor for the requested class to determine
1166
-     * if any dependencies exist, and if they can be injected.
1167
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1168
-     * PLZ NOTE: this is achieved by type hinting the constructor params
1169
-     * For example:
1170
-     *        if attempting to load a class "Foo" with the following constructor:
1171
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
1172
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
1173
-     *        but only IF they are NOT already present in the incoming arguments array,
1174
-     *        and the correct classes can be loaded
1175
-     *
1176
-     * @param ReflectionClass $reflector
1177
-     * @param string          $class_name
1178
-     * @param array           $arguments
1179
-     * @return array
1180
-     * @throws EE_Error
1181
-     * @throws ReflectionException
1182
-     */
1183
-    protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1184
-    {
1185
-        // let's examine the constructor
1186
-        $constructor = $reflector->getConstructor();
1187
-        // whu? huh? nothing?
1188
-        if (! $constructor) {
1189
-            return $arguments;
1190
-        }
1191
-        // get constructor parameters
1192
-        $params = $constructor->getParameters();
1193
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1194
-        $argument_keys = array_keys($arguments);
1195
-        // now loop thru all of the constructors expected parameters
1196
-        foreach ($params as $index => $param) {
1197
-            // is this a dependency for a specific class ?
1198
-            $param_class = $param->getClass()
1199
-                ? $param->getClass()->name
1200
-                : null;
1201
-            // BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1202
-            $param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1203
-                ? $this->_dependency_map->get_alias($param_class, $class_name)
1204
-                : $param_class;
1205
-            if (
1206
-                // param is not even a class
1207
-                $param_class === null
1208
-                // and something already exists in the incoming arguments for this param
1209
-                && array_key_exists($index, $argument_keys)
1210
-                && array_key_exists($argument_keys[$index], $arguments)
1211
-            ) {
1212
-                // so let's skip this argument and move on to the next
1213
-                continue;
1214
-            }
1215
-            if (
1216
-                // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1217
-                $param_class !== null
1218
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1219
-                && $arguments[$argument_keys[$index]] instanceof $param_class
1220
-            ) {
1221
-                // skip this argument and move on to the next
1222
-                continue;
1223
-            }
1224
-            if (
1225
-                // parameter is type hinted as a class, and should be injected
1226
-                $param_class !== null
1227
-                && $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1228
-            ) {
1229
-                $arguments = $this->_resolve_dependency(
1230
-                    $class_name,
1231
-                    $param_class,
1232
-                    $arguments,
1233
-                    $index,
1234
-                    $argument_keys
1235
-                );
1236
-            } else {
1237
-                try {
1238
-                    $arguments[$index] = $param->isDefaultValueAvailable()
1239
-                        ? $param->getDefaultValue()
1240
-                        : null;
1241
-                } catch (ReflectionException $e) {
1242
-                    throw new ReflectionException(
1243
-                        sprintf(
1244
-                            esc_html__('%1$s for parameter "$%2$s on classname "%3$s"', 'event_espresso'),
1245
-                            $e->getMessage(),
1246
-                            $param->getName(),
1247
-                            $class_name
1248
-                        )
1249
-                    );
1250
-                }
1251
-            }
1252
-        }
1253
-        return $arguments;
1254
-    }
1255
-
1256
-
1257
-
1258
-    /**
1259
-     * @param string $class_name
1260
-     * @param string $param_class
1261
-     * @param array  $arguments
1262
-     * @param mixed  $index
1263
-     * @param array  $argument_keys
1264
-     * @return array
1265
-     * @throws EE_Error
1266
-     * @throws ReflectionException
1267
-     * @throws InvalidArgumentException
1268
-     * @throws InvalidInterfaceException
1269
-     * @throws InvalidDataTypeException
1270
-     */
1271
-    protected function _resolve_dependency($class_name, $param_class, $arguments, $index, array $argument_keys)
1272
-    {
1273
-        $dependency = null;
1274
-        // should dependency be loaded from cache ?
1275
-        $cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1276
-            $class_name,
1277
-            $param_class
1278
-        );
1279
-        $cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1280
-        // we might have a dependency...
1281
-        // let's MAYBE try and find it in our cache if that's what's been requested
1282
-        $cached_class = $cache_on
1283
-            ? $this->_get_cached_class($param_class)
1284
-            : null;
1285
-        // and grab it if it exists
1286
-        if ($cached_class instanceof $param_class) {
1287
-            $dependency = $cached_class;
1288
-        } else if ($param_class !== $class_name) {
1289
-            // obtain the loader method from the dependency map
1290
-            $loader = $this->_dependency_map->class_loader($param_class);
1291
-            // is loader a custom closure ?
1292
-            if ($loader instanceof Closure) {
1293
-                $dependency = $loader($arguments);
1294
-            } else {
1295
-                // set the cache on property for the recursive loading call
1296
-                $this->_cache_on = $cache_on;
1297
-                // if not, then let's try and load it via the registry
1298
-                if ($loader && method_exists($this, $loader)) {
1299
-                    $dependency = $this->{$loader}($param_class);
1300
-                } else {
1301
-                    $dependency = LoaderFactory::getLoader()->load(
1302
-                        $param_class,
1303
-                        array(),
1304
-                        $cache_on
1305
-                    );
1306
-                }
1307
-            }
1308
-        }
1309
-        // did we successfully find the correct dependency ?
1310
-        if ($dependency instanceof $param_class) {
1311
-            // then let's inject it into the incoming array of arguments at the correct location
1312
-            $arguments[$index] = $dependency;
1313
-        }
1314
-        return $arguments;
1315
-    }
1316
-
1317
-
1318
-
1319
-    /**
1320
-     * _set_cached_class
1321
-     * attempts to cache the instantiated class locally
1322
-     * in one of the following places, in the following order:
1323
-     *        $this->{class_abbreviation}   ie:    $this->CART
1324
-     *        $this->{$class_name}          ie:    $this->Some_Class
1325
-     *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1326
-     *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1327
-     *
1328
-     * @param object $class_obj
1329
-     * @param string $class_name
1330
-     * @param string $class_prefix
1331
-     * @param bool   $from_db
1332
-     * @return void
1333
-     */
1334
-    protected function _set_cached_class($class_obj, $class_name, $class_prefix = '', $from_db = false)
1335
-    {
1336
-        if ($class_name === 'EE_Registry' || empty($class_obj)) {
1337
-            return;
1338
-        }
1339
-        // return newly instantiated class
1340
-        $class_abbreviation = $this->get_class_abbreviation($class_name, '');
1341
-        if ($class_abbreviation) {
1342
-            $this->{$class_abbreviation} = $class_obj;
1343
-            return;
1344
-        }
1345
-        $class_name = str_replace('\\', '_', $class_name);
1346
-        if (property_exists($this, $class_name)) {
1347
-            $this->{$class_name} = $class_obj;
1348
-            return;
1349
-        }
1350
-        if ($class_prefix === 'addon') {
1351
-            $this->addons->{$class_name} = $class_obj;
1352
-            return;
1353
-        }
1354
-        if (! $from_db) {
1355
-            $this->LIB->{$class_name} = $class_obj;
1356
-        }
1357
-    }
1358
-
1359
-
1360
-
1361
-    /**
1362
-     * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1363
-     *
1364
-     * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1365
-     *                          in the EE_Dependency_Map::$_class_loaders array,
1366
-     *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1367
-     * @param array  $arguments
1368
-     * @return object
1369
-     */
1370
-    public static function factory($classname, $arguments = array())
1371
-    {
1372
-        $loader = self::instance()->_dependency_map->class_loader($classname);
1373
-        if ($loader instanceof Closure) {
1374
-            return $loader($arguments);
1375
-        }
1376
-        if (method_exists(self::instance(), $loader)) {
1377
-            return self::instance()->{$loader}($classname, $arguments);
1378
-        }
1379
-        return null;
1380
-    }
1381
-
1382
-
1383
-
1384
-    /**
1385
-     * Gets the addon by its class name
1386
-     *
1387
-     * @param string $class_name
1388
-     * @return EE_Addon
1389
-     */
1390
-    public function getAddon($class_name)
1391
-    {
1392
-        $class_name = str_replace('\\', '_', $class_name);
1393
-        return $this->addons->{$class_name};
1394
-    }
1395
-
1396
-
1397
-    /**
1398
-     * removes the addon from the internal cache
1399
-     *
1400
-     * @param string $class_name
1401
-     * @return void
1402
-     */
1403
-    public function removeAddon($class_name)
1404
-    {
1405
-        $class_name = str_replace('\\', '_', $class_name);
1406
-        unset($this->addons->{$class_name});
1407
-    }
1408
-
1409
-
1410
-
1411
-    /**
1412
-     * Gets the addon by its name/slug (not classname. For that, just
1413
-     * use the get_addon() method above
1414
-     *
1415
-     * @param string $name
1416
-     * @return EE_Addon
1417
-     */
1418
-    public function get_addon_by_name($name)
1419
-    {
1420
-        foreach ($this->addons as $addon) {
1421
-            if ($addon->name() === $name) {
1422
-                return $addon;
1423
-            }
1424
-        }
1425
-        return null;
1426
-    }
1427
-
1428
-
1429
-
1430
-    /**
1431
-     * Gets an array of all the registered addons, where the keys are their names.
1432
-     * (ie, what each returns for their name() function)
1433
-     * They're already available on EE_Registry::instance()->addons as properties,
1434
-     * where each property's name is the addon's classname,
1435
-     * So if you just want to get the addon by classname,
1436
-     * OR use the get_addon() method above.
1437
-     * PLEASE  NOTE:
1438
-     * addons with Fully Qualified Class Names
1439
-     * have had the namespace separators converted to underscores,
1440
-     * so a classname like Fully\Qualified\ClassName
1441
-     * would have been converted to Fully_Qualified_ClassName
1442
-     *
1443
-     * @return EE_Addon[] where the KEYS are the addon's name()
1444
-     */
1445
-    public function get_addons_by_name()
1446
-    {
1447
-        $addons = array();
1448
-        foreach ($this->addons as $addon) {
1449
-            $addons[$addon->name()] = $addon;
1450
-        }
1451
-        return $addons;
1452
-    }
1453
-
1454
-
1455
-    /**
1456
-     * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1457
-     * a stale copy of it around
1458
-     *
1459
-     * @param string $model_name
1460
-     * @return \EEM_Base
1461
-     * @throws \EE_Error
1462
-     */
1463
-    public function reset_model($model_name)
1464
-    {
1465
-        $model_class_name = strpos($model_name, 'EEM_') !== 0
1466
-            ? "EEM_{$model_name}"
1467
-            : $model_name;
1468
-        if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1469
-            return null;
1470
-        }
1471
-        //get that model reset it and make sure we nuke the old reference to it
1472
-        if ($this->LIB->{$model_class_name} instanceof $model_class_name
1473
-            && is_callable(
1474
-                array($model_class_name, 'reset')
1475
-            )) {
1476
-            $this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1477
-        } else {
1478
-            throw new EE_Error(sprintf(esc_html__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1479
-        }
1480
-        return $this->LIB->{$model_class_name};
1481
-    }
1482
-
1483
-
1484
-
1485
-    /**
1486
-     * Resets the registry.
1487
-     * The criteria for what gets reset is based on what can be shared between sites on the same request when
1488
-     * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1489
-     * - $_dependency_map
1490
-     * - $_class_abbreviations
1491
-     * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1492
-     * - $REQ:  Still on the same request so no need to change.
1493
-     * - $CAP: There is no site specific state in the EE_Capability class.
1494
-     * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1495
-     * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1496
-     * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1497
-     *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1498
-     *             switch or on the restore.
1499
-     * - $modules
1500
-     * - $shortcodes
1501
-     * - $widgets
1502
-     *
1503
-     * @param boolean $hard             [deprecated]
1504
-     * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1505
-     *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1506
-     *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1507
-     * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1508
-     *                                  client
1509
-     *                                  code instead can just change the model context to a different blog id if
1510
-     *                                  necessary
1511
-     * @return EE_Registry
1512
-     * @throws EE_Error
1513
-     * @throws ReflectionException
1514
-     */
1515
-    public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1516
-    {
1517
-        $instance = self::instance();
1518
-        $instance->_cache_on = true;
1519
-        // reset some "special" classes
1520
-        EEH_Activation::reset();
1521
-        $hard = apply_filters( 'FHEE__EE_Registry__reset__hard', $hard);
1522
-        $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1523
-        $instance->CART = null;
1524
-        $instance->MRM = null;
1525
-        $instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1526
-        //messages reset
1527
-        EED_Messages::reset();
1528
-        //handle of objects cached on LIB
1529
-        foreach (array('LIB', 'modules') as $cache) {
1530
-            foreach ($instance->{$cache} as $class_name => $class) {
1531
-                if (self::_reset_and_unset_object($class, $reset_models)) {
1532
-                    unset($instance->{$cache}->{$class_name});
1533
-                }
1534
-            }
1535
-        }
1536
-        return $instance;
1537
-    }
1538
-
1539
-
1540
-
1541
-    /**
1542
-     * if passed object implements ResettableInterface, then call it's reset() method
1543
-     * if passed object implements InterminableInterface, then return false,
1544
-     * to indicate that it should NOT be cleared from the Registry cache
1545
-     *
1546
-     * @param      $object
1547
-     * @param bool $reset_models
1548
-     * @return bool returns true if cached object should be unset
1549
-     */
1550
-    private static function _reset_and_unset_object($object, $reset_models)
1551
-    {
1552
-        if (! is_object($object)) {
1553
-            // don't unset anything that's not an object
1554
-            return false;
1555
-        }
1556
-        if ($object instanceof EED_Module) {
1557
-            $object::reset();
1558
-            // don't unset modules
1559
-            return false;
1560
-        }
1561
-        if ($object instanceof ResettableInterface) {
1562
-            if ($object instanceof EEM_Base) {
1563
-                if ($reset_models) {
1564
-                    $object->reset();
1565
-                    return true;
1566
-                }
1567
-                return false;
1568
-            }
1569
-            $object->reset();
1570
-            return true;
1571
-        }
1572
-        if (! $object instanceof InterminableInterface) {
1573
-            return true;
1574
-        }
1575
-        return false;
1576
-    }
1577
-
1578
-
1579
-
1580
-    /**
1581
-     * Gets all the custom post type models defined
1582
-     *
1583
-     * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1584
-     */
1585
-    public function cpt_models()
1586
-    {
1587
-        $cpt_models = array();
1588
-        foreach ($this->non_abstract_db_models as $short_name => $classname) {
1589
-            if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1590
-                $cpt_models[$short_name] = $classname;
1591
-            }
1592
-        }
1593
-        return $cpt_models;
1594
-    }
1595
-
1596
-
1597
-
1598
-    /**
1599
-     * @return \EE_Config
1600
-     */
1601
-    public static function CFG()
1602
-    {
1603
-        return self::instance()->CFG;
1604
-    }
26
+	/**
27
+	 * @var EE_Registry $_instance
28
+	 */
29
+	private static $_instance;
30
+
31
+	/**
32
+	 * @var EE_Dependency_Map $_dependency_map
33
+	 */
34
+	protected $_dependency_map;
35
+
36
+	/**
37
+	 * @var array $_class_abbreviations
38
+	 */
39
+	protected $_class_abbreviations = array();
40
+
41
+	/**
42
+	 * @var CommandBusInterface $BUS
43
+	 */
44
+	public $BUS;
45
+
46
+	/**
47
+	 * @var EE_Cart $CART
48
+	 */
49
+	public $CART;
50
+
51
+	/**
52
+	 * @var EE_Config $CFG
53
+	 */
54
+	public $CFG;
55
+
56
+	/**
57
+	 * @var EE_Network_Config $NET_CFG
58
+	 */
59
+	public $NET_CFG;
60
+
61
+	/**
62
+	 * StdClass object for storing library classes in
63
+	 *
64
+	 * @var StdClass $LIB
65
+	 */
66
+	public $LIB;
67
+
68
+	/**
69
+	 * @var EE_Request_Handler $REQ
70
+	 */
71
+	public $REQ;
72
+
73
+	/**
74
+	 * @var EE_Session $SSN
75
+	 */
76
+	public $SSN;
77
+
78
+	/**
79
+	 * @since 4.5.0
80
+	 * @var EE_Capabilities $CAP
81
+	 */
82
+	public $CAP;
83
+
84
+	/**
85
+	 * @since 4.9.0
86
+	 * @var EE_Message_Resource_Manager $MRM
87
+	 */
88
+	public $MRM;
89
+
90
+
91
+	/**
92
+	 * @var Registry $AssetsRegistry
93
+	 */
94
+	public $AssetsRegistry;
95
+
96
+	/**
97
+	 * StdClass object for holding addons which have registered themselves to work with EE core
98
+	 *
99
+	 * @var EE_Addon[] $addons
100
+	 */
101
+	public $addons;
102
+
103
+	/**
104
+	 * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
105
+	 *
106
+	 * @var EEM_Base[] $models
107
+	 */
108
+	public $models = array();
109
+
110
+	/**
111
+	 * @var EED_Module[] $modules
112
+	 */
113
+	public $modules;
114
+
115
+	/**
116
+	 * @var EES_Shortcode[] $shortcodes
117
+	 */
118
+	public $shortcodes;
119
+
120
+	/**
121
+	 * @var WP_Widget[] $widgets
122
+	 */
123
+	public $widgets;
124
+
125
+	/**
126
+	 * this is an array of all implemented model names (i.e. not the parent abstract models, or models
127
+	 * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
128
+	 * Keys are model "short names" (eg "Event") as used in model relations, and values are
129
+	 * classnames (eg "EEM_Event")
130
+	 *
131
+	 * @var array $non_abstract_db_models
132
+	 */
133
+	public $non_abstract_db_models = array();
134
+
135
+
136
+	/**
137
+	 * internationalization for JS strings
138
+	 *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
139
+	 *    in js file:  var translatedString = eei18n.string_key;
140
+	 *
141
+	 * @var array $i18n_js_strings
142
+	 */
143
+	public static $i18n_js_strings = array();
144
+
145
+
146
+	/**
147
+	 * $main_file - path to espresso.php
148
+	 *
149
+	 * @var array $main_file
150
+	 */
151
+	public $main_file;
152
+
153
+	/**
154
+	 * array of ReflectionClass objects where the key is the class name
155
+	 *
156
+	 * @var ReflectionClass[] $_reflectors
157
+	 */
158
+	public $_reflectors;
159
+
160
+	/**
161
+	 * boolean flag to indicate whether or not to load/save dependencies from/to the cache
162
+	 *
163
+	 * @var boolean $_cache_on
164
+	 */
165
+	protected $_cache_on = true;
166
+
167
+
168
+
169
+	/**
170
+	 * @singleton method used to instantiate class object
171
+	 * @param  EE_Dependency_Map $dependency_map
172
+	 * @return EE_Registry instance
173
+	 * @throws InvalidArgumentException
174
+	 * @throws InvalidInterfaceException
175
+	 * @throws InvalidDataTypeException
176
+	 */
177
+	public static function instance(EE_Dependency_Map $dependency_map = null)
178
+	{
179
+		// check if class object is instantiated
180
+		if (! self::$_instance instanceof EE_Registry) {
181
+			self::$_instance = new self($dependency_map);
182
+		}
183
+		return self::$_instance;
184
+	}
185
+
186
+
187
+
188
+	/**
189
+	 * protected constructor to prevent direct creation
190
+	 *
191
+	 * @Constructor
192
+	 * @param  EE_Dependency_Map $dependency_map
193
+	 * @throws InvalidDataTypeException
194
+	 * @throws InvalidInterfaceException
195
+	 * @throws InvalidArgumentException
196
+	 */
197
+	protected function __construct(EE_Dependency_Map $dependency_map)
198
+	{
199
+		$this->_dependency_map = $dependency_map;
200
+		// $registry_container = new RegistryContainer();
201
+		$this->LIB = new RegistryContainer();
202
+		$this->addons = new RegistryContainer();
203
+		$this->modules = new RegistryContainer();
204
+		$this->shortcodes = new RegistryContainer();
205
+		$this->widgets = new RegistryContainer();
206
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
207
+	}
208
+
209
+
210
+
211
+	/**
212
+	 * initialize
213
+	 *
214
+	 * @throws EE_Error
215
+	 * @throws ReflectionException
216
+	 */
217
+	public function initialize()
218
+	{
219
+		$this->_class_abbreviations = apply_filters(
220
+			'FHEE__EE_Registry____construct___class_abbreviations',
221
+			array(
222
+				'EE_Config'                                       => 'CFG',
223
+				'EE_Session'                                      => 'SSN',
224
+				'EE_Capabilities'                                 => 'CAP',
225
+				'EE_Cart'                                         => 'CART',
226
+				'EE_Network_Config'                               => 'NET_CFG',
227
+				'EE_Request_Handler'                              => 'REQ',
228
+				'EE_Message_Resource_Manager'                     => 'MRM',
229
+				'EventEspresso\core\services\commands\CommandBus' => 'BUS',
230
+				'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
231
+			)
232
+		);
233
+		$this->load_core('Base', array(), true);
234
+		// add our request and response objects to the cache
235
+		$request_loader = $this->_dependency_map->class_loader('EE_Request');
236
+		$this->_set_cached_class(
237
+			$request_loader(),
238
+			'EE_Request'
239
+		);
240
+		$response_loader = $this->_dependency_map->class_loader('EE_Response');
241
+		$this->_set_cached_class(
242
+			$response_loader(),
243
+			'EE_Response'
244
+		);
245
+		add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
246
+	}
247
+
248
+
249
+
250
+	/**
251
+	 * @return void
252
+	 */
253
+	public function init()
254
+	{
255
+		// Get current page protocol
256
+		$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
257
+		// Output admin-ajax.php URL with same protocol as current page
258
+		self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
259
+		self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
260
+	}
261
+
262
+
263
+
264
+	/**
265
+	 * localize_i18n_js_strings
266
+	 *
267
+	 * @return string
268
+	 */
269
+	public static function localize_i18n_js_strings()
270
+	{
271
+		$i18n_js_strings = (array)self::$i18n_js_strings;
272
+		foreach ($i18n_js_strings as $key => $value) {
273
+			if (is_scalar($value)) {
274
+				$i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
275
+			}
276
+		}
277
+		return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
278
+	}
279
+
280
+
281
+
282
+	/**
283
+	 * @param mixed string | EED_Module $module
284
+	 * @throws EE_Error
285
+	 * @throws ReflectionException
286
+	 */
287
+	public function add_module($module)
288
+	{
289
+		if ($module instanceof EED_Module) {
290
+			$module_class = get_class($module);
291
+			$this->modules->{$module_class} = $module;
292
+		} else {
293
+			if ( ! class_exists('EE_Module_Request_Router', false)) {
294
+				$this->load_core('Module_Request_Router');
295
+			}
296
+			EE_Module_Request_Router::module_factory($module);
297
+		}
298
+	}
299
+
300
+
301
+
302
+	/**
303
+	 * @param string $module_name
304
+	 * @return mixed EED_Module | NULL
305
+	 */
306
+	public function get_module($module_name = '')
307
+	{
308
+		return isset($this->modules->{$module_name})
309
+			? $this->modules->{$module_name}
310
+			: null;
311
+	}
312
+
313
+
314
+
315
+	/**
316
+	 * loads core classes - must be singletons
317
+	 *
318
+	 * @param string $class_name - simple class name ie: session
319
+	 * @param mixed  $arguments
320
+	 * @param bool   $load_only
321
+	 * @return mixed
322
+	 * @throws EE_Error
323
+	 * @throws ReflectionException
324
+	 */
325
+	public function load_core($class_name, $arguments = array(), $load_only = false)
326
+	{
327
+		$core_paths = apply_filters(
328
+			'FHEE__EE_Registry__load_core__core_paths',
329
+			array(
330
+				EE_CORE,
331
+				EE_ADMIN,
332
+				EE_CPTS,
333
+				EE_CORE . 'data_migration_scripts' . DS,
334
+				EE_CORE . 'capabilities' . DS,
335
+				EE_CORE . 'request_stack' . DS,
336
+				EE_CORE . 'middleware' . DS,
337
+			)
338
+		);
339
+		// retrieve instantiated class
340
+		return $this->_load(
341
+			$core_paths,
342
+			'EE_',
343
+			$class_name,
344
+			'core',
345
+			$arguments,
346
+			false,
347
+			true,
348
+			$load_only
349
+		);
350
+	}
351
+
352
+
353
+
354
+	/**
355
+	 * loads service classes
356
+	 *
357
+	 * @param string $class_name - simple class name ie: session
358
+	 * @param mixed  $arguments
359
+	 * @param bool   $load_only
360
+	 * @return mixed
361
+	 * @throws EE_Error
362
+	 * @throws ReflectionException
363
+	 */
364
+	public function load_service($class_name, $arguments = array(), $load_only = false)
365
+	{
366
+		$service_paths = apply_filters(
367
+			'FHEE__EE_Registry__load_service__service_paths',
368
+			array(
369
+				EE_CORE . 'services' . DS,
370
+			)
371
+		);
372
+		// retrieve instantiated class
373
+		return $this->_load(
374
+			$service_paths,
375
+			'EE_',
376
+			$class_name,
377
+			'class',
378
+			$arguments,
379
+			false,
380
+			true,
381
+			$load_only
382
+		);
383
+	}
384
+
385
+
386
+
387
+	/**
388
+	 * loads data_migration_scripts
389
+	 *
390
+	 * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
391
+	 * @param mixed  $arguments
392
+	 * @return EE_Data_Migration_Script_Base|mixed
393
+	 * @throws EE_Error
394
+	 * @throws ReflectionException
395
+	 */
396
+	public function load_dms($class_name, $arguments = array())
397
+	{
398
+		// retrieve instantiated class
399
+		return $this->_load(
400
+			EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
401
+			'EE_DMS_',
402
+			$class_name,
403
+			'dms',
404
+			$arguments,
405
+			false,
406
+			false
407
+		);
408
+	}
409
+
410
+
411
+
412
+	/**
413
+	 * loads object creating classes - must be singletons
414
+	 *
415
+	 * @param string $class_name - simple class name ie: attendee
416
+	 * @param mixed  $arguments  - an array of arguments to pass to the class
417
+	 * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
418
+	 *                           instantiate
419
+	 * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
420
+	 *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
421
+	 * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
422
+	 *                           (default)
423
+	 * @return EE_Base_Class | bool
424
+	 * @throws EE_Error
425
+	 * @throws ReflectionException
426
+	 */
427
+	public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
428
+	{
429
+		$paths = apply_filters(
430
+			'FHEE__EE_Registry__load_class__paths', array(
431
+			EE_CORE,
432
+			EE_CLASSES,
433
+			EE_BUSINESS,
434
+		)
435
+		);
436
+		// retrieve instantiated class
437
+		return $this->_load(
438
+			$paths,
439
+			'EE_',
440
+			$class_name,
441
+			'class',
442
+			$arguments,
443
+			$from_db,
444
+			$cache,
445
+			$load_only
446
+		);
447
+	}
448
+
449
+
450
+
451
+	/**
452
+	 * loads helper classes - must be singletons
453
+	 *
454
+	 * @param string $class_name - simple class name ie: price
455
+	 * @param mixed  $arguments
456
+	 * @param bool   $load_only
457
+	 * @return EEH_Base | bool
458
+	 * @throws EE_Error
459
+	 * @throws ReflectionException
460
+	 */
461
+	public function load_helper($class_name, $arguments = array(), $load_only = true)
462
+	{
463
+		// todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
464
+		$helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
465
+		// retrieve instantiated class
466
+		return $this->_load(
467
+			$helper_paths,
468
+			'EEH_',
469
+			$class_name,
470
+			'helper',
471
+			$arguments,
472
+			false,
473
+			true,
474
+			$load_only
475
+		);
476
+	}
477
+
478
+
479
+
480
+	/**
481
+	 * loads core classes - must be singletons
482
+	 *
483
+	 * @param string $class_name - simple class name ie: session
484
+	 * @param mixed  $arguments
485
+	 * @param bool   $load_only
486
+	 * @param bool   $cache      whether to cache the object or not.
487
+	 * @return mixed
488
+	 * @throws EE_Error
489
+	 * @throws ReflectionException
490
+	 */
491
+	public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
492
+	{
493
+		$paths = array(
494
+			EE_LIBRARIES,
495
+			EE_LIBRARIES . 'messages' . DS,
496
+			EE_LIBRARIES . 'shortcodes' . DS,
497
+			EE_LIBRARIES . 'qtips' . DS,
498
+			EE_LIBRARIES . 'payment_methods' . DS,
499
+		);
500
+		// retrieve instantiated class
501
+		return $this->_load(
502
+			$paths,
503
+			'EE_',
504
+			$class_name,
505
+			'lib',
506
+			$arguments,
507
+			false,
508
+			$cache,
509
+			$load_only
510
+		);
511
+	}
512
+
513
+
514
+
515
+	/**
516
+	 * loads model classes - must be singletons
517
+	 *
518
+	 * @param string $class_name - simple class name ie: price
519
+	 * @param mixed  $arguments
520
+	 * @param bool   $load_only
521
+	 * @return EEM_Base | bool
522
+	 * @throws EE_Error
523
+	 * @throws ReflectionException
524
+	 */
525
+	public function load_model($class_name, $arguments = array(), $load_only = false)
526
+	{
527
+		$paths = apply_filters(
528
+			'FHEE__EE_Registry__load_model__paths', array(
529
+			EE_MODELS,
530
+			EE_CORE,
531
+		)
532
+		);
533
+		// retrieve instantiated class
534
+		return $this->_load(
535
+			$paths,
536
+			'EEM_',
537
+			$class_name,
538
+			'model',
539
+			$arguments,
540
+			false,
541
+			true,
542
+			$load_only
543
+		);
544
+	}
545
+
546
+
547
+
548
+	/**
549
+	 * loads model classes - must be singletons
550
+	 *
551
+	 * @param string $class_name - simple class name ie: price
552
+	 * @param mixed  $arguments
553
+	 * @param bool   $load_only
554
+	 * @return mixed | bool
555
+	 * @throws EE_Error
556
+	 * @throws ReflectionException
557
+	 */
558
+	public function load_model_class($class_name, $arguments = array(), $load_only = true)
559
+	{
560
+		$paths = array(
561
+			EE_MODELS . 'fields' . DS,
562
+			EE_MODELS . 'helpers' . DS,
563
+			EE_MODELS . 'relations' . DS,
564
+			EE_MODELS . 'strategies' . DS,
565
+		);
566
+		// retrieve instantiated class
567
+		return $this->_load(
568
+			$paths,
569
+			'EE_',
570
+			$class_name,
571
+			'',
572
+			$arguments,
573
+			false,
574
+			true,
575
+			$load_only
576
+		);
577
+	}
578
+
579
+
580
+
581
+	/**
582
+	 * Determines if $model_name is the name of an actual EE model.
583
+	 *
584
+	 * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
585
+	 * @return boolean
586
+	 */
587
+	public function is_model_name($model_name)
588
+	{
589
+		return isset($this->models[$model_name]);
590
+	}
591
+
592
+
593
+
594
+	/**
595
+	 * generic class loader
596
+	 *
597
+	 * @param string $path_to_file - directory path to file location, not including filename
598
+	 * @param string $file_name    - file name  ie:  my_file.php, including extension
599
+	 * @param string $type         - file type - core? class? helper? model?
600
+	 * @param mixed  $arguments
601
+	 * @param bool   $load_only
602
+	 * @return mixed
603
+	 * @throws EE_Error
604
+	 * @throws ReflectionException
605
+	 */
606
+	public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
607
+	{
608
+		// retrieve instantiated class
609
+		return $this->_load(
610
+			$path_to_file,
611
+			'',
612
+			$file_name,
613
+			$type,
614
+			$arguments,
615
+			false,
616
+			true,
617
+			$load_only
618
+		);
619
+	}
620
+
621
+
622
+
623
+	/**
624
+	 * @param string $path_to_file - directory path to file location, not including filename
625
+	 * @param string $class_name   - full class name  ie:  My_Class
626
+	 * @param string $type         - file type - core? class? helper? model?
627
+	 * @param mixed  $arguments
628
+	 * @param bool   $load_only
629
+	 * @return bool|EE_Addon|object
630
+	 * @throws EE_Error
631
+	 * @throws ReflectionException
632
+	 */
633
+	public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
634
+	{
635
+		// retrieve instantiated class
636
+		return $this->_load(
637
+			$path_to_file,
638
+			'addon',
639
+			$class_name,
640
+			$type,
641
+			$arguments,
642
+			false,
643
+			true,
644
+			$load_only
645
+		);
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 * instantiates, caches, and automatically resolves dependencies
652
+	 * for classes that use a Fully Qualified Class Name.
653
+	 * if the class is not capable of being loaded using PSR-4 autoloading,
654
+	 * then you need to use one of the existing load_*() methods
655
+	 * which can resolve the classname and filepath from the passed arguments
656
+	 *
657
+	 * @param bool|string $class_name   Fully Qualified Class Name
658
+	 * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
659
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
660
+	 * @param bool        $from_db      some classes are instantiated from the db
661
+	 *                                  and thus call a different method to instantiate
662
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
663
+	 * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
664
+	 * @return bool|null|mixed          null = failure to load or instantiate class object.
665
+	 *                                  object = class loaded and instantiated successfully.
666
+	 *                                  bool = fail or success when $load_only is true
667
+	 * @throws EE_Error
668
+	 * @throws ReflectionException
669
+	 */
670
+	public function create(
671
+		$class_name = false,
672
+		$arguments = array(),
673
+		$cache = false,
674
+		$from_db = false,
675
+		$load_only = false,
676
+		$addon = false
677
+	) {
678
+		$class_name = ltrim($class_name, '\\');
679
+		$class_name = $this->_dependency_map->get_alias($class_name);
680
+		$class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
681
+		// if a non-FQCN was passed, then verifyClassExists() might return an object
682
+		// or it could return null if the class just could not be found anywhere
683
+		if ($class_exists instanceof $class_name || $class_exists === null){
684
+			// either way, return the results
685
+			return $class_exists;
686
+		}
687
+		$class_name = $class_exists;
688
+		// if we're only loading the class and it already exists, then let's just return true immediately
689
+		if ($load_only) {
690
+			return true;
691
+		}
692
+		$addon = $addon
693
+			? 'addon'
694
+			: '';
695
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
696
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
697
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
698
+		if ($this->_cache_on && $cache && ! $load_only) {
699
+			// return object if it's already cached
700
+			$cached_class = $this->_get_cached_class($class_name, $addon);
701
+			if ($cached_class !== null) {
702
+				return $cached_class;
703
+			}
704
+		}
705
+		// obtain the loader method from the dependency map
706
+		$loader = $this->_dependency_map->class_loader($class_name);
707
+		// instantiate the requested object
708
+		if ($loader instanceof Closure) {
709
+			$class_obj = $loader($arguments);
710
+		} else if ($loader && method_exists($this, $loader)) {
711
+			$class_obj = $this->{$loader}($class_name, $arguments);
712
+		} else {
713
+			$class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
714
+		}
715
+		if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
716
+			// save it for later... kinda like gum  { : $
717
+			$this->_set_cached_class($class_obj, $class_name, $addon, $from_db);
718
+		}
719
+		$this->_cache_on = true;
720
+		return $class_obj;
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
727
+	 *
728
+	 * @param string $class_name
729
+	 * @param array  $arguments
730
+	 * @param int    $attempt
731
+	 * @return mixed
732
+	 */
733
+	private function loadOrVerifyClassExists($class_name, array $arguments, $attempt = 1) {
734
+		if (is_object($class_name) || class_exists($class_name)) {
735
+			return $class_name;
736
+		}
737
+		switch ($attempt) {
738
+			case 1:
739
+				// if it's a FQCN then maybe the class is registered with a preceding \
740
+				$class_name = strpos($class_name, '\\') !== false
741
+					? '\\' . ltrim($class_name, '\\')
742
+					: $class_name;
743
+				break;
744
+			case 2:
745
+				//
746
+				$loader = $this->_dependency_map->class_loader($class_name);
747
+				if ($loader && method_exists($this, $loader)) {
748
+					return $this->{$loader}($class_name, $arguments);
749
+				}
750
+				break;
751
+			case 3:
752
+			default;
753
+				return null;
754
+		}
755
+		$attempt++;
756
+		return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
757
+	}
758
+
759
+
760
+
761
+	/**
762
+	 * instantiates, caches, and injects dependencies for classes
763
+	 *
764
+	 * @param array       $file_paths   an array of paths to folders to look in
765
+	 * @param string      $class_prefix EE  or EEM or... ???
766
+	 * @param bool|string $class_name   $class name
767
+	 * @param string      $type         file type - core? class? helper? model?
768
+	 * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
769
+	 * @param bool        $from_db      some classes are instantiated from the db
770
+	 *                                  and thus call a different method to instantiate
771
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
772
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
773
+	 * @return bool|null|object null = failure to load or instantiate class object.
774
+	 *                                  object = class loaded and instantiated successfully.
775
+	 *                                  bool = fail or success when $load_only is true
776
+	 * @throws EE_Error
777
+	 * @throws ReflectionException
778
+	 */
779
+	protected function _load(
780
+		$file_paths = array(),
781
+		$class_prefix = 'EE_',
782
+		$class_name = false,
783
+		$type = 'class',
784
+		$arguments = array(),
785
+		$from_db = false,
786
+		$cache = true,
787
+		$load_only = false
788
+	) {
789
+		$class_name = ltrim($class_name, '\\');
790
+		// strip php file extension
791
+		$class_name = str_replace('.php', '', trim($class_name));
792
+		// does the class have a prefix ?
793
+		if (! empty($class_prefix) && $class_prefix !== 'addon') {
794
+			// make sure $class_prefix is uppercase
795
+			$class_prefix = strtoupper(trim($class_prefix));
796
+			// add class prefix ONCE!!!
797
+			$class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
798
+		}
799
+		$class_name = $this->_dependency_map->get_alias($class_name);
800
+		$class_exists = class_exists($class_name, false);
801
+		// if we're only loading the class and it already exists, then let's just return true immediately
802
+		if ($load_only && $class_exists) {
803
+			return true;
804
+		}
805
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
806
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
807
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
808
+		if ($this->_cache_on && $cache && ! $load_only) {
809
+			// return object if it's already cached
810
+			$cached_class = $this->_get_cached_class($class_name, $class_prefix);
811
+			if ($cached_class !== null) {
812
+				return $cached_class;
813
+			}
814
+		}
815
+		// if the class doesn't already exist.. then we need to try and find the file and load it
816
+		if (! $class_exists) {
817
+			// get full path to file
818
+			$path = $this->_resolve_path($class_name, $type, $file_paths);
819
+			// load the file
820
+			$loaded = $this->_require_file($path, $class_name, $type, $file_paths);
821
+			// if loading failed, or we are only loading a file but NOT instantiating an object
822
+			if (! $loaded || $load_only) {
823
+				// return boolean if only loading, or null if an object was expected
824
+				return $load_only
825
+					? $loaded
826
+					: null;
827
+			}
828
+		}
829
+		// instantiate the requested object
830
+		$class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
831
+		if ($this->_cache_on && $cache) {
832
+			// save it for later... kinda like gum  { : $
833
+			$this->_set_cached_class($class_obj, $class_name, $class_prefix, $from_db);
834
+		}
835
+		$this->_cache_on = true;
836
+		return $class_obj;
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * @param string $class_name
843
+	 * @param string $default have to specify something, but not anything that will conflict
844
+	 * @return mixed|string
845
+	 */
846
+	protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
847
+	{
848
+		return isset($this->_class_abbreviations[$class_name])
849
+			? $this->_class_abbreviations[$class_name]
850
+			: $default;
851
+	}
852
+
853
+	/**
854
+	 * attempts to find a cached version of the requested class
855
+	 * by looking in the following places:
856
+	 *        $this->{$class_abbreviation}            ie:    $this->CART
857
+	 *        $this->{$class_name}                        ie:    $this->Some_Class
858
+	 *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
859
+	 *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
860
+	 *
861
+	 * @param string $class_name
862
+	 * @param string $class_prefix
863
+	 * @return mixed
864
+	 */
865
+	protected function _get_cached_class($class_name, $class_prefix = '')
866
+	{
867
+		if ($class_name === 'EE_Registry') {
868
+			return $this;
869
+		}
870
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
871
+		$class_name = str_replace('\\', '_', $class_name);
872
+		// check if class has already been loaded, and return it if it has been
873
+		if (isset($this->{$class_abbreviation})) {
874
+			return $this->{$class_abbreviation};
875
+		}
876
+		if (isset ($this->{$class_name})) {
877
+			return $this->{$class_name};
878
+		}
879
+		if (isset ($this->LIB->{$class_name})) {
880
+			return $this->LIB->{$class_name};
881
+		}
882
+		if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
883
+			return $this->addons->{$class_name};
884
+		}
885
+		return null;
886
+	}
887
+
888
+
889
+
890
+	/**
891
+	 * removes a cached version of the requested class
892
+	 *
893
+	 * @param string  $class_name
894
+	 * @param boolean $addon
895
+	 * @return boolean
896
+	 */
897
+	public function clear_cached_class($class_name, $addon = false)
898
+	{
899
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
900
+		$class_name = str_replace('\\', '_', $class_name);
901
+		// check if class has already been loaded, and return it if it has been
902
+		if (isset($this->{$class_abbreviation})) {
903
+			$this->{$class_abbreviation} = null;
904
+			return true;
905
+		}
906
+		if (isset($this->{$class_name})) {
907
+			$this->{$class_name} = null;
908
+			return true;
909
+		}
910
+		if (isset($this->LIB->{$class_name})) {
911
+			unset($this->LIB->{$class_name});
912
+			return true;
913
+		}
914
+		if ($addon && isset($this->addons->{$class_name})) {
915
+			unset($this->addons->{$class_name});
916
+			return true;
917
+		}
918
+		return false;
919
+	}
920
+
921
+
922
+
923
+	/**
924
+	 * attempts to find a full valid filepath for the requested class.
925
+	 * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
926
+	 * then returns that path if the target file has been found and is readable
927
+	 *
928
+	 * @param string $class_name
929
+	 * @param string $type
930
+	 * @param array  $file_paths
931
+	 * @return string | bool
932
+	 */
933
+	protected function _resolve_path($class_name, $type = '', $file_paths = array())
934
+	{
935
+		// make sure $file_paths is an array
936
+		$file_paths = is_array($file_paths)
937
+			? $file_paths
938
+			: array($file_paths);
939
+		// cycle thru paths
940
+		foreach ($file_paths as $key => $file_path) {
941
+			// convert all separators to proper DS, if no filepath, then use EE_CLASSES
942
+			$file_path = $file_path
943
+				? str_replace(array('/', '\\'), DS, $file_path)
944
+				: EE_CLASSES;
945
+			// prep file type
946
+			$type = ! empty($type)
947
+				? trim($type, '.') . '.'
948
+				: '';
949
+			// build full file path
950
+			$file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
951
+			//does the file exist and can be read ?
952
+			if (is_readable($file_paths[$key])) {
953
+				return $file_paths[$key];
954
+			}
955
+		}
956
+		return false;
957
+	}
958
+
959
+
960
+
961
+	/**
962
+	 * basically just performs a require_once()
963
+	 * but with some error handling
964
+	 *
965
+	 * @param  string $path
966
+	 * @param  string $class_name
967
+	 * @param  string $type
968
+	 * @param  array  $file_paths
969
+	 * @return bool
970
+	 * @throws EE_Error
971
+	 * @throws ReflectionException
972
+	 */
973
+	protected function _require_file($path, $class_name, $type = '', $file_paths = array())
974
+	{
975
+		$this->resolve_legacy_class_parent($class_name);
976
+		// don't give up! you gotta...
977
+		try {
978
+			//does the file exist and can it be read ?
979
+			if (! $path) {
980
+				// just in case the file has already been autoloaded,
981
+				// but discrepancies in the naming schema are preventing it from
982
+				// being loaded via one of the EE_Registry::load_*() methods,
983
+				// then let's try one last hail mary before throwing an exception
984
+				// and call class_exists() again, but with autoloading turned ON
985
+				if(class_exists($class_name)) {
986
+					return true;
987
+				}
988
+				// so sorry, can't find the file
989
+				throw new EE_Error (
990
+					sprintf(
991
+						esc_html__(
992
+							'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
993
+							'event_espresso'
994
+						),
995
+						trim($type, '.'),
996
+						$class_name,
997
+						'<br />' . implode(',<br />', $file_paths)
998
+					)
999
+				);
1000
+			}
1001
+			// get the file
1002
+			require_once($path);
1003
+			// if the class isn't already declared somewhere
1004
+			if (class_exists($class_name, false) === false) {
1005
+				// so sorry, not a class
1006
+				throw new EE_Error(
1007
+					sprintf(
1008
+						esc_html__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
1009
+						$type,
1010
+						$path,
1011
+						$class_name
1012
+					)
1013
+				);
1014
+			}
1015
+		} catch (EE_Error $e) {
1016
+			$e->get_error();
1017
+			return false;
1018
+		}
1019
+		return true;
1020
+	}
1021
+
1022
+
1023
+
1024
+	/**
1025
+	 * Some of our legacy classes that extended a parent class would simply use a require() statement
1026
+	 * before their class declaration in order to ensure that the parent class was loaded.
1027
+	 * This is not ideal, but it's nearly impossible to determine the parent class of a non-namespaced class,
1028
+	 * without triggering a fatal error because the parent class has yet to be loaded and therefore doesn't exist.
1029
+	 *
1030
+	 * @param string $class_name
1031
+	 */
1032
+	protected function resolve_legacy_class_parent($class_name = '')
1033
+	{
1034
+		try {
1035
+			$legacy_parent_class_map = array(
1036
+				'EE_Payment_Processor' => 'core/business/EE_Processor_Base.class.php'
1037
+			);
1038
+			if(isset($legacy_parent_class_map[$class_name])) {
1039
+				require_once EE_PLUGIN_DIR_PATH . $legacy_parent_class_map[$class_name];
1040
+			}
1041
+		} catch (Exception $exception) {
1042
+		}
1043
+	}
1044
+
1045
+
1046
+
1047
+	/**
1048
+	 * _create_object
1049
+	 * Attempts to instantiate the requested class via any of the
1050
+	 * commonly used instantiation methods employed throughout EE.
1051
+	 * The priority for instantiation is as follows:
1052
+	 *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1053
+	 *        - model objects via their 'new_instance_from_db' method
1054
+	 *        - model objects via their 'new_instance' method
1055
+	 *        - "singleton" classes" via their 'instance' method
1056
+	 *    - standard instantiable classes via their __constructor
1057
+	 * Prior to instantiation, if the classname exists in the dependency_map,
1058
+	 * then the constructor for the requested class will be examined to determine
1059
+	 * if any dependencies exist, and if they can be injected.
1060
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1061
+	 *
1062
+	 * @param string $class_name
1063
+	 * @param array  $arguments
1064
+	 * @param string $type
1065
+	 * @param bool   $from_db
1066
+	 * @return null|object
1067
+	 * @throws EE_Error
1068
+	 * @throws ReflectionException
1069
+	 */
1070
+	protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
1071
+	{
1072
+		// create reflection
1073
+		$reflector = $this->get_ReflectionClass($class_name);
1074
+		// make sure arguments are an array
1075
+		$arguments = is_array($arguments)
1076
+			? $arguments
1077
+			: array($arguments);
1078
+		// and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1079
+		// else wrap it in an additional array so that it doesn't get split into multiple parameters
1080
+		$arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1081
+			? $arguments
1082
+			: array($arguments);
1083
+		// attempt to inject dependencies ?
1084
+		if ($this->_dependency_map->has($class_name)) {
1085
+			$arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1086
+		}
1087
+		// instantiate the class if possible
1088
+		if ($reflector->isAbstract()) {
1089
+			// nothing to instantiate, loading file was enough
1090
+			// does not throw an exception so $instantiation_mode is unused
1091
+			// $instantiation_mode = "1) no constructor abstract class";
1092
+			return true;
1093
+		}
1094
+		if (empty($arguments) && $reflector->getConstructor() === null && $reflector->isInstantiable()) {
1095
+			// no constructor = static methods only... nothing to instantiate, loading file was enough
1096
+			// $instantiation_mode = "2) no constructor but instantiable";
1097
+			return $reflector->newInstance();
1098
+		}
1099
+		if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1100
+			// $instantiation_mode = "3) new_instance_from_db()";
1101
+			return call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
1102
+		}
1103
+		if (method_exists($class_name, 'new_instance')) {
1104
+			// $instantiation_mode = "4) new_instance()";
1105
+			return call_user_func_array(array($class_name, 'new_instance'), $arguments);
1106
+		}
1107
+		if (method_exists($class_name, 'instance')) {
1108
+			// $instantiation_mode = "5) instance()";
1109
+			return call_user_func_array(array($class_name, 'instance'), $arguments);
1110
+		}
1111
+		if ($reflector->isInstantiable()) {
1112
+			// $instantiation_mode = "6) constructor";
1113
+			return $reflector->newInstanceArgs($arguments);
1114
+		}
1115
+		// heh ? something's not right !
1116
+		throw new EE_Error(
1117
+			sprintf(
1118
+				__('The %s file %s could not be instantiated.', 'event_espresso'),
1119
+				$type,
1120
+				$class_name
1121
+			)
1122
+		);
1123
+	}
1124
+
1125
+
1126
+
1127
+	/**
1128
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1129
+	 * @param array $array
1130
+	 * @return bool
1131
+	 */
1132
+	protected function _array_is_numerically_and_sequentially_indexed(array $array)
1133
+	{
1134
+		return ! empty($array)
1135
+			? array_keys($array) === range(0, count($array) - 1)
1136
+			: true;
1137
+	}
1138
+
1139
+
1140
+
1141
+	/**
1142
+	 * getReflectionClass
1143
+	 * checks if a ReflectionClass object has already been generated for a class
1144
+	 * and returns that instead of creating a new one
1145
+	 *
1146
+	 * @param string $class_name
1147
+	 * @return ReflectionClass
1148
+	 * @throws ReflectionException
1149
+	 */
1150
+	public function get_ReflectionClass($class_name)
1151
+	{
1152
+		if (
1153
+			! isset($this->_reflectors[$class_name])
1154
+			|| ! $this->_reflectors[$class_name] instanceof ReflectionClass
1155
+		) {
1156
+			$this->_reflectors[$class_name] = new ReflectionClass($class_name);
1157
+		}
1158
+		return $this->_reflectors[$class_name];
1159
+	}
1160
+
1161
+
1162
+
1163
+	/**
1164
+	 * _resolve_dependencies
1165
+	 * examines the constructor for the requested class to determine
1166
+	 * if any dependencies exist, and if they can be injected.
1167
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1168
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
1169
+	 * For example:
1170
+	 *        if attempting to load a class "Foo" with the following constructor:
1171
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
1172
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
1173
+	 *        but only IF they are NOT already present in the incoming arguments array,
1174
+	 *        and the correct classes can be loaded
1175
+	 *
1176
+	 * @param ReflectionClass $reflector
1177
+	 * @param string          $class_name
1178
+	 * @param array           $arguments
1179
+	 * @return array
1180
+	 * @throws EE_Error
1181
+	 * @throws ReflectionException
1182
+	 */
1183
+	protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1184
+	{
1185
+		// let's examine the constructor
1186
+		$constructor = $reflector->getConstructor();
1187
+		// whu? huh? nothing?
1188
+		if (! $constructor) {
1189
+			return $arguments;
1190
+		}
1191
+		// get constructor parameters
1192
+		$params = $constructor->getParameters();
1193
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1194
+		$argument_keys = array_keys($arguments);
1195
+		// now loop thru all of the constructors expected parameters
1196
+		foreach ($params as $index => $param) {
1197
+			// is this a dependency for a specific class ?
1198
+			$param_class = $param->getClass()
1199
+				? $param->getClass()->name
1200
+				: null;
1201
+			// BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1202
+			$param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1203
+				? $this->_dependency_map->get_alias($param_class, $class_name)
1204
+				: $param_class;
1205
+			if (
1206
+				// param is not even a class
1207
+				$param_class === null
1208
+				// and something already exists in the incoming arguments for this param
1209
+				&& array_key_exists($index, $argument_keys)
1210
+				&& array_key_exists($argument_keys[$index], $arguments)
1211
+			) {
1212
+				// so let's skip this argument and move on to the next
1213
+				continue;
1214
+			}
1215
+			if (
1216
+				// parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1217
+				$param_class !== null
1218
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1219
+				&& $arguments[$argument_keys[$index]] instanceof $param_class
1220
+			) {
1221
+				// skip this argument and move on to the next
1222
+				continue;
1223
+			}
1224
+			if (
1225
+				// parameter is type hinted as a class, and should be injected
1226
+				$param_class !== null
1227
+				&& $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1228
+			) {
1229
+				$arguments = $this->_resolve_dependency(
1230
+					$class_name,
1231
+					$param_class,
1232
+					$arguments,
1233
+					$index,
1234
+					$argument_keys
1235
+				);
1236
+			} else {
1237
+				try {
1238
+					$arguments[$index] = $param->isDefaultValueAvailable()
1239
+						? $param->getDefaultValue()
1240
+						: null;
1241
+				} catch (ReflectionException $e) {
1242
+					throw new ReflectionException(
1243
+						sprintf(
1244
+							esc_html__('%1$s for parameter "$%2$s on classname "%3$s"', 'event_espresso'),
1245
+							$e->getMessage(),
1246
+							$param->getName(),
1247
+							$class_name
1248
+						)
1249
+					);
1250
+				}
1251
+			}
1252
+		}
1253
+		return $arguments;
1254
+	}
1255
+
1256
+
1257
+
1258
+	/**
1259
+	 * @param string $class_name
1260
+	 * @param string $param_class
1261
+	 * @param array  $arguments
1262
+	 * @param mixed  $index
1263
+	 * @param array  $argument_keys
1264
+	 * @return array
1265
+	 * @throws EE_Error
1266
+	 * @throws ReflectionException
1267
+	 * @throws InvalidArgumentException
1268
+	 * @throws InvalidInterfaceException
1269
+	 * @throws InvalidDataTypeException
1270
+	 */
1271
+	protected function _resolve_dependency($class_name, $param_class, $arguments, $index, array $argument_keys)
1272
+	{
1273
+		$dependency = null;
1274
+		// should dependency be loaded from cache ?
1275
+		$cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1276
+			$class_name,
1277
+			$param_class
1278
+		);
1279
+		$cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1280
+		// we might have a dependency...
1281
+		// let's MAYBE try and find it in our cache if that's what's been requested
1282
+		$cached_class = $cache_on
1283
+			? $this->_get_cached_class($param_class)
1284
+			: null;
1285
+		// and grab it if it exists
1286
+		if ($cached_class instanceof $param_class) {
1287
+			$dependency = $cached_class;
1288
+		} else if ($param_class !== $class_name) {
1289
+			// obtain the loader method from the dependency map
1290
+			$loader = $this->_dependency_map->class_loader($param_class);
1291
+			// is loader a custom closure ?
1292
+			if ($loader instanceof Closure) {
1293
+				$dependency = $loader($arguments);
1294
+			} else {
1295
+				// set the cache on property for the recursive loading call
1296
+				$this->_cache_on = $cache_on;
1297
+				// if not, then let's try and load it via the registry
1298
+				if ($loader && method_exists($this, $loader)) {
1299
+					$dependency = $this->{$loader}($param_class);
1300
+				} else {
1301
+					$dependency = LoaderFactory::getLoader()->load(
1302
+						$param_class,
1303
+						array(),
1304
+						$cache_on
1305
+					);
1306
+				}
1307
+			}
1308
+		}
1309
+		// did we successfully find the correct dependency ?
1310
+		if ($dependency instanceof $param_class) {
1311
+			// then let's inject it into the incoming array of arguments at the correct location
1312
+			$arguments[$index] = $dependency;
1313
+		}
1314
+		return $arguments;
1315
+	}
1316
+
1317
+
1318
+
1319
+	/**
1320
+	 * _set_cached_class
1321
+	 * attempts to cache the instantiated class locally
1322
+	 * in one of the following places, in the following order:
1323
+	 *        $this->{class_abbreviation}   ie:    $this->CART
1324
+	 *        $this->{$class_name}          ie:    $this->Some_Class
1325
+	 *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1326
+	 *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1327
+	 *
1328
+	 * @param object $class_obj
1329
+	 * @param string $class_name
1330
+	 * @param string $class_prefix
1331
+	 * @param bool   $from_db
1332
+	 * @return void
1333
+	 */
1334
+	protected function _set_cached_class($class_obj, $class_name, $class_prefix = '', $from_db = false)
1335
+	{
1336
+		if ($class_name === 'EE_Registry' || empty($class_obj)) {
1337
+			return;
1338
+		}
1339
+		// return newly instantiated class
1340
+		$class_abbreviation = $this->get_class_abbreviation($class_name, '');
1341
+		if ($class_abbreviation) {
1342
+			$this->{$class_abbreviation} = $class_obj;
1343
+			return;
1344
+		}
1345
+		$class_name = str_replace('\\', '_', $class_name);
1346
+		if (property_exists($this, $class_name)) {
1347
+			$this->{$class_name} = $class_obj;
1348
+			return;
1349
+		}
1350
+		if ($class_prefix === 'addon') {
1351
+			$this->addons->{$class_name} = $class_obj;
1352
+			return;
1353
+		}
1354
+		if (! $from_db) {
1355
+			$this->LIB->{$class_name} = $class_obj;
1356
+		}
1357
+	}
1358
+
1359
+
1360
+
1361
+	/**
1362
+	 * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1363
+	 *
1364
+	 * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1365
+	 *                          in the EE_Dependency_Map::$_class_loaders array,
1366
+	 *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1367
+	 * @param array  $arguments
1368
+	 * @return object
1369
+	 */
1370
+	public static function factory($classname, $arguments = array())
1371
+	{
1372
+		$loader = self::instance()->_dependency_map->class_loader($classname);
1373
+		if ($loader instanceof Closure) {
1374
+			return $loader($arguments);
1375
+		}
1376
+		if (method_exists(self::instance(), $loader)) {
1377
+			return self::instance()->{$loader}($classname, $arguments);
1378
+		}
1379
+		return null;
1380
+	}
1381
+
1382
+
1383
+
1384
+	/**
1385
+	 * Gets the addon by its class name
1386
+	 *
1387
+	 * @param string $class_name
1388
+	 * @return EE_Addon
1389
+	 */
1390
+	public function getAddon($class_name)
1391
+	{
1392
+		$class_name = str_replace('\\', '_', $class_name);
1393
+		return $this->addons->{$class_name};
1394
+	}
1395
+
1396
+
1397
+	/**
1398
+	 * removes the addon from the internal cache
1399
+	 *
1400
+	 * @param string $class_name
1401
+	 * @return void
1402
+	 */
1403
+	public function removeAddon($class_name)
1404
+	{
1405
+		$class_name = str_replace('\\', '_', $class_name);
1406
+		unset($this->addons->{$class_name});
1407
+	}
1408
+
1409
+
1410
+
1411
+	/**
1412
+	 * Gets the addon by its name/slug (not classname. For that, just
1413
+	 * use the get_addon() method above
1414
+	 *
1415
+	 * @param string $name
1416
+	 * @return EE_Addon
1417
+	 */
1418
+	public function get_addon_by_name($name)
1419
+	{
1420
+		foreach ($this->addons as $addon) {
1421
+			if ($addon->name() === $name) {
1422
+				return $addon;
1423
+			}
1424
+		}
1425
+		return null;
1426
+	}
1427
+
1428
+
1429
+
1430
+	/**
1431
+	 * Gets an array of all the registered addons, where the keys are their names.
1432
+	 * (ie, what each returns for their name() function)
1433
+	 * They're already available on EE_Registry::instance()->addons as properties,
1434
+	 * where each property's name is the addon's classname,
1435
+	 * So if you just want to get the addon by classname,
1436
+	 * OR use the get_addon() method above.
1437
+	 * PLEASE  NOTE:
1438
+	 * addons with Fully Qualified Class Names
1439
+	 * have had the namespace separators converted to underscores,
1440
+	 * so a classname like Fully\Qualified\ClassName
1441
+	 * would have been converted to Fully_Qualified_ClassName
1442
+	 *
1443
+	 * @return EE_Addon[] where the KEYS are the addon's name()
1444
+	 */
1445
+	public function get_addons_by_name()
1446
+	{
1447
+		$addons = array();
1448
+		foreach ($this->addons as $addon) {
1449
+			$addons[$addon->name()] = $addon;
1450
+		}
1451
+		return $addons;
1452
+	}
1453
+
1454
+
1455
+	/**
1456
+	 * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1457
+	 * a stale copy of it around
1458
+	 *
1459
+	 * @param string $model_name
1460
+	 * @return \EEM_Base
1461
+	 * @throws \EE_Error
1462
+	 */
1463
+	public function reset_model($model_name)
1464
+	{
1465
+		$model_class_name = strpos($model_name, 'EEM_') !== 0
1466
+			? "EEM_{$model_name}"
1467
+			: $model_name;
1468
+		if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1469
+			return null;
1470
+		}
1471
+		//get that model reset it and make sure we nuke the old reference to it
1472
+		if ($this->LIB->{$model_class_name} instanceof $model_class_name
1473
+			&& is_callable(
1474
+				array($model_class_name, 'reset')
1475
+			)) {
1476
+			$this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1477
+		} else {
1478
+			throw new EE_Error(sprintf(esc_html__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1479
+		}
1480
+		return $this->LIB->{$model_class_name};
1481
+	}
1482
+
1483
+
1484
+
1485
+	/**
1486
+	 * Resets the registry.
1487
+	 * The criteria for what gets reset is based on what can be shared between sites on the same request when
1488
+	 * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1489
+	 * - $_dependency_map
1490
+	 * - $_class_abbreviations
1491
+	 * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1492
+	 * - $REQ:  Still on the same request so no need to change.
1493
+	 * - $CAP: There is no site specific state in the EE_Capability class.
1494
+	 * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1495
+	 * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1496
+	 * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1497
+	 *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1498
+	 *             switch or on the restore.
1499
+	 * - $modules
1500
+	 * - $shortcodes
1501
+	 * - $widgets
1502
+	 *
1503
+	 * @param boolean $hard             [deprecated]
1504
+	 * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1505
+	 *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1506
+	 *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1507
+	 * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1508
+	 *                                  client
1509
+	 *                                  code instead can just change the model context to a different blog id if
1510
+	 *                                  necessary
1511
+	 * @return EE_Registry
1512
+	 * @throws EE_Error
1513
+	 * @throws ReflectionException
1514
+	 */
1515
+	public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1516
+	{
1517
+		$instance = self::instance();
1518
+		$instance->_cache_on = true;
1519
+		// reset some "special" classes
1520
+		EEH_Activation::reset();
1521
+		$hard = apply_filters( 'FHEE__EE_Registry__reset__hard', $hard);
1522
+		$instance->CFG = EE_Config::reset($hard, $reinstantiate);
1523
+		$instance->CART = null;
1524
+		$instance->MRM = null;
1525
+		$instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1526
+		//messages reset
1527
+		EED_Messages::reset();
1528
+		//handle of objects cached on LIB
1529
+		foreach (array('LIB', 'modules') as $cache) {
1530
+			foreach ($instance->{$cache} as $class_name => $class) {
1531
+				if (self::_reset_and_unset_object($class, $reset_models)) {
1532
+					unset($instance->{$cache}->{$class_name});
1533
+				}
1534
+			}
1535
+		}
1536
+		return $instance;
1537
+	}
1538
+
1539
+
1540
+
1541
+	/**
1542
+	 * if passed object implements ResettableInterface, then call it's reset() method
1543
+	 * if passed object implements InterminableInterface, then return false,
1544
+	 * to indicate that it should NOT be cleared from the Registry cache
1545
+	 *
1546
+	 * @param      $object
1547
+	 * @param bool $reset_models
1548
+	 * @return bool returns true if cached object should be unset
1549
+	 */
1550
+	private static function _reset_and_unset_object($object, $reset_models)
1551
+	{
1552
+		if (! is_object($object)) {
1553
+			// don't unset anything that's not an object
1554
+			return false;
1555
+		}
1556
+		if ($object instanceof EED_Module) {
1557
+			$object::reset();
1558
+			// don't unset modules
1559
+			return false;
1560
+		}
1561
+		if ($object instanceof ResettableInterface) {
1562
+			if ($object instanceof EEM_Base) {
1563
+				if ($reset_models) {
1564
+					$object->reset();
1565
+					return true;
1566
+				}
1567
+				return false;
1568
+			}
1569
+			$object->reset();
1570
+			return true;
1571
+		}
1572
+		if (! $object instanceof InterminableInterface) {
1573
+			return true;
1574
+		}
1575
+		return false;
1576
+	}
1577
+
1578
+
1579
+
1580
+	/**
1581
+	 * Gets all the custom post type models defined
1582
+	 *
1583
+	 * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1584
+	 */
1585
+	public function cpt_models()
1586
+	{
1587
+		$cpt_models = array();
1588
+		foreach ($this->non_abstract_db_models as $short_name => $classname) {
1589
+			if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1590
+				$cpt_models[$short_name] = $classname;
1591
+			}
1592
+		}
1593
+		return $cpt_models;
1594
+	}
1595
+
1596
+
1597
+
1598
+	/**
1599
+	 * @return \EE_Config
1600
+	 */
1601
+	public static function CFG()
1602
+	{
1603
+		return self::instance()->CFG;
1604
+	}
1605 1605
 
1606 1606
 
1607 1607
 }
Please login to merge, or discard this patch.
core/EE_Error.core.php 2 patches
Spacing   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -101,14 +101,14 @@  discard block
 block discarded – undo
101 101
             default :
102 102
                 $to = get_option('admin_email');
103 103
         }
104
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
104
+        $subject = $type.' '.$message.' in '.EVENT_ESPRESSO_VERSION.' on '.site_url();
105 105
         $msg = EE_Error::_format_error($type, $message, $file, $line);
106 106
         if (function_exists('wp_mail')) {
107 107
             add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
108 108
             wp_mail($to, $subject, $msg);
109 109
         }
110 110
         echo '<div id="message" class="espresso-notices error"><p>';
111
-        echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
111
+        echo $type.': '.$message.'<br />'.$file.' line '.$line;
112 112
         echo '<br /></p></div>';
113 113
     }
114 114
 
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
             ? true
256 256
             : false;
257 257
         if ($check_stored && ! $has_error) {
258
-            $notices = (array)get_option('ee_notices', array());
258
+            $notices = (array) get_option('ee_notices', array());
259 259
             foreach ($notices as $type => $notice) {
260 260
                 if ($type === $type_to_check && $notice) {
261 261
                     return true;
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 	}
331 331
 </style>
332 332
 <div id="ee-error-message" class="error">';
333
-        if (! WP_DEBUG) {
333
+        if ( ! WP_DEBUG) {
334 334
             $output .= '
335 335
 	<p>';
336 336
         }
@@ -389,14 +389,14 @@  discard block
 block discarded – undo
389 389
                     $class_dsply = ! empty($class) ? $class : '&nbsp;';
390 390
                     $type_dsply = ! empty($type) ? $type : '&nbsp;';
391 391
                     $function_dsply = ! empty($function) ? $function : '&nbsp;';
392
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
392
+                    $args_dsply = ! empty($args) ? '( '.$args.' )' : '';
393 393
                     $trace_details .= '
394 394
 					<tr>
395
-						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
396
-						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
397
-						<td align="left" class="' . $zebra . '">' . $file_dsply . '</td>
398
-						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
399
-						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
395
+						<td align="right" class="' . $zebra.'">'.$nmbr_dsply.'</td>
396
+						<td align="right" class="' . $zebra.'">'.$line_dsply.'</td>
397
+						<td align="left" class="' . $zebra.'">'.$file_dsply.'</td>
398
+						<td align="left" class="' . $zebra.'">'.$class_dsply.'</td>
399
+						<td align="left" class="' . $zebra.'">'.$type_dsply.$function_dsply.$args_dsply.'</td>
400 400
 					</tr>';
401 401
                 }
402 402
                 $trace_details .= '
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
             }
406 406
             $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
407 407
             // add generic non-identifying messages for non-privileged users
408
-            if (! WP_DEBUG) {
408
+            if ( ! WP_DEBUG) {
409 409
                 $output .= '<span class="ee-error-user-msg-spn">'
410 410
                            . trim($ex['msg'])
411 411
                            . '</span> &nbsp; <sup>'
@@ -447,14 +447,14 @@  discard block
 block discarded – undo
447 447
                            . '-dv" class="ee-error-trace-dv" style="display: none;">
448 448
 				'
449 449
                            . $trace_details;
450
-                if (! empty($class)) {
450
+                if ( ! empty($class)) {
451 451
                     $output .= '
452 452
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
453 453
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
454 454
 						<h3>Class Details</h3>';
455 455
                     $a = new ReflectionClass($class);
456 456
                     $output .= '
457
-						<pre>' . $a . '</pre>
457
+						<pre>' . $a.'</pre>
458 458
 					</div>
459 459
 				</div>';
460 460
                 }
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
         }
467 467
         // remove last linebreak
468 468
         $output = substr($output, 0, -6);
469
-        if (! WP_DEBUG) {
469
+        if ( ! WP_DEBUG) {
470 470
             $output .= '
471 471
 	</p>';
472 472
         }
@@ -493,20 +493,20 @@  discard block
 block discarded – undo
493 493
     private function _convert_args_to_string($arguments = array(), $array = false)
494 494
     {
495 495
         $arg_string = '';
496
-        if (! empty($arguments)) {
496
+        if ( ! empty($arguments)) {
497 497
             $args = array();
498 498
             foreach ($arguments as $arg) {
499
-                if (! empty($arg)) {
499
+                if ( ! empty($arg)) {
500 500
                     if (is_string($arg)) {
501
-                        $args[] = " '" . $arg . "'";
501
+                        $args[] = " '".$arg."'";
502 502
                     } elseif (is_array($arg)) {
503
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
503
+                        $args[] = 'ARRAY('.$this->_convert_args_to_string($arg, true);
504 504
                     } elseif ($arg === null) {
505 505
                         $args[] = ' NULL';
506 506
                     } elseif (is_bool($arg)) {
507 507
                         $args[] = ($arg) ? ' TRUE' : ' FALSE';
508 508
                     } elseif (is_object($arg)) {
509
-                        $args[] = ' OBJECT ' . get_class($arg);
509
+                        $args[] = ' OBJECT '.get_class($arg);
510 510
                     } elseif (is_resource($arg)) {
511 511
                         $args[] = get_resource_type($arg);
512 512
                     } else {
@@ -609,7 +609,7 @@  discard block
 block discarded – undo
609 609
     {
610 610
         if (empty($msg)) {
611 611
             EE_Error::doing_it_wrong(
612
-                'EE_Error::add_' . $type . '()',
612
+                'EE_Error::add_'.$type.'()',
613 613
                 sprintf(
614 614
                     __('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
615 615
                         'event_espresso'),
@@ -645,11 +645,11 @@  discard block
 block discarded – undo
645 645
         do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
646 646
         $msg = WP_DEBUG ? $dev_msg : $user_msg;
647 647
         // add notice if message exists
648
-        if (! empty($msg)) {
648
+        if ( ! empty($msg)) {
649 649
             // get error code
650 650
             $notice_code = EE_Error::generate_error_code($file, $func, $line);
651 651
             if (WP_DEBUG && $type === 'errors') {
652
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
652
+                $msg .= '<br/><span class="tiny-text">'.$notice_code.'</span>';
653 653
             }
654 654
             // add notice. Index by code if it's not blank
655 655
             if ($notice_code) {
@@ -775,7 +775,7 @@  discard block
 block discarded – undo
775 775
         // EEH_Debug_Tools::printr( self::$_espresso_notices, 'espresso_notices  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
776 776
         // either save notices to the db
777 777
         if ($save_to_transient || isset($_REQUEST['activate-selected'])) {
778
-            $existing_notices  = get_option('ee_notices', array());
778
+            $existing_notices = get_option('ee_notices', array());
779 779
             $existing_notices = $existing_notices !== '' ? $existing_notices : array();
780 780
             self::$_espresso_notices = array_merge(
781 781
                 $existing_notices,
@@ -805,13 +805,13 @@  discard block
 block discarded – undo
805 805
         if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
806 806
             // combine messages
807 807
             $success_messages .= implode(self::$_espresso_notices['success'], '<br />');
808
-            $print_scripts    = true;
808
+            $print_scripts = true;
809 809
         }
810 810
         // check for attention messages
811 811
         if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
812 812
             // combine messages
813 813
             $attention_messages .= implode(self::$_espresso_notices['attention'], '<br />');
814
-            $print_scripts      = true;
814
+            $print_scripts = true;
815 815
         }
816 816
         // check for error messages
817 817
         if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
@@ -820,7 +820,7 @@  discard block
 block discarded – undo
820 820
                 : __('An error has occurred:<br />', 'event_espresso');
821 821
             // combine messages
822 822
             $error_messages .= implode(self::$_espresso_notices['errors'], '<br />');
823
-            $print_scripts  = true;
823
+            $print_scripts = true;
824 824
         }
825 825
         if ($format_output) {
826 826
 
@@ -902,7 +902,7 @@  discard block
 block discarded – undo
902 902
      */
903 903
     private static function _print_scripts($force_print = false)
904 904
     {
905
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
905
+        if ( ! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
906 906
             if (wp_script_is('ee_error_js', 'enqueued')) {
907 907
                 return '';
908 908
             }
@@ -916,12 +916,12 @@  discard block
 block discarded – undo
916 916
             return '
917 917
 <script>
918 918
 /* <![CDATA[ */
919
-var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
919
+var ee_settings = {"wp_debug":"' . WP_DEBUG.'"};
920 920
 /* ]]> */
921 921
 </script>
922
-<script src="' . includes_url() . 'js/jquery/jquery.js" type="text/javascript"></script>
923
-<script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
924
-<script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
922
+<script src="' . includes_url().'js/jquery/jquery.js" type="text/javascript"></script>
923
+<script src="' . EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js'.'?ver='.espresso_version().'" type="text/javascript"></script>
924
+<script src="' . EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js'.'?ver='.espresso_version().'" type="text/javascript"></script>
925 925
 ';
926 926
         }
927 927
         return '';
@@ -952,8 +952,8 @@  discard block
 block discarded – undo
952 952
     {
953 953
         $file       = explode('.', basename($file));
954 954
         $error_code = ! empty($file[0]) ? $file[0] : '';
955
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
956
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
955
+        $error_code .= ! empty($func) ? ' - '.$func : '';
956
+        $error_code .= ! empty($line) ? ' - '.$line : '';
957 957
         return $error_code;
958 958
     }
959 959
 
@@ -979,18 +979,18 @@  discard block
 block discarded – undo
979 979
         if (empty($ex)) {
980 980
             return;
981 981
         }
982
-        if (! $time) {
982
+        if ( ! $time) {
983 983
             $time = time();
984 984
         }
985 985
         $exception_log = '----------------------------------------------------------------------------------------'
986 986
                          . PHP_EOL;
987
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
988
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
989
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
990
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
991
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
992
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
993
-        $exception_log .= $ex['string'] . PHP_EOL;
987
+        $exception_log .= '['.date('Y-m-d H:i:s', $time).']  Exception Details'.PHP_EOL;
988
+        $exception_log .= 'Message: '.$ex['msg'].PHP_EOL;
989
+        $exception_log .= 'Code: '.$ex['code'].PHP_EOL;
990
+        $exception_log .= 'File: '.$ex['file'].PHP_EOL;
991
+        $exception_log .= 'Line No: '.$ex['line'].PHP_EOL;
992
+        $exception_log .= 'Stack trace: '.PHP_EOL;
993
+        $exception_log .= $ex['string'].PHP_EOL;
994 994
         $exception_log .= '----------------------------------------------------------------------------------------'
995 995
                           . PHP_EOL;
996 996
         try {
@@ -1163,14 +1163,14 @@  discard block
 block discarded – undo
1163 1163
     // js for error handling
1164 1164
     wp_register_script(
1165 1165
         'espresso_core',
1166
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1166
+        EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
1167 1167
         array('jquery'),
1168 1168
         EVENT_ESPRESSO_VERSION,
1169 1169
         false
1170 1170
     );
1171 1171
     wp_register_script(
1172 1172
         'ee_error_js',
1173
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1173
+        EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js',
1174 1174
         array('espresso_core'),
1175 1175
         EVENT_ESPRESSO_VERSION,
1176 1176
         false
Please login to merge, or discard this patch.
Indentation   +1027 added lines, -1027 removed lines patch added patch discarded remove patch
@@ -11,8 +11,8 @@  discard block
 block discarded – undo
11 11
 // if you're a dev and want to receive all errors via email
12 12
 // add this to your wp-config.php: define( 'EE_ERROR_EMAILS', TRUE );
13 13
 if (defined('WP_DEBUG') && WP_DEBUG === true && defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS === true) {
14
-    set_error_handler(array('EE_Error', 'error_handler'));
15
-    register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
14
+	set_error_handler(array('EE_Error', 'error_handler'));
15
+	register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
16 16
 }
17 17
 
18 18
 
@@ -28,253 +28,253 @@  discard block
 block discarded – undo
28 28
 {
29 29
 
30 30
 
31
-    /**
32
-     * name of the file to log exceptions to
33
-     *
34
-     * @var string
35
-     */
36
-    private static $_exception_log_file = 'espresso_error_log.txt';
37
-
38
-    /**
39
-     *    stores details for all exception
40
-     *
41
-     * @var array
42
-     */
43
-    private static $_all_exceptions = array();
44
-
45
-    /**
46
-     *    tracks number of errors
47
-     *
48
-     * @var int
49
-     */
50
-    private static $_error_count = 0;
51
-
52
-    /**
53
-     * @var array $_espresso_notices
54
-     */
55
-    private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
56
-
57
-
58
-
59
-    /**
60
-     * @override default exception handling
61
-     * @param string         $message
62
-     * @param int            $code
63
-     * @param Exception|null $previous
64
-     */
65
-    public function __construct($message, $code = 0, Exception $previous = null)
66
-    {
67
-        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
68
-            parent::__construct($message, $code);
69
-        } else {
70
-            parent::__construct($message, $code, $previous);
71
-        }
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     *    error_handler
78
-     *
79
-     * @param $code
80
-     * @param $message
81
-     * @param $file
82
-     * @param $line
83
-     * @return void
84
-     */
85
-    public static function error_handler($code, $message, $file, $line)
86
-    {
87
-        $type = EE_Error::error_type($code);
88
-        $site = site_url();
89
-        switch ($site) {
90
-            case 'http://ee4.eventespresso.com/' :
91
-            case 'http://ee4decaf.eventespresso.com/' :
92
-            case 'http://ee4hf.eventespresso.com/' :
93
-            case 'http://ee4a.eventespresso.com/' :
94
-            case 'http://ee4ad.eventespresso.com/' :
95
-            case 'http://ee4b.eventespresso.com/' :
96
-            case 'http://ee4bd.eventespresso.com/' :
97
-            case 'http://ee4d.eventespresso.com/' :
98
-            case 'http://ee4dd.eventespresso.com/' :
99
-                $to = '[email protected]';
100
-                break;
101
-            default :
102
-                $to = get_option('admin_email');
103
-        }
104
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
105
-        $msg = EE_Error::_format_error($type, $message, $file, $line);
106
-        if (function_exists('wp_mail')) {
107
-            add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
108
-            wp_mail($to, $subject, $msg);
109
-        }
110
-        echo '<div id="message" class="espresso-notices error"><p>';
111
-        echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
112
-        echo '<br /></p></div>';
113
-    }
114
-
115
-
116
-
117
-    /**
118
-     * error_type
119
-     * http://www.php.net/manual/en/errorfunc.constants.php#109430
120
-     *
121
-     * @param $code
122
-     * @return string
123
-     */
124
-    public static function error_type($code)
125
-    {
126
-        switch ($code) {
127
-            case E_ERROR: // 1 //
128
-                return 'E_ERROR';
129
-            case E_WARNING: // 2 //
130
-                return 'E_WARNING';
131
-            case E_PARSE: // 4 //
132
-                return 'E_PARSE';
133
-            case E_NOTICE: // 8 //
134
-                return 'E_NOTICE';
135
-            case E_CORE_ERROR: // 16 //
136
-                return 'E_CORE_ERROR';
137
-            case E_CORE_WARNING: // 32 //
138
-                return 'E_CORE_WARNING';
139
-            case E_COMPILE_ERROR: // 64 //
140
-                return 'E_COMPILE_ERROR';
141
-            case E_COMPILE_WARNING: // 128 //
142
-                return 'E_COMPILE_WARNING';
143
-            case E_USER_ERROR: // 256 //
144
-                return 'E_USER_ERROR';
145
-            case E_USER_WARNING: // 512 //
146
-                return 'E_USER_WARNING';
147
-            case E_USER_NOTICE: // 1024 //
148
-                return 'E_USER_NOTICE';
149
-            case E_STRICT: // 2048 //
150
-                return 'E_STRICT';
151
-            case E_RECOVERABLE_ERROR: // 4096 //
152
-                return 'E_RECOVERABLE_ERROR';
153
-            case E_DEPRECATED: // 8192 //
154
-                return 'E_DEPRECATED';
155
-            case E_USER_DEPRECATED: // 16384 //
156
-                return 'E_USER_DEPRECATED';
157
-            case E_ALL: // 16384 //
158
-                return 'E_ALL';
159
-        }
160
-        return '';
161
-    }
162
-
163
-
164
-
165
-    /**
166
-     *    fatal_error_handler
167
-     *
168
-     * @return void
169
-     */
170
-    public static function fatal_error_handler()
171
-    {
172
-        $last_error = error_get_last();
173
-        if ($last_error['type'] === E_ERROR) {
174
-            EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
175
-        }
176
-    }
177
-
178
-
179
-
180
-    /**
181
-     * _format_error
182
-     *
183
-     * @param $code
184
-     * @param $message
185
-     * @param $file
186
-     * @param $line
187
-     * @return string
188
-     */
189
-    private static function _format_error($code, $message, $file, $line)
190
-    {
191
-        $html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
192
-        $html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
193
-        $html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
194
-        $html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
195
-        $html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
196
-        $html .= '</tbody></table>';
197
-        return $html;
198
-    }
199
-
200
-
201
-
202
-    /**
203
-     * set_content_type
204
-     *
205
-     * @param $content_type
206
-     * @return string
207
-     */
208
-    public static function set_content_type($content_type)
209
-    {
210
-        return 'text/html';
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * @return void
217
-     * @throws EE_Error
218
-     * @throws ReflectionException
219
-     */
220
-    public function get_error()
221
-    {
222
-        if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
223
-            throw $this;
224
-        }
225
-        // get separate user and developer messages if they exist
226
-        $msg = explode('||', $this->getMessage());
227
-        $user_msg = $msg[0];
228
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
229
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
230
-        // add details to _all_exceptions array
231
-        $x_time = time();
232
-        self::$_all_exceptions[$x_time]['name'] = get_class($this);
233
-        self::$_all_exceptions[$x_time]['file'] = $this->getFile();
234
-        self::$_all_exceptions[$x_time]['line'] = $this->getLine();
235
-        self::$_all_exceptions[$x_time]['msg'] = $msg;
236
-        self::$_all_exceptions[$x_time]['code'] = $this->getCode();
237
-        self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
238
-        self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
239
-        self::$_error_count++;
240
-        //add_action( 'shutdown', array( $this, 'display_errors' ));
241
-        $this->display_errors();
242
-    }
243
-
244
-
245
-
246
-    /**
247
-     * @param bool   $check_stored
248
-     * @param string $type_to_check
249
-     * @return bool
250
-     */
251
-    public static function has_error($check_stored = false, $type_to_check = 'errors')
252
-    {
253
-        $has_error = isset(self::$_espresso_notices[$type_to_check])
254
-                     && ! empty(self::$_espresso_notices[$type_to_check])
255
-            ? true
256
-            : false;
257
-        if ($check_stored && ! $has_error) {
258
-            $notices = (array)get_option('ee_notices', array());
259
-            foreach ($notices as $type => $notice) {
260
-                if ($type === $type_to_check && $notice) {
261
-                    return true;
262
-                }
263
-            }
264
-        }
265
-        return $has_error;
266
-    }
267
-
268
-
269
-
270
-    /**
271
-     * @echo string
272
-     * @throws \ReflectionException
273
-     */
274
-    public function display_errors()
275
-    {
276
-        $trace_details = '';
277
-        $output = '
31
+	/**
32
+	 * name of the file to log exceptions to
33
+	 *
34
+	 * @var string
35
+	 */
36
+	private static $_exception_log_file = 'espresso_error_log.txt';
37
+
38
+	/**
39
+	 *    stores details for all exception
40
+	 *
41
+	 * @var array
42
+	 */
43
+	private static $_all_exceptions = array();
44
+
45
+	/**
46
+	 *    tracks number of errors
47
+	 *
48
+	 * @var int
49
+	 */
50
+	private static $_error_count = 0;
51
+
52
+	/**
53
+	 * @var array $_espresso_notices
54
+	 */
55
+	private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
56
+
57
+
58
+
59
+	/**
60
+	 * @override default exception handling
61
+	 * @param string         $message
62
+	 * @param int            $code
63
+	 * @param Exception|null $previous
64
+	 */
65
+	public function __construct($message, $code = 0, Exception $previous = null)
66
+	{
67
+		if (version_compare(PHP_VERSION, '5.3.0', '<')) {
68
+			parent::__construct($message, $code);
69
+		} else {
70
+			parent::__construct($message, $code, $previous);
71
+		}
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 *    error_handler
78
+	 *
79
+	 * @param $code
80
+	 * @param $message
81
+	 * @param $file
82
+	 * @param $line
83
+	 * @return void
84
+	 */
85
+	public static function error_handler($code, $message, $file, $line)
86
+	{
87
+		$type = EE_Error::error_type($code);
88
+		$site = site_url();
89
+		switch ($site) {
90
+			case 'http://ee4.eventespresso.com/' :
91
+			case 'http://ee4decaf.eventespresso.com/' :
92
+			case 'http://ee4hf.eventespresso.com/' :
93
+			case 'http://ee4a.eventespresso.com/' :
94
+			case 'http://ee4ad.eventespresso.com/' :
95
+			case 'http://ee4b.eventespresso.com/' :
96
+			case 'http://ee4bd.eventespresso.com/' :
97
+			case 'http://ee4d.eventespresso.com/' :
98
+			case 'http://ee4dd.eventespresso.com/' :
99
+				$to = '[email protected]';
100
+				break;
101
+			default :
102
+				$to = get_option('admin_email');
103
+		}
104
+		$subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
105
+		$msg = EE_Error::_format_error($type, $message, $file, $line);
106
+		if (function_exists('wp_mail')) {
107
+			add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
108
+			wp_mail($to, $subject, $msg);
109
+		}
110
+		echo '<div id="message" class="espresso-notices error"><p>';
111
+		echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
112
+		echo '<br /></p></div>';
113
+	}
114
+
115
+
116
+
117
+	/**
118
+	 * error_type
119
+	 * http://www.php.net/manual/en/errorfunc.constants.php#109430
120
+	 *
121
+	 * @param $code
122
+	 * @return string
123
+	 */
124
+	public static function error_type($code)
125
+	{
126
+		switch ($code) {
127
+			case E_ERROR: // 1 //
128
+				return 'E_ERROR';
129
+			case E_WARNING: // 2 //
130
+				return 'E_WARNING';
131
+			case E_PARSE: // 4 //
132
+				return 'E_PARSE';
133
+			case E_NOTICE: // 8 //
134
+				return 'E_NOTICE';
135
+			case E_CORE_ERROR: // 16 //
136
+				return 'E_CORE_ERROR';
137
+			case E_CORE_WARNING: // 32 //
138
+				return 'E_CORE_WARNING';
139
+			case E_COMPILE_ERROR: // 64 //
140
+				return 'E_COMPILE_ERROR';
141
+			case E_COMPILE_WARNING: // 128 //
142
+				return 'E_COMPILE_WARNING';
143
+			case E_USER_ERROR: // 256 //
144
+				return 'E_USER_ERROR';
145
+			case E_USER_WARNING: // 512 //
146
+				return 'E_USER_WARNING';
147
+			case E_USER_NOTICE: // 1024 //
148
+				return 'E_USER_NOTICE';
149
+			case E_STRICT: // 2048 //
150
+				return 'E_STRICT';
151
+			case E_RECOVERABLE_ERROR: // 4096 //
152
+				return 'E_RECOVERABLE_ERROR';
153
+			case E_DEPRECATED: // 8192 //
154
+				return 'E_DEPRECATED';
155
+			case E_USER_DEPRECATED: // 16384 //
156
+				return 'E_USER_DEPRECATED';
157
+			case E_ALL: // 16384 //
158
+				return 'E_ALL';
159
+		}
160
+		return '';
161
+	}
162
+
163
+
164
+
165
+	/**
166
+	 *    fatal_error_handler
167
+	 *
168
+	 * @return void
169
+	 */
170
+	public static function fatal_error_handler()
171
+	{
172
+		$last_error = error_get_last();
173
+		if ($last_error['type'] === E_ERROR) {
174
+			EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
175
+		}
176
+	}
177
+
178
+
179
+
180
+	/**
181
+	 * _format_error
182
+	 *
183
+	 * @param $code
184
+	 * @param $message
185
+	 * @param $file
186
+	 * @param $line
187
+	 * @return string
188
+	 */
189
+	private static function _format_error($code, $message, $file, $line)
190
+	{
191
+		$html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
192
+		$html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
193
+		$html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
194
+		$html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
195
+		$html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
196
+		$html .= '</tbody></table>';
197
+		return $html;
198
+	}
199
+
200
+
201
+
202
+	/**
203
+	 * set_content_type
204
+	 *
205
+	 * @param $content_type
206
+	 * @return string
207
+	 */
208
+	public static function set_content_type($content_type)
209
+	{
210
+		return 'text/html';
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * @return void
217
+	 * @throws EE_Error
218
+	 * @throws ReflectionException
219
+	 */
220
+	public function get_error()
221
+	{
222
+		if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
223
+			throw $this;
224
+		}
225
+		// get separate user and developer messages if they exist
226
+		$msg = explode('||', $this->getMessage());
227
+		$user_msg = $msg[0];
228
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
229
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
230
+		// add details to _all_exceptions array
231
+		$x_time = time();
232
+		self::$_all_exceptions[$x_time]['name'] = get_class($this);
233
+		self::$_all_exceptions[$x_time]['file'] = $this->getFile();
234
+		self::$_all_exceptions[$x_time]['line'] = $this->getLine();
235
+		self::$_all_exceptions[$x_time]['msg'] = $msg;
236
+		self::$_all_exceptions[$x_time]['code'] = $this->getCode();
237
+		self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
238
+		self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
239
+		self::$_error_count++;
240
+		//add_action( 'shutdown', array( $this, 'display_errors' ));
241
+		$this->display_errors();
242
+	}
243
+
244
+
245
+
246
+	/**
247
+	 * @param bool   $check_stored
248
+	 * @param string $type_to_check
249
+	 * @return bool
250
+	 */
251
+	public static function has_error($check_stored = false, $type_to_check = 'errors')
252
+	{
253
+		$has_error = isset(self::$_espresso_notices[$type_to_check])
254
+					 && ! empty(self::$_espresso_notices[$type_to_check])
255
+			? true
256
+			: false;
257
+		if ($check_stored && ! $has_error) {
258
+			$notices = (array)get_option('ee_notices', array());
259
+			foreach ($notices as $type => $notice) {
260
+				if ($type === $type_to_check && $notice) {
261
+					return true;
262
+				}
263
+			}
264
+		}
265
+		return $has_error;
266
+	}
267
+
268
+
269
+
270
+	/**
271
+	 * @echo string
272
+	 * @throws \ReflectionException
273
+	 */
274
+	public function display_errors()
275
+	{
276
+		$trace_details = '';
277
+		$output = '
278 278
 <style type="text/css">
279 279
 	#ee-error-message {
280 280
 		max-width:90% !important;
@@ -330,21 +330,21 @@  discard block
 block discarded – undo
330 330
 	}
331 331
 </style>
332 332
 <div id="ee-error-message" class="error">';
333
-        if (! WP_DEBUG) {
334
-            $output .= '
333
+		if (! WP_DEBUG) {
334
+			$output .= '
335 335
 	<p>';
336
-        }
337
-        // cycle thru errors
338
-        foreach (self::$_all_exceptions as $time => $ex) {
339
-            $error_code = '';
340
-            // process trace info
341
-            if (empty($ex['trace'])) {
342
-                $trace_details .= __(
343
-                    'Sorry, but no trace information was available for this exception.',
344
-                    'event_espresso'
345
-                );
346
-            } else {
347
-                $trace_details .= '
336
+		}
337
+		// cycle thru errors
338
+		foreach (self::$_all_exceptions as $time => $ex) {
339
+			$error_code = '';
340
+			// process trace info
341
+			if (empty($ex['trace'])) {
342
+				$trace_details .= __(
343
+					'Sorry, but no trace information was available for this exception.',
344
+					'event_espresso'
345
+				);
346
+			} else {
347
+				$trace_details .= '
348 348
 			<div id="ee-trace-details">
349 349
 			<table width="100%" border="0" cellpadding="5" cellspacing="0">
350 350
 				<tr>
@@ -354,43 +354,43 @@  discard block
 block discarded – undo
354 354
 					<th scope="col" align="left">Class</th>
355 355
 					<th scope="col" align="left">Method( arguments )</th>
356 356
 				</tr>';
357
-                $last_on_stack = count($ex['trace']) - 1;
358
-                // reverse array so that stack is in proper chronological order
359
-                $sorted_trace = array_reverse($ex['trace']);
360
-                foreach ($sorted_trace as $nmbr => $trace) {
361
-                    $file = isset($trace['file']) ? $trace['file'] : '';
362
-                    $class = isset($trace['class']) ? $trace['class'] : '';
363
-                    $type = isset($trace['type']) ? $trace['type'] : '';
364
-                    $function = isset($trace['function']) ? $trace['function'] : '';
365
-                    $args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
366
-                    $line = isset($trace['line']) ? $trace['line'] : '';
367
-                    $zebra = ($nmbr % 2) ? ' odd' : '';
368
-                    if (empty($file) && ! empty($class)) {
369
-                        $a = new ReflectionClass($class);
370
-                        $file = $a->getFileName();
371
-                        if (empty($line) && ! empty($function)) {
372
-                            try {
373
-                                //if $function is a closure, this throws an exception
374
-                                $b = new ReflectionMethod($class, $function);
375
-                                $line = $b->getStartLine();
376
-                            } catch (Exception $closure_exception) {
377
-                                $line = 'unknown';
378
-                            }
379
-                        }
380
-                    }
381
-                    if ($nmbr === $last_on_stack) {
382
-                        $file = $ex['file'] !== '' ? $ex['file'] : $file;
383
-                        $line = $ex['line'] !== '' ? $ex['line'] : $line;
384
-                        $error_code = self::generate_error_code($file, $trace['function'], $line);
385
-                    }
386
-                    $nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
387
-                    $line_dsply = ! empty($line) ? $line : '&nbsp;';
388
-                    $file_dsply = ! empty($file) ? $file : '&nbsp;';
389
-                    $class_dsply = ! empty($class) ? $class : '&nbsp;';
390
-                    $type_dsply = ! empty($type) ? $type : '&nbsp;';
391
-                    $function_dsply = ! empty($function) ? $function : '&nbsp;';
392
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
393
-                    $trace_details .= '
357
+				$last_on_stack = count($ex['trace']) - 1;
358
+				// reverse array so that stack is in proper chronological order
359
+				$sorted_trace = array_reverse($ex['trace']);
360
+				foreach ($sorted_trace as $nmbr => $trace) {
361
+					$file = isset($trace['file']) ? $trace['file'] : '';
362
+					$class = isset($trace['class']) ? $trace['class'] : '';
363
+					$type = isset($trace['type']) ? $trace['type'] : '';
364
+					$function = isset($trace['function']) ? $trace['function'] : '';
365
+					$args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
366
+					$line = isset($trace['line']) ? $trace['line'] : '';
367
+					$zebra = ($nmbr % 2) ? ' odd' : '';
368
+					if (empty($file) && ! empty($class)) {
369
+						$a = new ReflectionClass($class);
370
+						$file = $a->getFileName();
371
+						if (empty($line) && ! empty($function)) {
372
+							try {
373
+								//if $function is a closure, this throws an exception
374
+								$b = new ReflectionMethod($class, $function);
375
+								$line = $b->getStartLine();
376
+							} catch (Exception $closure_exception) {
377
+								$line = 'unknown';
378
+							}
379
+						}
380
+					}
381
+					if ($nmbr === $last_on_stack) {
382
+						$file = $ex['file'] !== '' ? $ex['file'] : $file;
383
+						$line = $ex['line'] !== '' ? $ex['line'] : $line;
384
+						$error_code = self::generate_error_code($file, $trace['function'], $line);
385
+					}
386
+					$nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
387
+					$line_dsply = ! empty($line) ? $line : '&nbsp;';
388
+					$file_dsply = ! empty($file) ? $file : '&nbsp;';
389
+					$class_dsply = ! empty($class) ? $class : '&nbsp;';
390
+					$type_dsply = ! empty($type) ? $type : '&nbsp;';
391
+					$function_dsply = ! empty($function) ? $function : '&nbsp;';
392
+					$args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
393
+					$trace_details .= '
394 394
 					<tr>
395 395
 						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
396 396
 						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
@@ -398,523 +398,523 @@  discard block
 block discarded – undo
398 398
 						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
399 399
 						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
400 400
 					</tr>';
401
-                }
402
-                $trace_details .= '
401
+				}
402
+				$trace_details .= '
403 403
 			 </table>
404 404
 			</div>';
405
-            }
406
-            $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
407
-            // add generic non-identifying messages for non-privileged users
408
-            if (! WP_DEBUG) {
409
-                $output .= '<span class="ee-error-user-msg-spn">'
410
-                           . trim($ex['msg'])
411
-                           . '</span> &nbsp; <sup>'
412
-                           . $ex['code']
413
-                           . '</sup><br />';
414
-            } else {
415
-                // or helpful developer messages if debugging is on
416
-                $output .= '
405
+			}
406
+			$ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
407
+			// add generic non-identifying messages for non-privileged users
408
+			if (! WP_DEBUG) {
409
+				$output .= '<span class="ee-error-user-msg-spn">'
410
+						   . trim($ex['msg'])
411
+						   . '</span> &nbsp; <sup>'
412
+						   . $ex['code']
413
+						   . '</sup><br />';
414
+			} else {
415
+				// or helpful developer messages if debugging is on
416
+				$output .= '
417 417
 		<div class="ee-error-dev-msg-dv">
418 418
 			<p class="ee-error-dev-msg-pg">
419 419
 				<strong class="ee-error-dev-msg-str">An '
420
-                           . $ex['name']
421
-                           . ' exception was thrown!</strong>  &nbsp; <span>code: '
422
-                           . $ex['code']
423
-                           . '</span><br />
420
+						   . $ex['name']
421
+						   . ' exception was thrown!</strong>  &nbsp; <span>code: '
422
+						   . $ex['code']
423
+						   . '</span><br />
424 424
 				<span class="big-text">"'
425
-                           . trim($ex['msg'])
426
-                           . '"</span><br/>
425
+						   . trim($ex['msg'])
426
+						   . '"</span><br/>
427 427
 				<a id="display-ee-error-trace-'
428
-                           . self::$_error_count
429
-                           . $time
430
-                           . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
431
-                           . self::$_error_count
432
-                           . $time
433
-                           . '">
428
+						   . self::$_error_count
429
+						   . $time
430
+						   . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
431
+						   . self::$_error_count
432
+						   . $time
433
+						   . '">
434 434
 					'
435
-                           . __('click to view backtrace and class/method details', 'event_espresso')
436
-                           . '
435
+						   . __('click to view backtrace and class/method details', 'event_espresso')
436
+						   . '
437 437
 				</a><br />
438 438
 				<span class="small-text lt-grey-text">'
439
-                           . $ex['file']
440
-                           . ' &nbsp; ( line no: '
441
-                           . $ex['line']
442
-                           . ' )</span>
439
+						   . $ex['file']
440
+						   . ' &nbsp; ( line no: '
441
+						   . $ex['line']
442
+						   . ' )</span>
443 443
 			</p>
444 444
 			<div id="ee-error-trace-'
445
-                           . self::$_error_count
446
-                           . $time
447
-                           . '-dv" class="ee-error-trace-dv" style="display: none;">
445
+						   . self::$_error_count
446
+						   . $time
447
+						   . '-dv" class="ee-error-trace-dv" style="display: none;">
448 448
 				'
449
-                           . $trace_details;
450
-                if (! empty($class)) {
451
-                    $output .= '
449
+						   . $trace_details;
450
+				if (! empty($class)) {
451
+					$output .= '
452 452
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
453 453
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
454 454
 						<h3>Class Details</h3>';
455
-                    $a = new ReflectionClass($class);
456
-                    $output .= '
455
+					$a = new ReflectionClass($class);
456
+					$output .= '
457 457
 						<pre>' . $a . '</pre>
458 458
 					</div>
459 459
 				</div>';
460
-                }
461
-                $output .= '
460
+				}
461
+				$output .= '
462 462
 			</div>
463 463
 		</div>
464 464
 		<br />';
465
-            }
466
-            $this->write_to_error_log($time, $ex);
467
-        }
468
-        // remove last linebreak
469
-        $output = substr($output, 0, -6);
470
-        if (! WP_DEBUG) {
471
-            $output .= '
465
+			}
466
+			$this->write_to_error_log($time, $ex);
467
+		}
468
+		// remove last linebreak
469
+		$output = substr($output, 0, -6);
470
+		if (! WP_DEBUG) {
471
+			$output .= '
472 472
 	</p>';
473
-        }
474
-        $output .= '
473
+		}
474
+		$output .= '
475 475
 </div>';
476
-        $output .= self::_print_scripts(true);
477
-        if (defined('DOING_AJAX')) {
478
-            echo wp_json_encode(array('error' => $output));
479
-            exit();
480
-        }
481
-        echo $output;
482
-        die();
483
-    }
484
-
485
-
486
-
487
-    /**
488
-     *    generate string from exception trace args
489
-     *
490
-     * @param array $arguments
491
-     * @param bool  $array
492
-     * @return string
493
-     */
494
-    private function _convert_args_to_string($arguments = array(), $array = false)
495
-    {
496
-        $arg_string = '';
497
-        if (! empty($arguments)) {
498
-            $args = array();
499
-            foreach ($arguments as $arg) {
500
-                if (! empty($arg)) {
501
-                    if (is_string($arg)) {
502
-                        $args[] = " '" . $arg . "'";
503
-                    } elseif (is_array($arg)) {
504
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
505
-                    } elseif ($arg === null) {
506
-                        $args[] = ' NULL';
507
-                    } elseif (is_bool($arg)) {
508
-                        $args[] = ($arg) ? ' TRUE' : ' FALSE';
509
-                    } elseif (is_object($arg)) {
510
-                        $args[] = ' OBJECT ' . get_class($arg);
511
-                    } elseif (is_resource($arg)) {
512
-                        $args[] = get_resource_type($arg);
513
-                    } else {
514
-                        $args[] = $arg;
515
-                    }
516
-                }
517
-            }
518
-            $arg_string = implode(', ', $args);
519
-        }
520
-        if ($array) {
521
-            $arg_string .= ' )';
522
-        }
523
-        return $arg_string;
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     *    add error message
530
-     *
531
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
532
-     *                            separate messages for user || dev
533
-     * @param        string $file the file that the error occurred in - just use __FILE__
534
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
535
-     * @param        string $line the line number where the error occurred - just use __LINE__
536
-     * @return        void
537
-     */
538
-    public static function add_error($msg = null, $file = null, $func = null, $line = null)
539
-    {
540
-        self::_add_notice('errors', $msg, $file, $func, $line);
541
-        self::$_error_count++;
542
-    }
543
-
544
-
545
-
546
-    /**
547
-     * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
548
-     * adds an error
549
-     *
550
-     * @param string $msg
551
-     * @param string $file
552
-     * @param string $func
553
-     * @param string $line
554
-     * @throws EE_Error
555
-     */
556
-    public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
557
-    {
558
-        if (WP_DEBUG) {
559
-            throw new EE_Error($msg);
560
-        }
561
-        EE_Error::add_error($msg, $file, $func, $line);
562
-    }
563
-
564
-
565
-
566
-    /**
567
-     *    add success message
568
-     *
569
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
570
-     *                            separate messages for user || dev
571
-     * @param        string $file the file that the error occurred in - just use __FILE__
572
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
573
-     * @param        string $line the line number where the error occurred - just use __LINE__
574
-     * @return        void
575
-     */
576
-    public static function add_success($msg = null, $file = null, $func = null, $line = null)
577
-    {
578
-        self::_add_notice('success', $msg, $file, $func, $line);
579
-    }
580
-
581
-
582
-
583
-    /**
584
-     *    add attention message
585
-     *
586
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
587
-     *                            separate messages for user || dev
588
-     * @param        string $file the file that the error occurred in - just use __FILE__
589
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
590
-     * @param        string $line the line number where the error occurred - just use __LINE__
591
-     * @return        void
592
-     */
593
-    public static function add_attention($msg = null, $file = null, $func = null, $line = null)
594
-    {
595
-        self::_add_notice('attention', $msg, $file, $func, $line);
596
-    }
597
-
598
-
599
-
600
-    /**
601
-     * @param string $type whether the message is for a success or error notification
602
-     * @param string $msg the message to display to users or developers
603
-     *                    - adding a double pipe || (OR) creates separate messages for user || dev
604
-     * @param string $file the file that the error occurred in - just use __FILE__
605
-     * @param string $func the function/method that the error occurred in - just use __FUNCTION__
606
-     * @param string $line the line number where the error occurred - just use __LINE__
607
-     * @return void
608
-     */
609
-    private static function _add_notice($type = 'success', $msg = '', $file = '', $func = '', $line = '')
610
-    {
611
-        if (empty($msg)) {
612
-            EE_Error::doing_it_wrong(
613
-                'EE_Error::add_' . $type . '()',
614
-                sprintf(
615
-                    __('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
616
-                        'event_espresso'),
617
-                    $type,
618
-                    $file,
619
-                    $line
620
-                ),
621
-                EVENT_ESPRESSO_VERSION
622
-            );
623
-        }
624
-        if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
625
-            EE_Error::doing_it_wrong(
626
-                'EE_Error::add_error()',
627
-                __('You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
628
-                    'event_espresso'),
629
-                EVENT_ESPRESSO_VERSION
630
-            );
631
-        }
632
-        // get separate user and developer messages if they exist
633
-        $msg      = explode('||', $msg);
634
-        $user_msg = $msg[0];
635
-        $dev_msg  = isset($msg[1]) ? $msg[1] : $msg[0];
636
-        /**
637
-         * Do an action so other code can be triggered when a notice is created
638
-         *
639
-         * @param string $type     can be 'errors', 'attention', or 'success'
640
-         * @param string $user_msg message displayed to user when WP_DEBUG is off
641
-         * @param string $user_msg message displayed to user when WP_DEBUG is on
642
-         * @param string $file     file where error was generated
643
-         * @param string $func     function where error was generated
644
-         * @param string $line     line where error was generated
645
-         */
646
-        do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
647
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
648
-        // add notice if message exists
649
-        if (! empty($msg)) {
650
-            // get error code
651
-            $notice_code = EE_Error::generate_error_code($file, $func, $line);
652
-            if (WP_DEBUG && $type === 'errors') {
653
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
654
-            }
655
-            // add notice. Index by code if it's not blank
656
-            if ($notice_code) {
657
-                self::$_espresso_notices[$type][$notice_code] = $msg;
658
-            } else {
659
-                self::$_espresso_notices[$type][] = $msg;
660
-            }
661
-            add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
662
-        }
663
-    }
664
-
665
-
666
-    /**
667
-     * in some case it may be necessary to overwrite the existing success messages
668
-     *
669
-     * @return        void
670
-     */
671
-    public static function overwrite_success()
672
-    {
673
-        self::$_espresso_notices['success'] = false;
674
-    }
675
-
676
-
677
-
678
-    /**
679
-     * in some case it may be necessary to overwrite the existing attention messages
680
-     *
681
-     * @return void
682
-     */
683
-    public static function overwrite_attention()
684
-    {
685
-        self::$_espresso_notices['attention'] = false;
686
-    }
687
-
688
-
689
-
690
-    /**
691
-     * in some case it may be necessary to overwrite the existing error messages
692
-     *
693
-     * @return void
694
-     */
695
-    public static function overwrite_errors()
696
-    {
697
-        self::$_espresso_notices['errors'] = false;
698
-    }
699
-
700
-
701
-
702
-    /**
703
-     * @return void
704
-     */
705
-    public static function reset_notices()
706
-    {
707
-        self::$_espresso_notices['success']   = false;
708
-        self::$_espresso_notices['attention'] = false;
709
-        self::$_espresso_notices['errors']    = false;
710
-    }
711
-
712
-
713
-
714
-    /**
715
-     * @return int
716
-     */
717
-    public static function has_notices()
718
-    {
719
-        $has_notices = 0;
720
-        // check for success messages
721
-        $has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])
722
-            ? 3
723
-            : $has_notices;
724
-        // check for attention messages
725
-        $has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])
726
-            ? 2
727
-            : $has_notices;
728
-        // check for error messages
729
-        $has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])
730
-            ? 1
731
-            : $has_notices;
732
-        return $has_notices;
733
-    }
734
-
735
-
736
-    /**
737
-     * This simply returns non formatted error notices as they were sent into the EE_Error object.
738
-     *
739
-     * @since 4.9.0
740
-     * @return array
741
-     */
742
-    public static function get_vanilla_notices()
743
-    {
744
-        return array(
745
-            'success'   => isset(self::$_espresso_notices['success'])
746
-                ? self::$_espresso_notices['success']
747
-                : array(),
748
-            'attention' => isset(self::$_espresso_notices['attention'])
749
-                ? self::$_espresso_notices['attention']
750
-                : array(),
751
-            'errors'    => isset(self::$_espresso_notices['errors'])
752
-                ? self::$_espresso_notices['errors']
753
-                : array(),
754
-        );
755
-    }
756
-
757
-
758
-
759
-    /**
760
-     * compile all error or success messages into one string
761
-     *
762
-     * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
763
-     * @param boolean $format_output     whether or not to format the messages for display in the WP admin
764
-     * @param boolean $save_to_transient whether or not to save notices to the db for retrieval on next request
765
-     *                                          - ONLY do this just before redirecting
766
-     * @param boolean $remove_empty      whether or not to unset empty messages
767
-     * @return array
768
-     */
769
-    public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
770
-    {
771
-        // do_action('AHEE_log', __FILE__, __FUNCTION__, '');
772
-        $success_messages   = '';
773
-        $attention_messages = '';
774
-        $error_messages     = '';
775
-        $print_scripts      = false;
776
-        // EEH_Debug_Tools::printr( self::$_espresso_notices, 'espresso_notices  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
777
-        // either save notices to the db
778
-        if ($save_to_transient || isset($_REQUEST['activate-selected'])) {
779
-            $existing_notices  = get_option('ee_notices', array());
780
-            $existing_notices = $existing_notices !== '' ? $existing_notices : array();
781
-            self::$_espresso_notices = array_merge(
782
-                $existing_notices,
783
-                self::$_espresso_notices
784
-            );
785
-            update_option('ee_notices', self::$_espresso_notices);
786
-            return array();
787
-        }
788
-        // grab any notices that have been previously saved
789
-        if ($notices = get_option('ee_notices', false)) {
790
-            foreach ($notices as $type => $notice) {
791
-                if (is_array($notice) && ! empty($notice)) {
792
-                    // make sure that existing notice type is an array
793
-                    self::$_espresso_notices[$type] = is_array(self::$_espresso_notices[$type])
794
-                                                      && ! empty(self::$_espresso_notices[$type])
795
-                        ? self::$_espresso_notices[$type]
796
-                        : array();
797
-                    // merge stored notices with any newly created ones
798
-                    self::$_espresso_notices[$type] = array_merge(self::$_espresso_notices[$type], $notice);
799
-                    $print_scripts                  = true;
800
-                }
801
-            }
802
-            // now clear any stored notices
803
-            update_option('ee_notices', false);
804
-        }
805
-        // check for success messages
806
-        if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
807
-            // combine messages
808
-            $success_messages .= implode(self::$_espresso_notices['success'], '<br />');
809
-            $print_scripts    = true;
810
-        }
811
-        // check for attention messages
812
-        if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
813
-            // combine messages
814
-            $attention_messages .= implode(self::$_espresso_notices['attention'], '<br />');
815
-            $print_scripts      = true;
816
-        }
817
-        // check for error messages
818
-        if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
819
-            $error_messages .= count(self::$_espresso_notices['errors']) > 1
820
-                ? __('The following errors have occurred:<br />', 'event_espresso')
821
-                : __('An error has occurred:<br />', 'event_espresso');
822
-            // combine messages
823
-            $error_messages .= implode(self::$_espresso_notices['errors'], '<br />');
824
-            $print_scripts  = true;
825
-        }
826
-        if ($format_output) {
827
-
828
-            $notices = '<div id="espresso-notices">';
829
-            $close = is_admin() ? ''
830
-                : '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"></span></a>';
831
-            if ($success_messages !== '') {
832
-                $css_id    = is_admin() ? 'message' : 'espresso-notices-success';
833
-                $css_class = is_admin() ? 'updated fade' : 'success fade-away';
834
-                //showMessage( $success_messages );
835
-                $notices .= '<div id="'
836
-                            . $css_id
837
-                            . '" class="espresso-notices '
838
-                            . $css_class
839
-                            . '" style="display:none;"><p>'
840
-                            . $success_messages
841
-                            . '</p>'
842
-                            . $close
843
-                            . '</div>';
844
-            }
845
-            if ($attention_messages !== '') {
846
-                $css_id    = is_admin() ? 'message' : 'espresso-notices-attention';
847
-                $css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
848
-                //showMessage( $error_messages, TRUE );
849
-                $notices .= '<div id="'
850
-                            . $css_id
851
-                            . '" class="espresso-notices '
852
-                            . $css_class
853
-                            . '" style="display:none;"><p>'
854
-                            . $attention_messages
855
-                            . '</p>'
856
-                            . $close
857
-                            . '</div>';
858
-            }
859
-            if ($error_messages !== '') {
860
-                $css_id    = is_admin() ? 'message' : 'espresso-notices-error';
861
-                $css_class = is_admin() ? 'error' : 'error fade-away';
862
-                //showMessage( $error_messages, TRUE );
863
-                $notices .= '<div id="'
864
-                            . $css_id
865
-                            . '" class="espresso-notices '
866
-                            . $css_class
867
-                            . '" style="display:none;"><p>'
868
-                            . $error_messages
869
-                            . '</p>'
870
-                            . $close
871
-                            . '</div>';
872
-            }
873
-            $notices .= '</div>';
874
-        } else {
875
-
876
-            $notices = array(
877
-                'success'   => $success_messages,
878
-                'attention' => $attention_messages,
879
-                'errors'    => $error_messages,
880
-            );
881
-            if ($remove_empty) {
882
-                // remove empty notices
883
-                foreach ($notices as $type => $notice) {
884
-                    if (empty($notice)) {
885
-                        unset($notices[$type]);
886
-                    }
887
-                }
888
-            }
889
-        }
890
-        if ($print_scripts) {
891
-            self::_print_scripts();
892
-        }
893
-        return $notices;
894
-    }
895
-
896
-
897
-
898
-    /**
899
-     * _print_scripts
900
-     *
901
-     * @param    bool $force_print
902
-     * @return    string
903
-     */
904
-    private static function _print_scripts($force_print = false)
905
-    {
906
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
907
-            if (wp_script_is('ee_error_js', 'enqueued')) {
908
-                return '';
909
-            }
910
-            if (wp_script_is('ee_error_js', 'registered')) {
911
-                wp_enqueue_style('espresso_default');
912
-                wp_enqueue_style('espresso_custom_css');
913
-                wp_enqueue_script('ee_error_js');
914
-                wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
915
-            }
916
-        } else {
917
-            return '
476
+		$output .= self::_print_scripts(true);
477
+		if (defined('DOING_AJAX')) {
478
+			echo wp_json_encode(array('error' => $output));
479
+			exit();
480
+		}
481
+		echo $output;
482
+		die();
483
+	}
484
+
485
+
486
+
487
+	/**
488
+	 *    generate string from exception trace args
489
+	 *
490
+	 * @param array $arguments
491
+	 * @param bool  $array
492
+	 * @return string
493
+	 */
494
+	private function _convert_args_to_string($arguments = array(), $array = false)
495
+	{
496
+		$arg_string = '';
497
+		if (! empty($arguments)) {
498
+			$args = array();
499
+			foreach ($arguments as $arg) {
500
+				if (! empty($arg)) {
501
+					if (is_string($arg)) {
502
+						$args[] = " '" . $arg . "'";
503
+					} elseif (is_array($arg)) {
504
+						$args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
505
+					} elseif ($arg === null) {
506
+						$args[] = ' NULL';
507
+					} elseif (is_bool($arg)) {
508
+						$args[] = ($arg) ? ' TRUE' : ' FALSE';
509
+					} elseif (is_object($arg)) {
510
+						$args[] = ' OBJECT ' . get_class($arg);
511
+					} elseif (is_resource($arg)) {
512
+						$args[] = get_resource_type($arg);
513
+					} else {
514
+						$args[] = $arg;
515
+					}
516
+				}
517
+			}
518
+			$arg_string = implode(', ', $args);
519
+		}
520
+		if ($array) {
521
+			$arg_string .= ' )';
522
+		}
523
+		return $arg_string;
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 *    add error message
530
+	 *
531
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
532
+	 *                            separate messages for user || dev
533
+	 * @param        string $file the file that the error occurred in - just use __FILE__
534
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
535
+	 * @param        string $line the line number where the error occurred - just use __LINE__
536
+	 * @return        void
537
+	 */
538
+	public static function add_error($msg = null, $file = null, $func = null, $line = null)
539
+	{
540
+		self::_add_notice('errors', $msg, $file, $func, $line);
541
+		self::$_error_count++;
542
+	}
543
+
544
+
545
+
546
+	/**
547
+	 * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
548
+	 * adds an error
549
+	 *
550
+	 * @param string $msg
551
+	 * @param string $file
552
+	 * @param string $func
553
+	 * @param string $line
554
+	 * @throws EE_Error
555
+	 */
556
+	public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
557
+	{
558
+		if (WP_DEBUG) {
559
+			throw new EE_Error($msg);
560
+		}
561
+		EE_Error::add_error($msg, $file, $func, $line);
562
+	}
563
+
564
+
565
+
566
+	/**
567
+	 *    add success message
568
+	 *
569
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
570
+	 *                            separate messages for user || dev
571
+	 * @param        string $file the file that the error occurred in - just use __FILE__
572
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
573
+	 * @param        string $line the line number where the error occurred - just use __LINE__
574
+	 * @return        void
575
+	 */
576
+	public static function add_success($msg = null, $file = null, $func = null, $line = null)
577
+	{
578
+		self::_add_notice('success', $msg, $file, $func, $line);
579
+	}
580
+
581
+
582
+
583
+	/**
584
+	 *    add attention message
585
+	 *
586
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
587
+	 *                            separate messages for user || dev
588
+	 * @param        string $file the file that the error occurred in - just use __FILE__
589
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
590
+	 * @param        string $line the line number where the error occurred - just use __LINE__
591
+	 * @return        void
592
+	 */
593
+	public static function add_attention($msg = null, $file = null, $func = null, $line = null)
594
+	{
595
+		self::_add_notice('attention', $msg, $file, $func, $line);
596
+	}
597
+
598
+
599
+
600
+	/**
601
+	 * @param string $type whether the message is for a success or error notification
602
+	 * @param string $msg the message to display to users or developers
603
+	 *                    - adding a double pipe || (OR) creates separate messages for user || dev
604
+	 * @param string $file the file that the error occurred in - just use __FILE__
605
+	 * @param string $func the function/method that the error occurred in - just use __FUNCTION__
606
+	 * @param string $line the line number where the error occurred - just use __LINE__
607
+	 * @return void
608
+	 */
609
+	private static function _add_notice($type = 'success', $msg = '', $file = '', $func = '', $line = '')
610
+	{
611
+		if (empty($msg)) {
612
+			EE_Error::doing_it_wrong(
613
+				'EE_Error::add_' . $type . '()',
614
+				sprintf(
615
+					__('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
616
+						'event_espresso'),
617
+					$type,
618
+					$file,
619
+					$line
620
+				),
621
+				EVENT_ESPRESSO_VERSION
622
+			);
623
+		}
624
+		if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
625
+			EE_Error::doing_it_wrong(
626
+				'EE_Error::add_error()',
627
+				__('You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
628
+					'event_espresso'),
629
+				EVENT_ESPRESSO_VERSION
630
+			);
631
+		}
632
+		// get separate user and developer messages if they exist
633
+		$msg      = explode('||', $msg);
634
+		$user_msg = $msg[0];
635
+		$dev_msg  = isset($msg[1]) ? $msg[1] : $msg[0];
636
+		/**
637
+		 * Do an action so other code can be triggered when a notice is created
638
+		 *
639
+		 * @param string $type     can be 'errors', 'attention', or 'success'
640
+		 * @param string $user_msg message displayed to user when WP_DEBUG is off
641
+		 * @param string $user_msg message displayed to user when WP_DEBUG is on
642
+		 * @param string $file     file where error was generated
643
+		 * @param string $func     function where error was generated
644
+		 * @param string $line     line where error was generated
645
+		 */
646
+		do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
647
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
648
+		// add notice if message exists
649
+		if (! empty($msg)) {
650
+			// get error code
651
+			$notice_code = EE_Error::generate_error_code($file, $func, $line);
652
+			if (WP_DEBUG && $type === 'errors') {
653
+				$msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
654
+			}
655
+			// add notice. Index by code if it's not blank
656
+			if ($notice_code) {
657
+				self::$_espresso_notices[$type][$notice_code] = $msg;
658
+			} else {
659
+				self::$_espresso_notices[$type][] = $msg;
660
+			}
661
+			add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
662
+		}
663
+	}
664
+
665
+
666
+	/**
667
+	 * in some case it may be necessary to overwrite the existing success messages
668
+	 *
669
+	 * @return        void
670
+	 */
671
+	public static function overwrite_success()
672
+	{
673
+		self::$_espresso_notices['success'] = false;
674
+	}
675
+
676
+
677
+
678
+	/**
679
+	 * in some case it may be necessary to overwrite the existing attention messages
680
+	 *
681
+	 * @return void
682
+	 */
683
+	public static function overwrite_attention()
684
+	{
685
+		self::$_espresso_notices['attention'] = false;
686
+	}
687
+
688
+
689
+
690
+	/**
691
+	 * in some case it may be necessary to overwrite the existing error messages
692
+	 *
693
+	 * @return void
694
+	 */
695
+	public static function overwrite_errors()
696
+	{
697
+		self::$_espresso_notices['errors'] = false;
698
+	}
699
+
700
+
701
+
702
+	/**
703
+	 * @return void
704
+	 */
705
+	public static function reset_notices()
706
+	{
707
+		self::$_espresso_notices['success']   = false;
708
+		self::$_espresso_notices['attention'] = false;
709
+		self::$_espresso_notices['errors']    = false;
710
+	}
711
+
712
+
713
+
714
+	/**
715
+	 * @return int
716
+	 */
717
+	public static function has_notices()
718
+	{
719
+		$has_notices = 0;
720
+		// check for success messages
721
+		$has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])
722
+			? 3
723
+			: $has_notices;
724
+		// check for attention messages
725
+		$has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])
726
+			? 2
727
+			: $has_notices;
728
+		// check for error messages
729
+		$has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])
730
+			? 1
731
+			: $has_notices;
732
+		return $has_notices;
733
+	}
734
+
735
+
736
+	/**
737
+	 * This simply returns non formatted error notices as they were sent into the EE_Error object.
738
+	 *
739
+	 * @since 4.9.0
740
+	 * @return array
741
+	 */
742
+	public static function get_vanilla_notices()
743
+	{
744
+		return array(
745
+			'success'   => isset(self::$_espresso_notices['success'])
746
+				? self::$_espresso_notices['success']
747
+				: array(),
748
+			'attention' => isset(self::$_espresso_notices['attention'])
749
+				? self::$_espresso_notices['attention']
750
+				: array(),
751
+			'errors'    => isset(self::$_espresso_notices['errors'])
752
+				? self::$_espresso_notices['errors']
753
+				: array(),
754
+		);
755
+	}
756
+
757
+
758
+
759
+	/**
760
+	 * compile all error or success messages into one string
761
+	 *
762
+	 * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
763
+	 * @param boolean $format_output     whether or not to format the messages for display in the WP admin
764
+	 * @param boolean $save_to_transient whether or not to save notices to the db for retrieval on next request
765
+	 *                                          - ONLY do this just before redirecting
766
+	 * @param boolean $remove_empty      whether or not to unset empty messages
767
+	 * @return array
768
+	 */
769
+	public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
770
+	{
771
+		// do_action('AHEE_log', __FILE__, __FUNCTION__, '');
772
+		$success_messages   = '';
773
+		$attention_messages = '';
774
+		$error_messages     = '';
775
+		$print_scripts      = false;
776
+		// EEH_Debug_Tools::printr( self::$_espresso_notices, 'espresso_notices  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
777
+		// either save notices to the db
778
+		if ($save_to_transient || isset($_REQUEST['activate-selected'])) {
779
+			$existing_notices  = get_option('ee_notices', array());
780
+			$existing_notices = $existing_notices !== '' ? $existing_notices : array();
781
+			self::$_espresso_notices = array_merge(
782
+				$existing_notices,
783
+				self::$_espresso_notices
784
+			);
785
+			update_option('ee_notices', self::$_espresso_notices);
786
+			return array();
787
+		}
788
+		// grab any notices that have been previously saved
789
+		if ($notices = get_option('ee_notices', false)) {
790
+			foreach ($notices as $type => $notice) {
791
+				if (is_array($notice) && ! empty($notice)) {
792
+					// make sure that existing notice type is an array
793
+					self::$_espresso_notices[$type] = is_array(self::$_espresso_notices[$type])
794
+													  && ! empty(self::$_espresso_notices[$type])
795
+						? self::$_espresso_notices[$type]
796
+						: array();
797
+					// merge stored notices with any newly created ones
798
+					self::$_espresso_notices[$type] = array_merge(self::$_espresso_notices[$type], $notice);
799
+					$print_scripts                  = true;
800
+				}
801
+			}
802
+			// now clear any stored notices
803
+			update_option('ee_notices', false);
804
+		}
805
+		// check for success messages
806
+		if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
807
+			// combine messages
808
+			$success_messages .= implode(self::$_espresso_notices['success'], '<br />');
809
+			$print_scripts    = true;
810
+		}
811
+		// check for attention messages
812
+		if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
813
+			// combine messages
814
+			$attention_messages .= implode(self::$_espresso_notices['attention'], '<br />');
815
+			$print_scripts      = true;
816
+		}
817
+		// check for error messages
818
+		if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
819
+			$error_messages .= count(self::$_espresso_notices['errors']) > 1
820
+				? __('The following errors have occurred:<br />', 'event_espresso')
821
+				: __('An error has occurred:<br />', 'event_espresso');
822
+			// combine messages
823
+			$error_messages .= implode(self::$_espresso_notices['errors'], '<br />');
824
+			$print_scripts  = true;
825
+		}
826
+		if ($format_output) {
827
+
828
+			$notices = '<div id="espresso-notices">';
829
+			$close = is_admin() ? ''
830
+				: '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"></span></a>';
831
+			if ($success_messages !== '') {
832
+				$css_id    = is_admin() ? 'message' : 'espresso-notices-success';
833
+				$css_class = is_admin() ? 'updated fade' : 'success fade-away';
834
+				//showMessage( $success_messages );
835
+				$notices .= '<div id="'
836
+							. $css_id
837
+							. '" class="espresso-notices '
838
+							. $css_class
839
+							. '" style="display:none;"><p>'
840
+							. $success_messages
841
+							. '</p>'
842
+							. $close
843
+							. '</div>';
844
+			}
845
+			if ($attention_messages !== '') {
846
+				$css_id    = is_admin() ? 'message' : 'espresso-notices-attention';
847
+				$css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
848
+				//showMessage( $error_messages, TRUE );
849
+				$notices .= '<div id="'
850
+							. $css_id
851
+							. '" class="espresso-notices '
852
+							. $css_class
853
+							. '" style="display:none;"><p>'
854
+							. $attention_messages
855
+							. '</p>'
856
+							. $close
857
+							. '</div>';
858
+			}
859
+			if ($error_messages !== '') {
860
+				$css_id    = is_admin() ? 'message' : 'espresso-notices-error';
861
+				$css_class = is_admin() ? 'error' : 'error fade-away';
862
+				//showMessage( $error_messages, TRUE );
863
+				$notices .= '<div id="'
864
+							. $css_id
865
+							. '" class="espresso-notices '
866
+							. $css_class
867
+							. '" style="display:none;"><p>'
868
+							. $error_messages
869
+							. '</p>'
870
+							. $close
871
+							. '</div>';
872
+			}
873
+			$notices .= '</div>';
874
+		} else {
875
+
876
+			$notices = array(
877
+				'success'   => $success_messages,
878
+				'attention' => $attention_messages,
879
+				'errors'    => $error_messages,
880
+			);
881
+			if ($remove_empty) {
882
+				// remove empty notices
883
+				foreach ($notices as $type => $notice) {
884
+					if (empty($notice)) {
885
+						unset($notices[$type]);
886
+					}
887
+				}
888
+			}
889
+		}
890
+		if ($print_scripts) {
891
+			self::_print_scripts();
892
+		}
893
+		return $notices;
894
+	}
895
+
896
+
897
+
898
+	/**
899
+	 * _print_scripts
900
+	 *
901
+	 * @param    bool $force_print
902
+	 * @return    string
903
+	 */
904
+	private static function _print_scripts($force_print = false)
905
+	{
906
+		if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
907
+			if (wp_script_is('ee_error_js', 'enqueued')) {
908
+				return '';
909
+			}
910
+			if (wp_script_is('ee_error_js', 'registered')) {
911
+				wp_enqueue_style('espresso_default');
912
+				wp_enqueue_style('espresso_custom_css');
913
+				wp_enqueue_script('ee_error_js');
914
+				wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
915
+			}
916
+		} else {
917
+			return '
918 918
 <script>
919 919
 /* <![CDATA[ */
920 920
 var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
@@ -924,223 +924,223 @@  discard block
 block discarded – undo
924 924
 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
925 925
 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
926 926
 ';
927
-        }
928
-        return '';
929
-    }
930
-
931
-
932
-
933
-    /**
934
-     * @return void
935
-     */
936
-    public static function enqueue_error_scripts()
937
-    {
938
-        self::_print_scripts();
939
-    }
940
-
941
-
942
-
943
-    /**
944
-     * create error code from filepath, function name,
945
-     * and line number where exception or error was thrown
946
-     *
947
-     * @param string $file
948
-     * @param string $func
949
-     * @param string $line
950
-     * @return string
951
-     */
952
-    public static function generate_error_code($file = '', $func = '', $line = '')
953
-    {
954
-        $file       = explode('.', basename($file));
955
-        $error_code = ! empty($file[0]) ? $file[0] : '';
956
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
957
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
958
-        return $error_code;
959
-    }
960
-
961
-
962
-
963
-    /**
964
-     * write exception details to log file
965
-     * Since 4.9.53.rc.006 this writes to the standard PHP log file, not EE's custom log file
966
-     *
967
-     * @param int   $time
968
-     * @param array $ex
969
-     * @param bool  $clear
970
-     * @return void
971
-     */
972
-    public function write_to_error_log($time = 0, $ex = array(), $clear = false)
973
-    {
974
-        if (empty($ex)) {
975
-            return;
976
-        }
977
-        if (! $time) {
978
-            $time = time();
979
-        }
980
-        $exception_log = '----------------------------------------------------------------------------------------'
981
-                         . PHP_EOL;
982
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
983
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
984
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
985
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
986
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
987
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
988
-        $exception_log .= $ex['string'] . PHP_EOL;
989
-        $exception_log .= '----------------------------------------------------------------------------------------'
990
-                          . PHP_EOL;
991
-        try {
992
-            error_log($exception_log);
993
-        } catch (EE_Error $e) {
994
-            EE_Error::add_error(sprintf(__('Event Espresso error logging could not be setup because: %s',
995
-                'event_espresso'), $e->getMessage()));
996
-        }
997
-    }
998
-
999
-
1000
-
1001
-    /**
1002
-     * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1003
-     * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1004
-     * but the code execution is done in a manner that could lead to unexpected results
1005
-     * (i.e. running to early, or too late in WP or EE loading process).
1006
-     * A good test for knowing whether to use this method is:
1007
-     * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1008
-     * Yes -> use EE_Error::add_error() or throw new EE_Error()
1009
-     * 2. If this is loaded before something else, it won't break anything,
1010
-     * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1011
-     *
1012
-     * @uses   constant WP_DEBUG test if wp_debug is on or not
1013
-     * @param string $function      The function that was called
1014
-     * @param string $message       A message explaining what has been done incorrectly
1015
-     * @param string $version       The version of Event Espresso where the error was added
1016
-     * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1017
-     *                              for a deprecated function. This allows deprecation to occur during one version,
1018
-     *                              but not have any notices appear until a later version. This allows developers
1019
-     *                              extra time to update their code before notices appear.
1020
-     * @param int    $error_type
1021
-     */
1022
-    public static function doing_it_wrong(
1023
-        $function,
1024
-        $message,
1025
-        $version,
1026
-        $applies_when = '',
1027
-        $error_type = null
1028
-    ) {
1029
-        if (defined('WP_DEBUG') && WP_DEBUG) {
1030
-            EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1031
-        }
1032
-    }
1033
-
1034
-
1035
-
1036
-    /**
1037
-     * Like get_notices, but returns an array of all the notices of the given type.
1038
-     *
1039
-     * @return array {
1040
-     *  @type array $success   all the success messages
1041
-     *  @type array $errors    all the error messages
1042
-     *  @type array $attention all the attention messages
1043
-     * }
1044
-     */
1045
-    public static function get_raw_notices()
1046
-    {
1047
-        return self::$_espresso_notices;
1048
-    }
1049
-
1050
-
1051
-
1052
-    /**
1053
-     * @deprecated 4.9.27
1054
-     * @param string $pan_name     the name, or key of the Persistent Admin Notice to be stored
1055
-     * @param string $pan_message  the message to be stored persistently until dismissed
1056
-     * @param bool   $force_update allows one to enforce the reappearance of a persistent message.
1057
-     * @return void
1058
-     * @throws InvalidDataTypeException
1059
-     */
1060
-    public static function add_persistent_admin_notice($pan_name = '', $pan_message, $force_update = false)
1061
-    {
1062
-        new PersistentAdminNotice(
1063
-            $pan_name,
1064
-            $pan_message,
1065
-            $force_update
1066
-        );
1067
-        EE_Error::doing_it_wrong(
1068
-            __METHOD__,
1069
-            sprintf(
1070
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1071
-                '\EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
1072
-            ),
1073
-            '4.9.27'
1074
-        );
1075
-    }
1076
-
1077
-
1078
-
1079
-    /**
1080
-     * @deprecated 4.9.27
1081
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
1082
-     * @param bool   $purge
1083
-     * @param bool   $return
1084
-     * @throws DomainException
1085
-     * @throws InvalidInterfaceException
1086
-     * @throws InvalidDataTypeException
1087
-     * @throws ServiceNotFoundException
1088
-     * @throws InvalidArgumentException
1089
-     */
1090
-    public static function dismiss_persistent_admin_notice($pan_name = '', $purge = false, $return = false)
1091
-    {
1092
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
1093
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
1094
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1095
-        );
1096
-        $persistent_admin_notice_manager->dismissNotice($pan_name, $purge, $return);
1097
-        EE_Error::doing_it_wrong(
1098
-            __METHOD__,
1099
-            sprintf(
1100
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1101
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1102
-            ),
1103
-            '4.9.27'
1104
-        );
1105
-    }
1106
-
1107
-
1108
-
1109
-    /**
1110
-     * @deprecated 4.9.27
1111
-     * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
1112
-     * @param  string $pan_message the message to be stored persistently until dismissed
1113
-     * @param  string $return_url  URL to go back to after nag notice is dismissed
1114
-     */
1115
-    public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
1116
-    {
1117
-        EE_Error::doing_it_wrong(
1118
-            __METHOD__,
1119
-            sprintf(
1120
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1121
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1122
-            ),
1123
-            '4.9.27'
1124
-        );
1125
-    }
1126
-
1127
-
1128
-
1129
-    /**
1130
-     * @deprecated 4.9.27
1131
-     * @param string $return_url
1132
-     */
1133
-    public static function get_persistent_admin_notices($return_url = '')
1134
-    {
1135
-        EE_Error::doing_it_wrong(
1136
-            __METHOD__,
1137
-            sprintf(
1138
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1139
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1140
-            ),
1141
-            '4.9.27'
1142
-        );
1143
-    }
927
+		}
928
+		return '';
929
+	}
930
+
931
+
932
+
933
+	/**
934
+	 * @return void
935
+	 */
936
+	public static function enqueue_error_scripts()
937
+	{
938
+		self::_print_scripts();
939
+	}
940
+
941
+
942
+
943
+	/**
944
+	 * create error code from filepath, function name,
945
+	 * and line number where exception or error was thrown
946
+	 *
947
+	 * @param string $file
948
+	 * @param string $func
949
+	 * @param string $line
950
+	 * @return string
951
+	 */
952
+	public static function generate_error_code($file = '', $func = '', $line = '')
953
+	{
954
+		$file       = explode('.', basename($file));
955
+		$error_code = ! empty($file[0]) ? $file[0] : '';
956
+		$error_code .= ! empty($func) ? ' - ' . $func : '';
957
+		$error_code .= ! empty($line) ? ' - ' . $line : '';
958
+		return $error_code;
959
+	}
960
+
961
+
962
+
963
+	/**
964
+	 * write exception details to log file
965
+	 * Since 4.9.53.rc.006 this writes to the standard PHP log file, not EE's custom log file
966
+	 *
967
+	 * @param int   $time
968
+	 * @param array $ex
969
+	 * @param bool  $clear
970
+	 * @return void
971
+	 */
972
+	public function write_to_error_log($time = 0, $ex = array(), $clear = false)
973
+	{
974
+		if (empty($ex)) {
975
+			return;
976
+		}
977
+		if (! $time) {
978
+			$time = time();
979
+		}
980
+		$exception_log = '----------------------------------------------------------------------------------------'
981
+						 . PHP_EOL;
982
+		$exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
983
+		$exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
984
+		$exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
985
+		$exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
986
+		$exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
987
+		$exception_log .= 'Stack trace: ' . PHP_EOL;
988
+		$exception_log .= $ex['string'] . PHP_EOL;
989
+		$exception_log .= '----------------------------------------------------------------------------------------'
990
+						  . PHP_EOL;
991
+		try {
992
+			error_log($exception_log);
993
+		} catch (EE_Error $e) {
994
+			EE_Error::add_error(sprintf(__('Event Espresso error logging could not be setup because: %s',
995
+				'event_espresso'), $e->getMessage()));
996
+		}
997
+	}
998
+
999
+
1000
+
1001
+	/**
1002
+	 * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1003
+	 * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1004
+	 * but the code execution is done in a manner that could lead to unexpected results
1005
+	 * (i.e. running to early, or too late in WP or EE loading process).
1006
+	 * A good test for knowing whether to use this method is:
1007
+	 * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1008
+	 * Yes -> use EE_Error::add_error() or throw new EE_Error()
1009
+	 * 2. If this is loaded before something else, it won't break anything,
1010
+	 * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1011
+	 *
1012
+	 * @uses   constant WP_DEBUG test if wp_debug is on or not
1013
+	 * @param string $function      The function that was called
1014
+	 * @param string $message       A message explaining what has been done incorrectly
1015
+	 * @param string $version       The version of Event Espresso where the error was added
1016
+	 * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1017
+	 *                              for a deprecated function. This allows deprecation to occur during one version,
1018
+	 *                              but not have any notices appear until a later version. This allows developers
1019
+	 *                              extra time to update their code before notices appear.
1020
+	 * @param int    $error_type
1021
+	 */
1022
+	public static function doing_it_wrong(
1023
+		$function,
1024
+		$message,
1025
+		$version,
1026
+		$applies_when = '',
1027
+		$error_type = null
1028
+	) {
1029
+		if (defined('WP_DEBUG') && WP_DEBUG) {
1030
+			EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1031
+		}
1032
+	}
1033
+
1034
+
1035
+
1036
+	/**
1037
+	 * Like get_notices, but returns an array of all the notices of the given type.
1038
+	 *
1039
+	 * @return array {
1040
+	 *  @type array $success   all the success messages
1041
+	 *  @type array $errors    all the error messages
1042
+	 *  @type array $attention all the attention messages
1043
+	 * }
1044
+	 */
1045
+	public static function get_raw_notices()
1046
+	{
1047
+		return self::$_espresso_notices;
1048
+	}
1049
+
1050
+
1051
+
1052
+	/**
1053
+	 * @deprecated 4.9.27
1054
+	 * @param string $pan_name     the name, or key of the Persistent Admin Notice to be stored
1055
+	 * @param string $pan_message  the message to be stored persistently until dismissed
1056
+	 * @param bool   $force_update allows one to enforce the reappearance of a persistent message.
1057
+	 * @return void
1058
+	 * @throws InvalidDataTypeException
1059
+	 */
1060
+	public static function add_persistent_admin_notice($pan_name = '', $pan_message, $force_update = false)
1061
+	{
1062
+		new PersistentAdminNotice(
1063
+			$pan_name,
1064
+			$pan_message,
1065
+			$force_update
1066
+		);
1067
+		EE_Error::doing_it_wrong(
1068
+			__METHOD__,
1069
+			sprintf(
1070
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1071
+				'\EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
1072
+			),
1073
+			'4.9.27'
1074
+		);
1075
+	}
1076
+
1077
+
1078
+
1079
+	/**
1080
+	 * @deprecated 4.9.27
1081
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
1082
+	 * @param bool   $purge
1083
+	 * @param bool   $return
1084
+	 * @throws DomainException
1085
+	 * @throws InvalidInterfaceException
1086
+	 * @throws InvalidDataTypeException
1087
+	 * @throws ServiceNotFoundException
1088
+	 * @throws InvalidArgumentException
1089
+	 */
1090
+	public static function dismiss_persistent_admin_notice($pan_name = '', $purge = false, $return = false)
1091
+	{
1092
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
1093
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
1094
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1095
+		);
1096
+		$persistent_admin_notice_manager->dismissNotice($pan_name, $purge, $return);
1097
+		EE_Error::doing_it_wrong(
1098
+			__METHOD__,
1099
+			sprintf(
1100
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1101
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1102
+			),
1103
+			'4.9.27'
1104
+		);
1105
+	}
1106
+
1107
+
1108
+
1109
+	/**
1110
+	 * @deprecated 4.9.27
1111
+	 * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
1112
+	 * @param  string $pan_message the message to be stored persistently until dismissed
1113
+	 * @param  string $return_url  URL to go back to after nag notice is dismissed
1114
+	 */
1115
+	public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
1116
+	{
1117
+		EE_Error::doing_it_wrong(
1118
+			__METHOD__,
1119
+			sprintf(
1120
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1121
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1122
+			),
1123
+			'4.9.27'
1124
+		);
1125
+	}
1126
+
1127
+
1128
+
1129
+	/**
1130
+	 * @deprecated 4.9.27
1131
+	 * @param string $return_url
1132
+	 */
1133
+	public static function get_persistent_admin_notices($return_url = '')
1134
+	{
1135
+		EE_Error::doing_it_wrong(
1136
+			__METHOD__,
1137
+			sprintf(
1138
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1139
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1140
+			),
1141
+			'4.9.27'
1142
+		);
1143
+	}
1144 1144
 
1145 1145
 
1146 1146
 
@@ -1155,27 +1155,27 @@  discard block
 block discarded – undo
1155 1155
  */
1156 1156
 function espresso_error_enqueue_scripts()
1157 1157
 {
1158
-    // js for error handling
1159
-    wp_register_script(
1160
-        'espresso_core',
1161
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1162
-        array('jquery'),
1163
-        EVENT_ESPRESSO_VERSION,
1164
-        false
1165
-    );
1166
-    wp_register_script(
1167
-        'ee_error_js',
1168
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1169
-        array('espresso_core'),
1170
-        EVENT_ESPRESSO_VERSION,
1171
-        false
1172
-    );
1158
+	// js for error handling
1159
+	wp_register_script(
1160
+		'espresso_core',
1161
+		EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1162
+		array('jquery'),
1163
+		EVENT_ESPRESSO_VERSION,
1164
+		false
1165
+	);
1166
+	wp_register_script(
1167
+		'ee_error_js',
1168
+		EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1169
+		array('espresso_core'),
1170
+		EVENT_ESPRESSO_VERSION,
1171
+		false
1172
+	);
1173 1173
 }
1174 1174
 
1175 1175
 if (is_admin()) {
1176
-    add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1176
+	add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1177 1177
 } else {
1178
-    add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1178
+	add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1179 1179
 }
1180 1180
 
1181 1181
 
Please login to merge, or discard this patch.
core/EE_System.core.php 2 patches
Indentation   +1236 added lines, -1236 removed lines patch added patch discarded remove patch
@@ -21,1242 +21,1242 @@
 block discarded – undo
21 21
 {
22 22
 
23 23
 
24
-    /**
25
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
26
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
27
-     */
28
-    const req_type_normal = 0;
29
-
30
-    /**
31
-     * Indicates this is a brand new installation of EE so we should install
32
-     * tables and default data etc
33
-     */
34
-    const req_type_new_activation = 1;
35
-
36
-    /**
37
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
38
-     * and we just exited maintenance mode). We MUST check the database is setup properly
39
-     * and that default data is setup too
40
-     */
41
-    const req_type_reactivation = 2;
42
-
43
-    /**
44
-     * indicates that EE has been upgraded since its previous request.
45
-     * We may have data migration scripts to call and will want to trigger maintenance mode
46
-     */
47
-    const req_type_upgrade = 3;
48
-
49
-    /**
50
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
51
-     */
52
-    const req_type_downgrade = 4;
53
-
54
-    /**
55
-     * @deprecated since version 4.6.0.dev.006
56
-     * Now whenever a new_activation is detected the request type is still just
57
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
58
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
59
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
60
-     * (Specifically, when the migration manager indicates migrations are finished
61
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
62
-     */
63
-    const req_type_activation_but_not_installed = 5;
64
-
65
-    /**
66
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
67
-     */
68
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
69
-
70
-
71
-    /**
72
-     * @var EE_System $_instance
73
-     */
74
-    private static $_instance;
75
-
76
-    /**
77
-     * @var EE_Registry $registry
78
-     */
79
-    private $registry;
80
-
81
-    /**
82
-     * @var LoaderInterface $loader
83
-     */
84
-    private $loader;
85
-
86
-    /**
87
-     * @var EE_Capabilities $capabilities
88
-     */
89
-    private $capabilities;
90
-
91
-    /**
92
-     * @var EE_Request $request
93
-     */
94
-    private $request;
95
-
96
-    /**
97
-     * @var EE_Maintenance_Mode $maintenance_mode
98
-     */
99
-    private $maintenance_mode;
100
-
101
-    /**
102
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
103
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
104
-     *
105
-     * @var int $_req_type
106
-     */
107
-    private $_req_type;
108
-
109
-    /**
110
-     * Whether or not there was a non-micro version change in EE core version during this request
111
-     *
112
-     * @var boolean $_major_version_change
113
-     */
114
-    private $_major_version_change = false;
115
-
116
-
117
-
118
-    /**
119
-     * @singleton method used to instantiate class object
120
-     * @param EE_Registry|null         $registry
121
-     * @param LoaderInterface|null     $loader
122
-     * @param EE_Capabilities|null     $capabilities
123
-     * @param EE_Request|null          $request
124
-     * @param EE_Maintenance_Mode|null $maintenance_mode
125
-     * @return EE_System
126
-     */
127
-    public static function instance(
128
-        EE_Registry $registry = null,
129
-        LoaderInterface $loader = null,
130
-        EE_Capabilities $capabilities = null,
131
-        EE_Request $request = null,
132
-        EE_Maintenance_Mode $maintenance_mode = null
133
-    ) {
134
-        // check if class object is instantiated
135
-        if (! self::$_instance instanceof EE_System) {
136
-            self::$_instance = new self($registry, $loader, $capabilities, $request, $maintenance_mode);
137
-        }
138
-        return self::$_instance;
139
-    }
140
-
141
-
142
-
143
-    /**
144
-     * resets the instance and returns it
145
-     *
146
-     * @return EE_System
147
-     */
148
-    public static function reset()
149
-    {
150
-        self::$_instance->_req_type = null;
151
-        //make sure none of the old hooks are left hanging around
152
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
153
-        //we need to reset the migration manager in order for it to detect DMSs properly
154
-        EE_Data_Migration_Manager::reset();
155
-        self::instance()->detect_activations_or_upgrades();
156
-        self::instance()->perform_activations_upgrades_and_migrations();
157
-        return self::instance();
158
-    }
159
-
160
-
161
-
162
-    /**
163
-     * sets hooks for running rest of system
164
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
165
-     * starting EE Addons from any other point may lead to problems
166
-     *
167
-     * @param EE_Registry         $registry
168
-     * @param LoaderInterface     $loader
169
-     * @param EE_Capabilities     $capabilities
170
-     * @param EE_Request          $request
171
-     * @param EE_Maintenance_Mode $maintenance_mode
172
-     */
173
-    private function __construct(
174
-        EE_Registry $registry,
175
-        LoaderInterface $loader,
176
-        EE_Capabilities $capabilities,
177
-        EE_Request $request,
178
-        EE_Maintenance_Mode $maintenance_mode
179
-    ) {
180
-        $this->registry = $registry;
181
-        $this->loader = $loader;
182
-        $this->capabilities = $capabilities;
183
-        $this->request = $request;
184
-        $this->maintenance_mode = $maintenance_mode;
185
-        do_action('AHEE__EE_System__construct__begin', $this);
186
-        add_action(
187
-            'AHEE__EE_Bootstrap__load_espresso_addons',
188
-            array($this, 'loadCapabilities'),
189
-            5
190
-        );
191
-        add_action(
192
-            'AHEE__EE_Bootstrap__load_espresso_addons',
193
-            array($this, 'loadCommandBus'),
194
-            7
195
-        );
196
-        add_action(
197
-            'AHEE__EE_Bootstrap__load_espresso_addons',
198
-            array($this, 'loadPluginApi'),
199
-            9
200
-        );
201
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
202
-        add_action(
203
-            'AHEE__EE_Bootstrap__load_espresso_addons',
204
-            array($this, 'load_espresso_addons')
205
-        );
206
-        // when an ee addon is activated, we want to call the core hook(s) again
207
-        // because the newly-activated addon didn't get a chance to run at all
208
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
209
-        // detect whether install or upgrade
210
-        add_action(
211
-            'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
212
-            array($this, 'detect_activations_or_upgrades'),
213
-            3
214
-        );
215
-        // load EE_Config, EE_Textdomain, etc
216
-        add_action(
217
-            'AHEE__EE_Bootstrap__load_core_configuration',
218
-            array($this, 'load_core_configuration'),
219
-            5
220
-        );
221
-        // load EE_Config, EE_Textdomain, etc
222
-        add_action(
223
-            'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
224
-            array($this, 'register_shortcodes_modules_and_widgets'),
225
-            7
226
-        );
227
-        // you wanna get going? I wanna get going... let's get going!
228
-        add_action(
229
-            'AHEE__EE_Bootstrap__brew_espresso',
230
-            array($this, 'brew_espresso'),
231
-            9
232
-        );
233
-        //other housekeeping
234
-        //exclude EE critical pages from wp_list_pages
235
-        add_filter(
236
-            'wp_list_pages_excludes',
237
-            array($this, 'remove_pages_from_wp_list_pages'),
238
-            10
239
-        );
240
-        // ALL EE Addons should use the following hook point to attach their initial setup too
241
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
242
-        do_action('AHEE__EE_System__construct__complete', $this);
243
-    }
244
-
245
-
246
-
247
-    /**
248
-     * load and setup EE_Capabilities
249
-     *
250
-     * @return void
251
-     * @throws EE_Error
252
-     */
253
-    public function loadCapabilities()
254
-    {
255
-        $this->loader->getShared('EE_Capabilities');
256
-        add_action(
257
-            'AHEE__EE_Capabilities__init_caps__before_initialization',
258
-            function() {
259
-                LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
260
-            }
261
-        );
262
-    }
263
-
264
-
265
-
266
-    /**
267
-     * create and cache the CommandBus, and also add middleware
268
-     * The CapChecker middleware requires the use of EE_Capabilities
269
-     * which is why we need to load the CommandBus after Caps are set up
270
-     *
271
-     * @return void
272
-     * @throws EE_Error
273
-     */
274
-    public function loadCommandBus()
275
-    {
276
-        $this->loader->getShared(
277
-            'CommandBusInterface',
278
-            array(
279
-                null,
280
-                apply_filters(
281
-                    'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
282
-                    array(
283
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
284
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
285
-                    )
286
-                ),
287
-            )
288
-        );
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * @return void
295
-     * @throws EE_Error
296
-     */
297
-    public function loadPluginApi()
298
-    {
299
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
300
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
301
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
302
-    }
303
-
304
-
305
-    /**
306
-     * @param string $addon_name
307
-     * @param string $version_constant
308
-     * @param string $min_version_required
309
-     * @param string $load_callback
310
-     * @param string $plugin_file_constant
311
-     * @return void
312
-     */
313
-    private function deactivateIncompatibleAddon(
314
-        $addon_name,
315
-        $version_constant,
316
-        $min_version_required,
317
-        $load_callback,
318
-        $plugin_file_constant
319
-    ) {
320
-        if (! defined($version_constant)) {
321
-            return;
322
-        }
323
-        $addon_version = constant($version_constant);
324
-        if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
325
-            remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
326
-            if (! function_exists('deactivate_plugins')) {
327
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
328
-            }
329
-            deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
330
-            unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
331
-            EE_Error::add_error(
332
-                sprintf(
333
-                    esc_html__(
334
-                        'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
335
-                        'event_espresso'
336
-                    ),
337
-                    $addon_name,
338
-                    $min_version_required
339
-                ),
340
-                __FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
341
-            );
342
-            EE_Error::get_notices(false, true);
343
-        }
344
-    }
345
-
346
-
347
-    /**
348
-     * load_espresso_addons
349
-     * allow addons to load first so that they can set hooks for running DMS's, etc
350
-     * this is hooked into both:
351
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
352
-     *        which runs during the WP 'plugins_loaded' action at priority 5
353
-     *    and the WP 'activate_plugin' hook point
354
-     *
355
-     * @access public
356
-     * @return void
357
-     */
358
-    public function load_espresso_addons()
359
-    {
360
-        $this->deactivateIncompatibleAddon(
361
-            'Wait Lists',
362
-            'EE_WAIT_LISTS_VERSION',
363
-            '1.0.0.rc.074',
364
-            'load_espresso_wait_lists',
365
-            'EE_WAIT_LISTS_PLUGIN_FILE'
366
-        );
367
-        $this->deactivateIncompatibleAddon(
368
-            'Automated Upcoming Event Notifications',
369
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
370
-            '1.0.0.rc.091',
371
-            'load_espresso_automated_upcoming_event_notification',
372
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
373
-        );
374
-        do_action('AHEE__EE_System__load_espresso_addons');
375
-        //if the WP API basic auth plugin isn't already loaded, load it now.
376
-        //We want it for mobile apps. Just include the entire plugin
377
-        //also, don't load the basic auth when a plugin is getting activated, because
378
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
379
-        //and causes a fatal error
380
-        if (
381
-            ! (
382
-                isset($_GET['activate'])
383
-                && $_GET['activate'] === 'true'
384
-            )
385
-            && ! function_exists('json_basic_auth_handler')
386
-            && ! function_exists('json_basic_auth_error')
387
-            && ! (
388
-                isset($_GET['action'])
389
-                && in_array($_GET['action'], array('activate', 'activate-selected'), true)
390
-            )
391
-        ) {
392
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
393
-        }
394
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
395
-    }
396
-
397
-
398
-
399
-    /**
400
-     * detect_activations_or_upgrades
401
-     * Checks for activation or upgrade of core first;
402
-     * then also checks if any registered addons have been activated or upgraded
403
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
404
-     * which runs during the WP 'plugins_loaded' action at priority 3
405
-     *
406
-     * @access public
407
-     * @return void
408
-     */
409
-    public function detect_activations_or_upgrades()
410
-    {
411
-        //first off: let's make sure to handle core
412
-        $this->detect_if_activation_or_upgrade();
413
-        foreach ($this->registry->addons as $addon) {
414
-            if ($addon instanceof EE_Addon) {
415
-                //detect teh request type for that addon
416
-                $addon->detect_activation_or_upgrade();
417
-            }
418
-        }
419
-    }
420
-
421
-
422
-
423
-    /**
424
-     * detect_if_activation_or_upgrade
425
-     * Takes care of detecting whether this is a brand new install or code upgrade,
426
-     * and either setting up the DB or setting up maintenance mode etc.
427
-     *
428
-     * @access public
429
-     * @return void
430
-     */
431
-    public function detect_if_activation_or_upgrade()
432
-    {
433
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
434
-        // check if db has been updated, or if its a brand-new installation
435
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
436
-        $request_type = $this->detect_req_type($espresso_db_update);
437
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
438
-        switch ($request_type) {
439
-            case EE_System::req_type_new_activation:
440
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
441
-                $this->_handle_core_version_change($espresso_db_update);
442
-                break;
443
-            case EE_System::req_type_reactivation:
444
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
445
-                $this->_handle_core_version_change($espresso_db_update);
446
-                break;
447
-            case EE_System::req_type_upgrade:
448
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
449
-                //migrations may be required now that we've upgraded
450
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
451
-                $this->_handle_core_version_change($espresso_db_update);
452
-                //				echo "done upgrade";die;
453
-                break;
454
-            case EE_System::req_type_downgrade:
455
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
456
-                //its possible migrations are no longer required
457
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
458
-                $this->_handle_core_version_change($espresso_db_update);
459
-                break;
460
-            case EE_System::req_type_normal:
461
-            default:
462
-                //				$this->_maybe_redirect_to_ee_about();
463
-                break;
464
-        }
465
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
466
-    }
467
-
468
-
469
-
470
-    /**
471
-     * Updates the list of installed versions and sets hooks for
472
-     * initializing the database later during the request
473
-     *
474
-     * @param array $espresso_db_update
475
-     */
476
-    private function _handle_core_version_change($espresso_db_update)
477
-    {
478
-        $this->update_list_of_installed_versions($espresso_db_update);
479
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
480
-        add_action(
481
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
482
-            array($this, 'initialize_db_if_no_migrations_required')
483
-        );
484
-    }
485
-
486
-
487
-
488
-    /**
489
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
490
-     * information about what versions of EE have been installed and activated,
491
-     * NOT necessarily the state of the database
492
-     *
493
-     * @param mixed $espresso_db_update the value of the WordPress option.
494
-     *                                            If not supplied, fetches it from the options table
495
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
496
-     */
497
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
498
-    {
499
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
500
-        if (! $espresso_db_update) {
501
-            $espresso_db_update = get_option('espresso_db_update');
502
-        }
503
-        // check that option is an array
504
-        if (! is_array($espresso_db_update)) {
505
-            // if option is FALSE, then it never existed
506
-            if ($espresso_db_update === false) {
507
-                // make $espresso_db_update an array and save option with autoload OFF
508
-                $espresso_db_update = array();
509
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
510
-            } else {
511
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
512
-                $espresso_db_update = array($espresso_db_update => array());
513
-                update_option('espresso_db_update', $espresso_db_update);
514
-            }
515
-        } else {
516
-            $corrected_db_update = array();
517
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
518
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
519
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
520
-                    //the key is an int, and the value IS NOT an array
521
-                    //so it must be numerically-indexed, where values are versions installed...
522
-                    //fix it!
523
-                    $version_string = $should_be_array;
524
-                    $corrected_db_update[$version_string] = array('unknown-date');
525
-                } else {
526
-                    //ok it checks out
527
-                    $corrected_db_update[$should_be_version_string] = $should_be_array;
528
-                }
529
-            }
530
-            $espresso_db_update = $corrected_db_update;
531
-            update_option('espresso_db_update', $espresso_db_update);
532
-        }
533
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
534
-        return $espresso_db_update;
535
-    }
536
-
537
-
538
-
539
-    /**
540
-     * Does the traditional work of setting up the plugin's database and adding default data.
541
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
542
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
543
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
544
-     * so that it will be done when migrations are finished
545
-     *
546
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
547
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
548
-     *                                       This is a resource-intensive job
549
-     *                                       so we prefer to only do it when necessary
550
-     * @return void
551
-     * @throws EE_Error
552
-     */
553
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
554
-    {
555
-        $request_type = $this->detect_req_type();
556
-        //only initialize system if we're not in maintenance mode.
557
-        if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
558
-            update_option('ee_flush_rewrite_rules', true);
559
-            if ($verify_schema) {
560
-                EEH_Activation::initialize_db_and_folders();
561
-            }
562
-            EEH_Activation::initialize_db_content();
563
-            EEH_Activation::system_initialization();
564
-            if ($initialize_addons_too) {
565
-                $this->initialize_addons();
566
-            }
567
-        } else {
568
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
569
-        }
570
-        if ($request_type === EE_System::req_type_new_activation
571
-            || $request_type === EE_System::req_type_reactivation
572
-            || (
573
-                $request_type === EE_System::req_type_upgrade
574
-                && $this->is_major_version_change()
575
-            )
576
-        ) {
577
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
578
-        }
579
-    }
580
-
581
-
582
-
583
-    /**
584
-     * Initializes the db for all registered addons
585
-     *
586
-     * @throws EE_Error
587
-     */
588
-    public function initialize_addons()
589
-    {
590
-        //foreach registered addon, make sure its db is up-to-date too
591
-        foreach ($this->registry->addons as $addon) {
592
-            if ($addon instanceof EE_Addon) {
593
-                $addon->initialize_db_if_no_migrations_required();
594
-            }
595
-        }
596
-    }
597
-
598
-
599
-
600
-    /**
601
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
602
-     *
603
-     * @param    array  $version_history
604
-     * @param    string $current_version_to_add version to be added to the version history
605
-     * @return    boolean success as to whether or not this option was changed
606
-     */
607
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
608
-    {
609
-        if (! $version_history) {
610
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
611
-        }
612
-        if ($current_version_to_add === null) {
613
-            $current_version_to_add = espresso_version();
614
-        }
615
-        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
616
-        // re-save
617
-        return update_option('espresso_db_update', $version_history);
618
-    }
619
-
620
-
621
-
622
-    /**
623
-     * Detects if the current version indicated in the has existed in the list of
624
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
625
-     *
626
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
627
-     *                                  If not supplied, fetches it from the options table.
628
-     *                                  Also, caches its result so later parts of the code can also know whether
629
-     *                                  there's been an update or not. This way we can add the current version to
630
-     *                                  espresso_db_update, but still know if this is a new install or not
631
-     * @return int one of the constants on EE_System::req_type_
632
-     */
633
-    public function detect_req_type($espresso_db_update = null)
634
-    {
635
-        if ($this->_req_type === null) {
636
-            $espresso_db_update = ! empty($espresso_db_update)
637
-                ? $espresso_db_update
638
-                : $this->fix_espresso_db_upgrade_option();
639
-            $this->_req_type = EE_System::detect_req_type_given_activation_history(
640
-                $espresso_db_update,
641
-                'ee_espresso_activation', espresso_version()
642
-            );
643
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
644
-        }
645
-        return $this->_req_type;
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     * Returns whether or not there was a non-micro version change (ie, change in either
652
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
653
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
654
-     *
655
-     * @param $activation_history
656
-     * @return bool
657
-     */
658
-    private function _detect_major_version_change($activation_history)
659
-    {
660
-        $previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
661
-        $previous_version_parts = explode('.', $previous_version);
662
-        $current_version_parts = explode('.', espresso_version());
663
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
664
-               && ($previous_version_parts[0] !== $current_version_parts[0]
665
-                   || $previous_version_parts[1] !== $current_version_parts[1]
666
-               );
667
-    }
668
-
669
-
670
-
671
-    /**
672
-     * Returns true if either the major or minor version of EE changed during this request.
673
-     * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
674
-     *
675
-     * @return bool
676
-     */
677
-    public function is_major_version_change()
678
-    {
679
-        return $this->_major_version_change;
680
-    }
681
-
682
-
683
-
684
-    /**
685
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
686
-     * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
687
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
688
-     * just activated to (for core that will always be espresso_version())
689
-     *
690
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
691
-     *                                                 ee plugin. for core that's 'espresso_db_update'
692
-     * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
693
-     *                                                 indicate that this plugin was just activated
694
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
695
-     *                                                 espresso_version())
696
-     * @return int one of the constants on EE_System::req_type_*
697
-     */
698
-    public static function detect_req_type_given_activation_history(
699
-        $activation_history_for_addon,
700
-        $activation_indicator_option_name,
701
-        $version_to_upgrade_to
702
-    ) {
703
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
704
-        if ($activation_history_for_addon) {
705
-            //it exists, so this isn't a completely new install
706
-            //check if this version already in that list of previously installed versions
707
-            if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
708
-                //it a version we haven't seen before
709
-                if ($version_is_higher === 1) {
710
-                    $req_type = EE_System::req_type_upgrade;
711
-                } else {
712
-                    $req_type = EE_System::req_type_downgrade;
713
-                }
714
-                delete_option($activation_indicator_option_name);
715
-            } else {
716
-                // its not an update. maybe a reactivation?
717
-                if (get_option($activation_indicator_option_name, false)) {
718
-                    if ($version_is_higher === -1) {
719
-                        $req_type = EE_System::req_type_downgrade;
720
-                    } else if ($version_is_higher === 0) {
721
-                        //we've seen this version before, but it's an activation. must be a reactivation
722
-                        $req_type = EE_System::req_type_reactivation;
723
-                    } else {//$version_is_higher === 1
724
-                        $req_type = EE_System::req_type_upgrade;
725
-                    }
726
-                    delete_option($activation_indicator_option_name);
727
-                } else {
728
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
729
-                    if ($version_is_higher === -1) {
730
-                        $req_type = EE_System::req_type_downgrade;
731
-                    } else if ($version_is_higher === 0) {
732
-                        //we've seen this version before and it's not an activation. its normal request
733
-                        $req_type = EE_System::req_type_normal;
734
-                    } else {//$version_is_higher === 1
735
-                        $req_type = EE_System::req_type_upgrade;
736
-                    }
737
-                }
738
-            }
739
-        } else {
740
-            //brand new install
741
-            $req_type = EE_System::req_type_new_activation;
742
-            delete_option($activation_indicator_option_name);
743
-        }
744
-        return $req_type;
745
-    }
746
-
747
-
748
-
749
-    /**
750
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
751
-     * the $activation_history_for_addon
752
-     *
753
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
754
-     *                                             sometimes containing 'unknown-date'
755
-     * @param string $version_to_upgrade_to        (current version)
756
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
757
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
758
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
759
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
760
-     */
761
-    private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
762
-    {
763
-        //find the most recently-activated version
764
-        $most_recently_active_version =
765
-            EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
766
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
767
-    }
768
-
769
-
770
-
771
-    /**
772
-     * Gets the most recently active version listed in the activation history,
773
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
774
-     *
775
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
776
-     *                                   sometimes containing 'unknown-date'
777
-     * @return string
778
-     */
779
-    private static function _get_most_recently_active_version_from_activation_history($activation_history)
780
-    {
781
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
782
-        $most_recently_active_version = '0.0.0.dev.000';
783
-        if (is_array($activation_history)) {
784
-            foreach ($activation_history as $version => $times_activated) {
785
-                //check there is a record of when this version was activated. Otherwise,
786
-                //mark it as unknown
787
-                if (! $times_activated) {
788
-                    $times_activated = array('unknown-date');
789
-                }
790
-                if (is_string($times_activated)) {
791
-                    $times_activated = array($times_activated);
792
-                }
793
-                foreach ($times_activated as $an_activation) {
794
-                    if ($an_activation !== 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
795
-                        $most_recently_active_version = $version;
796
-                        $most_recently_active_version_activation = $an_activation === 'unknown-date'
797
-                            ? '1970-01-01 00:00:00'
798
-                            : $an_activation;
799
-                    }
800
-                }
801
-            }
802
-        }
803
-        return $most_recently_active_version;
804
-    }
805
-
806
-
807
-
808
-    /**
809
-     * This redirects to the about EE page after activation
810
-     *
811
-     * @return void
812
-     */
813
-    public function redirect_to_about_ee()
814
-    {
815
-        $notices = EE_Error::get_notices(false);
816
-        //if current user is an admin and it's not an ajax or rest request
817
-        if (
818
-            ! (defined('DOING_AJAX') && DOING_AJAX)
819
-            && ! (defined('REST_REQUEST') && REST_REQUEST)
820
-            && ! isset($notices['errors'])
821
-            && apply_filters(
822
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
823
-                $this->capabilities->current_user_can('manage_options', 'espresso_about_default')
824
-            )
825
-        ) {
826
-            $query_params = array('page' => 'espresso_about');
827
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
828
-                $query_params['new_activation'] = true;
829
-            }
830
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
831
-                $query_params['reactivation'] = true;
832
-            }
833
-            $url = add_query_arg($query_params, admin_url('admin.php'));
834
-            wp_safe_redirect($url);
835
-            exit();
836
-        }
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * load_core_configuration
843
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
844
-     * which runs during the WP 'plugins_loaded' action at priority 5
845
-     *
846
-     * @return void
847
-     * @throws ReflectionException
848
-     */
849
-    public function load_core_configuration()
850
-    {
851
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
852
-        $this->loader->getShared('EE_Load_Textdomain');
853
-        //load textdomain
854
-        EE_Load_Textdomain::load_textdomain();
855
-        // load and setup EE_Config and EE_Network_Config
856
-        $config = $this->loader->getShared('EE_Config');
857
-        $this->loader->getShared('EE_Network_Config');
858
-        // setup autoloaders
859
-        // enable logging?
860
-        if ($config->admin->use_full_logging) {
861
-            $this->loader->getShared('EE_Log');
862
-        }
863
-        // check for activation errors
864
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
865
-        if ($activation_errors) {
866
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
867
-            update_option('ee_plugin_activation_errors', false);
868
-        }
869
-        // get model names
870
-        $this->_parse_model_names();
871
-        //load caf stuff a chance to play during the activation process too.
872
-        $this->_maybe_brew_regular();
873
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
874
-    }
875
-
876
-
877
-
878
-    /**
879
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
880
-     *
881
-     * @return void
882
-     * @throws ReflectionException
883
-     */
884
-    private function _parse_model_names()
885
-    {
886
-        //get all the files in the EE_MODELS folder that end in .model.php
887
-        $models = glob(EE_MODELS . '*.model.php');
888
-        $model_names = array();
889
-        $non_abstract_db_models = array();
890
-        foreach ($models as $model) {
891
-            // get model classname
892
-            $classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
893
-            $short_name = str_replace('EEM_', '', $classname);
894
-            $reflectionClass = new ReflectionClass($classname);
895
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
896
-                $non_abstract_db_models[$short_name] = $classname;
897
-            }
898
-            $model_names[$short_name] = $classname;
899
-        }
900
-        $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
901
-        $this->registry->non_abstract_db_models = apply_filters(
902
-            'FHEE__EE_System__parse_implemented_model_names',
903
-            $non_abstract_db_models
904
-        );
905
-    }
906
-
907
-
908
-
909
-    /**
910
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
911
-     * that need to be setup before our EE_System launches.
912
-     *
913
-     * @return void
914
-     */
915
-    private function _maybe_brew_regular()
916
-    {
917
-        if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
918
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
919
-        }
920
-    }
921
-
922
-
923
-
924
-    /**
925
-     * register_shortcodes_modules_and_widgets
926
-     * generate lists of shortcodes and modules, then verify paths and classes
927
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
928
-     * which runs during the WP 'plugins_loaded' action at priority 7
929
-     *
930
-     * @access public
931
-     * @return void
932
-     * @throws Exception
933
-     */
934
-    public function register_shortcodes_modules_and_widgets()
935
-    {
936
-        try {
937
-            // load, register, and add shortcodes the new way
938
-            $this->loader->getShared(
939
-                'EventEspresso\core\services\shortcodes\ShortcodesManager',
940
-                array(
941
-                    // and the old way, but we'll put it under control of the new system
942
-                    EE_Config::getLegacyShortcodesManager()
943
-                )
944
-            );
945
-        } catch (Exception $exception) {
946
-            new ExceptionStackTraceDisplay($exception);
947
-        }
948
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
949
-        // check for addons using old hook point
950
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
951
-            $this->_incompatible_addon_error();
952
-        }
953
-    }
954
-
955
-
956
-
957
-    /**
958
-     * _incompatible_addon_error
959
-     *
960
-     * @access public
961
-     * @return void
962
-     */
963
-    private function _incompatible_addon_error()
964
-    {
965
-        // get array of classes hooking into here
966
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
967
-            'AHEE__EE_System__register_shortcodes_modules_and_addons'
968
-        );
969
-        if (! empty($class_names)) {
970
-            $msg = __(
971
-                'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
972
-                'event_espresso'
973
-            );
974
-            $msg .= '<ul>';
975
-            foreach ($class_names as $class_name) {
976
-                $msg .= '<li><b>Event Espresso - ' . str_replace(
977
-                        array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
978
-                        $class_name
979
-                    ) . '</b></li>';
980
-            }
981
-            $msg .= '</ul>';
982
-            $msg .= __(
983
-                'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
984
-                'event_espresso'
985
-            );
986
-            // save list of incompatible addons to wp-options for later use
987
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
988
-            if (is_admin()) {
989
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
990
-            }
991
-        }
992
-    }
993
-
994
-
995
-
996
-    /**
997
-     * brew_espresso
998
-     * begins the process of setting hooks for initializing EE in the correct order
999
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1000
-     * which runs during the WP 'plugins_loaded' action at priority 9
1001
-     *
1002
-     * @return void
1003
-     */
1004
-    public function brew_espresso()
1005
-    {
1006
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
1007
-        // load some final core systems
1008
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
1009
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1010
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
1011
-        add_action('init', array($this, 'load_controllers'), 7);
1012
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
1013
-        add_action('init', array($this, 'initialize'), 10);
1014
-        add_action('init', array($this, 'initialize_last'), 100);
1015
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1016
-            // pew pew pew
1017
-            $this->loader->getShared('EE_PUE');
1018
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1019
-        }
1020
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
1021
-    }
1022
-
1023
-
1024
-
1025
-    /**
1026
-     *    set_hooks_for_core
1027
-     *
1028
-     * @access public
1029
-     * @return    void
1030
-     * @throws EE_Error
1031
-     */
1032
-    public function set_hooks_for_core()
1033
-    {
1034
-        $this->_deactivate_incompatible_addons();
1035
-        do_action('AHEE__EE_System__set_hooks_for_core');
1036
-        //caps need to be initialized on every request so that capability maps are set.
1037
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1038
-        $this->registry->CAP->init_caps();
1039
-    }
1040
-
1041
-
1042
-
1043
-    /**
1044
-     * Using the information gathered in EE_System::_incompatible_addon_error,
1045
-     * deactivates any addons considered incompatible with the current version of EE
1046
-     */
1047
-    private function _deactivate_incompatible_addons()
1048
-    {
1049
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
1050
-        if (! empty($incompatible_addons)) {
1051
-            $active_plugins = get_option('active_plugins', array());
1052
-            foreach ($active_plugins as $active_plugin) {
1053
-                foreach ($incompatible_addons as $incompatible_addon) {
1054
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
1055
-                        unset($_GET['activate']);
1056
-                        espresso_deactivate_plugin($active_plugin);
1057
-                    }
1058
-                }
1059
-            }
1060
-        }
1061
-    }
1062
-
1063
-
1064
-
1065
-    /**
1066
-     *    perform_activations_upgrades_and_migrations
1067
-     *
1068
-     * @access public
1069
-     * @return    void
1070
-     */
1071
-    public function perform_activations_upgrades_and_migrations()
1072
-    {
1073
-        //first check if we had previously attempted to setup EE's directories but failed
1074
-        if (EEH_Activation::upload_directories_incomplete()) {
1075
-            EEH_Activation::create_upload_directories();
1076
-        }
1077
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1078
-    }
1079
-
1080
-
1081
-
1082
-    /**
1083
-     *    load_CPTs_and_session
1084
-     *
1085
-     * @access public
1086
-     * @return    void
1087
-     */
1088
-    public function load_CPTs_and_session()
1089
-    {
1090
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
1091
-        // register Custom Post Types
1092
-        $this->loader->getShared('EE_Register_CPTs');
1093
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1094
-    }
1095
-
1096
-
1097
-
1098
-    /**
1099
-     * load_controllers
1100
-     * this is the best place to load any additional controllers that needs access to EE core.
1101
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1102
-     * time
1103
-     *
1104
-     * @access public
1105
-     * @return void
1106
-     */
1107
-    public function load_controllers()
1108
-    {
1109
-        do_action('AHEE__EE_System__load_controllers__start');
1110
-        // let's get it started
1111
-        if (! is_admin() && ! $this->maintenance_mode->level()) {
1112
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1113
-            $this->loader->getShared('EE_Front_Controller');
1114
-        } else if (! EE_FRONT_AJAX) {
1115
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1116
-            $this->loader->getShared('EE_Admin');
1117
-        }
1118
-        do_action('AHEE__EE_System__load_controllers__complete');
1119
-    }
1120
-
1121
-
1122
-
1123
-    /**
1124
-     * core_loaded_and_ready
1125
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1126
-     *
1127
-     * @access public
1128
-     * @return void
1129
-     */
1130
-    public function core_loaded_and_ready()
1131
-    {
1132
-        $this->loader->getShared('EE_Session');
1133
-        do_action('AHEE__EE_System__core_loaded_and_ready');
1134
-        // load_espresso_template_tags
1135
-        if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1136
-            require_once(EE_PUBLIC . 'template_tags.php');
1137
-        }
1138
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1139
-        $this->loader->getShared('EventEspresso\core\services\assets\Registry');
1140
-    }
1141
-
1142
-
1143
-
1144
-    /**
1145
-     * initialize
1146
-     * this is the best place to begin initializing client code
1147
-     *
1148
-     * @access public
1149
-     * @return void
1150
-     */
1151
-    public function initialize()
1152
-    {
1153
-        do_action('AHEE__EE_System__initialize');
1154
-    }
1155
-
1156
-
1157
-
1158
-    /**
1159
-     * initialize_last
1160
-     * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1161
-     * initialize has done so
1162
-     *
1163
-     * @access public
1164
-     * @return void
1165
-     */
1166
-    public function initialize_last()
1167
-    {
1168
-        do_action('AHEE__EE_System__initialize_last');
1169
-        add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1170
-    }
1171
-
1172
-
1173
-
1174
-    /**
1175
-     * @return void
1176
-     * @throws EE_Error
1177
-     */
1178
-    public function addEspressoToolbar()
1179
-    {
1180
-        $this->loader->getShared(
1181
-            'EventEspresso\core\domain\services\admin\AdminToolBar',
1182
-            array($this->registry->CAP)
1183
-        );
1184
-    }
1185
-
1186
-
1187
-
1188
-    /**
1189
-     * do_not_cache
1190
-     * sets no cache headers and defines no cache constants for WP plugins
1191
-     *
1192
-     * @access public
1193
-     * @return void
1194
-     */
1195
-    public static function do_not_cache()
1196
-    {
1197
-        // set no cache constants
1198
-        if (! defined('DONOTCACHEPAGE')) {
1199
-            define('DONOTCACHEPAGE', true);
1200
-        }
1201
-        if (! defined('DONOTCACHCEOBJECT')) {
1202
-            define('DONOTCACHCEOBJECT', true);
1203
-        }
1204
-        if (! defined('DONOTCACHEDB')) {
1205
-            define('DONOTCACHEDB', true);
1206
-        }
1207
-        // add no cache headers
1208
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1209
-        // plus a little extra for nginx and Google Chrome
1210
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1211
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1212
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1213
-    }
1214
-
1215
-
1216
-
1217
-    /**
1218
-     *    extra_nocache_headers
1219
-     *
1220
-     * @access    public
1221
-     * @param $headers
1222
-     * @return    array
1223
-     */
1224
-    public static function extra_nocache_headers($headers)
1225
-    {
1226
-        // for NGINX
1227
-        $headers['X-Accel-Expires'] = 0;
1228
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1229
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1230
-        return $headers;
1231
-    }
1232
-
1233
-
1234
-
1235
-    /**
1236
-     *    nocache_headers
1237
-     *
1238
-     * @access    public
1239
-     * @return    void
1240
-     */
1241
-    public static function nocache_headers()
1242
-    {
1243
-        nocache_headers();
1244
-    }
1245
-
1246
-
1247
-
1248
-
1249
-    /**
1250
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1251
-     * never returned with the function.
1252
-     *
1253
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1254
-     * @return array
1255
-     */
1256
-    public function remove_pages_from_wp_list_pages($exclude_array)
1257
-    {
1258
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1259
-    }
24
+	/**
25
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
26
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
27
+	 */
28
+	const req_type_normal = 0;
29
+
30
+	/**
31
+	 * Indicates this is a brand new installation of EE so we should install
32
+	 * tables and default data etc
33
+	 */
34
+	const req_type_new_activation = 1;
35
+
36
+	/**
37
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
38
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
39
+	 * and that default data is setup too
40
+	 */
41
+	const req_type_reactivation = 2;
42
+
43
+	/**
44
+	 * indicates that EE has been upgraded since its previous request.
45
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
46
+	 */
47
+	const req_type_upgrade = 3;
48
+
49
+	/**
50
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
51
+	 */
52
+	const req_type_downgrade = 4;
53
+
54
+	/**
55
+	 * @deprecated since version 4.6.0.dev.006
56
+	 * Now whenever a new_activation is detected the request type is still just
57
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
58
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
59
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
60
+	 * (Specifically, when the migration manager indicates migrations are finished
61
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
62
+	 */
63
+	const req_type_activation_but_not_installed = 5;
64
+
65
+	/**
66
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
67
+	 */
68
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
69
+
70
+
71
+	/**
72
+	 * @var EE_System $_instance
73
+	 */
74
+	private static $_instance;
75
+
76
+	/**
77
+	 * @var EE_Registry $registry
78
+	 */
79
+	private $registry;
80
+
81
+	/**
82
+	 * @var LoaderInterface $loader
83
+	 */
84
+	private $loader;
85
+
86
+	/**
87
+	 * @var EE_Capabilities $capabilities
88
+	 */
89
+	private $capabilities;
90
+
91
+	/**
92
+	 * @var EE_Request $request
93
+	 */
94
+	private $request;
95
+
96
+	/**
97
+	 * @var EE_Maintenance_Mode $maintenance_mode
98
+	 */
99
+	private $maintenance_mode;
100
+
101
+	/**
102
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
103
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
104
+	 *
105
+	 * @var int $_req_type
106
+	 */
107
+	private $_req_type;
108
+
109
+	/**
110
+	 * Whether or not there was a non-micro version change in EE core version during this request
111
+	 *
112
+	 * @var boolean $_major_version_change
113
+	 */
114
+	private $_major_version_change = false;
115
+
116
+
117
+
118
+	/**
119
+	 * @singleton method used to instantiate class object
120
+	 * @param EE_Registry|null         $registry
121
+	 * @param LoaderInterface|null     $loader
122
+	 * @param EE_Capabilities|null     $capabilities
123
+	 * @param EE_Request|null          $request
124
+	 * @param EE_Maintenance_Mode|null $maintenance_mode
125
+	 * @return EE_System
126
+	 */
127
+	public static function instance(
128
+		EE_Registry $registry = null,
129
+		LoaderInterface $loader = null,
130
+		EE_Capabilities $capabilities = null,
131
+		EE_Request $request = null,
132
+		EE_Maintenance_Mode $maintenance_mode = null
133
+	) {
134
+		// check if class object is instantiated
135
+		if (! self::$_instance instanceof EE_System) {
136
+			self::$_instance = new self($registry, $loader, $capabilities, $request, $maintenance_mode);
137
+		}
138
+		return self::$_instance;
139
+	}
140
+
141
+
142
+
143
+	/**
144
+	 * resets the instance and returns it
145
+	 *
146
+	 * @return EE_System
147
+	 */
148
+	public static function reset()
149
+	{
150
+		self::$_instance->_req_type = null;
151
+		//make sure none of the old hooks are left hanging around
152
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
153
+		//we need to reset the migration manager in order for it to detect DMSs properly
154
+		EE_Data_Migration_Manager::reset();
155
+		self::instance()->detect_activations_or_upgrades();
156
+		self::instance()->perform_activations_upgrades_and_migrations();
157
+		return self::instance();
158
+	}
159
+
160
+
161
+
162
+	/**
163
+	 * sets hooks for running rest of system
164
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
165
+	 * starting EE Addons from any other point may lead to problems
166
+	 *
167
+	 * @param EE_Registry         $registry
168
+	 * @param LoaderInterface     $loader
169
+	 * @param EE_Capabilities     $capabilities
170
+	 * @param EE_Request          $request
171
+	 * @param EE_Maintenance_Mode $maintenance_mode
172
+	 */
173
+	private function __construct(
174
+		EE_Registry $registry,
175
+		LoaderInterface $loader,
176
+		EE_Capabilities $capabilities,
177
+		EE_Request $request,
178
+		EE_Maintenance_Mode $maintenance_mode
179
+	) {
180
+		$this->registry = $registry;
181
+		$this->loader = $loader;
182
+		$this->capabilities = $capabilities;
183
+		$this->request = $request;
184
+		$this->maintenance_mode = $maintenance_mode;
185
+		do_action('AHEE__EE_System__construct__begin', $this);
186
+		add_action(
187
+			'AHEE__EE_Bootstrap__load_espresso_addons',
188
+			array($this, 'loadCapabilities'),
189
+			5
190
+		);
191
+		add_action(
192
+			'AHEE__EE_Bootstrap__load_espresso_addons',
193
+			array($this, 'loadCommandBus'),
194
+			7
195
+		);
196
+		add_action(
197
+			'AHEE__EE_Bootstrap__load_espresso_addons',
198
+			array($this, 'loadPluginApi'),
199
+			9
200
+		);
201
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
202
+		add_action(
203
+			'AHEE__EE_Bootstrap__load_espresso_addons',
204
+			array($this, 'load_espresso_addons')
205
+		);
206
+		// when an ee addon is activated, we want to call the core hook(s) again
207
+		// because the newly-activated addon didn't get a chance to run at all
208
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
209
+		// detect whether install or upgrade
210
+		add_action(
211
+			'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
212
+			array($this, 'detect_activations_or_upgrades'),
213
+			3
214
+		);
215
+		// load EE_Config, EE_Textdomain, etc
216
+		add_action(
217
+			'AHEE__EE_Bootstrap__load_core_configuration',
218
+			array($this, 'load_core_configuration'),
219
+			5
220
+		);
221
+		// load EE_Config, EE_Textdomain, etc
222
+		add_action(
223
+			'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
224
+			array($this, 'register_shortcodes_modules_and_widgets'),
225
+			7
226
+		);
227
+		// you wanna get going? I wanna get going... let's get going!
228
+		add_action(
229
+			'AHEE__EE_Bootstrap__brew_espresso',
230
+			array($this, 'brew_espresso'),
231
+			9
232
+		);
233
+		//other housekeeping
234
+		//exclude EE critical pages from wp_list_pages
235
+		add_filter(
236
+			'wp_list_pages_excludes',
237
+			array($this, 'remove_pages_from_wp_list_pages'),
238
+			10
239
+		);
240
+		// ALL EE Addons should use the following hook point to attach their initial setup too
241
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
242
+		do_action('AHEE__EE_System__construct__complete', $this);
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 * load and setup EE_Capabilities
249
+	 *
250
+	 * @return void
251
+	 * @throws EE_Error
252
+	 */
253
+	public function loadCapabilities()
254
+	{
255
+		$this->loader->getShared('EE_Capabilities');
256
+		add_action(
257
+			'AHEE__EE_Capabilities__init_caps__before_initialization',
258
+			function() {
259
+				LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
260
+			}
261
+		);
262
+	}
263
+
264
+
265
+
266
+	/**
267
+	 * create and cache the CommandBus, and also add middleware
268
+	 * The CapChecker middleware requires the use of EE_Capabilities
269
+	 * which is why we need to load the CommandBus after Caps are set up
270
+	 *
271
+	 * @return void
272
+	 * @throws EE_Error
273
+	 */
274
+	public function loadCommandBus()
275
+	{
276
+		$this->loader->getShared(
277
+			'CommandBusInterface',
278
+			array(
279
+				null,
280
+				apply_filters(
281
+					'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
282
+					array(
283
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
284
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
285
+					)
286
+				),
287
+			)
288
+		);
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * @return void
295
+	 * @throws EE_Error
296
+	 */
297
+	public function loadPluginApi()
298
+	{
299
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
300
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
301
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
302
+	}
303
+
304
+
305
+	/**
306
+	 * @param string $addon_name
307
+	 * @param string $version_constant
308
+	 * @param string $min_version_required
309
+	 * @param string $load_callback
310
+	 * @param string $plugin_file_constant
311
+	 * @return void
312
+	 */
313
+	private function deactivateIncompatibleAddon(
314
+		$addon_name,
315
+		$version_constant,
316
+		$min_version_required,
317
+		$load_callback,
318
+		$plugin_file_constant
319
+	) {
320
+		if (! defined($version_constant)) {
321
+			return;
322
+		}
323
+		$addon_version = constant($version_constant);
324
+		if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
325
+			remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
326
+			if (! function_exists('deactivate_plugins')) {
327
+				require_once ABSPATH . 'wp-admin/includes/plugin.php';
328
+			}
329
+			deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
330
+			unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
331
+			EE_Error::add_error(
332
+				sprintf(
333
+					esc_html__(
334
+						'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
335
+						'event_espresso'
336
+					),
337
+					$addon_name,
338
+					$min_version_required
339
+				),
340
+				__FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
341
+			);
342
+			EE_Error::get_notices(false, true);
343
+		}
344
+	}
345
+
346
+
347
+	/**
348
+	 * load_espresso_addons
349
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
350
+	 * this is hooked into both:
351
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
352
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
353
+	 *    and the WP 'activate_plugin' hook point
354
+	 *
355
+	 * @access public
356
+	 * @return void
357
+	 */
358
+	public function load_espresso_addons()
359
+	{
360
+		$this->deactivateIncompatibleAddon(
361
+			'Wait Lists',
362
+			'EE_WAIT_LISTS_VERSION',
363
+			'1.0.0.rc.074',
364
+			'load_espresso_wait_lists',
365
+			'EE_WAIT_LISTS_PLUGIN_FILE'
366
+		);
367
+		$this->deactivateIncompatibleAddon(
368
+			'Automated Upcoming Event Notifications',
369
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
370
+			'1.0.0.rc.091',
371
+			'load_espresso_automated_upcoming_event_notification',
372
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
373
+		);
374
+		do_action('AHEE__EE_System__load_espresso_addons');
375
+		//if the WP API basic auth plugin isn't already loaded, load it now.
376
+		//We want it for mobile apps. Just include the entire plugin
377
+		//also, don't load the basic auth when a plugin is getting activated, because
378
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
379
+		//and causes a fatal error
380
+		if (
381
+			! (
382
+				isset($_GET['activate'])
383
+				&& $_GET['activate'] === 'true'
384
+			)
385
+			&& ! function_exists('json_basic_auth_handler')
386
+			&& ! function_exists('json_basic_auth_error')
387
+			&& ! (
388
+				isset($_GET['action'])
389
+				&& in_array($_GET['action'], array('activate', 'activate-selected'), true)
390
+			)
391
+		) {
392
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
393
+		}
394
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
395
+	}
396
+
397
+
398
+
399
+	/**
400
+	 * detect_activations_or_upgrades
401
+	 * Checks for activation or upgrade of core first;
402
+	 * then also checks if any registered addons have been activated or upgraded
403
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
404
+	 * which runs during the WP 'plugins_loaded' action at priority 3
405
+	 *
406
+	 * @access public
407
+	 * @return void
408
+	 */
409
+	public function detect_activations_or_upgrades()
410
+	{
411
+		//first off: let's make sure to handle core
412
+		$this->detect_if_activation_or_upgrade();
413
+		foreach ($this->registry->addons as $addon) {
414
+			if ($addon instanceof EE_Addon) {
415
+				//detect teh request type for that addon
416
+				$addon->detect_activation_or_upgrade();
417
+			}
418
+		}
419
+	}
420
+
421
+
422
+
423
+	/**
424
+	 * detect_if_activation_or_upgrade
425
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
426
+	 * and either setting up the DB or setting up maintenance mode etc.
427
+	 *
428
+	 * @access public
429
+	 * @return void
430
+	 */
431
+	public function detect_if_activation_or_upgrade()
432
+	{
433
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
434
+		// check if db has been updated, or if its a brand-new installation
435
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
436
+		$request_type = $this->detect_req_type($espresso_db_update);
437
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
438
+		switch ($request_type) {
439
+			case EE_System::req_type_new_activation:
440
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
441
+				$this->_handle_core_version_change($espresso_db_update);
442
+				break;
443
+			case EE_System::req_type_reactivation:
444
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
445
+				$this->_handle_core_version_change($espresso_db_update);
446
+				break;
447
+			case EE_System::req_type_upgrade:
448
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
449
+				//migrations may be required now that we've upgraded
450
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
451
+				$this->_handle_core_version_change($espresso_db_update);
452
+				//				echo "done upgrade";die;
453
+				break;
454
+			case EE_System::req_type_downgrade:
455
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
456
+				//its possible migrations are no longer required
457
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
458
+				$this->_handle_core_version_change($espresso_db_update);
459
+				break;
460
+			case EE_System::req_type_normal:
461
+			default:
462
+				//				$this->_maybe_redirect_to_ee_about();
463
+				break;
464
+		}
465
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
466
+	}
467
+
468
+
469
+
470
+	/**
471
+	 * Updates the list of installed versions and sets hooks for
472
+	 * initializing the database later during the request
473
+	 *
474
+	 * @param array $espresso_db_update
475
+	 */
476
+	private function _handle_core_version_change($espresso_db_update)
477
+	{
478
+		$this->update_list_of_installed_versions($espresso_db_update);
479
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
480
+		add_action(
481
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
482
+			array($this, 'initialize_db_if_no_migrations_required')
483
+		);
484
+	}
485
+
486
+
487
+
488
+	/**
489
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
490
+	 * information about what versions of EE have been installed and activated,
491
+	 * NOT necessarily the state of the database
492
+	 *
493
+	 * @param mixed $espresso_db_update the value of the WordPress option.
494
+	 *                                            If not supplied, fetches it from the options table
495
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
496
+	 */
497
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
498
+	{
499
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
500
+		if (! $espresso_db_update) {
501
+			$espresso_db_update = get_option('espresso_db_update');
502
+		}
503
+		// check that option is an array
504
+		if (! is_array($espresso_db_update)) {
505
+			// if option is FALSE, then it never existed
506
+			if ($espresso_db_update === false) {
507
+				// make $espresso_db_update an array and save option with autoload OFF
508
+				$espresso_db_update = array();
509
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
510
+			} else {
511
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
512
+				$espresso_db_update = array($espresso_db_update => array());
513
+				update_option('espresso_db_update', $espresso_db_update);
514
+			}
515
+		} else {
516
+			$corrected_db_update = array();
517
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
518
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
519
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
520
+					//the key is an int, and the value IS NOT an array
521
+					//so it must be numerically-indexed, where values are versions installed...
522
+					//fix it!
523
+					$version_string = $should_be_array;
524
+					$corrected_db_update[$version_string] = array('unknown-date');
525
+				} else {
526
+					//ok it checks out
527
+					$corrected_db_update[$should_be_version_string] = $should_be_array;
528
+				}
529
+			}
530
+			$espresso_db_update = $corrected_db_update;
531
+			update_option('espresso_db_update', $espresso_db_update);
532
+		}
533
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
534
+		return $espresso_db_update;
535
+	}
536
+
537
+
538
+
539
+	/**
540
+	 * Does the traditional work of setting up the plugin's database and adding default data.
541
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
542
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
543
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
544
+	 * so that it will be done when migrations are finished
545
+	 *
546
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
547
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
548
+	 *                                       This is a resource-intensive job
549
+	 *                                       so we prefer to only do it when necessary
550
+	 * @return void
551
+	 * @throws EE_Error
552
+	 */
553
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
554
+	{
555
+		$request_type = $this->detect_req_type();
556
+		//only initialize system if we're not in maintenance mode.
557
+		if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
558
+			update_option('ee_flush_rewrite_rules', true);
559
+			if ($verify_schema) {
560
+				EEH_Activation::initialize_db_and_folders();
561
+			}
562
+			EEH_Activation::initialize_db_content();
563
+			EEH_Activation::system_initialization();
564
+			if ($initialize_addons_too) {
565
+				$this->initialize_addons();
566
+			}
567
+		} else {
568
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
569
+		}
570
+		if ($request_type === EE_System::req_type_new_activation
571
+			|| $request_type === EE_System::req_type_reactivation
572
+			|| (
573
+				$request_type === EE_System::req_type_upgrade
574
+				&& $this->is_major_version_change()
575
+			)
576
+		) {
577
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
578
+		}
579
+	}
580
+
581
+
582
+
583
+	/**
584
+	 * Initializes the db for all registered addons
585
+	 *
586
+	 * @throws EE_Error
587
+	 */
588
+	public function initialize_addons()
589
+	{
590
+		//foreach registered addon, make sure its db is up-to-date too
591
+		foreach ($this->registry->addons as $addon) {
592
+			if ($addon instanceof EE_Addon) {
593
+				$addon->initialize_db_if_no_migrations_required();
594
+			}
595
+		}
596
+	}
597
+
598
+
599
+
600
+	/**
601
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
602
+	 *
603
+	 * @param    array  $version_history
604
+	 * @param    string $current_version_to_add version to be added to the version history
605
+	 * @return    boolean success as to whether or not this option was changed
606
+	 */
607
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
608
+	{
609
+		if (! $version_history) {
610
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
611
+		}
612
+		if ($current_version_to_add === null) {
613
+			$current_version_to_add = espresso_version();
614
+		}
615
+		$version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
616
+		// re-save
617
+		return update_option('espresso_db_update', $version_history);
618
+	}
619
+
620
+
621
+
622
+	/**
623
+	 * Detects if the current version indicated in the has existed in the list of
624
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
625
+	 *
626
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
627
+	 *                                  If not supplied, fetches it from the options table.
628
+	 *                                  Also, caches its result so later parts of the code can also know whether
629
+	 *                                  there's been an update or not. This way we can add the current version to
630
+	 *                                  espresso_db_update, but still know if this is a new install or not
631
+	 * @return int one of the constants on EE_System::req_type_
632
+	 */
633
+	public function detect_req_type($espresso_db_update = null)
634
+	{
635
+		if ($this->_req_type === null) {
636
+			$espresso_db_update = ! empty($espresso_db_update)
637
+				? $espresso_db_update
638
+				: $this->fix_espresso_db_upgrade_option();
639
+			$this->_req_type = EE_System::detect_req_type_given_activation_history(
640
+				$espresso_db_update,
641
+				'ee_espresso_activation', espresso_version()
642
+			);
643
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
644
+		}
645
+		return $this->_req_type;
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 * Returns whether or not there was a non-micro version change (ie, change in either
652
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
653
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
654
+	 *
655
+	 * @param $activation_history
656
+	 * @return bool
657
+	 */
658
+	private function _detect_major_version_change($activation_history)
659
+	{
660
+		$previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
661
+		$previous_version_parts = explode('.', $previous_version);
662
+		$current_version_parts = explode('.', espresso_version());
663
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
664
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
665
+				   || $previous_version_parts[1] !== $current_version_parts[1]
666
+			   );
667
+	}
668
+
669
+
670
+
671
+	/**
672
+	 * Returns true if either the major or minor version of EE changed during this request.
673
+	 * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
674
+	 *
675
+	 * @return bool
676
+	 */
677
+	public function is_major_version_change()
678
+	{
679
+		return $this->_major_version_change;
680
+	}
681
+
682
+
683
+
684
+	/**
685
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
686
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
687
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
688
+	 * just activated to (for core that will always be espresso_version())
689
+	 *
690
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
691
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
692
+	 * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
693
+	 *                                                 indicate that this plugin was just activated
694
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
695
+	 *                                                 espresso_version())
696
+	 * @return int one of the constants on EE_System::req_type_*
697
+	 */
698
+	public static function detect_req_type_given_activation_history(
699
+		$activation_history_for_addon,
700
+		$activation_indicator_option_name,
701
+		$version_to_upgrade_to
702
+	) {
703
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
704
+		if ($activation_history_for_addon) {
705
+			//it exists, so this isn't a completely new install
706
+			//check if this version already in that list of previously installed versions
707
+			if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
708
+				//it a version we haven't seen before
709
+				if ($version_is_higher === 1) {
710
+					$req_type = EE_System::req_type_upgrade;
711
+				} else {
712
+					$req_type = EE_System::req_type_downgrade;
713
+				}
714
+				delete_option($activation_indicator_option_name);
715
+			} else {
716
+				// its not an update. maybe a reactivation?
717
+				if (get_option($activation_indicator_option_name, false)) {
718
+					if ($version_is_higher === -1) {
719
+						$req_type = EE_System::req_type_downgrade;
720
+					} else if ($version_is_higher === 0) {
721
+						//we've seen this version before, but it's an activation. must be a reactivation
722
+						$req_type = EE_System::req_type_reactivation;
723
+					} else {//$version_is_higher === 1
724
+						$req_type = EE_System::req_type_upgrade;
725
+					}
726
+					delete_option($activation_indicator_option_name);
727
+				} else {
728
+					//we've seen this version before and the activation indicate doesn't show it was just activated
729
+					if ($version_is_higher === -1) {
730
+						$req_type = EE_System::req_type_downgrade;
731
+					} else if ($version_is_higher === 0) {
732
+						//we've seen this version before and it's not an activation. its normal request
733
+						$req_type = EE_System::req_type_normal;
734
+					} else {//$version_is_higher === 1
735
+						$req_type = EE_System::req_type_upgrade;
736
+					}
737
+				}
738
+			}
739
+		} else {
740
+			//brand new install
741
+			$req_type = EE_System::req_type_new_activation;
742
+			delete_option($activation_indicator_option_name);
743
+		}
744
+		return $req_type;
745
+	}
746
+
747
+
748
+
749
+	/**
750
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
751
+	 * the $activation_history_for_addon
752
+	 *
753
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
754
+	 *                                             sometimes containing 'unknown-date'
755
+	 * @param string $version_to_upgrade_to        (current version)
756
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
757
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
758
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
759
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
760
+	 */
761
+	private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
762
+	{
763
+		//find the most recently-activated version
764
+		$most_recently_active_version =
765
+			EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
766
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
767
+	}
768
+
769
+
770
+
771
+	/**
772
+	 * Gets the most recently active version listed in the activation history,
773
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
774
+	 *
775
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
776
+	 *                                   sometimes containing 'unknown-date'
777
+	 * @return string
778
+	 */
779
+	private static function _get_most_recently_active_version_from_activation_history($activation_history)
780
+	{
781
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
782
+		$most_recently_active_version = '0.0.0.dev.000';
783
+		if (is_array($activation_history)) {
784
+			foreach ($activation_history as $version => $times_activated) {
785
+				//check there is a record of when this version was activated. Otherwise,
786
+				//mark it as unknown
787
+				if (! $times_activated) {
788
+					$times_activated = array('unknown-date');
789
+				}
790
+				if (is_string($times_activated)) {
791
+					$times_activated = array($times_activated);
792
+				}
793
+				foreach ($times_activated as $an_activation) {
794
+					if ($an_activation !== 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
795
+						$most_recently_active_version = $version;
796
+						$most_recently_active_version_activation = $an_activation === 'unknown-date'
797
+							? '1970-01-01 00:00:00'
798
+							: $an_activation;
799
+					}
800
+				}
801
+			}
802
+		}
803
+		return $most_recently_active_version;
804
+	}
805
+
806
+
807
+
808
+	/**
809
+	 * This redirects to the about EE page after activation
810
+	 *
811
+	 * @return void
812
+	 */
813
+	public function redirect_to_about_ee()
814
+	{
815
+		$notices = EE_Error::get_notices(false);
816
+		//if current user is an admin and it's not an ajax or rest request
817
+		if (
818
+			! (defined('DOING_AJAX') && DOING_AJAX)
819
+			&& ! (defined('REST_REQUEST') && REST_REQUEST)
820
+			&& ! isset($notices['errors'])
821
+			&& apply_filters(
822
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
823
+				$this->capabilities->current_user_can('manage_options', 'espresso_about_default')
824
+			)
825
+		) {
826
+			$query_params = array('page' => 'espresso_about');
827
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
828
+				$query_params['new_activation'] = true;
829
+			}
830
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
831
+				$query_params['reactivation'] = true;
832
+			}
833
+			$url = add_query_arg($query_params, admin_url('admin.php'));
834
+			wp_safe_redirect($url);
835
+			exit();
836
+		}
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * load_core_configuration
843
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
844
+	 * which runs during the WP 'plugins_loaded' action at priority 5
845
+	 *
846
+	 * @return void
847
+	 * @throws ReflectionException
848
+	 */
849
+	public function load_core_configuration()
850
+	{
851
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
852
+		$this->loader->getShared('EE_Load_Textdomain');
853
+		//load textdomain
854
+		EE_Load_Textdomain::load_textdomain();
855
+		// load and setup EE_Config and EE_Network_Config
856
+		$config = $this->loader->getShared('EE_Config');
857
+		$this->loader->getShared('EE_Network_Config');
858
+		// setup autoloaders
859
+		// enable logging?
860
+		if ($config->admin->use_full_logging) {
861
+			$this->loader->getShared('EE_Log');
862
+		}
863
+		// check for activation errors
864
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
865
+		if ($activation_errors) {
866
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
867
+			update_option('ee_plugin_activation_errors', false);
868
+		}
869
+		// get model names
870
+		$this->_parse_model_names();
871
+		//load caf stuff a chance to play during the activation process too.
872
+		$this->_maybe_brew_regular();
873
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
874
+	}
875
+
876
+
877
+
878
+	/**
879
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
880
+	 *
881
+	 * @return void
882
+	 * @throws ReflectionException
883
+	 */
884
+	private function _parse_model_names()
885
+	{
886
+		//get all the files in the EE_MODELS folder that end in .model.php
887
+		$models = glob(EE_MODELS . '*.model.php');
888
+		$model_names = array();
889
+		$non_abstract_db_models = array();
890
+		foreach ($models as $model) {
891
+			// get model classname
892
+			$classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
893
+			$short_name = str_replace('EEM_', '', $classname);
894
+			$reflectionClass = new ReflectionClass($classname);
895
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
896
+				$non_abstract_db_models[$short_name] = $classname;
897
+			}
898
+			$model_names[$short_name] = $classname;
899
+		}
900
+		$this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
901
+		$this->registry->non_abstract_db_models = apply_filters(
902
+			'FHEE__EE_System__parse_implemented_model_names',
903
+			$non_abstract_db_models
904
+		);
905
+	}
906
+
907
+
908
+
909
+	/**
910
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
911
+	 * that need to be setup before our EE_System launches.
912
+	 *
913
+	 * @return void
914
+	 */
915
+	private function _maybe_brew_regular()
916
+	{
917
+		if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
918
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
919
+		}
920
+	}
921
+
922
+
923
+
924
+	/**
925
+	 * register_shortcodes_modules_and_widgets
926
+	 * generate lists of shortcodes and modules, then verify paths and classes
927
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
928
+	 * which runs during the WP 'plugins_loaded' action at priority 7
929
+	 *
930
+	 * @access public
931
+	 * @return void
932
+	 * @throws Exception
933
+	 */
934
+	public function register_shortcodes_modules_and_widgets()
935
+	{
936
+		try {
937
+			// load, register, and add shortcodes the new way
938
+			$this->loader->getShared(
939
+				'EventEspresso\core\services\shortcodes\ShortcodesManager',
940
+				array(
941
+					// and the old way, but we'll put it under control of the new system
942
+					EE_Config::getLegacyShortcodesManager()
943
+				)
944
+			);
945
+		} catch (Exception $exception) {
946
+			new ExceptionStackTraceDisplay($exception);
947
+		}
948
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
949
+		// check for addons using old hook point
950
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
951
+			$this->_incompatible_addon_error();
952
+		}
953
+	}
954
+
955
+
956
+
957
+	/**
958
+	 * _incompatible_addon_error
959
+	 *
960
+	 * @access public
961
+	 * @return void
962
+	 */
963
+	private function _incompatible_addon_error()
964
+	{
965
+		// get array of classes hooking into here
966
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
967
+			'AHEE__EE_System__register_shortcodes_modules_and_addons'
968
+		);
969
+		if (! empty($class_names)) {
970
+			$msg = __(
971
+				'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
972
+				'event_espresso'
973
+			);
974
+			$msg .= '<ul>';
975
+			foreach ($class_names as $class_name) {
976
+				$msg .= '<li><b>Event Espresso - ' . str_replace(
977
+						array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
978
+						$class_name
979
+					) . '</b></li>';
980
+			}
981
+			$msg .= '</ul>';
982
+			$msg .= __(
983
+				'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
984
+				'event_espresso'
985
+			);
986
+			// save list of incompatible addons to wp-options for later use
987
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
988
+			if (is_admin()) {
989
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
990
+			}
991
+		}
992
+	}
993
+
994
+
995
+
996
+	/**
997
+	 * brew_espresso
998
+	 * begins the process of setting hooks for initializing EE in the correct order
999
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1000
+	 * which runs during the WP 'plugins_loaded' action at priority 9
1001
+	 *
1002
+	 * @return void
1003
+	 */
1004
+	public function brew_espresso()
1005
+	{
1006
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
1007
+		// load some final core systems
1008
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
1009
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1010
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
1011
+		add_action('init', array($this, 'load_controllers'), 7);
1012
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
1013
+		add_action('init', array($this, 'initialize'), 10);
1014
+		add_action('init', array($this, 'initialize_last'), 100);
1015
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1016
+			// pew pew pew
1017
+			$this->loader->getShared('EE_PUE');
1018
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1019
+		}
1020
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
1021
+	}
1022
+
1023
+
1024
+
1025
+	/**
1026
+	 *    set_hooks_for_core
1027
+	 *
1028
+	 * @access public
1029
+	 * @return    void
1030
+	 * @throws EE_Error
1031
+	 */
1032
+	public function set_hooks_for_core()
1033
+	{
1034
+		$this->_deactivate_incompatible_addons();
1035
+		do_action('AHEE__EE_System__set_hooks_for_core');
1036
+		//caps need to be initialized on every request so that capability maps are set.
1037
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1038
+		$this->registry->CAP->init_caps();
1039
+	}
1040
+
1041
+
1042
+
1043
+	/**
1044
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
1045
+	 * deactivates any addons considered incompatible with the current version of EE
1046
+	 */
1047
+	private function _deactivate_incompatible_addons()
1048
+	{
1049
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
1050
+		if (! empty($incompatible_addons)) {
1051
+			$active_plugins = get_option('active_plugins', array());
1052
+			foreach ($active_plugins as $active_plugin) {
1053
+				foreach ($incompatible_addons as $incompatible_addon) {
1054
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
1055
+						unset($_GET['activate']);
1056
+						espresso_deactivate_plugin($active_plugin);
1057
+					}
1058
+				}
1059
+			}
1060
+		}
1061
+	}
1062
+
1063
+
1064
+
1065
+	/**
1066
+	 *    perform_activations_upgrades_and_migrations
1067
+	 *
1068
+	 * @access public
1069
+	 * @return    void
1070
+	 */
1071
+	public function perform_activations_upgrades_and_migrations()
1072
+	{
1073
+		//first check if we had previously attempted to setup EE's directories but failed
1074
+		if (EEH_Activation::upload_directories_incomplete()) {
1075
+			EEH_Activation::create_upload_directories();
1076
+		}
1077
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1078
+	}
1079
+
1080
+
1081
+
1082
+	/**
1083
+	 *    load_CPTs_and_session
1084
+	 *
1085
+	 * @access public
1086
+	 * @return    void
1087
+	 */
1088
+	public function load_CPTs_and_session()
1089
+	{
1090
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
1091
+		// register Custom Post Types
1092
+		$this->loader->getShared('EE_Register_CPTs');
1093
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1094
+	}
1095
+
1096
+
1097
+
1098
+	/**
1099
+	 * load_controllers
1100
+	 * this is the best place to load any additional controllers that needs access to EE core.
1101
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1102
+	 * time
1103
+	 *
1104
+	 * @access public
1105
+	 * @return void
1106
+	 */
1107
+	public function load_controllers()
1108
+	{
1109
+		do_action('AHEE__EE_System__load_controllers__start');
1110
+		// let's get it started
1111
+		if (! is_admin() && ! $this->maintenance_mode->level()) {
1112
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1113
+			$this->loader->getShared('EE_Front_Controller');
1114
+		} else if (! EE_FRONT_AJAX) {
1115
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1116
+			$this->loader->getShared('EE_Admin');
1117
+		}
1118
+		do_action('AHEE__EE_System__load_controllers__complete');
1119
+	}
1120
+
1121
+
1122
+
1123
+	/**
1124
+	 * core_loaded_and_ready
1125
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1126
+	 *
1127
+	 * @access public
1128
+	 * @return void
1129
+	 */
1130
+	public function core_loaded_and_ready()
1131
+	{
1132
+		$this->loader->getShared('EE_Session');
1133
+		do_action('AHEE__EE_System__core_loaded_and_ready');
1134
+		// load_espresso_template_tags
1135
+		if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1136
+			require_once(EE_PUBLIC . 'template_tags.php');
1137
+		}
1138
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1139
+		$this->loader->getShared('EventEspresso\core\services\assets\Registry');
1140
+	}
1141
+
1142
+
1143
+
1144
+	/**
1145
+	 * initialize
1146
+	 * this is the best place to begin initializing client code
1147
+	 *
1148
+	 * @access public
1149
+	 * @return void
1150
+	 */
1151
+	public function initialize()
1152
+	{
1153
+		do_action('AHEE__EE_System__initialize');
1154
+	}
1155
+
1156
+
1157
+
1158
+	/**
1159
+	 * initialize_last
1160
+	 * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1161
+	 * initialize has done so
1162
+	 *
1163
+	 * @access public
1164
+	 * @return void
1165
+	 */
1166
+	public function initialize_last()
1167
+	{
1168
+		do_action('AHEE__EE_System__initialize_last');
1169
+		add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1170
+	}
1171
+
1172
+
1173
+
1174
+	/**
1175
+	 * @return void
1176
+	 * @throws EE_Error
1177
+	 */
1178
+	public function addEspressoToolbar()
1179
+	{
1180
+		$this->loader->getShared(
1181
+			'EventEspresso\core\domain\services\admin\AdminToolBar',
1182
+			array($this->registry->CAP)
1183
+		);
1184
+	}
1185
+
1186
+
1187
+
1188
+	/**
1189
+	 * do_not_cache
1190
+	 * sets no cache headers and defines no cache constants for WP plugins
1191
+	 *
1192
+	 * @access public
1193
+	 * @return void
1194
+	 */
1195
+	public static function do_not_cache()
1196
+	{
1197
+		// set no cache constants
1198
+		if (! defined('DONOTCACHEPAGE')) {
1199
+			define('DONOTCACHEPAGE', true);
1200
+		}
1201
+		if (! defined('DONOTCACHCEOBJECT')) {
1202
+			define('DONOTCACHCEOBJECT', true);
1203
+		}
1204
+		if (! defined('DONOTCACHEDB')) {
1205
+			define('DONOTCACHEDB', true);
1206
+		}
1207
+		// add no cache headers
1208
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1209
+		// plus a little extra for nginx and Google Chrome
1210
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1211
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1212
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1213
+	}
1214
+
1215
+
1216
+
1217
+	/**
1218
+	 *    extra_nocache_headers
1219
+	 *
1220
+	 * @access    public
1221
+	 * @param $headers
1222
+	 * @return    array
1223
+	 */
1224
+	public static function extra_nocache_headers($headers)
1225
+	{
1226
+		// for NGINX
1227
+		$headers['X-Accel-Expires'] = 0;
1228
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1229
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1230
+		return $headers;
1231
+	}
1232
+
1233
+
1234
+
1235
+	/**
1236
+	 *    nocache_headers
1237
+	 *
1238
+	 * @access    public
1239
+	 * @return    void
1240
+	 */
1241
+	public static function nocache_headers()
1242
+	{
1243
+		nocache_headers();
1244
+	}
1245
+
1246
+
1247
+
1248
+
1249
+	/**
1250
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1251
+	 * never returned with the function.
1252
+	 *
1253
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1254
+	 * @return array
1255
+	 */
1256
+	public function remove_pages_from_wp_list_pages($exclude_array)
1257
+	{
1258
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1259
+	}
1260 1260
 
1261 1261
 
1262 1262
 
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
         EE_Maintenance_Mode $maintenance_mode = null
133 133
     ) {
134 134
         // check if class object is instantiated
135
-        if (! self::$_instance instanceof EE_System) {
135
+        if ( ! self::$_instance instanceof EE_System) {
136 136
             self::$_instance = new self($registry, $loader, $capabilities, $request, $maintenance_mode);
137 137
         }
138 138
         return self::$_instance;
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
     {
299 299
         // set autoloaders for all of the classes implementing EEI_Plugin_API
300 300
         // which provide helpers for EE plugin authors to more easily register certain components with EE.
301
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
301
+        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'plugin_api');
302 302
     }
303 303
 
304 304
 
@@ -317,14 +317,14 @@  discard block
 block discarded – undo
317 317
         $load_callback,
318 318
         $plugin_file_constant
319 319
     ) {
320
-        if (! defined($version_constant)) {
320
+        if ( ! defined($version_constant)) {
321 321
             return;
322 322
         }
323 323
         $addon_version = constant($version_constant);
324 324
         if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
325 325
             remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
326
-            if (! function_exists('deactivate_plugins')) {
327
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
326
+            if ( ! function_exists('deactivate_plugins')) {
327
+                require_once ABSPATH.'wp-admin/includes/plugin.php';
328 328
             }
329 329
             deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
330 330
             unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
                     $addon_name,
338 338
                     $min_version_required
339 339
                 ),
340
-                __FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
340
+                __FILE__, __FUNCTION__."({$addon_name})", __LINE__
341 341
             );
342 342
             EE_Error::get_notices(false, true);
343 343
         }
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
                 && in_array($_GET['action'], array('activate', 'activate-selected'), true)
390 390
             )
391 391
         ) {
392
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
392
+            include_once EE_THIRD_PARTY.'wp-api-basic-auth'.DS.'basic-auth.php';
393 393
         }
394 394
         do_action('AHEE__EE_System__load_espresso_addons__complete');
395 395
     }
@@ -497,11 +497,11 @@  discard block
 block discarded – undo
497 497
     private function fix_espresso_db_upgrade_option($espresso_db_update = null)
498 498
     {
499 499
         do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
500
-        if (! $espresso_db_update) {
500
+        if ( ! $espresso_db_update) {
501 501
             $espresso_db_update = get_option('espresso_db_update');
502 502
         }
503 503
         // check that option is an array
504
-        if (! is_array($espresso_db_update)) {
504
+        if ( ! is_array($espresso_db_update)) {
505 505
             // if option is FALSE, then it never existed
506 506
             if ($espresso_db_update === false) {
507 507
                 // make $espresso_db_update an array and save option with autoload OFF
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
      */
607 607
     public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
608 608
     {
609
-        if (! $version_history) {
609
+        if ( ! $version_history) {
610 610
             $version_history = $this->fix_espresso_db_upgrade_option($version_history);
611 611
         }
612 612
         if ($current_version_to_add === null) {
@@ -704,7 +704,7 @@  discard block
 block discarded – undo
704 704
         if ($activation_history_for_addon) {
705 705
             //it exists, so this isn't a completely new install
706 706
             //check if this version already in that list of previously installed versions
707
-            if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
707
+            if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
708 708
                 //it a version we haven't seen before
709 709
                 if ($version_is_higher === 1) {
710 710
                     $req_type = EE_System::req_type_upgrade;
@@ -784,7 +784,7 @@  discard block
 block discarded – undo
784 784
             foreach ($activation_history as $version => $times_activated) {
785 785
                 //check there is a record of when this version was activated. Otherwise,
786 786
                 //mark it as unknown
787
-                if (! $times_activated) {
787
+                if ( ! $times_activated) {
788 788
                     $times_activated = array('unknown-date');
789 789
                 }
790 790
                 if (is_string($times_activated)) {
@@ -884,7 +884,7 @@  discard block
 block discarded – undo
884 884
     private function _parse_model_names()
885 885
     {
886 886
         //get all the files in the EE_MODELS folder that end in .model.php
887
-        $models = glob(EE_MODELS . '*.model.php');
887
+        $models = glob(EE_MODELS.'*.model.php');
888 888
         $model_names = array();
889 889
         $non_abstract_db_models = array();
890 890
         foreach ($models as $model) {
@@ -914,8 +914,8 @@  discard block
 block discarded – undo
914 914
      */
915 915
     private function _maybe_brew_regular()
916 916
     {
917
-        if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
918
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
917
+        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH.'brewing_regular.php')) {
918
+            require_once EE_CAFF_PATH.'brewing_regular.php';
919 919
         }
920 920
     }
921 921
 
@@ -966,17 +966,17 @@  discard block
 block discarded – undo
966 966
         $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
967 967
             'AHEE__EE_System__register_shortcodes_modules_and_addons'
968 968
         );
969
-        if (! empty($class_names)) {
969
+        if ( ! empty($class_names)) {
970 970
             $msg = __(
971 971
                 'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
972 972
                 'event_espresso'
973 973
             );
974 974
             $msg .= '<ul>';
975 975
             foreach ($class_names as $class_name) {
976
-                $msg .= '<li><b>Event Espresso - ' . str_replace(
976
+                $msg .= '<li><b>Event Espresso - '.str_replace(
977 977
                         array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
978 978
                         $class_name
979
-                    ) . '</b></li>';
979
+                    ).'</b></li>';
980 980
             }
981 981
             $msg .= '</ul>';
982 982
             $msg .= __(
@@ -1047,7 +1047,7 @@  discard block
 block discarded – undo
1047 1047
     private function _deactivate_incompatible_addons()
1048 1048
     {
1049 1049
         $incompatible_addons = get_option('ee_incompatible_addons', array());
1050
-        if (! empty($incompatible_addons)) {
1050
+        if ( ! empty($incompatible_addons)) {
1051 1051
             $active_plugins = get_option('active_plugins', array());
1052 1052
             foreach ($active_plugins as $active_plugin) {
1053 1053
                 foreach ($incompatible_addons as $incompatible_addon) {
@@ -1108,10 +1108,10 @@  discard block
 block discarded – undo
1108 1108
     {
1109 1109
         do_action('AHEE__EE_System__load_controllers__start');
1110 1110
         // let's get it started
1111
-        if (! is_admin() && ! $this->maintenance_mode->level()) {
1111
+        if ( ! is_admin() && ! $this->maintenance_mode->level()) {
1112 1112
             do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1113 1113
             $this->loader->getShared('EE_Front_Controller');
1114
-        } else if (! EE_FRONT_AJAX) {
1114
+        } else if ( ! EE_FRONT_AJAX) {
1115 1115
             do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1116 1116
             $this->loader->getShared('EE_Admin');
1117 1117
         }
@@ -1132,8 +1132,8 @@  discard block
 block discarded – undo
1132 1132
         $this->loader->getShared('EE_Session');
1133 1133
         do_action('AHEE__EE_System__core_loaded_and_ready');
1134 1134
         // load_espresso_template_tags
1135
-        if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1136
-            require_once(EE_PUBLIC . 'template_tags.php');
1135
+        if (is_readable(EE_PUBLIC.'template_tags.php')) {
1136
+            require_once(EE_PUBLIC.'template_tags.php');
1137 1137
         }
1138 1138
         do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1139 1139
         $this->loader->getShared('EventEspresso\core\services\assets\Registry');
@@ -1195,13 +1195,13 @@  discard block
 block discarded – undo
1195 1195
     public static function do_not_cache()
1196 1196
     {
1197 1197
         // set no cache constants
1198
-        if (! defined('DONOTCACHEPAGE')) {
1198
+        if ( ! defined('DONOTCACHEPAGE')) {
1199 1199
             define('DONOTCACHEPAGE', true);
1200 1200
         }
1201
-        if (! defined('DONOTCACHCEOBJECT')) {
1201
+        if ( ! defined('DONOTCACHCEOBJECT')) {
1202 1202
             define('DONOTCACHCEOBJECT', true);
1203 1203
         }
1204
-        if (! defined('DONOTCACHEDB')) {
1204
+        if ( ! defined('DONOTCACHEDB')) {
1205 1205
             define('DONOTCACHEDB', true);
1206 1206
         }
1207 1207
         // add no cache headers
Please login to merge, or discard this patch.
core/helpers/EEH_Template.helper.php 2 patches
Indentation   +930 added lines, -930 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if (! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('NO direct script access allowed');
3
+	exit('NO direct script access allowed');
4 4
 }
5 5
 /**
6 6
  * Event Espresso
@@ -16,35 +16,35 @@  discard block
 block discarded – undo
16 16
 
17 17
 
18 18
 if ( ! function_exists('espresso_get_template_part')) {
19
-    /**
20
-     * espresso_get_template_part
21
-     * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead, and doesn't add base versions of files
22
-     * so not a very useful function at all except that it adds familiarity PLUS filtering based off of the entire template part name
23
-     *
24
-     * @param string $slug The slug name for the generic template.
25
-     * @param string $name The name of the specialised template.
26
-     * @return string        the html output for the formatted money value
27
-     */
28
-    function espresso_get_template_part($slug = null, $name = null)
29
-    {
30
-        EEH_Template::get_template_part($slug, $name);
31
-    }
19
+	/**
20
+	 * espresso_get_template_part
21
+	 * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead, and doesn't add base versions of files
22
+	 * so not a very useful function at all except that it adds familiarity PLUS filtering based off of the entire template part name
23
+	 *
24
+	 * @param string $slug The slug name for the generic template.
25
+	 * @param string $name The name of the specialised template.
26
+	 * @return string        the html output for the formatted money value
27
+	 */
28
+	function espresso_get_template_part($slug = null, $name = null)
29
+	{
30
+		EEH_Template::get_template_part($slug, $name);
31
+	}
32 32
 }
33 33
 
34 34
 
35 35
 if ( ! function_exists('espresso_get_object_css_class')) {
36
-    /**
37
-     * espresso_get_object_css_class - attempts to generate a css class based on the type of EE object passed
38
-     *
39
-     * @param EE_Base_Class $object the EE object the css class is being generated for
40
-     * @param  string       $prefix added to the beginning of the generated class
41
-     * @param  string       $suffix added to the end of the generated class
42
-     * @return string
43
-     */
44
-    function espresso_get_object_css_class($object = null, $prefix = '', $suffix = '')
45
-    {
46
-        return EEH_Template::get_object_css_class($object, $prefix, $suffix);
47
-    }
36
+	/**
37
+	 * espresso_get_object_css_class - attempts to generate a css class based on the type of EE object passed
38
+	 *
39
+	 * @param EE_Base_Class $object the EE object the css class is being generated for
40
+	 * @param  string       $prefix added to the beginning of the generated class
41
+	 * @param  string       $suffix added to the end of the generated class
42
+	 * @return string
43
+	 */
44
+	function espresso_get_object_css_class($object = null, $prefix = '', $suffix = '')
45
+	{
46
+		return EEH_Template::get_object_css_class($object, $prefix, $suffix);
47
+	}
48 48
 }
49 49
 
50 50
 
@@ -59,650 +59,650 @@  discard block
 block discarded – undo
59 59
 class EEH_Template
60 60
 {
61 61
 
62
-    private static $_espresso_themes = array();
63
-
64
-
65
-    /**
66
-     *    is_espresso_theme - returns TRUE or FALSE on whether the currently active WP theme is an espresso theme
67
-     *
68
-     * @return boolean
69
-     */
70
-    public static function is_espresso_theme()
71
-    {
72
-        return wp_get_theme()->get('TextDomain') == 'event_espresso' ? true : false;
73
-    }
74
-
75
-    /**
76
-     *    load_espresso_theme_functions - if current theme is an espresso theme, or uses ee theme template parts, then
77
-     *    load it's functions.php file ( if not already loaded )
78
-     *
79
-     * @return void
80
-     */
81
-    public static function load_espresso_theme_functions()
82
-    {
83
-        if ( ! defined('EE_THEME_FUNCTIONS_LOADED')) {
84
-            if (is_readable(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php')) {
85
-                require_once(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php');
86
-            }
87
-        }
88
-    }
89
-
90
-
91
-    /**
92
-     *    get_espresso_themes - returns an array of Espresso Child themes located in the /templates/ directory
93
-     *
94
-     * @return array
95
-     */
96
-    public static function get_espresso_themes()
97
-    {
98
-        if (empty(EEH_Template::$_espresso_themes)) {
99
-            $espresso_themes = glob(EE_PUBLIC . '*', GLOB_ONLYDIR);
100
-            if (empty($espresso_themes)) {
101
-                return array();
102
-            }
103
-            if (($key = array_search('global_assets', $espresso_themes)) !== false) {
104
-                unset($espresso_themes[$key]);
105
-            }
106
-            EEH_Template::$_espresso_themes = array();
107
-            foreach ($espresso_themes as $espresso_theme) {
108
-                EEH_Template::$_espresso_themes[basename($espresso_theme)] = $espresso_theme;
109
-            }
110
-        }
111
-        return EEH_Template::$_espresso_themes;
112
-    }
113
-
114
-
115
-    /**
116
-     * EEH_Template::get_template_part
117
-     * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead,
118
-     * and doesn't add base versions of files so not a very useful function at all except that it adds familiarity PLUS
119
-     * filtering based off of the entire template part name
120
-     *
121
-     * @param string $slug The slug name for the generic template.
122
-     * @param string $name The name of the specialised template.
123
-     * @param array  $template_args
124
-     * @param bool   $return_string
125
-     * @return string        the html output for the formatted money value
126
-     */
127
-    public static function get_template_part(
128
-        $slug = null,
129
-        $name = null,
130
-        $template_args = array(),
131
-        $return_string = false
132
-    ) {
133
-        do_action("get_template_part_{$slug}-{$name}", $slug, $name);
134
-        $templates = array();
135
-        $name      = (string)$name;
136
-        if ($name != '') {
137
-            $templates[] = "{$slug}-{$name}.php";
138
-        }
139
-        // allow template parts to be turned off via something like: add_filter( 'FHEE__content_espresso_events_tickets_template__display_datetimes', '__return_false' );
140
-        if (apply_filters("FHEE__EEH_Template__get_template_part__display__{$slug}_{$name}", true)) {
141
-            EEH_Template::locate_template($templates, $template_args, true, $return_string);
142
-        }
143
-    }
144
-
145
-
146
-    /**
147
-     *    locate_template
148
-     *    locate a template file by looking in the following places, in the following order:
149
-     *        <server path up to>/wp-content/themes/<current active WordPress theme>/
150
-     *        <assumed full absolute server path>
151
-     *        <server path up to>/wp-content/uploads/espresso/templates/<current EE theme>/
152
-     *        <server path up to>/wp-content/uploads/espresso/templates/
153
-     *        <server path up to>/wp-content/plugins/<EE4 folder>/public/<current EE theme>/
154
-     *        <server path up to>/wp-content/plugins/<EE4 folder>/core/templates/<current EE theme>/
155
-     *        <server path up to>/wp-content/plugins/<EE4 folder>/
156
-     *    as soon as the template is found in one of these locations, it will be returned or loaded
157
-     *        Example:
158
-     *          You are using the WordPress Twenty Sixteen theme,
159
-     *        and you want to customize the "some-event.template.php" template,
160
-     *          which is located in the "/relative/path/to/" folder relative to the main EE plugin folder.
161
-     *          Assuming WP is installed on your server in the "/home/public_html/" folder,
162
-     *        EEH_Template::locate_template() will look at the following paths in order until the template is found:
163
-     *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
164
-     *        /relative/path/to/some-event.template.php
165
-     *        /home/public_html/wp-content/uploads/espresso/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
166
-     *        /home/public_html/wp-content/uploads/espresso/templates/relative/path/to/some-event.template.php
167
-     *        /home/public_html/wp-content/plugins/event-espresso-core-reg/public/Espresso_Arabica_2014/relative/path/to/some-event.template.php
168
-     *        /home/public_html/wp-content/plugins/event-espresso-core-reg/core/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
169
-     *        /home/public_html/wp-content/plugins/event-espresso-core-reg/relative/path/to/some-event.template.php
170
-     *          Had you passed an absolute path to your template that was in some other location,
171
-     *        ie: "/absolute/path/to/some-event.template.php"
172
-     *          then the search would have been :
173
-     *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
174
-     *        /absolute/path/to/some-event.template.php
175
-     *          and stopped there upon finding it in the second location
176
-     *
177
-     * @param array|string $templates       array of template file names including extension (or just a single string)
178
-     * @param  array       $template_args   an array of arguments to be extracted for use in the template
179
-     * @param  boolean     $load            whether to pass the located template path on to the
180
-     *                                      EEH_Template::display_template() method or simply return it
181
-     * @param  boolean     $return_string   whether to send output immediately to screen, or capture and return as a
182
-     *                                      string
183
-     * @param boolean      $check_if_custom If TRUE, this flags this method to return boolean for whether this will
184
-     *                                      generate a custom template or not. Used in places where you don't actually
185
-     *                                      load the template, you just want to know if there's a custom version of it.
186
-     * @return mixed
187
-     */
188
-    public static function locate_template(
189
-        $templates = array(),
190
-        $template_args = array(),
191
-        $load = true,
192
-        $return_string = true,
193
-        $check_if_custom = false
194
-    ) {
195
-        // first use WP locate_template to check for template in the current theme folder
196
-        $template_path = locate_template($templates);
197
-
198
-        if ($check_if_custom && ! empty($template_path)) {
199
-            return true;
200
-        }
201
-
202
-        // not in the theme
203
-        if (empty($template_path)) {
204
-            // not even a template to look for ?
205
-            if (empty($templates)) {
206
-                // get post_type
207
-                $post_type = EE_Registry::instance()->REQ->get('post_type');
208
-                // get array of EE Custom Post Types
209
-                $EE_CPTs = EE_Register_CPTs::get_CPTs();
210
-                // build template name based on request
211
-                if (isset($EE_CPTs[$post_type])) {
212
-                    $archive_or_single = is_archive() ? 'archive' : '';
213
-                    $archive_or_single = is_single() ? 'single' : $archive_or_single;
214
-                    $templates         = $archive_or_single . '-' . $post_type . '.php';
215
-                }
216
-            }
217
-            // currently active EE template theme
218
-            $current_theme = EE_Config::get_current_theme();
219
-
220
-            // array of paths to folders that may contain templates
221
-            $template_folder_paths = array(
222
-                // first check the /wp-content/uploads/espresso/templates/(current EE theme)/  folder for an EE theme template file
223
-                EVENT_ESPRESSO_TEMPLATE_DIR . $current_theme,
224
-                // then in the root of the /wp-content/uploads/espresso/templates/ folder
225
-                EVENT_ESPRESSO_TEMPLATE_DIR,
226
-            );
227
-
228
-            //add core plugin folders for checking only if we're not $check_if_custom
229
-            if ( ! $check_if_custom) {
230
-                $core_paths            = array(
231
-                    // in the  /wp-content/plugins/(EE4 folder)/public/(current EE theme)/ folder within the plugin
232
-                    EE_PUBLIC . $current_theme,
233
-                    // in the  /wp-content/plugins/(EE4 folder)/core/templates/(current EE theme)/ folder within the plugin
234
-                    EE_TEMPLATES . $current_theme,
235
-                    // or maybe relative from the plugin root: /wp-content/plugins/(EE4 folder)/
236
-                    EE_PLUGIN_DIR_PATH,
237
-                );
238
-                $template_folder_paths = array_merge($template_folder_paths, $core_paths);
239
-            }
240
-
241
-            // now filter that array
242
-            $template_folder_paths = apply_filters('FHEE__EEH_Template__locate_template__template_folder_paths',
243
-                $template_folder_paths);
244
-            $templates             = is_array($templates) ? $templates : array($templates);
245
-            $template_folder_paths = is_array($template_folder_paths) ? $template_folder_paths : array($template_folder_paths);
246
-            // array to hold all possible template paths
247
-            $full_template_paths = array();
248
-
249
-            // loop through $templates
250
-            foreach ($templates as $template) {
251
-                // normalize directory separators
252
-                $template                      = EEH_File::standardise_directory_separators($template);
253
-                $file_name                     = basename($template);
254
-                $template_path_minus_file_name = substr($template, 0, (strlen($file_name) * -1));
255
-                // while looping through all template folder paths
256
-                foreach ($template_folder_paths as $template_folder_path) {
257
-                    // normalize directory separators
258
-                    $template_folder_path = EEH_File::standardise_directory_separators($template_folder_path);
259
-                    // determine if any common base path exists between the two paths
260
-                    $common_base_path = EEH_Template::_find_common_base_path(
261
-                        array($template_folder_path, $template_path_minus_file_name)
262
-                    );
263
-                    if ($common_base_path !== '') {
264
-                        // both paths have a common base, so just tack the filename onto our search path
265
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $file_name;
266
-                    } else {
267
-                        // no common base path, so let's just concatenate
268
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $template;
269
-                    }
270
-                    // build up our template locations array by adding our resolved paths
271
-                    $full_template_paths[] = $resolved_path;
272
-                }
273
-                // if $template is an absolute path, then we'll tack it onto the start of our array so that it gets searched first
274
-                array_unshift($full_template_paths, $template);
275
-                // path to the directory of the current theme: /wp-content/themes/(current WP theme)/
276
-                array_unshift($full_template_paths, get_stylesheet_directory() . DS . $file_name);
277
-            }
278
-            // filter final array of full template paths
279
-            $full_template_paths = apply_filters('FHEE__EEH_Template__locate_template__full_template_paths',
280
-                $full_template_paths, $file_name);
281
-            // now loop through our final array of template location paths and check each location
282
-            foreach ((array)$full_template_paths as $full_template_path) {
283
-                if (is_readable($full_template_path)) {
284
-                    $template_path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $full_template_path);
285
-                    break;
286
-                }
287
-            }
288
-        }
289
-
290
-        // hook that can be used to display the full template path that will be used
291
-        do_action('AHEE__EEH_Template__locate_template__full_template_path', $template_path);
292
-
293
-        // if we got it and you want to see it...
294
-        if ($template_path && $load && ! $check_if_custom) {
295
-            if ($return_string) {
296
-                return EEH_Template::display_template($template_path, $template_args, true);
297
-            } else {
298
-                EEH_Template::display_template($template_path, $template_args, false);
299
-            }
300
-        }
301
-        return $check_if_custom && ! empty($template_path) ? true : $template_path;
302
-    }
303
-
304
-
305
-    /**
306
-     * _find_common_base_path
307
-     * given two paths, this determines if there is a common base path between the two
308
-     *
309
-     * @param array $paths
310
-     * @return string
311
-     */
312
-    protected static function _find_common_base_path($paths)
313
-    {
314
-        $last_offset      = 0;
315
-        $common_base_path = '';
316
-        while (($index = strpos($paths[0], DS, $last_offset)) !== false) {
317
-            $dir_length = $index - $last_offset + 1;
318
-            $directory  = substr($paths[0], $last_offset, $dir_length);
319
-            foreach ($paths as $path) {
320
-                if (substr($path, $last_offset, $dir_length) != $directory) {
321
-                    return $common_base_path;
322
-                }
323
-            }
324
-            $common_base_path .= $directory;
325
-            $last_offset = $index + 1;
326
-        }
327
-        return substr($common_base_path, 0, -1);
328
-    }
329
-
330
-
331
-    /**
332
-     * load and display a template
333
-     *
334
-     * @param bool|string $template_path server path to the file to be loaded, including file name and extension
335
-     * @param  array      $template_args an array of arguments to be extracted for use in the template
336
-     * @param  boolean    $return_string whether to send output immediately to screen, or capture and return as a string
337
-     * @param bool        $throw_exceptions if set to true, will throw an exception if the template is either
338
-     *                                      not found or is not readable
339
-     * @return mixed string
340
-     * @throws \DomainException
341
-     */
62
+	private static $_espresso_themes = array();
63
+
64
+
65
+	/**
66
+	 *    is_espresso_theme - returns TRUE or FALSE on whether the currently active WP theme is an espresso theme
67
+	 *
68
+	 * @return boolean
69
+	 */
70
+	public static function is_espresso_theme()
71
+	{
72
+		return wp_get_theme()->get('TextDomain') == 'event_espresso' ? true : false;
73
+	}
74
+
75
+	/**
76
+	 *    load_espresso_theme_functions - if current theme is an espresso theme, or uses ee theme template parts, then
77
+	 *    load it's functions.php file ( if not already loaded )
78
+	 *
79
+	 * @return void
80
+	 */
81
+	public static function load_espresso_theme_functions()
82
+	{
83
+		if ( ! defined('EE_THEME_FUNCTIONS_LOADED')) {
84
+			if (is_readable(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php')) {
85
+				require_once(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php');
86
+			}
87
+		}
88
+	}
89
+
90
+
91
+	/**
92
+	 *    get_espresso_themes - returns an array of Espresso Child themes located in the /templates/ directory
93
+	 *
94
+	 * @return array
95
+	 */
96
+	public static function get_espresso_themes()
97
+	{
98
+		if (empty(EEH_Template::$_espresso_themes)) {
99
+			$espresso_themes = glob(EE_PUBLIC . '*', GLOB_ONLYDIR);
100
+			if (empty($espresso_themes)) {
101
+				return array();
102
+			}
103
+			if (($key = array_search('global_assets', $espresso_themes)) !== false) {
104
+				unset($espresso_themes[$key]);
105
+			}
106
+			EEH_Template::$_espresso_themes = array();
107
+			foreach ($espresso_themes as $espresso_theme) {
108
+				EEH_Template::$_espresso_themes[basename($espresso_theme)] = $espresso_theme;
109
+			}
110
+		}
111
+		return EEH_Template::$_espresso_themes;
112
+	}
113
+
114
+
115
+	/**
116
+	 * EEH_Template::get_template_part
117
+	 * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead,
118
+	 * and doesn't add base versions of files so not a very useful function at all except that it adds familiarity PLUS
119
+	 * filtering based off of the entire template part name
120
+	 *
121
+	 * @param string $slug The slug name for the generic template.
122
+	 * @param string $name The name of the specialised template.
123
+	 * @param array  $template_args
124
+	 * @param bool   $return_string
125
+	 * @return string        the html output for the formatted money value
126
+	 */
127
+	public static function get_template_part(
128
+		$slug = null,
129
+		$name = null,
130
+		$template_args = array(),
131
+		$return_string = false
132
+	) {
133
+		do_action("get_template_part_{$slug}-{$name}", $slug, $name);
134
+		$templates = array();
135
+		$name      = (string)$name;
136
+		if ($name != '') {
137
+			$templates[] = "{$slug}-{$name}.php";
138
+		}
139
+		// allow template parts to be turned off via something like: add_filter( 'FHEE__content_espresso_events_tickets_template__display_datetimes', '__return_false' );
140
+		if (apply_filters("FHEE__EEH_Template__get_template_part__display__{$slug}_{$name}", true)) {
141
+			EEH_Template::locate_template($templates, $template_args, true, $return_string);
142
+		}
143
+	}
144
+
145
+
146
+	/**
147
+	 *    locate_template
148
+	 *    locate a template file by looking in the following places, in the following order:
149
+	 *        <server path up to>/wp-content/themes/<current active WordPress theme>/
150
+	 *        <assumed full absolute server path>
151
+	 *        <server path up to>/wp-content/uploads/espresso/templates/<current EE theme>/
152
+	 *        <server path up to>/wp-content/uploads/espresso/templates/
153
+	 *        <server path up to>/wp-content/plugins/<EE4 folder>/public/<current EE theme>/
154
+	 *        <server path up to>/wp-content/plugins/<EE4 folder>/core/templates/<current EE theme>/
155
+	 *        <server path up to>/wp-content/plugins/<EE4 folder>/
156
+	 *    as soon as the template is found in one of these locations, it will be returned or loaded
157
+	 *        Example:
158
+	 *          You are using the WordPress Twenty Sixteen theme,
159
+	 *        and you want to customize the "some-event.template.php" template,
160
+	 *          which is located in the "/relative/path/to/" folder relative to the main EE plugin folder.
161
+	 *          Assuming WP is installed on your server in the "/home/public_html/" folder,
162
+	 *        EEH_Template::locate_template() will look at the following paths in order until the template is found:
163
+	 *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
164
+	 *        /relative/path/to/some-event.template.php
165
+	 *        /home/public_html/wp-content/uploads/espresso/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
166
+	 *        /home/public_html/wp-content/uploads/espresso/templates/relative/path/to/some-event.template.php
167
+	 *        /home/public_html/wp-content/plugins/event-espresso-core-reg/public/Espresso_Arabica_2014/relative/path/to/some-event.template.php
168
+	 *        /home/public_html/wp-content/plugins/event-espresso-core-reg/core/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
169
+	 *        /home/public_html/wp-content/plugins/event-espresso-core-reg/relative/path/to/some-event.template.php
170
+	 *          Had you passed an absolute path to your template that was in some other location,
171
+	 *        ie: "/absolute/path/to/some-event.template.php"
172
+	 *          then the search would have been :
173
+	 *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
174
+	 *        /absolute/path/to/some-event.template.php
175
+	 *          and stopped there upon finding it in the second location
176
+	 *
177
+	 * @param array|string $templates       array of template file names including extension (or just a single string)
178
+	 * @param  array       $template_args   an array of arguments to be extracted for use in the template
179
+	 * @param  boolean     $load            whether to pass the located template path on to the
180
+	 *                                      EEH_Template::display_template() method or simply return it
181
+	 * @param  boolean     $return_string   whether to send output immediately to screen, or capture and return as a
182
+	 *                                      string
183
+	 * @param boolean      $check_if_custom If TRUE, this flags this method to return boolean for whether this will
184
+	 *                                      generate a custom template or not. Used in places where you don't actually
185
+	 *                                      load the template, you just want to know if there's a custom version of it.
186
+	 * @return mixed
187
+	 */
188
+	public static function locate_template(
189
+		$templates = array(),
190
+		$template_args = array(),
191
+		$load = true,
192
+		$return_string = true,
193
+		$check_if_custom = false
194
+	) {
195
+		// first use WP locate_template to check for template in the current theme folder
196
+		$template_path = locate_template($templates);
197
+
198
+		if ($check_if_custom && ! empty($template_path)) {
199
+			return true;
200
+		}
201
+
202
+		// not in the theme
203
+		if (empty($template_path)) {
204
+			// not even a template to look for ?
205
+			if (empty($templates)) {
206
+				// get post_type
207
+				$post_type = EE_Registry::instance()->REQ->get('post_type');
208
+				// get array of EE Custom Post Types
209
+				$EE_CPTs = EE_Register_CPTs::get_CPTs();
210
+				// build template name based on request
211
+				if (isset($EE_CPTs[$post_type])) {
212
+					$archive_or_single = is_archive() ? 'archive' : '';
213
+					$archive_or_single = is_single() ? 'single' : $archive_or_single;
214
+					$templates         = $archive_or_single . '-' . $post_type . '.php';
215
+				}
216
+			}
217
+			// currently active EE template theme
218
+			$current_theme = EE_Config::get_current_theme();
219
+
220
+			// array of paths to folders that may contain templates
221
+			$template_folder_paths = array(
222
+				// first check the /wp-content/uploads/espresso/templates/(current EE theme)/  folder for an EE theme template file
223
+				EVENT_ESPRESSO_TEMPLATE_DIR . $current_theme,
224
+				// then in the root of the /wp-content/uploads/espresso/templates/ folder
225
+				EVENT_ESPRESSO_TEMPLATE_DIR,
226
+			);
227
+
228
+			//add core plugin folders for checking only if we're not $check_if_custom
229
+			if ( ! $check_if_custom) {
230
+				$core_paths            = array(
231
+					// in the  /wp-content/plugins/(EE4 folder)/public/(current EE theme)/ folder within the plugin
232
+					EE_PUBLIC . $current_theme,
233
+					// in the  /wp-content/plugins/(EE4 folder)/core/templates/(current EE theme)/ folder within the plugin
234
+					EE_TEMPLATES . $current_theme,
235
+					// or maybe relative from the plugin root: /wp-content/plugins/(EE4 folder)/
236
+					EE_PLUGIN_DIR_PATH,
237
+				);
238
+				$template_folder_paths = array_merge($template_folder_paths, $core_paths);
239
+			}
240
+
241
+			// now filter that array
242
+			$template_folder_paths = apply_filters('FHEE__EEH_Template__locate_template__template_folder_paths',
243
+				$template_folder_paths);
244
+			$templates             = is_array($templates) ? $templates : array($templates);
245
+			$template_folder_paths = is_array($template_folder_paths) ? $template_folder_paths : array($template_folder_paths);
246
+			// array to hold all possible template paths
247
+			$full_template_paths = array();
248
+
249
+			// loop through $templates
250
+			foreach ($templates as $template) {
251
+				// normalize directory separators
252
+				$template                      = EEH_File::standardise_directory_separators($template);
253
+				$file_name                     = basename($template);
254
+				$template_path_minus_file_name = substr($template, 0, (strlen($file_name) * -1));
255
+				// while looping through all template folder paths
256
+				foreach ($template_folder_paths as $template_folder_path) {
257
+					// normalize directory separators
258
+					$template_folder_path = EEH_File::standardise_directory_separators($template_folder_path);
259
+					// determine if any common base path exists between the two paths
260
+					$common_base_path = EEH_Template::_find_common_base_path(
261
+						array($template_folder_path, $template_path_minus_file_name)
262
+					);
263
+					if ($common_base_path !== '') {
264
+						// both paths have a common base, so just tack the filename onto our search path
265
+						$resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $file_name;
266
+					} else {
267
+						// no common base path, so let's just concatenate
268
+						$resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $template;
269
+					}
270
+					// build up our template locations array by adding our resolved paths
271
+					$full_template_paths[] = $resolved_path;
272
+				}
273
+				// if $template is an absolute path, then we'll tack it onto the start of our array so that it gets searched first
274
+				array_unshift($full_template_paths, $template);
275
+				// path to the directory of the current theme: /wp-content/themes/(current WP theme)/
276
+				array_unshift($full_template_paths, get_stylesheet_directory() . DS . $file_name);
277
+			}
278
+			// filter final array of full template paths
279
+			$full_template_paths = apply_filters('FHEE__EEH_Template__locate_template__full_template_paths',
280
+				$full_template_paths, $file_name);
281
+			// now loop through our final array of template location paths and check each location
282
+			foreach ((array)$full_template_paths as $full_template_path) {
283
+				if (is_readable($full_template_path)) {
284
+					$template_path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $full_template_path);
285
+					break;
286
+				}
287
+			}
288
+		}
289
+
290
+		// hook that can be used to display the full template path that will be used
291
+		do_action('AHEE__EEH_Template__locate_template__full_template_path', $template_path);
292
+
293
+		// if we got it and you want to see it...
294
+		if ($template_path && $load && ! $check_if_custom) {
295
+			if ($return_string) {
296
+				return EEH_Template::display_template($template_path, $template_args, true);
297
+			} else {
298
+				EEH_Template::display_template($template_path, $template_args, false);
299
+			}
300
+		}
301
+		return $check_if_custom && ! empty($template_path) ? true : $template_path;
302
+	}
303
+
304
+
305
+	/**
306
+	 * _find_common_base_path
307
+	 * given two paths, this determines if there is a common base path between the two
308
+	 *
309
+	 * @param array $paths
310
+	 * @return string
311
+	 */
312
+	protected static function _find_common_base_path($paths)
313
+	{
314
+		$last_offset      = 0;
315
+		$common_base_path = '';
316
+		while (($index = strpos($paths[0], DS, $last_offset)) !== false) {
317
+			$dir_length = $index - $last_offset + 1;
318
+			$directory  = substr($paths[0], $last_offset, $dir_length);
319
+			foreach ($paths as $path) {
320
+				if (substr($path, $last_offset, $dir_length) != $directory) {
321
+					return $common_base_path;
322
+				}
323
+			}
324
+			$common_base_path .= $directory;
325
+			$last_offset = $index + 1;
326
+		}
327
+		return substr($common_base_path, 0, -1);
328
+	}
329
+
330
+
331
+	/**
332
+	 * load and display a template
333
+	 *
334
+	 * @param bool|string $template_path server path to the file to be loaded, including file name and extension
335
+	 * @param  array      $template_args an array of arguments to be extracted for use in the template
336
+	 * @param  boolean    $return_string whether to send output immediately to screen, or capture and return as a string
337
+	 * @param bool        $throw_exceptions if set to true, will throw an exception if the template is either
338
+	 *                                      not found or is not readable
339
+	 * @return mixed string
340
+	 * @throws \DomainException
341
+	 */
342 342
 	public static function display_template(
343
-        $template_path    = false,
344
-        $template_args    = array(),
345
-        $return_string    = false,
346
-        $throw_exceptions = false
347
-    ) {
348
-
349
-        /**
350
-         * These two filters are intended for last minute changes to templates being loaded and/or template arg
351
-         * modifications.  NOTE... modifying these things can cause breakage as most templates running through
352
-         * the display_template method are templates we DON'T want modified (usually because of js
353
-         * dependencies etc).  So unless you know what you are doing, do NOT filter templates or template args
354
-         * using this.
355
-         *
356
-         * @since 4.6.0
357
-         */
358
-        $template_path = (string) apply_filters('FHEE__EEH_Template__display_template__template_path', $template_path);
359
-        $template_args = (array) apply_filters('FHEE__EEH_Template__display_template__template_args', $template_args);
360
-
361
-        // you gimme nuttin - YOU GET NUTTIN !!
362
-        if ( ! $template_path || ! is_readable($template_path)) {
363
-            return '';
364
-        }
365
-        // if $template_args are not in an array, then make it so
366
-        if ( ! is_array($template_args) && ! is_object($template_args)) {
367
-            $template_args = array($template_args);
368
-        }
369
-        extract( $template_args, EXTR_SKIP );
370
-        // ignore whether template is accessible ?
371
-        if ( $throw_exceptions && ! is_readable( $template_path ) ) {
372
-            throw new \DomainException(
373
-                    esc_html__(
374
-                            'Invalid, unreadable, or missing file.',
375
-                            'event_espresso'
376
-                    )
377
-            );
378
-        }
379
-
380
-
381
-        if ($return_string) {
382
-            // because we want to return a string, we are going to capture the output
383
-            ob_start();
384
-            include($template_path);
385
-            return ob_get_clean();
386
-        } else {
387
-            include($template_path);
388
-        }
389
-        return '';
390
-    }
391
-
392
-
393
-    /**
394
-     * get_object_css_class - attempts to generate a css class based on the type of EE object passed
395
-     *
396
-     * @param EE_Base_Class $object the EE object the css class is being generated for
397
-     * @param  string       $prefix added to the beginning of the generated class
398
-     * @param  string       $suffix added to the end of the generated class
399
-     * @return string
400
-     */
401
-    public static function get_object_css_class($object = null, $prefix = '', $suffix = '')
402
-    {
403
-        // in the beginning...
404
-        $prefix = ! empty($prefix) ? rtrim($prefix, '-') . '-' : '';
405
-        // da muddle
406
-        $class = '';
407
-        // the end
408
-        $suffix = ! empty($suffix) ? '-' . ltrim($suffix, '-') : '';
409
-        // is the passed object an EE object ?
410
-        if ($object instanceof EE_Base_Class) {
411
-            // grab the exact type of object
412
-            $obj_class = get_class($object);
413
-            // depending on the type of object...
414
-            switch ($obj_class) {
415
-                // no specifics just yet...
416
-                default :
417
-                    $class = strtolower(str_replace('_', '-', $obj_class));
418
-                    $class .= method_exists($obj_class, 'name') ? '-' . sanitize_title($object->name()) : '';
419
-
420
-            }
421
-        }
422
-        return $prefix . $class . $suffix;
423
-    }
424
-
425
-
426
-
427
-    /**
428
-     * EEH_Template::format_currency
429
-     * This helper takes a raw float value and formats it according to the default config country currency settings, or
430
-     * the country currency settings from the supplied country ISO code
431
-     *
432
-     * @param  float   $amount       raw money value
433
-     * @param  boolean $return_raw   whether to return the formatted float value only with no currency sign or code
434
-     * @param  boolean $display_code whether to display the country code (USD). Default = TRUE
435
-     * @param string   $CNT_ISO      2 letter ISO code for a country
436
-     * @param string   $cur_code_span_class
437
-     * @return string        the html output for the formatted money value
438
-     * @throws \EE_Error
439
-     */
440
-    public static function format_currency(
441
-        $amount = null,
442
-        $return_raw = false,
443
-        $display_code = true,
444
-        $CNT_ISO = '',
445
-        $cur_code_span_class = 'currency-code'
446
-    ) {
447
-        // ensure amount was received
448
-        if ($amount === null) {
449
-            $msg = __('In order to format currency, an amount needs to be passed.', 'event_espresso');
450
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
451
-            return '';
452
-        }
453
-        //ensure amount is float
454
-        $amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float)$amount);
455
-        $CNT_ISO = apply_filters('FHEE__EEH_Template__format_currency__CNT_ISO', $CNT_ISO, $amount);
456
-        // filter raw amount (allows 0.00 to be changed to "free" for example)
457
-        $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount', $amount, $return_raw);
458
-        // still a number or was amount converted to a string like "free" ?
459
-        if (is_float($amount_formatted)) {
460
-            // was a country ISO code passed ? if so generate currency config object for that country
461
-            $mny = $CNT_ISO !== '' ? new EE_Currency_Config($CNT_ISO) : null;
462
-            // verify results
463
-            if ( ! $mny instanceof EE_Currency_Config) {
464
-                // set default config country currency settings
465
-                $mny = EE_Registry::instance()->CFG->currency instanceof EE_Currency_Config
466
-                    ? EE_Registry::instance()->CFG->currency
467
-                    : new EE_Currency_Config();
468
-            }
469
-            // format float
470
-            $amount_formatted = number_format($amount, $mny->dec_plc, $mny->dec_mrk, $mny->thsnds);
471
-            // add formatting ?
472
-            if ( ! $return_raw) {
473
-                // add currency sign
474
-                if ($mny->sign_b4) {
475
-                    if ($amount >= 0) {
476
-                        $amount_formatted = $mny->sign . $amount_formatted;
477
-                    } else {
478
-                        $amount_formatted = '-' . $mny->sign . str_replace('-', '', $amount_formatted);
479
-                    }
480
-
481
-                } else {
482
-                    $amount_formatted = $amount_formatted . $mny->sign;
483
-                }
484
-
485
-                // filter to allow global setting of display_code
486
-                $display_code = apply_filters('FHEE__EEH_Template__format_currency__display_code', $display_code);
487
-
488
-                // add currency code ?
489
-                $amount_formatted = $display_code ? $amount_formatted . ' <span class="' . $cur_code_span_class . '">(' . $mny->code . ')</span>' : $amount_formatted;
490
-            }
491
-            // filter results
492
-            $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount_formatted',
493
-                $amount_formatted, $mny, $return_raw);
494
-        }
495
-        // clean up vars
496
-        unset($mny);
497
-        // return formatted currency amount
498
-        return $amount_formatted;
499
-    }
500
-
501
-
502
-    /**
503
-     * This function is used for outputting the localized label for a given status id in the schema requested (and
504
-     * possibly plural).  The intended use of this function is only for cases where wanting a label outside of a
505
-     * related status model or model object (i.e. in documentation etc.)
506
-     *
507
-     * @param  string  $status_id Status ID matching a registered status in the esp_status table.  If there is no
508
-     *                            match, then 'Unknown' will be returned.
509
-     * @param  boolean $plural    Whether to return plural or not
510
-     * @param  string  $schema    'UPPER', 'lower', or 'Sentence'
511
-     * @return string             The localized label for the status id.
512
-     */
513
-    public static function pretty_status($status_id, $plural = false, $schema = 'upper')
514
-    {
515
-        /** @type EEM_Status $EEM_Status */
516
-        $EEM_Status = EE_Registry::instance()->load_model('Status');
517
-        $status     = $EEM_Status->localized_status(array($status_id => __('unknown', 'event_espresso')), $plural,
518
-            $schema);
519
-        return $status[$status_id];
520
-    }
521
-
522
-
523
-    /**
524
-     * This helper just returns a button or link for the given parameters
525
-     *
526
-     * @param  string $url   the url for the link, note that `esc_url` will be called on it
527
-     * @param  string $label What is the label you want displayed for the button
528
-     * @param  string $class what class is used for the button (defaults to 'button-primary')
529
-     * @param string  $icon
530
-     * @param string  $title
531
-     * @return string the html output for the button
532
-     */
533
-    public static function get_button_or_link($url, $label, $class = 'button-primary', $icon = '', $title = '')
534
-    {
535
-        $icon_html = '';
536
-        if ( ! empty($icon)) {
537
-            $dashicons = preg_split("(ee-icon |dashicons )", $icon);
538
-            $dashicons = array_filter($dashicons);
539
-            $count     = count($dashicons);
540
-            $icon_html .= $count > 1 ? '<span class="ee-composite-dashicon">' : '';
541
-            foreach ($dashicons as $dashicon) {
542
-                $type = strpos($dashicon, 'ee-icon') !== false ? 'ee-icon ' : 'dashicons ';
543
-                $icon_html .= '<span class="' . $type . $dashicon . '"></span>';
544
-            }
545
-            $icon_html .= $count > 1 ? '</span>' : '';
546
-        }
547
-        $label  = ! empty($icon) ? $icon_html . $label : $label;
548
-        $button = '<a id="' . sanitize_title_with_dashes($label) . '" href="' . esc_url($url) . '" class="' . $class . '" title="' . $title . '">' . $label . '</a>';
549
-        return $button;
550
-    }
551
-
552
-
553
-    /**
554
-     * This returns a generated link that will load the related help tab on admin pages.
555
-     *
556
-     * @param  string     $help_tab_id the id for the connected help tab
557
-     * @param bool|string $page        The page identifier for the page the help tab is on
558
-     * @param bool|string $action      The action (route) for the admin page the help tab is on.
559
-     * @param bool|string $icon_style  (optional) include css class for the style you want to use for the help icon.
560
-     * @param bool|string $help_text   (optional) send help text you want to use for the link if default not to be used
561
-     * @return string              generated link
562
-     */
563
-    public static function get_help_tab_link(
564
-        $help_tab_id,
565
-        $page = false,
566
-        $action = false,
567
-        $icon_style = false,
568
-        $help_text = false
569
-    ) {
570
-
571
-        if ( ! $page) {
572
-            $page = isset($_REQUEST['page']) && ! empty($_REQUEST['page']) ? sanitize_key($_REQUEST['page']) : $page;
573
-        }
574
-
575
-        if ( ! $action) {
576
-            $action = isset($_REQUEST['action']) && ! empty($_REQUEST['action']) ? sanitize_key($_REQUEST['action']) : $action;
577
-        }
578
-
579
-        $action = empty($action) ? 'default' : $action;
580
-
581
-
582
-        $help_tab_lnk = $page . '-' . $action . '-' . $help_tab_id;
583
-        $icon         = ! $icon_style ? ' dashicons-editor-help' : $icon_style;
584
-        $help_text    = ! $help_text ? '' : $help_text;
585
-        return '<a id="' . $help_tab_lnk . '" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22' . $icon . '" title="' . esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
586
-                'event_espresso') . '" > ' . $help_text . ' </a>';
587
-    }
588
-
589
-
590
-    /**
591
-     * This helper generates the html structure for the jquery joyride plugin with the given params.
592
-     *
593
-     * @link http://zurb.com/playground/jquery-joyride-feature-tour-plugin
594
-     * @see  EE_Admin_Page->_stop_callback() for the construct expected for the $stops param.
595
-     * @param EE_Help_Tour
596
-     * @return string         html
597
-     */
598
-    public static function help_tour_stops_generator(EE_Help_Tour $tour)
599
-    {
600
-        $id    = $tour->get_slug();
601
-        $stops = $tour->get_stops();
602
-
603
-        $content = '<ol style="display:none" id="' . $id . '">';
604
-
605
-        foreach ($stops as $stop) {
606
-            $data_id    = ! empty($stop['id']) ? ' data-id="' . $stop['id'] . '"' : '';
607
-            $data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="' . $stop['class'] . '"' : '';
608
-
609
-            //if container is set to modal then let's make sure we set the options accordingly
610
-            if (empty($data_id) && empty($data_class)) {
611
-                $stop['options']['modal']  = true;
612
-                $stop['options']['expose'] = true;
613
-            }
614
-
615
-            $custom_class  = ! empty($stop['custom_class']) ? ' class="' . $stop['custom_class'] . '"' : '';
616
-            $button_text   = ! empty($stop['button_text']) ? ' data-button="' . $stop['button_text'] . '"' : '';
617
-            $inner_content = isset($stop['content']) ? $stop['content'] : '';
618
-
619
-            //options
620
-            if (isset($stop['options']) && is_array($stop['options'])) {
621
-                $options = ' data-options="';
622
-                foreach ($stop['options'] as $option => $value) {
623
-                    $options .= $option . ':' . $value . ';';
624
-                }
625
-                $options .= '"';
626
-            } else {
627
-                $options = '';
628
-            }
629
-
630
-            //let's put all together
631
-            $content .= '<li' . $data_id . $data_class . $custom_class . $button_text . $options . '>' . $inner_content . '</li>';
632
-        }
633
-
634
-        $content .= '</ol>';
635
-        return $content;
636
-    }
637
-
638
-
639
-    /**
640
-     * This is a helper method to generate a status legend for a given status array.
641
-     * Note this will only work if the incoming statuses have a key in the EEM_Status->localized_status() methods
642
-     * status_array.
643
-     *
644
-     * @param  array  $status_array  array of statuses that will make up the legend. In format:
645
-     *                               array(
646
-     *                               'status_item' => 'status_name'
647
-     *                               )
648
-     * @param  string $active_status This is used to indicate what the active status is IF that is to be highlighted in
649
-     *                               the legend.
650
-     * @throws EE_Error
651
-     * @return string               html structure for status.
652
-     */
653
-    public static function status_legend($status_array, $active_status = '')
654
-    {
655
-        if ( ! is_array($status_array)) {
656
-            throw new EE_Error(esc_html__('The EEH_Template::status_legend helper required the incoming status_array argument to be an array!',
657
-                'event_espresso'));
658
-        }
659
-
660
-        $setup_array = array();
661
-        foreach ($status_array as $item => $status) {
662
-            $setup_array[$item] = array(
663
-                'class'  => 'ee-status-legend ee-status-legend-' . $status,
664
-                'desc'   => EEH_Template::pretty_status($status, false, 'sentence'),
665
-                'status' => $status,
666
-            );
667
-        }
668
-
669
-        $content = '<div class="ee-list-table-legend-container">' . "\n";
670
-        $content .= '<h4 class="status-legend-title">' . esc_html__('Status Legend', 'event_espresso') . '</h4>' . "\n";
671
-        $content .= '<dl class="ee-list-table-legend">' . "\n\t";
672
-        foreach ($setup_array as $item => $details) {
673
-            $active_class = $active_status == $details['status'] ? ' class="ee-is-active-status"' : '';
674
-            $content .= '<dt id="ee-legend-item-tooltip-' . $item . '"' . $active_class . '>' . "\n\t\t";
675
-            $content .= '<span class="' . $details['class'] . '"></span>' . "\n\t\t";
676
-            $content .= '<span class="ee-legend-description">' . $details['desc'] . '</span>' . "\n\t";
677
-            $content .= '</dt>' . "\n";
678
-        }
679
-        $content .= '</dl>' . "\n";
680
-        $content .= '</div>' . "\n";
681
-        return $content;
682
-    }
683
-
684
-
685
-    /**
686
-     * Gets HTML for laying out a deeply-nested array (and objects) in a format
687
-     * that's nice for presenting in the wp admin
688
-     *
689
-     * @param mixed $data
690
-     * @return string
691
-     */
692
-    public static function layout_array_as_table($data)
693
-    {
694
-        if (is_object($data) || $data instanceof __PHP_Incomplete_Class) {
695
-            $data = (array)$data;
696
-        }
697
-        ob_start();
698
-        if (is_array($data)) {
699
-            if (EEH_Array::is_associative_array($data)) {
700
-                ?>
343
+		$template_path    = false,
344
+		$template_args    = array(),
345
+		$return_string    = false,
346
+		$throw_exceptions = false
347
+	) {
348
+
349
+		/**
350
+		 * These two filters are intended for last minute changes to templates being loaded and/or template arg
351
+		 * modifications.  NOTE... modifying these things can cause breakage as most templates running through
352
+		 * the display_template method are templates we DON'T want modified (usually because of js
353
+		 * dependencies etc).  So unless you know what you are doing, do NOT filter templates or template args
354
+		 * using this.
355
+		 *
356
+		 * @since 4.6.0
357
+		 */
358
+		$template_path = (string) apply_filters('FHEE__EEH_Template__display_template__template_path', $template_path);
359
+		$template_args = (array) apply_filters('FHEE__EEH_Template__display_template__template_args', $template_args);
360
+
361
+		// you gimme nuttin - YOU GET NUTTIN !!
362
+		if ( ! $template_path || ! is_readable($template_path)) {
363
+			return '';
364
+		}
365
+		// if $template_args are not in an array, then make it so
366
+		if ( ! is_array($template_args) && ! is_object($template_args)) {
367
+			$template_args = array($template_args);
368
+		}
369
+		extract( $template_args, EXTR_SKIP );
370
+		// ignore whether template is accessible ?
371
+		if ( $throw_exceptions && ! is_readable( $template_path ) ) {
372
+			throw new \DomainException(
373
+					esc_html__(
374
+							'Invalid, unreadable, or missing file.',
375
+							'event_espresso'
376
+					)
377
+			);
378
+		}
379
+
380
+
381
+		if ($return_string) {
382
+			// because we want to return a string, we are going to capture the output
383
+			ob_start();
384
+			include($template_path);
385
+			return ob_get_clean();
386
+		} else {
387
+			include($template_path);
388
+		}
389
+		return '';
390
+	}
391
+
392
+
393
+	/**
394
+	 * get_object_css_class - attempts to generate a css class based on the type of EE object passed
395
+	 *
396
+	 * @param EE_Base_Class $object the EE object the css class is being generated for
397
+	 * @param  string       $prefix added to the beginning of the generated class
398
+	 * @param  string       $suffix added to the end of the generated class
399
+	 * @return string
400
+	 */
401
+	public static function get_object_css_class($object = null, $prefix = '', $suffix = '')
402
+	{
403
+		// in the beginning...
404
+		$prefix = ! empty($prefix) ? rtrim($prefix, '-') . '-' : '';
405
+		// da muddle
406
+		$class = '';
407
+		// the end
408
+		$suffix = ! empty($suffix) ? '-' . ltrim($suffix, '-') : '';
409
+		// is the passed object an EE object ?
410
+		if ($object instanceof EE_Base_Class) {
411
+			// grab the exact type of object
412
+			$obj_class = get_class($object);
413
+			// depending on the type of object...
414
+			switch ($obj_class) {
415
+				// no specifics just yet...
416
+				default :
417
+					$class = strtolower(str_replace('_', '-', $obj_class));
418
+					$class .= method_exists($obj_class, 'name') ? '-' . sanitize_title($object->name()) : '';
419
+
420
+			}
421
+		}
422
+		return $prefix . $class . $suffix;
423
+	}
424
+
425
+
426
+
427
+	/**
428
+	 * EEH_Template::format_currency
429
+	 * This helper takes a raw float value and formats it according to the default config country currency settings, or
430
+	 * the country currency settings from the supplied country ISO code
431
+	 *
432
+	 * @param  float   $amount       raw money value
433
+	 * @param  boolean $return_raw   whether to return the formatted float value only with no currency sign or code
434
+	 * @param  boolean $display_code whether to display the country code (USD). Default = TRUE
435
+	 * @param string   $CNT_ISO      2 letter ISO code for a country
436
+	 * @param string   $cur_code_span_class
437
+	 * @return string        the html output for the formatted money value
438
+	 * @throws \EE_Error
439
+	 */
440
+	public static function format_currency(
441
+		$amount = null,
442
+		$return_raw = false,
443
+		$display_code = true,
444
+		$CNT_ISO = '',
445
+		$cur_code_span_class = 'currency-code'
446
+	) {
447
+		// ensure amount was received
448
+		if ($amount === null) {
449
+			$msg = __('In order to format currency, an amount needs to be passed.', 'event_espresso');
450
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
451
+			return '';
452
+		}
453
+		//ensure amount is float
454
+		$amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float)$amount);
455
+		$CNT_ISO = apply_filters('FHEE__EEH_Template__format_currency__CNT_ISO', $CNT_ISO, $amount);
456
+		// filter raw amount (allows 0.00 to be changed to "free" for example)
457
+		$amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount', $amount, $return_raw);
458
+		// still a number or was amount converted to a string like "free" ?
459
+		if (is_float($amount_formatted)) {
460
+			// was a country ISO code passed ? if so generate currency config object for that country
461
+			$mny = $CNT_ISO !== '' ? new EE_Currency_Config($CNT_ISO) : null;
462
+			// verify results
463
+			if ( ! $mny instanceof EE_Currency_Config) {
464
+				// set default config country currency settings
465
+				$mny = EE_Registry::instance()->CFG->currency instanceof EE_Currency_Config
466
+					? EE_Registry::instance()->CFG->currency
467
+					: new EE_Currency_Config();
468
+			}
469
+			// format float
470
+			$amount_formatted = number_format($amount, $mny->dec_plc, $mny->dec_mrk, $mny->thsnds);
471
+			// add formatting ?
472
+			if ( ! $return_raw) {
473
+				// add currency sign
474
+				if ($mny->sign_b4) {
475
+					if ($amount >= 0) {
476
+						$amount_formatted = $mny->sign . $amount_formatted;
477
+					} else {
478
+						$amount_formatted = '-' . $mny->sign . str_replace('-', '', $amount_formatted);
479
+					}
480
+
481
+				} else {
482
+					$amount_formatted = $amount_formatted . $mny->sign;
483
+				}
484
+
485
+				// filter to allow global setting of display_code
486
+				$display_code = apply_filters('FHEE__EEH_Template__format_currency__display_code', $display_code);
487
+
488
+				// add currency code ?
489
+				$amount_formatted = $display_code ? $amount_formatted . ' <span class="' . $cur_code_span_class . '">(' . $mny->code . ')</span>' : $amount_formatted;
490
+			}
491
+			// filter results
492
+			$amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount_formatted',
493
+				$amount_formatted, $mny, $return_raw);
494
+		}
495
+		// clean up vars
496
+		unset($mny);
497
+		// return formatted currency amount
498
+		return $amount_formatted;
499
+	}
500
+
501
+
502
+	/**
503
+	 * This function is used for outputting the localized label for a given status id in the schema requested (and
504
+	 * possibly plural).  The intended use of this function is only for cases where wanting a label outside of a
505
+	 * related status model or model object (i.e. in documentation etc.)
506
+	 *
507
+	 * @param  string  $status_id Status ID matching a registered status in the esp_status table.  If there is no
508
+	 *                            match, then 'Unknown' will be returned.
509
+	 * @param  boolean $plural    Whether to return plural or not
510
+	 * @param  string  $schema    'UPPER', 'lower', or 'Sentence'
511
+	 * @return string             The localized label for the status id.
512
+	 */
513
+	public static function pretty_status($status_id, $plural = false, $schema = 'upper')
514
+	{
515
+		/** @type EEM_Status $EEM_Status */
516
+		$EEM_Status = EE_Registry::instance()->load_model('Status');
517
+		$status     = $EEM_Status->localized_status(array($status_id => __('unknown', 'event_espresso')), $plural,
518
+			$schema);
519
+		return $status[$status_id];
520
+	}
521
+
522
+
523
+	/**
524
+	 * This helper just returns a button or link for the given parameters
525
+	 *
526
+	 * @param  string $url   the url for the link, note that `esc_url` will be called on it
527
+	 * @param  string $label What is the label you want displayed for the button
528
+	 * @param  string $class what class is used for the button (defaults to 'button-primary')
529
+	 * @param string  $icon
530
+	 * @param string  $title
531
+	 * @return string the html output for the button
532
+	 */
533
+	public static function get_button_or_link($url, $label, $class = 'button-primary', $icon = '', $title = '')
534
+	{
535
+		$icon_html = '';
536
+		if ( ! empty($icon)) {
537
+			$dashicons = preg_split("(ee-icon |dashicons )", $icon);
538
+			$dashicons = array_filter($dashicons);
539
+			$count     = count($dashicons);
540
+			$icon_html .= $count > 1 ? '<span class="ee-composite-dashicon">' : '';
541
+			foreach ($dashicons as $dashicon) {
542
+				$type = strpos($dashicon, 'ee-icon') !== false ? 'ee-icon ' : 'dashicons ';
543
+				$icon_html .= '<span class="' . $type . $dashicon . '"></span>';
544
+			}
545
+			$icon_html .= $count > 1 ? '</span>' : '';
546
+		}
547
+		$label  = ! empty($icon) ? $icon_html . $label : $label;
548
+		$button = '<a id="' . sanitize_title_with_dashes($label) . '" href="' . esc_url($url) . '" class="' . $class . '" title="' . $title . '">' . $label . '</a>';
549
+		return $button;
550
+	}
551
+
552
+
553
+	/**
554
+	 * This returns a generated link that will load the related help tab on admin pages.
555
+	 *
556
+	 * @param  string     $help_tab_id the id for the connected help tab
557
+	 * @param bool|string $page        The page identifier for the page the help tab is on
558
+	 * @param bool|string $action      The action (route) for the admin page the help tab is on.
559
+	 * @param bool|string $icon_style  (optional) include css class for the style you want to use for the help icon.
560
+	 * @param bool|string $help_text   (optional) send help text you want to use for the link if default not to be used
561
+	 * @return string              generated link
562
+	 */
563
+	public static function get_help_tab_link(
564
+		$help_tab_id,
565
+		$page = false,
566
+		$action = false,
567
+		$icon_style = false,
568
+		$help_text = false
569
+	) {
570
+
571
+		if ( ! $page) {
572
+			$page = isset($_REQUEST['page']) && ! empty($_REQUEST['page']) ? sanitize_key($_REQUEST['page']) : $page;
573
+		}
574
+
575
+		if ( ! $action) {
576
+			$action = isset($_REQUEST['action']) && ! empty($_REQUEST['action']) ? sanitize_key($_REQUEST['action']) : $action;
577
+		}
578
+
579
+		$action = empty($action) ? 'default' : $action;
580
+
581
+
582
+		$help_tab_lnk = $page . '-' . $action . '-' . $help_tab_id;
583
+		$icon         = ! $icon_style ? ' dashicons-editor-help' : $icon_style;
584
+		$help_text    = ! $help_text ? '' : $help_text;
585
+		return '<a id="' . $help_tab_lnk . '" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22' . $icon . '" title="' . esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
586
+				'event_espresso') . '" > ' . $help_text . ' </a>';
587
+	}
588
+
589
+
590
+	/**
591
+	 * This helper generates the html structure for the jquery joyride plugin with the given params.
592
+	 *
593
+	 * @link http://zurb.com/playground/jquery-joyride-feature-tour-plugin
594
+	 * @see  EE_Admin_Page->_stop_callback() for the construct expected for the $stops param.
595
+	 * @param EE_Help_Tour
596
+	 * @return string         html
597
+	 */
598
+	public static function help_tour_stops_generator(EE_Help_Tour $tour)
599
+	{
600
+		$id    = $tour->get_slug();
601
+		$stops = $tour->get_stops();
602
+
603
+		$content = '<ol style="display:none" id="' . $id . '">';
604
+
605
+		foreach ($stops as $stop) {
606
+			$data_id    = ! empty($stop['id']) ? ' data-id="' . $stop['id'] . '"' : '';
607
+			$data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="' . $stop['class'] . '"' : '';
608
+
609
+			//if container is set to modal then let's make sure we set the options accordingly
610
+			if (empty($data_id) && empty($data_class)) {
611
+				$stop['options']['modal']  = true;
612
+				$stop['options']['expose'] = true;
613
+			}
614
+
615
+			$custom_class  = ! empty($stop['custom_class']) ? ' class="' . $stop['custom_class'] . '"' : '';
616
+			$button_text   = ! empty($stop['button_text']) ? ' data-button="' . $stop['button_text'] . '"' : '';
617
+			$inner_content = isset($stop['content']) ? $stop['content'] : '';
618
+
619
+			//options
620
+			if (isset($stop['options']) && is_array($stop['options'])) {
621
+				$options = ' data-options="';
622
+				foreach ($stop['options'] as $option => $value) {
623
+					$options .= $option . ':' . $value . ';';
624
+				}
625
+				$options .= '"';
626
+			} else {
627
+				$options = '';
628
+			}
629
+
630
+			//let's put all together
631
+			$content .= '<li' . $data_id . $data_class . $custom_class . $button_text . $options . '>' . $inner_content . '</li>';
632
+		}
633
+
634
+		$content .= '</ol>';
635
+		return $content;
636
+	}
637
+
638
+
639
+	/**
640
+	 * This is a helper method to generate a status legend for a given status array.
641
+	 * Note this will only work if the incoming statuses have a key in the EEM_Status->localized_status() methods
642
+	 * status_array.
643
+	 *
644
+	 * @param  array  $status_array  array of statuses that will make up the legend. In format:
645
+	 *                               array(
646
+	 *                               'status_item' => 'status_name'
647
+	 *                               )
648
+	 * @param  string $active_status This is used to indicate what the active status is IF that is to be highlighted in
649
+	 *                               the legend.
650
+	 * @throws EE_Error
651
+	 * @return string               html structure for status.
652
+	 */
653
+	public static function status_legend($status_array, $active_status = '')
654
+	{
655
+		if ( ! is_array($status_array)) {
656
+			throw new EE_Error(esc_html__('The EEH_Template::status_legend helper required the incoming status_array argument to be an array!',
657
+				'event_espresso'));
658
+		}
659
+
660
+		$setup_array = array();
661
+		foreach ($status_array as $item => $status) {
662
+			$setup_array[$item] = array(
663
+				'class'  => 'ee-status-legend ee-status-legend-' . $status,
664
+				'desc'   => EEH_Template::pretty_status($status, false, 'sentence'),
665
+				'status' => $status,
666
+			);
667
+		}
668
+
669
+		$content = '<div class="ee-list-table-legend-container">' . "\n";
670
+		$content .= '<h4 class="status-legend-title">' . esc_html__('Status Legend', 'event_espresso') . '</h4>' . "\n";
671
+		$content .= '<dl class="ee-list-table-legend">' . "\n\t";
672
+		foreach ($setup_array as $item => $details) {
673
+			$active_class = $active_status == $details['status'] ? ' class="ee-is-active-status"' : '';
674
+			$content .= '<dt id="ee-legend-item-tooltip-' . $item . '"' . $active_class . '>' . "\n\t\t";
675
+			$content .= '<span class="' . $details['class'] . '"></span>' . "\n\t\t";
676
+			$content .= '<span class="ee-legend-description">' . $details['desc'] . '</span>' . "\n\t";
677
+			$content .= '</dt>' . "\n";
678
+		}
679
+		$content .= '</dl>' . "\n";
680
+		$content .= '</div>' . "\n";
681
+		return $content;
682
+	}
683
+
684
+
685
+	/**
686
+	 * Gets HTML for laying out a deeply-nested array (and objects) in a format
687
+	 * that's nice for presenting in the wp admin
688
+	 *
689
+	 * @param mixed $data
690
+	 * @return string
691
+	 */
692
+	public static function layout_array_as_table($data)
693
+	{
694
+		if (is_object($data) || $data instanceof __PHP_Incomplete_Class) {
695
+			$data = (array)$data;
696
+		}
697
+		ob_start();
698
+		if (is_array($data)) {
699
+			if (EEH_Array::is_associative_array($data)) {
700
+				?>
701 701
                 <table class="widefat">
702 702
                     <tbody>
703 703
                     <?php
704
-                    foreach ($data as $data_key => $data_values) {
705
-                        ?>
704
+					foreach ($data as $data_key => $data_values) {
705
+						?>
706 706
                         <tr>
707 707
                             <td>
708 708
                                 <?php echo $data_key; ?>
@@ -712,248 +712,248 @@  discard block
 block discarded – undo
712 712
                             </td>
713 713
                         </tr>
714 714
                         <?php
715
-                    } ?>
715
+					} ?>
716 716
                     </tbody>
717 717
                 </table>
718 718
                 <?php
719
-            } else {
720
-                ?>
719
+			} else {
720
+				?>
721 721
                 <ul>
722 722
                     <?php
723
-                    foreach ($data as $datum) {
724
-                        echo "<li>";
725
-                        echo self::layout_array_as_table($datum);
726
-                        echo "</li>";
727
-                    } ?>
723
+					foreach ($data as $datum) {
724
+						echo "<li>";
725
+						echo self::layout_array_as_table($datum);
726
+						echo "</li>";
727
+					} ?>
728 728
                 </ul>
729 729
                 <?php
730
-            }
731
-        } else {
732
-            //simple value
733
-            echo esc_html($data);
734
-        }
735
-        return ob_get_clean();
736
-    }
737
-
738
-
739
-    /**
740
-     * wrapper for self::get_paging_html() that simply echos the generated paging html
741
-     *
742
-     * @since 4.4.0
743
-     * @see   self:get_paging_html() for argument docs.
744
-     * @param        $total_items
745
-     * @param        $current
746
-     * @param        $per_page
747
-     * @param        $url
748
-     * @param bool   $show_num_field
749
-     * @param string $paged_arg_name
750
-     * @param array  $items_label
751
-     * @return string
752
-     */
753
-    public static function paging_html(
754
-        $total_items,
755
-        $current,
756
-        $per_page,
757
-        $url,
758
-        $show_num_field = true,
759
-        $paged_arg_name = 'paged',
760
-        $items_label = array()
761
-    ) {
762
-        echo self::get_paging_html($total_items, $current, $per_page, $url, $show_num_field, $paged_arg_name,
763
-            $items_label);
764
-    }
765
-
766
-
767
-    /**
768
-     * A method for generating paging similar to WP_List_Table
769
-     *
770
-     * @since    4.4.0
771
-     * @see      wp-admin/includes/class-wp-list-table.php WP_List_Table::pagination()
772
-     * @param  integer $total_items     How many total items there are to page.
773
-     * @param  integer $current         What the current page is.
774
-     * @param  integer $per_page        How many items per page.
775
-     * @param  string  $url             What the base url for page links is.
776
-     * @param  boolean $show_num_field  Whether to show the input for changing page number.
777
-     * @param  string  $paged_arg_name  The name of the key for the paged query argument.
778
-     * @param  array   $items_label     An array of singular/plural values for the items label:
779
-     *                                  array(
780
-     *                                  'single' => 'item',
781
-     *                                  'plural' => 'items'
782
-     *                                  )
783
-     * @return  string
784
-     */
785
-    public static function get_paging_html(
786
-        $total_items,
787
-        $current,
788
-        $per_page,
789
-        $url,
790
-        $show_num_field = true,
791
-        $paged_arg_name = 'paged',
792
-        $items_label = array()
793
-    ) {
794
-        $page_links     = array();
795
-        $disable_first  = $disable_last = '';
796
-        $total_items    = (int)$total_items;
797
-        $per_page       = (int)$per_page;
798
-        $current        = (int)$current;
799
-        $paged_arg_name = empty($paged_arg_name) ? 'paged' : sanitize_key($paged_arg_name);
800
-
801
-        //filter items_label
802
-        $items_label = apply_filters(
803
-            'FHEE__EEH_Template__get_paging_html__items_label',
804
-            $items_label
805
-        );
806
-
807
-        if (empty($items_label)
808
-            || ! is_array($items_label)
809
-            || ! isset($items_label['single'])
810
-            || ! isset($items_label['plural'])
811
-        ) {
812
-            $items_label = array(
813
-                'single' => __('1 item', 'event_espresso'),
814
-                'plural' => __('%s items', 'event_espresso'),
815
-            );
816
-        } else {
817
-            $items_label = array(
818
-                'single' => '1 ' . esc_html($items_label['single']),
819
-                'plural' => '%s ' . esc_html($items_label['plural']),
820
-            );
821
-        }
822
-
823
-        $total_pages = ceil($total_items / $per_page);
824
-
825
-        if ($total_pages <= 1) {
826
-            return '';
827
-        }
828
-
829
-        $item_label = $total_items > 1 ? sprintf($items_label['plural'], $total_items) : $items_label['single'];
830
-
831
-        $output = '<span class="displaying-num">' . $item_label . '</span>';
832
-
833
-        if ($current === 1) {
834
-            $disable_first = ' disabled';
835
-        }
836
-        if ($current == $total_pages) {
837
-            $disable_last = ' disabled';
838
-        }
839
-
840
-        $page_links[] = sprintf("<a class='%s' title='%s' href='%s'>%s</a>",
841
-            'first-page' . $disable_first,
842
-            esc_attr__('Go to the first page'),
843
-            esc_url(remove_query_arg($paged_arg_name, $url)),
844
-            '&laquo;'
845
-        );
846
-
847
-        $page_links[] = sprintf(
848
-            '<a class="%s" title="%s" href="%s">%s</a>',
849
-            'prev-page' . $disable_first,
850
-            esc_attr__('Go to the previous page'),
851
-            esc_url(add_query_arg($paged_arg_name, max(1, $current - 1), $url)),
852
-            '&lsaquo;'
853
-        );
854
-
855
-        if ( ! $show_num_field) {
856
-            $html_current_page = $current;
857
-        } else {
858
-            $html_current_page = sprintf("<input class='current-page' title='%s' type='text' name=$paged_arg_name value='%s' size='%d' />",
859
-                esc_attr__('Current page'),
860
-                $current,
861
-                strlen($total_pages)
862
-            );
863
-        }
864
-
865
-        $html_total_pages = sprintf(
866
-            '<span class="total-pages">%s</span>',
867
-            number_format_i18n($total_pages)
868
-        );
869
-        $page_links[]     = sprintf(
870
-            _x('%3$s%1$s of %2$s%4$s', 'paging'),
871
-            $html_current_page,
872
-            $html_total_pages,
873
-            '<span class="paging-input">',
874
-            '</span>'
875
-        );
876
-
877
-        $page_links[] = sprintf(
878
-            '<a class="%s" title="%s" href="%s">%s</a>',
879
-            'next-page' . $disable_last,
880
-            esc_attr__('Go to the next page'),
881
-            esc_url(add_query_arg($paged_arg_name, min($total_pages, $current + 1), $url)),
882
-            '&rsaquo;'
883
-        );
884
-
885
-        $page_links[] = sprintf(
886
-            '<a class="%s" title="%s" href="%s">%s</a>',
887
-            'last-page' . $disable_last,
888
-            esc_attr__('Go to the last page'),
889
-            esc_url(add_query_arg($paged_arg_name, $total_pages, $url)),
890
-            '&raquo;'
891
-        );
892
-
893
-        $output .= "\n" . '<span class="pagination-links">' . join("\n", $page_links) . '</span>';
894
-        // set page class
895
-        if ($total_pages) {
896
-            $page_class = $total_pages < 2 ? ' one-page' : '';
897
-        } else {
898
-            $page_class = ' no-pages';
899
-        }
900
-
901
-        return '<div class="tablenav"><div class="tablenav-pages' . $page_class . '">' . $output . '</div></div>';
902
-    }
903
-
904
-
905
-    /**
906
-     * @param string $wrap_class
907
-     * @param string $wrap_id
908
-     * @return string
909
-     */
910
-    public static function powered_by_event_espresso($wrap_class = '', $wrap_id = '', array $query_args = array())
911
-    {
912
-        $admin = is_admin() && ! (defined('DOING_AJAX') && DOING_AJAX);
913
-        if (
914
-            ! $admin &&
915
-            ! apply_filters(
916
-                'FHEE__EEH_Template__powered_by_event_espresso__show_reg_footer',
917
-                EE_Registry::instance()->CFG->admin->show_reg_footer
918
-            )
919
-        ) {
920
-            return '';
921
-        }
922
-        $tag        = $admin ? 'span' : 'div';
923
-        $attributes = ! empty($wrap_id) ? " id=\"{$wrap_id}\"" : '';
924
-        $wrap_class = $admin ? "{$wrap_class} float-left" : $wrap_class;
925
-        $attributes .= ! empty($wrap_class)
926
-            ? " class=\"{$wrap_class} powered-by-event-espresso-credit\""
927
-            : ' class="powered-by-event-espresso-credit"';
928
-        $query_args = array_merge(
929
-            array(
930
-                'ap_id'        => EE_Registry::instance()->CFG->admin->affiliate_id(),
931
-                'utm_source'   => 'powered_by_event_espresso',
932
-                'utm_medium'   => 'link',
933
-                'utm_campaign' => 'powered_by',
934
-            ),
935
-            $query_args
936
-        );
937
-        $powered_by = apply_filters('FHEE__EEH_Template__powered_by_event_espresso_text',
938
-            $admin ? 'Event Espresso - ' . EVENT_ESPRESSO_VERSION : 'Event Espresso');
939
-        $url        = add_query_arg($query_args, 'https://eventespresso.com/');
940
-        $url        = apply_filters('FHEE__EEH_Template__powered_by_event_espresso__url', $url);
941
-        return (string)apply_filters(
942
-            'FHEE__EEH_Template__powered_by_event_espresso__html',
943
-            sprintf(
944
-                esc_html_x(
945
-                    '%3$s%1$sOnline event registration and ticketing powered by %2$s%3$s',
946
-                    'Online event registration and ticketing powered by [link to eventespresso.com]',
947
-                    'event_espresso'
948
-                ),
949
-                "<{$tag}{$attributes}>",
950
-                "<a href=\"{$url}\" target=\"_blank\" rel=\"nofollow\">{$powered_by}</a></{$tag}>",
951
-                $admin ? '' : '<br />'
952
-            ),
953
-            $wrap_class,
954
-            $wrap_id
955
-        );
956
-    }
730
+			}
731
+		} else {
732
+			//simple value
733
+			echo esc_html($data);
734
+		}
735
+		return ob_get_clean();
736
+	}
737
+
738
+
739
+	/**
740
+	 * wrapper for self::get_paging_html() that simply echos the generated paging html
741
+	 *
742
+	 * @since 4.4.0
743
+	 * @see   self:get_paging_html() for argument docs.
744
+	 * @param        $total_items
745
+	 * @param        $current
746
+	 * @param        $per_page
747
+	 * @param        $url
748
+	 * @param bool   $show_num_field
749
+	 * @param string $paged_arg_name
750
+	 * @param array  $items_label
751
+	 * @return string
752
+	 */
753
+	public static function paging_html(
754
+		$total_items,
755
+		$current,
756
+		$per_page,
757
+		$url,
758
+		$show_num_field = true,
759
+		$paged_arg_name = 'paged',
760
+		$items_label = array()
761
+	) {
762
+		echo self::get_paging_html($total_items, $current, $per_page, $url, $show_num_field, $paged_arg_name,
763
+			$items_label);
764
+	}
765
+
766
+
767
+	/**
768
+	 * A method for generating paging similar to WP_List_Table
769
+	 *
770
+	 * @since    4.4.0
771
+	 * @see      wp-admin/includes/class-wp-list-table.php WP_List_Table::pagination()
772
+	 * @param  integer $total_items     How many total items there are to page.
773
+	 * @param  integer $current         What the current page is.
774
+	 * @param  integer $per_page        How many items per page.
775
+	 * @param  string  $url             What the base url for page links is.
776
+	 * @param  boolean $show_num_field  Whether to show the input for changing page number.
777
+	 * @param  string  $paged_arg_name  The name of the key for the paged query argument.
778
+	 * @param  array   $items_label     An array of singular/plural values for the items label:
779
+	 *                                  array(
780
+	 *                                  'single' => 'item',
781
+	 *                                  'plural' => 'items'
782
+	 *                                  )
783
+	 * @return  string
784
+	 */
785
+	public static function get_paging_html(
786
+		$total_items,
787
+		$current,
788
+		$per_page,
789
+		$url,
790
+		$show_num_field = true,
791
+		$paged_arg_name = 'paged',
792
+		$items_label = array()
793
+	) {
794
+		$page_links     = array();
795
+		$disable_first  = $disable_last = '';
796
+		$total_items    = (int)$total_items;
797
+		$per_page       = (int)$per_page;
798
+		$current        = (int)$current;
799
+		$paged_arg_name = empty($paged_arg_name) ? 'paged' : sanitize_key($paged_arg_name);
800
+
801
+		//filter items_label
802
+		$items_label = apply_filters(
803
+			'FHEE__EEH_Template__get_paging_html__items_label',
804
+			$items_label
805
+		);
806
+
807
+		if (empty($items_label)
808
+			|| ! is_array($items_label)
809
+			|| ! isset($items_label['single'])
810
+			|| ! isset($items_label['plural'])
811
+		) {
812
+			$items_label = array(
813
+				'single' => __('1 item', 'event_espresso'),
814
+				'plural' => __('%s items', 'event_espresso'),
815
+			);
816
+		} else {
817
+			$items_label = array(
818
+				'single' => '1 ' . esc_html($items_label['single']),
819
+				'plural' => '%s ' . esc_html($items_label['plural']),
820
+			);
821
+		}
822
+
823
+		$total_pages = ceil($total_items / $per_page);
824
+
825
+		if ($total_pages <= 1) {
826
+			return '';
827
+		}
828
+
829
+		$item_label = $total_items > 1 ? sprintf($items_label['plural'], $total_items) : $items_label['single'];
830
+
831
+		$output = '<span class="displaying-num">' . $item_label . '</span>';
832
+
833
+		if ($current === 1) {
834
+			$disable_first = ' disabled';
835
+		}
836
+		if ($current == $total_pages) {
837
+			$disable_last = ' disabled';
838
+		}
839
+
840
+		$page_links[] = sprintf("<a class='%s' title='%s' href='%s'>%s</a>",
841
+			'first-page' . $disable_first,
842
+			esc_attr__('Go to the first page'),
843
+			esc_url(remove_query_arg($paged_arg_name, $url)),
844
+			'&laquo;'
845
+		);
846
+
847
+		$page_links[] = sprintf(
848
+			'<a class="%s" title="%s" href="%s">%s</a>',
849
+			'prev-page' . $disable_first,
850
+			esc_attr__('Go to the previous page'),
851
+			esc_url(add_query_arg($paged_arg_name, max(1, $current - 1), $url)),
852
+			'&lsaquo;'
853
+		);
854
+
855
+		if ( ! $show_num_field) {
856
+			$html_current_page = $current;
857
+		} else {
858
+			$html_current_page = sprintf("<input class='current-page' title='%s' type='text' name=$paged_arg_name value='%s' size='%d' />",
859
+				esc_attr__('Current page'),
860
+				$current,
861
+				strlen($total_pages)
862
+			);
863
+		}
864
+
865
+		$html_total_pages = sprintf(
866
+			'<span class="total-pages">%s</span>',
867
+			number_format_i18n($total_pages)
868
+		);
869
+		$page_links[]     = sprintf(
870
+			_x('%3$s%1$s of %2$s%4$s', 'paging'),
871
+			$html_current_page,
872
+			$html_total_pages,
873
+			'<span class="paging-input">',
874
+			'</span>'
875
+		);
876
+
877
+		$page_links[] = sprintf(
878
+			'<a class="%s" title="%s" href="%s">%s</a>',
879
+			'next-page' . $disable_last,
880
+			esc_attr__('Go to the next page'),
881
+			esc_url(add_query_arg($paged_arg_name, min($total_pages, $current + 1), $url)),
882
+			'&rsaquo;'
883
+		);
884
+
885
+		$page_links[] = sprintf(
886
+			'<a class="%s" title="%s" href="%s">%s</a>',
887
+			'last-page' . $disable_last,
888
+			esc_attr__('Go to the last page'),
889
+			esc_url(add_query_arg($paged_arg_name, $total_pages, $url)),
890
+			'&raquo;'
891
+		);
892
+
893
+		$output .= "\n" . '<span class="pagination-links">' . join("\n", $page_links) . '</span>';
894
+		// set page class
895
+		if ($total_pages) {
896
+			$page_class = $total_pages < 2 ? ' one-page' : '';
897
+		} else {
898
+			$page_class = ' no-pages';
899
+		}
900
+
901
+		return '<div class="tablenav"><div class="tablenav-pages' . $page_class . '">' . $output . '</div></div>';
902
+	}
903
+
904
+
905
+	/**
906
+	 * @param string $wrap_class
907
+	 * @param string $wrap_id
908
+	 * @return string
909
+	 */
910
+	public static function powered_by_event_espresso($wrap_class = '', $wrap_id = '', array $query_args = array())
911
+	{
912
+		$admin = is_admin() && ! (defined('DOING_AJAX') && DOING_AJAX);
913
+		if (
914
+			! $admin &&
915
+			! apply_filters(
916
+				'FHEE__EEH_Template__powered_by_event_espresso__show_reg_footer',
917
+				EE_Registry::instance()->CFG->admin->show_reg_footer
918
+			)
919
+		) {
920
+			return '';
921
+		}
922
+		$tag        = $admin ? 'span' : 'div';
923
+		$attributes = ! empty($wrap_id) ? " id=\"{$wrap_id}\"" : '';
924
+		$wrap_class = $admin ? "{$wrap_class} float-left" : $wrap_class;
925
+		$attributes .= ! empty($wrap_class)
926
+			? " class=\"{$wrap_class} powered-by-event-espresso-credit\""
927
+			: ' class="powered-by-event-espresso-credit"';
928
+		$query_args = array_merge(
929
+			array(
930
+				'ap_id'        => EE_Registry::instance()->CFG->admin->affiliate_id(),
931
+				'utm_source'   => 'powered_by_event_espresso',
932
+				'utm_medium'   => 'link',
933
+				'utm_campaign' => 'powered_by',
934
+			),
935
+			$query_args
936
+		);
937
+		$powered_by = apply_filters('FHEE__EEH_Template__powered_by_event_espresso_text',
938
+			$admin ? 'Event Espresso - ' . EVENT_ESPRESSO_VERSION : 'Event Espresso');
939
+		$url        = add_query_arg($query_args, 'https://eventespresso.com/');
940
+		$url        = apply_filters('FHEE__EEH_Template__powered_by_event_espresso__url', $url);
941
+		return (string)apply_filters(
942
+			'FHEE__EEH_Template__powered_by_event_espresso__html',
943
+			sprintf(
944
+				esc_html_x(
945
+					'%3$s%1$sOnline event registration and ticketing powered by %2$s%3$s',
946
+					'Online event registration and ticketing powered by [link to eventespresso.com]',
947
+					'event_espresso'
948
+				),
949
+				"<{$tag}{$attributes}>",
950
+				"<a href=\"{$url}\" target=\"_blank\" rel=\"nofollow\">{$powered_by}</a></{$tag}>",
951
+				$admin ? '' : '<br />'
952
+			),
953
+			$wrap_class,
954
+			$wrap_id
955
+		);
956
+	}
957 957
 
958 958
 
959 959
 } //end EEH_Template class
@@ -962,33 +962,33 @@  discard block
 block discarded – undo
962 962
 
963 963
 
964 964
 if ( ! function_exists('espresso_pagination')) {
965
-    /**
966
-     *    espresso_pagination
967
-     *
968
-     * @access    public
969
-     * @return    void
970
-     */
971
-    function espresso_pagination()
972
-    {
973
-        global $wp_query;
974
-        $big        = 999999999; // need an unlikely integer
975
-        $pagination = paginate_links(
976
-            array(
977
-                'base'         => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
978
-                'format'       => '?paged=%#%',
979
-                'current'      => max(1, get_query_var('paged')),
980
-                'total'        => $wp_query->max_num_pages,
981
-                'show_all'     => true,
982
-                'end_size'     => 10,
983
-                'mid_size'     => 6,
984
-                'prev_next'    => true,
985
-                'prev_text'    => __('&lsaquo; PREV', 'event_espresso'),
986
-                'next_text'    => __('NEXT &rsaquo;', 'event_espresso'),
987
-                'type'         => 'plain',
988
-                'add_args'     => false,
989
-                'add_fragment' => '',
990
-            )
991
-        );
992
-        echo ! empty($pagination) ? '<div class="ee-pagination-dv ee-clear-float">' . $pagination . '</div>' : '';
993
-    }
965
+	/**
966
+	 *    espresso_pagination
967
+	 *
968
+	 * @access    public
969
+	 * @return    void
970
+	 */
971
+	function espresso_pagination()
972
+	{
973
+		global $wp_query;
974
+		$big        = 999999999; // need an unlikely integer
975
+		$pagination = paginate_links(
976
+			array(
977
+				'base'         => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
978
+				'format'       => '?paged=%#%',
979
+				'current'      => max(1, get_query_var('paged')),
980
+				'total'        => $wp_query->max_num_pages,
981
+				'show_all'     => true,
982
+				'end_size'     => 10,
983
+				'mid_size'     => 6,
984
+				'prev_next'    => true,
985
+				'prev_text'    => __('&lsaquo; PREV', 'event_espresso'),
986
+				'next_text'    => __('NEXT &rsaquo;', 'event_espresso'),
987
+				'type'         => 'plain',
988
+				'add_args'     => false,
989
+				'add_fragment' => '',
990
+			)
991
+		);
992
+		echo ! empty($pagination) ? '<div class="ee-pagination-dv ee-clear-float">' . $pagination . '</div>' : '';
993
+	}
994 994
 }
995 995
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (! defined('EVENT_ESPRESSO_VERSION')) {
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3 3
     exit('NO direct script access allowed');
4 4
 }
5 5
 /**
@@ -81,8 +81,8 @@  discard block
 block discarded – undo
81 81
     public static function load_espresso_theme_functions()
82 82
     {
83 83
         if ( ! defined('EE_THEME_FUNCTIONS_LOADED')) {
84
-            if (is_readable(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php')) {
85
-                require_once(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php');
84
+            if (is_readable(EE_PUBLIC.EE_Config::get_current_theme().DS.'functions.php')) {
85
+                require_once(EE_PUBLIC.EE_Config::get_current_theme().DS.'functions.php');
86 86
             }
87 87
         }
88 88
     }
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
     public static function get_espresso_themes()
97 97
     {
98 98
         if (empty(EEH_Template::$_espresso_themes)) {
99
-            $espresso_themes = glob(EE_PUBLIC . '*', GLOB_ONLYDIR);
99
+            $espresso_themes = glob(EE_PUBLIC.'*', GLOB_ONLYDIR);
100 100
             if (empty($espresso_themes)) {
101 101
                 return array();
102 102
             }
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
     ) {
133 133
         do_action("get_template_part_{$slug}-{$name}", $slug, $name);
134 134
         $templates = array();
135
-        $name      = (string)$name;
135
+        $name      = (string) $name;
136 136
         if ($name != '') {
137 137
             $templates[] = "{$slug}-{$name}.php";
138 138
         }
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
                 if (isset($EE_CPTs[$post_type])) {
212 212
                     $archive_or_single = is_archive() ? 'archive' : '';
213 213
                     $archive_or_single = is_single() ? 'single' : $archive_or_single;
214
-                    $templates         = $archive_or_single . '-' . $post_type . '.php';
214
+                    $templates         = $archive_or_single.'-'.$post_type.'.php';
215 215
                 }
216 216
             }
217 217
             // currently active EE template theme
@@ -220,18 +220,18 @@  discard block
 block discarded – undo
220 220
             // array of paths to folders that may contain templates
221 221
             $template_folder_paths = array(
222 222
                 // first check the /wp-content/uploads/espresso/templates/(current EE theme)/  folder for an EE theme template file
223
-                EVENT_ESPRESSO_TEMPLATE_DIR . $current_theme,
223
+                EVENT_ESPRESSO_TEMPLATE_DIR.$current_theme,
224 224
                 // then in the root of the /wp-content/uploads/espresso/templates/ folder
225 225
                 EVENT_ESPRESSO_TEMPLATE_DIR,
226 226
             );
227 227
 
228 228
             //add core plugin folders for checking only if we're not $check_if_custom
229 229
             if ( ! $check_if_custom) {
230
-                $core_paths            = array(
230
+                $core_paths = array(
231 231
                     // in the  /wp-content/plugins/(EE4 folder)/public/(current EE theme)/ folder within the plugin
232
-                    EE_PUBLIC . $current_theme,
232
+                    EE_PUBLIC.$current_theme,
233 233
                     // in the  /wp-content/plugins/(EE4 folder)/core/templates/(current EE theme)/ folder within the plugin
234
-                    EE_TEMPLATES . $current_theme,
234
+                    EE_TEMPLATES.$current_theme,
235 235
                     // or maybe relative from the plugin root: /wp-content/plugins/(EE4 folder)/
236 236
                     EE_PLUGIN_DIR_PATH,
237 237
                 );
@@ -262,10 +262,10 @@  discard block
 block discarded – undo
262 262
                     );
263 263
                     if ($common_base_path !== '') {
264 264
                         // both paths have a common base, so just tack the filename onto our search path
265
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $file_name;
265
+                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path).$file_name;
266 266
                     } else {
267 267
                         // no common base path, so let's just concatenate
268
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $template;
268
+                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path).$template;
269 269
                     }
270 270
                     // build up our template locations array by adding our resolved paths
271 271
                     $full_template_paths[] = $resolved_path;
@@ -273,13 +273,13 @@  discard block
 block discarded – undo
273 273
                 // if $template is an absolute path, then we'll tack it onto the start of our array so that it gets searched first
274 274
                 array_unshift($full_template_paths, $template);
275 275
                 // path to the directory of the current theme: /wp-content/themes/(current WP theme)/
276
-                array_unshift($full_template_paths, get_stylesheet_directory() . DS . $file_name);
276
+                array_unshift($full_template_paths, get_stylesheet_directory().DS.$file_name);
277 277
             }
278 278
             // filter final array of full template paths
279 279
             $full_template_paths = apply_filters('FHEE__EEH_Template__locate_template__full_template_paths',
280 280
                 $full_template_paths, $file_name);
281 281
             // now loop through our final array of template location paths and check each location
282
-            foreach ((array)$full_template_paths as $full_template_path) {
282
+            foreach ((array) $full_template_paths as $full_template_path) {
283 283
                 if (is_readable($full_template_path)) {
284 284
                     $template_path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $full_template_path);
285 285
                     break;
@@ -366,9 +366,9 @@  discard block
 block discarded – undo
366 366
         if ( ! is_array($template_args) && ! is_object($template_args)) {
367 367
             $template_args = array($template_args);
368 368
         }
369
-        extract( $template_args, EXTR_SKIP );
369
+        extract($template_args, EXTR_SKIP);
370 370
         // ignore whether template is accessible ?
371
-        if ( $throw_exceptions && ! is_readable( $template_path ) ) {
371
+        if ($throw_exceptions && ! is_readable($template_path)) {
372 372
             throw new \DomainException(
373 373
                     esc_html__(
374 374
                             'Invalid, unreadable, or missing file.',
@@ -401,11 +401,11 @@  discard block
 block discarded – undo
401 401
     public static function get_object_css_class($object = null, $prefix = '', $suffix = '')
402 402
     {
403 403
         // in the beginning...
404
-        $prefix = ! empty($prefix) ? rtrim($prefix, '-') . '-' : '';
404
+        $prefix = ! empty($prefix) ? rtrim($prefix, '-').'-' : '';
405 405
         // da muddle
406 406
         $class = '';
407 407
         // the end
408
-        $suffix = ! empty($suffix) ? '-' . ltrim($suffix, '-') : '';
408
+        $suffix = ! empty($suffix) ? '-'.ltrim($suffix, '-') : '';
409 409
         // is the passed object an EE object ?
410 410
         if ($object instanceof EE_Base_Class) {
411 411
             // grab the exact type of object
@@ -415,11 +415,11 @@  discard block
 block discarded – undo
415 415
                 // no specifics just yet...
416 416
                 default :
417 417
                     $class = strtolower(str_replace('_', '-', $obj_class));
418
-                    $class .= method_exists($obj_class, 'name') ? '-' . sanitize_title($object->name()) : '';
418
+                    $class .= method_exists($obj_class, 'name') ? '-'.sanitize_title($object->name()) : '';
419 419
 
420 420
             }
421 421
         }
422
-        return $prefix . $class . $suffix;
422
+        return $prefix.$class.$suffix;
423 423
     }
424 424
 
425 425
 
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
             return '';
452 452
         }
453 453
         //ensure amount is float
454
-        $amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float)$amount);
454
+        $amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float) $amount);
455 455
         $CNT_ISO = apply_filters('FHEE__EEH_Template__format_currency__CNT_ISO', $CNT_ISO, $amount);
456 456
         // filter raw amount (allows 0.00 to be changed to "free" for example)
457 457
         $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount', $amount, $return_raw);
@@ -473,20 +473,20 @@  discard block
 block discarded – undo
473 473
                 // add currency sign
474 474
                 if ($mny->sign_b4) {
475 475
                     if ($amount >= 0) {
476
-                        $amount_formatted = $mny->sign . $amount_formatted;
476
+                        $amount_formatted = $mny->sign.$amount_formatted;
477 477
                     } else {
478
-                        $amount_formatted = '-' . $mny->sign . str_replace('-', '', $amount_formatted);
478
+                        $amount_formatted = '-'.$mny->sign.str_replace('-', '', $amount_formatted);
479 479
                     }
480 480
 
481 481
                 } else {
482
-                    $amount_formatted = $amount_formatted . $mny->sign;
482
+                    $amount_formatted = $amount_formatted.$mny->sign;
483 483
                 }
484 484
 
485 485
                 // filter to allow global setting of display_code
486 486
                 $display_code = apply_filters('FHEE__EEH_Template__format_currency__display_code', $display_code);
487 487
 
488 488
                 // add currency code ?
489
-                $amount_formatted = $display_code ? $amount_formatted . ' <span class="' . $cur_code_span_class . '">(' . $mny->code . ')</span>' : $amount_formatted;
489
+                $amount_formatted = $display_code ? $amount_formatted.' <span class="'.$cur_code_span_class.'">('.$mny->code.')</span>' : $amount_formatted;
490 490
             }
491 491
             // filter results
492 492
             $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount_formatted',
@@ -540,12 +540,12 @@  discard block
 block discarded – undo
540 540
             $icon_html .= $count > 1 ? '<span class="ee-composite-dashicon">' : '';
541 541
             foreach ($dashicons as $dashicon) {
542 542
                 $type = strpos($dashicon, 'ee-icon') !== false ? 'ee-icon ' : 'dashicons ';
543
-                $icon_html .= '<span class="' . $type . $dashicon . '"></span>';
543
+                $icon_html .= '<span class="'.$type.$dashicon.'"></span>';
544 544
             }
545 545
             $icon_html .= $count > 1 ? '</span>' : '';
546 546
         }
547
-        $label  = ! empty($icon) ? $icon_html . $label : $label;
548
-        $button = '<a id="' . sanitize_title_with_dashes($label) . '" href="' . esc_url($url) . '" class="' . $class . '" title="' . $title . '">' . $label . '</a>';
547
+        $label  = ! empty($icon) ? $icon_html.$label : $label;
548
+        $button = '<a id="'.sanitize_title_with_dashes($label).'" href="'.esc_url($url).'" class="'.$class.'" title="'.$title.'">'.$label.'</a>';
549 549
         return $button;
550 550
     }
551 551
 
@@ -579,11 +579,11 @@  discard block
 block discarded – undo
579 579
         $action = empty($action) ? 'default' : $action;
580 580
 
581 581
 
582
-        $help_tab_lnk = $page . '-' . $action . '-' . $help_tab_id;
582
+        $help_tab_lnk = $page.'-'.$action.'-'.$help_tab_id;
583 583
         $icon         = ! $icon_style ? ' dashicons-editor-help' : $icon_style;
584 584
         $help_text    = ! $help_text ? '' : $help_text;
585
-        return '<a id="' . $help_tab_lnk . '" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22' . $icon . '" title="' . esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
586
-                'event_espresso') . '" > ' . $help_text . ' </a>';
585
+        return '<a id="'.$help_tab_lnk.'" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22'.$icon.'" title="'.esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
586
+                'event_espresso').'" > '.$help_text.' </a>';
587 587
     }
588 588
 
589 589
 
@@ -600,11 +600,11 @@  discard block
 block discarded – undo
600 600
         $id    = $tour->get_slug();
601 601
         $stops = $tour->get_stops();
602 602
 
603
-        $content = '<ol style="display:none" id="' . $id . '">';
603
+        $content = '<ol style="display:none" id="'.$id.'">';
604 604
 
605 605
         foreach ($stops as $stop) {
606
-            $data_id    = ! empty($stop['id']) ? ' data-id="' . $stop['id'] . '"' : '';
607
-            $data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="' . $stop['class'] . '"' : '';
606
+            $data_id    = ! empty($stop['id']) ? ' data-id="'.$stop['id'].'"' : '';
607
+            $data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="'.$stop['class'].'"' : '';
608 608
 
609 609
             //if container is set to modal then let's make sure we set the options accordingly
610 610
             if (empty($data_id) && empty($data_class)) {
@@ -612,15 +612,15 @@  discard block
 block discarded – undo
612 612
                 $stop['options']['expose'] = true;
613 613
             }
614 614
 
615
-            $custom_class  = ! empty($stop['custom_class']) ? ' class="' . $stop['custom_class'] . '"' : '';
616
-            $button_text   = ! empty($stop['button_text']) ? ' data-button="' . $stop['button_text'] . '"' : '';
615
+            $custom_class  = ! empty($stop['custom_class']) ? ' class="'.$stop['custom_class'].'"' : '';
616
+            $button_text   = ! empty($stop['button_text']) ? ' data-button="'.$stop['button_text'].'"' : '';
617 617
             $inner_content = isset($stop['content']) ? $stop['content'] : '';
618 618
 
619 619
             //options
620 620
             if (isset($stop['options']) && is_array($stop['options'])) {
621 621
                 $options = ' data-options="';
622 622
                 foreach ($stop['options'] as $option => $value) {
623
-                    $options .= $option . ':' . $value . ';';
623
+                    $options .= $option.':'.$value.';';
624 624
                 }
625 625
                 $options .= '"';
626 626
             } else {
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
             }
629 629
 
630 630
             //let's put all together
631
-            $content .= '<li' . $data_id . $data_class . $custom_class . $button_text . $options . '>' . $inner_content . '</li>';
631
+            $content .= '<li'.$data_id.$data_class.$custom_class.$button_text.$options.'>'.$inner_content.'</li>';
632 632
         }
633 633
 
634 634
         $content .= '</ol>';
@@ -660,24 +660,24 @@  discard block
 block discarded – undo
660 660
         $setup_array = array();
661 661
         foreach ($status_array as $item => $status) {
662 662
             $setup_array[$item] = array(
663
-                'class'  => 'ee-status-legend ee-status-legend-' . $status,
663
+                'class'  => 'ee-status-legend ee-status-legend-'.$status,
664 664
                 'desc'   => EEH_Template::pretty_status($status, false, 'sentence'),
665 665
                 'status' => $status,
666 666
             );
667 667
         }
668 668
 
669
-        $content = '<div class="ee-list-table-legend-container">' . "\n";
670
-        $content .= '<h4 class="status-legend-title">' . esc_html__('Status Legend', 'event_espresso') . '</h4>' . "\n";
671
-        $content .= '<dl class="ee-list-table-legend">' . "\n\t";
669
+        $content = '<div class="ee-list-table-legend-container">'."\n";
670
+        $content .= '<h4 class="status-legend-title">'.esc_html__('Status Legend', 'event_espresso').'</h4>'."\n";
671
+        $content .= '<dl class="ee-list-table-legend">'."\n\t";
672 672
         foreach ($setup_array as $item => $details) {
673 673
             $active_class = $active_status == $details['status'] ? ' class="ee-is-active-status"' : '';
674
-            $content .= '<dt id="ee-legend-item-tooltip-' . $item . '"' . $active_class . '>' . "\n\t\t";
675
-            $content .= '<span class="' . $details['class'] . '"></span>' . "\n\t\t";
676
-            $content .= '<span class="ee-legend-description">' . $details['desc'] . '</span>' . "\n\t";
677
-            $content .= '</dt>' . "\n";
674
+            $content .= '<dt id="ee-legend-item-tooltip-'.$item.'"'.$active_class.'>'."\n\t\t";
675
+            $content .= '<span class="'.$details['class'].'"></span>'."\n\t\t";
676
+            $content .= '<span class="ee-legend-description">'.$details['desc'].'</span>'."\n\t";
677
+            $content .= '</dt>'."\n";
678 678
         }
679
-        $content .= '</dl>' . "\n";
680
-        $content .= '</div>' . "\n";
679
+        $content .= '</dl>'."\n";
680
+        $content .= '</div>'."\n";
681 681
         return $content;
682 682
     }
683 683
 
@@ -692,7 +692,7 @@  discard block
 block discarded – undo
692 692
     public static function layout_array_as_table($data)
693 693
     {
694 694
         if (is_object($data) || $data instanceof __PHP_Incomplete_Class) {
695
-            $data = (array)$data;
695
+            $data = (array) $data;
696 696
         }
697 697
         ob_start();
698 698
         if (is_array($data)) {
@@ -793,9 +793,9 @@  discard block
 block discarded – undo
793 793
     ) {
794 794
         $page_links     = array();
795 795
         $disable_first  = $disable_last = '';
796
-        $total_items    = (int)$total_items;
797
-        $per_page       = (int)$per_page;
798
-        $current        = (int)$current;
796
+        $total_items    = (int) $total_items;
797
+        $per_page       = (int) $per_page;
798
+        $current        = (int) $current;
799 799
         $paged_arg_name = empty($paged_arg_name) ? 'paged' : sanitize_key($paged_arg_name);
800 800
 
801 801
         //filter items_label
@@ -815,8 +815,8 @@  discard block
 block discarded – undo
815 815
             );
816 816
         } else {
817 817
             $items_label = array(
818
-                'single' => '1 ' . esc_html($items_label['single']),
819
-                'plural' => '%s ' . esc_html($items_label['plural']),
818
+                'single' => '1 '.esc_html($items_label['single']),
819
+                'plural' => '%s '.esc_html($items_label['plural']),
820 820
             );
821 821
         }
822 822
 
@@ -828,7 +828,7 @@  discard block
 block discarded – undo
828 828
 
829 829
         $item_label = $total_items > 1 ? sprintf($items_label['plural'], $total_items) : $items_label['single'];
830 830
 
831
-        $output = '<span class="displaying-num">' . $item_label . '</span>';
831
+        $output = '<span class="displaying-num">'.$item_label.'</span>';
832 832
 
833 833
         if ($current === 1) {
834 834
             $disable_first = ' disabled';
@@ -838,7 +838,7 @@  discard block
 block discarded – undo
838 838
         }
839 839
 
840 840
         $page_links[] = sprintf("<a class='%s' title='%s' href='%s'>%s</a>",
841
-            'first-page' . $disable_first,
841
+            'first-page'.$disable_first,
842 842
             esc_attr__('Go to the first page'),
843 843
             esc_url(remove_query_arg($paged_arg_name, $url)),
844 844
             '&laquo;'
@@ -846,7 +846,7 @@  discard block
 block discarded – undo
846 846
 
847 847
         $page_links[] = sprintf(
848 848
             '<a class="%s" title="%s" href="%s">%s</a>',
849
-            'prev-page' . $disable_first,
849
+            'prev-page'.$disable_first,
850 850
             esc_attr__('Go to the previous page'),
851 851
             esc_url(add_query_arg($paged_arg_name, max(1, $current - 1), $url)),
852 852
             '&lsaquo;'
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
             '<span class="total-pages">%s</span>',
867 867
             number_format_i18n($total_pages)
868 868
         );
869
-        $page_links[]     = sprintf(
869
+        $page_links[] = sprintf(
870 870
             _x('%3$s%1$s of %2$s%4$s', 'paging'),
871 871
             $html_current_page,
872 872
             $html_total_pages,
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
 
877 877
         $page_links[] = sprintf(
878 878
             '<a class="%s" title="%s" href="%s">%s</a>',
879
-            'next-page' . $disable_last,
879
+            'next-page'.$disable_last,
880 880
             esc_attr__('Go to the next page'),
881 881
             esc_url(add_query_arg($paged_arg_name, min($total_pages, $current + 1), $url)),
882 882
             '&rsaquo;'
@@ -884,13 +884,13 @@  discard block
 block discarded – undo
884 884
 
885 885
         $page_links[] = sprintf(
886 886
             '<a class="%s" title="%s" href="%s">%s</a>',
887
-            'last-page' . $disable_last,
887
+            'last-page'.$disable_last,
888 888
             esc_attr__('Go to the last page'),
889 889
             esc_url(add_query_arg($paged_arg_name, $total_pages, $url)),
890 890
             '&raquo;'
891 891
         );
892 892
 
893
-        $output .= "\n" . '<span class="pagination-links">' . join("\n", $page_links) . '</span>';
893
+        $output .= "\n".'<span class="pagination-links">'.join("\n", $page_links).'</span>';
894 894
         // set page class
895 895
         if ($total_pages) {
896 896
             $page_class = $total_pages < 2 ? ' one-page' : '';
@@ -898,7 +898,7 @@  discard block
 block discarded – undo
898 898
             $page_class = ' no-pages';
899 899
         }
900 900
 
901
-        return '<div class="tablenav"><div class="tablenav-pages' . $page_class . '">' . $output . '</div></div>';
901
+        return '<div class="tablenav"><div class="tablenav-pages'.$page_class.'">'.$output.'</div></div>';
902 902
     }
903 903
 
904 904
 
@@ -935,10 +935,10 @@  discard block
 block discarded – undo
935 935
             $query_args
936 936
         );
937 937
         $powered_by = apply_filters('FHEE__EEH_Template__powered_by_event_espresso_text',
938
-            $admin ? 'Event Espresso - ' . EVENT_ESPRESSO_VERSION : 'Event Espresso');
938
+            $admin ? 'Event Espresso - '.EVENT_ESPRESSO_VERSION : 'Event Espresso');
939 939
         $url        = add_query_arg($query_args, 'https://eventespresso.com/');
940 940
         $url        = apply_filters('FHEE__EEH_Template__powered_by_event_espresso__url', $url);
941
-        return (string)apply_filters(
941
+        return (string) apply_filters(
942 942
             'FHEE__EEH_Template__powered_by_event_espresso__html',
943 943
             sprintf(
944 944
                 esc_html_x(
@@ -989,6 +989,6 @@  discard block
 block discarded – undo
989 989
                 'add_fragment' => '',
990 990
             )
991 991
         );
992
-        echo ! empty($pagination) ? '<div class="ee-pagination-dv ee-clear-float">' . $pagination . '</div>' : '';
992
+        echo ! empty($pagination) ? '<div class="ee-pagination-dv ee-clear-float">'.$pagination.'</div>' : '';
993 993
     }
994 994
 }
995 995
\ No newline at end of file
Please login to merge, or discard this patch.
strategies/display/EE_Submit_Input_Display_Strategy.strategy.php 2 patches
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -12,29 +12,29 @@
 block discarded – undo
12 12
 class EE_Submit_Input_Display_Strategy extends EE_Display_Strategy_Base
13 13
 {
14 14
 
15
-    /**
16
-     * @return string of html to display the input
17
-     */
18
-    public function display()
19
-    {
20
-        $default_value = $this->_input->get_default();
21
-        if ($this->_input->get_normalization_strategy() instanceof EE_Normalization_Strategy_Base) {
22
-            $default_value = $this->_input->get_normalization_strategy()->unnormalize($default_value);
23
-        }
24
-        $html = $this->_opening_tag('input');
25
-        $html .= $this->_attributes_string(
26
-            array_merge(
27
-                $this->_standard_attributes_array(),
28
-                array(
29
-                    'type'  => 'submit',
30
-                    'value' => $default_value,
31
-                    //overwrite the standard id with the backwards compatible one
32
-                    'id' => $this->_input->html_id() . '-submit',
33
-                    'class' => $this->_input->html_class() . ' ' . $this->_input->button_css_attributes()
34
-                )
35
-            )
36
-        );
37
-        $html .= $this->_close_tag();
38
-        return $html;
15
+	/**
16
+	 * @return string of html to display the input
17
+	 */
18
+	public function display()
19
+	{
20
+		$default_value = $this->_input->get_default();
21
+		if ($this->_input->get_normalization_strategy() instanceof EE_Normalization_Strategy_Base) {
22
+			$default_value = $this->_input->get_normalization_strategy()->unnormalize($default_value);
23
+		}
24
+		$html = $this->_opening_tag('input');
25
+		$html .= $this->_attributes_string(
26
+			array_merge(
27
+				$this->_standard_attributes_array(),
28
+				array(
29
+					'type'  => 'submit',
30
+					'value' => $default_value,
31
+					//overwrite the standard id with the backwards compatible one
32
+					'id' => $this->_input->html_id() . '-submit',
33
+					'class' => $this->_input->html_class() . ' ' . $this->_input->button_css_attributes()
34
+				)
35
+			)
36
+		);
37
+		$html .= $this->_close_tag();
38
+		return $html;
39 39
 	}
40 40
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -29,8 +29,8 @@
 block discarded – undo
29 29
                     'type'  => 'submit',
30 30
                     'value' => $default_value,
31 31
                     //overwrite the standard id with the backwards compatible one
32
-                    'id' => $this->_input->html_id() . '-submit',
33
-                    'class' => $this->_input->html_class() . ' ' . $this->_input->button_css_attributes()
32
+                    'id' => $this->_input->html_id().'-submit',
33
+                    'class' => $this->_input->html_class().' '.$this->_input->button_css_attributes()
34 34
                 )
35 35
             )
36 36
         );
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.
Spacing   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
         $this->_admin_base_url  = EE_MSG_ADMIN_URL;
95 95
         $this->_admin_base_path = EE_MSG_ADMIN;
96 96
         
97
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
97
+        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state'] : array();
98 98
         
99 99
         $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
100 100
         $this->_load_message_resource_manager();
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
             array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
254 254
             $messenger_options
255 255
         );
256
-        $input             = new EE_Select_Input(
256
+        $input = new EE_Select_Input(
257 257
             $messenger_options,
258 258
             array(
259 259
                 'html_name'  => 'ee_messenger_filter_by',
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
             array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
292 292
             $message_type_options
293 293
         );
294
-        $input                = new EE_Select_Input(
294
+        $input = new EE_Select_Input(
295 295
             $message_type_options,
296 296
             array(
297 297
                 'html_name'  => 'ee_message_type_filter_by',
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
             array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
330 330
             $context_options
331 331
         );
332
-        $input           = new EE_Select_Input(
332
+        $input = new EE_Select_Input(
333 333
             $context_options,
334 334
             array(
335 335
                 'html_name'  => 'ee_context_filter_by',
@@ -711,53 +711,53 @@  discard block
 block discarded – undo
711 711
     
712 712
     public function messages_help_tab()
713 713
     {
714
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
714
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_help_tab.template.php');
715 715
     }
716 716
     
717 717
     
718 718
     public function messengers_help_tab()
719 719
     {
720
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
720
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messenger_help_tab.template.php');
721 721
     }
722 722
     
723 723
     
724 724
     public function message_types_help_tab()
725 725
     {
726
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
726
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_type_help_tab.template.php');
727 727
     }
728 728
     
729 729
     
730 730
     public function messages_overview_help_tab()
731 731
     {
732
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
732
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_overview_help_tab.template.php');
733 733
     }
734 734
     
735 735
     
736 736
     public function message_templates_help_tab()
737 737
     {
738
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
738
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_templates_help_tab.template.php');
739 739
     }
740 740
     
741 741
     
742 742
     public function edit_message_template_help_tab()
743 743
     {
744
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
744
+        $args['img1'] = '<img src="'.EE_MSG_ASSETS_URL.'images/editor.png'.'" alt="'
745 745
                         . esc_attr__('Editor Title', 'event_espresso')
746 746
                         . '" />';
747
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
747
+        $args['img2'] = '<img src="'.EE_MSG_ASSETS_URL.'images/switch-context.png'.'" alt="'
748 748
                         . esc_attr__('Context Switcher and Preview', 'event_espresso')
749 749
                         . '" />';
750
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
750
+        $args['img3'] = '<img class="left" src="'.EE_MSG_ASSETS_URL.'images/form-fields.png'.'" alt="'
751 751
                         . esc_attr__('Message Template Form Fields', 'event_espresso')
752 752
                         . '" />';
753
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
753
+        $args['img4'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/shortcodes-metabox.png'.'" alt="'
754 754
                         . esc_attr__('Shortcodes Metabox', 'event_espresso')
755 755
                         . '" />';
756
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
756
+        $args['img5'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/publish-meta-box.png'.'" alt="'
757 757
                         . esc_attr__('Publish Metabox', 'event_espresso')
758 758
                         . '" />';
759 759
         EEH_Template::display_template(
760
-            EE_MSG_TEMPLATE_PATH  . 'ee_msg_messages_templates_editor_help_tab.template.php',
760
+            EE_MSG_TEMPLATE_PATH.'ee_msg_messages_templates_editor_help_tab.template.php',
761 761
             $args
762 762
         );
763 763
     }
@@ -768,7 +768,7 @@  discard block
 block discarded – undo
768 768
         $this->_set_shortcodes();
769 769
         $args['shortcodes'] = $this->_shortcodes;
770 770
         EEH_Template::display_template(
771
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
771
+            EE_MSG_TEMPLATE_PATH.'ee_msg_messages_shortcodes_help_tab.template.php',
772 772
             $args
773 773
         );
774 774
     }
@@ -776,16 +776,16 @@  discard block
 block discarded – undo
776 776
     
777 777
     public function preview_message_help_tab()
778 778
     {
779
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
779
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_preview_help_tab.template.php');
780 780
     }
781 781
     
782 782
     
783 783
     public function settings_help_tab()
784 784
     {
785
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
786
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
787
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
788
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
785
+        $args['img1'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-active.png'
786
+                        . '" alt="'.esc_attr__('Active Email Tab', 'event_espresso').'" />';
787
+        $args['img2'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-inactive.png'
788
+                        . '" alt="'.esc_attr__('Inactive Email Tab', 'event_espresso').'" />';
789 789
         $args['img3'] = '<div class="switch">'
790 790
                         . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
791 791
                         . ' type="checkbox" checked="checked">'
@@ -796,18 +796,18 @@  discard block
 block discarded – undo
796 796
                         . ' type="checkbox">'
797 797
                         . '<label for="ee-on-off-toggle-on"></label>'
798 798
                         . '</div>';
799
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
799
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_settings_help_tab.template.php', $args);
800 800
     }
801 801
     
802 802
     
803 803
     public function load_scripts_styles()
804 804
     {
805
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
805
+        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL.'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
806 806
         wp_enqueue_style('espresso_ee_msg');
807 807
         
808
-        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
808
+        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL.'ee-messages-settings.js',
809 809
             array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
810
-        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
810
+        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL.'ee_message_admin_list_table.js',
811 811
             array('ee-dialog'), EVENT_ESPRESSO_VERSION);
812 812
     }
813 813
     
@@ -839,7 +839,7 @@  discard block
 block discarded – undo
839 839
         
840 840
         $this->_set_shortcodes();
841 841
         
842
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
842
+        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
843 843
             esc_html__(
844 844
                 '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.',
845 845
                 'event_espresso'
@@ -858,7 +858,7 @@  discard block
 block discarded – undo
858 858
         
859 859
         wp_register_script(
860 860
             'ee_msgs_edit_js',
861
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
861
+            EE_MSG_ASSETS_URL.'ee_message_editor.js',
862 862
             array('jquery'),
863 863
             EVENT_ESPRESSO_VERSION
864 864
         );
@@ -901,7 +901,7 @@  discard block
 block discarded – undo
901 901
     {
902 902
         wp_register_style(
903 903
             'ee-message-settings',
904
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
904
+            EE_MSG_ASSETS_URL.'ee_message_settings.css',
905 905
             array(),
906 906
             EVENT_ESPRESSO_VERSION
907 907
         );
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
             }
988 988
             $status_bulk_actions = $common_bulk_actions;
989 989
             //unset bulk actions not applying to status
990
-            if (! empty($status_bulk_actions)) {
990
+            if ( ! empty($status_bulk_actions)) {
991 991
                 switch ($status) {
992 992
                     case EEM_Message::status_idle:
993 993
                     case EEM_Message::status_resend:
@@ -1012,7 +1012,7 @@  discard block
 block discarded – undo
1012 1012
             }
1013 1013
 
1014 1014
             //skip adding messenger executing status to views because it will be included with the Failed view.
1015
-            if ( $status === EEM_Message::status_messenger_executing ) {
1015
+            if ($status === EEM_Message::status_messenger_executing) {
1016 1016
                 continue;
1017 1017
             }
1018 1018
             
@@ -1064,37 +1064,37 @@  discard block
 block discarded – undo
1064 1064
         /** @type array $status_items status legend setup */
1065 1065
         $status_items = array(
1066 1066
             'sent_status'       => array(
1067
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1067
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_sent,
1068 1068
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
1069 1069
             ),
1070 1070
             'idle_status'       => array(
1071
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1071
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_idle,
1072 1072
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
1073 1073
             ),
1074 1074
             'failed_status'     => array(
1075
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1075
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_failed,
1076 1076
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
1077 1077
             ),
1078 1078
             'messenger_executing_status' => array(
1079
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1079
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_messenger_executing,
1080 1080
                 'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
1081 1081
             ),
1082 1082
             'resend_status'     => array(
1083
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1083
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_resend,
1084 1084
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
1085 1085
             ),
1086 1086
             'incomplete_status' => array(
1087
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1087
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_incomplete,
1088 1088
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
1089 1089
             ),
1090 1090
             'retry_status'      => array(
1091
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1091
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_retry,
1092 1092
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
1093 1093
             )
1094 1094
         );
1095 1095
         if (EEM_Message::debug()) {
1096 1096
             $status_items['debug_only_status'] = array(
1097
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1097
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_debug_only,
1098 1098
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1099 1099
             );
1100 1100
         }
@@ -1106,8 +1106,8 @@  discard block
 block discarded – undo
1106 1106
     protected function _custom_mtps_preview()
1107 1107
     {
1108 1108
         $this->_admin_page_title              = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1109
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1110
-            . ' alt="' . esc_attr__('Preview Custom Message Templates screenshot', 'event_espresso') . '" />';
1109
+        $this->_template_args['preview_img']  = '<img src="'.EE_MSG_ASSETS_URL.'images/custom_mtps_preview.png"'
1110
+            . ' alt="'.esc_attr__('Preview Custom Message Templates screenshot', 'event_espresso').'" />';
1111 1111
         $this->_template_args['preview_text'] = '<strong>'
1112 1112
             . esc_html__(
1113 1113
                 '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.',
@@ -1389,7 +1389,7 @@  discard block
 block discarded – undo
1389 1389
                             //let's verify if we need this extra field via the shortcodes parameter.
1390 1390
                             $continue = false;
1391 1391
                             if (isset($extra_array['shortcodes_required'])) {
1392
-                                foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1392
+                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1393 1393
                                     if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1394 1394
                                         $continue = true;
1395 1395
                                     }
@@ -1399,7 +1399,7 @@  discard block
 block discarded – undo
1399 1399
                                 }
1400 1400
                             }
1401 1401
                             
1402
-                            $field_id                                = $reference_field
1402
+                            $field_id = $reference_field
1403 1403
                                                                        . '-'
1404 1404
                                                                        . $extra_field
1405 1405
                                                                        . '-content';
@@ -1407,8 +1407,8 @@  discard block
 block discarded – undo
1407 1407
                             $template_form_fields[$field_id]['name'] = 'MTP_template_fields['
1408 1408
                                                                        . $reference_field
1409 1409
                                                                        . '][content]['
1410
-                                                                       . $extra_field . ']';
1411
-                            $css_class                               = isset($extra_array['css_class'])
1410
+                                                                       . $extra_field.']';
1411
+                            $css_class = isset($extra_array['css_class'])
1412 1412
                                 ? $extra_array['css_class']
1413 1413
                                 : '';
1414 1414
                             
@@ -1419,7 +1419,7 @@  discard block
 block discarded – undo
1419 1419
                                     is_array($validators[$extra_field])
1420 1420
                                     && isset($validators[$extra_field]['msg'])
1421 1421
                                 )
1422
-                                ? 'validate-error ' . $css_class
1422
+                                ? 'validate-error '.$css_class
1423 1423
                                 : $css_class;
1424 1424
                             
1425 1425
                             $template_form_fields[$field_id]['value'] = ! empty($message_templates)
@@ -1450,11 +1450,11 @@  discard block
 block discarded – undo
1450 1450
                                 
1451 1451
                             }/**/
1452 1452
                         }
1453
-                        $templatefield_MTP_id          = $reference_field . '-MTP_ID';
1454
-                        $templatefield_templatename_id = $reference_field . '-name';
1453
+                        $templatefield_MTP_id          = $reference_field.'-MTP_ID';
1454
+                        $templatefield_templatename_id = $reference_field.'-name';
1455 1455
                         
1456 1456
                         $template_form_fields[$templatefield_MTP_id] = array(
1457
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1457
+                            'name'       => 'MTP_template_fields['.$reference_field.'][MTP_ID]',
1458 1458
                             'label'      => null,
1459 1459
                             'input'      => 'hidden',
1460 1460
                             'type'       => 'int',
@@ -1467,7 +1467,7 @@  discard block
 block discarded – undo
1467 1467
                         );
1468 1468
                         
1469 1469
                         $template_form_fields[$templatefield_templatename_id] = array(
1470
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1470
+                            'name'       => 'MTP_template_fields['.$reference_field.'][name]',
1471 1471
                             'label'      => null,
1472 1472
                             'input'      => 'hidden',
1473 1473
                             'type'       => 'string',
@@ -1481,9 +1481,9 @@  discard block
 block discarded – undo
1481 1481
                     }
1482 1482
                     continue; //skip the next stuff, we got the necessary fields here for this dataset.
1483 1483
                 } else {
1484
-                    $field_id                                 = $template_field . '-content';
1484
+                    $field_id                                 = $template_field.'-content';
1485 1485
                     $template_form_fields[$field_id]          = $field_setup_array;
1486
-                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1486
+                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields['.$template_field.'][content]';
1487 1487
                     $message_template                         = isset($message_templates[$context][$template_field])
1488 1488
                         ? $message_templates[$context][$template_field]
1489 1489
                         : null;
@@ -1506,7 +1506,7 @@  discard block
 block discarded – undo
1506 1506
                     $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1507 1507
                                                                     && in_array($template_field, $v_fields, true)
1508 1508
                                                                     && isset($validators[$template_field]['msg'])
1509
-                        ? 'validate-error ' . $css_class
1509
+                        ? 'validate-error '.$css_class
1510 1510
                         : $css_class;
1511 1511
                     
1512 1512
                     //shortcode selector
@@ -1517,12 +1517,12 @@  discard block
 block discarded – undo
1517 1517
                 
1518 1518
                 //k took care of content field(s) now let's take care of others.
1519 1519
                 
1520
-                $templatefield_MTP_id                = $template_field . '-MTP_ID';
1521
-                $templatefield_field_templatename_id = $template_field . '-name';
1520
+                $templatefield_MTP_id                = $template_field.'-MTP_ID';
1521
+                $templatefield_field_templatename_id = $template_field.'-name';
1522 1522
                 
1523 1523
                 //foreach template field there are actually two form fields created
1524 1524
                 $template_form_fields[$templatefield_MTP_id] = array(
1525
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1525
+                    'name'       => 'MTP_template_fields['.$template_field.'][MTP_ID]',
1526 1526
                     'label'      => null,
1527 1527
                     'input'      => 'hidden',
1528 1528
                     'type'       => 'int',
@@ -1535,7 +1535,7 @@  discard block
 block discarded – undo
1535 1535
                 );
1536 1536
                 
1537 1537
                 $template_form_fields[$templatefield_field_templatename_id] = array(
1538
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1538
+                    'name'       => 'MTP_template_fields['.$template_field.'][name]',
1539 1539
                     'label'      => null,
1540 1540
                     'input'      => 'hidden',
1541 1541
                     'type'       => 'string',
@@ -1653,7 +1653,7 @@  discard block
 block discarded – undo
1653 1653
                 'format'     => '%d',
1654 1654
                 'db-col'     => 'MTP_deleted'
1655 1655
             );
1656
-            $sidebar_form_fields['ee-msg-author']  = array(
1656
+            $sidebar_form_fields['ee-msg-author'] = array(
1657 1657
                 'name'       => 'MTP_user_id',
1658 1658
                 'label'      => esc_html__('Author', 'event_espresso'),
1659 1659
                 'input'      => 'hidden',
@@ -1672,17 +1672,17 @@  discard block
 block discarded – undo
1672 1672
                 'value' => $action
1673 1673
             );
1674 1674
             
1675
-            $sidebar_form_fields['ee-msg-id']        = array(
1675
+            $sidebar_form_fields['ee-msg-id'] = array(
1676 1676
                 'name'  => 'id',
1677 1677
                 'input' => 'hidden',
1678 1678
                 'type'  => 'int',
1679 1679
                 'value' => $GRP_ID
1680 1680
             );
1681 1681
             $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1682
-                'name'  => $action . '_nonce',
1682
+                'name'  => $action.'_nonce',
1683 1683
                 'input' => 'hidden',
1684 1684
                 'type'  => 'string',
1685
-                'value' => wp_create_nonce($action . '_nonce')
1685
+                'value' => wp_create_nonce($action.'_nonce')
1686 1686
             );
1687 1687
             
1688 1688
             if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
@@ -1714,7 +1714,7 @@  discard block
 block discarded – undo
1714 1714
         );
1715 1715
         
1716 1716
         //add preview button
1717
-        $preview_url    = parent::add_query_args_and_nonce(
1717
+        $preview_url = parent::add_query_args_and_nonce(
1718 1718
             array(
1719 1719
                 'message_type' => $message_template_group->message_type(),
1720 1720
                 'messenger'    => $message_template_group->messenger(),
@@ -1724,7 +1724,7 @@  discard block
 block discarded – undo
1724 1724
             ),
1725 1725
             $this->_admin_base_url
1726 1726
         );
1727
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1727
+        $preview_button = '<a href="'.$preview_url.'" class="button-secondary messages-preview-button">'
1728 1728
                           . esc_html__('Preview', 'event_espresso')
1729 1729
                           . '</a>';
1730 1730
         
@@ -1761,7 +1761,7 @@  discard block
 block discarded – undo
1761 1761
         
1762 1762
         $this->_template_path = $this->_template_args['GRP_ID']
1763 1763
             ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1764
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1764
+            : EE_MSG_TEMPLATE_PATH.'ee_msg_details_main_add_meta_box.template.php';
1765 1765
         
1766 1766
         //send along EE_Message_Template_Group object for further template use.
1767 1767
         $this->_template_args['MTP'] = $message_template_group;
@@ -1816,7 +1816,7 @@  discard block
 block discarded – undo
1816 1816
     ) {
1817 1817
         $template_args = array(
1818 1818
             'context' => $context,
1819
-            'nonce' => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1819
+            'nonce' => wp_create_nonce('activate_'.$context.'_toggle_nonce'),
1820 1820
             'is_active' => $message_template_group->is_context_active($context),
1821 1821
             'on_off_action' => $message_template_group->is_context_active($context)
1822 1822
                 ? 'context-off'
@@ -1825,7 +1825,7 @@  discard block
 block discarded – undo
1825 1825
             'message_template_group_id' => $message_template_group->ID()
1826 1826
         );
1827 1827
         return EEH_Template::display_template(
1828
-          EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1828
+          EE_MSG_TEMPLATE_PATH.'ee_msg_editor_active_context_element.template.php',
1829 1829
           $template_args,
1830 1830
           true
1831 1831
         );
@@ -1845,7 +1845,7 @@  discard block
 block discarded – undo
1845 1845
     {
1846 1846
         $success = true;
1847 1847
         //check for required data
1848
-        if (!isset(
1848
+        if ( ! isset(
1849 1849
             $this->_req_data['message_template_group_id'],
1850 1850
             $this->_req_data['context'],
1851 1851
             $this->_req_data['status']
@@ -1862,10 +1862,10 @@  discard block
 block discarded – undo
1862 1862
         $nonce = isset($this->_req_data['toggle_context_nonce'])
1863 1863
             ? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1864 1864
             : '';
1865
-        $nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1865
+        $nonce_ref = 'activate_'.$this->_req_data['context'].'_toggle_nonce';
1866 1866
         $this->_verify_nonce($nonce, $nonce_ref);
1867 1867
         $status = $this->_req_data['status'];
1868
-        if ($status !== 'off' && $status !=='on') {
1868
+        if ($status !== 'off' && $status !== 'on') {
1869 1869
             EE_Error::add_error(
1870 1870
                 sprintf(
1871 1871
                     esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
@@ -1880,7 +1880,7 @@  discard block
 block discarded – undo
1880 1880
         $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1881 1881
             $this->_req_data['message_template_group_id']
1882 1882
         );
1883
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1883
+        if ( ! $message_template_group instanceof EE_Message_Template_Group) {
1884 1884
             EE_Error::add_error(
1885 1885
                 sprintf(
1886 1886
                     esc_html__(
@@ -2125,7 +2125,7 @@  discard block
 block discarded – undo
2125 2125
         }
2126 2126
         
2127 2127
         //let's add a button to go back to the edit view
2128
-        $query_args             = array(
2128
+        $query_args = array(
2129 2129
             'id'      => $this->_req_data['GRP_ID'],
2130 2130
             'context' => $this->_req_data['context'],
2131 2131
             'action'  => 'edit_message_template'
@@ -2151,7 +2151,7 @@  discard block
 block discarded – undo
2151 2151
         );
2152 2152
         //setup display of preview.
2153 2153
         $this->_admin_page_title                    = $preview_title;
2154
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2154
+        $this->_template_args['admin_page_content'] = $preview_button.'<br />'.$preview;
2155 2155
         $this->_template_args['data']['force_json'] = true;
2156 2156
         
2157 2157
         return '';
@@ -2257,7 +2257,7 @@  discard block
 block discarded – undo
2257 2257
         }
2258 2258
         
2259 2259
         //setup variation select values for the currently selected template.
2260
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
2260
+        $variations = $this->_message_template_group->get_template_pack()->get_variations(
2261 2261
             $this->_message_template_group->messenger(),
2262 2262
             $this->_message_template_group->message_type()
2263 2263
         );
@@ -2271,12 +2271,12 @@  discard block
 block discarded – undo
2271 2271
         
2272 2272
         $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2273 2273
         
2274
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
2274
+        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2275 2275
             'MTP_template_pack',
2276 2276
             $tp_select_values,
2277 2277
             $this->_message_template_group->get_template_pack_name()
2278 2278
         );
2279
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
2279
+        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
2280 2280
             'MTP_template_variation',
2281 2281
             $variations_select_values,
2282 2282
             $this->_message_template_group->get_template_pack_variation()
@@ -2286,7 +2286,7 @@  discard block
 block discarded – undo
2286 2286
         $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
2287 2287
         $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2288 2288
         
2289
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2289
+        $template = EE_MSG_TEMPLATE_PATH.'template_pack_and_variations_metabox.template.php';
2290 2290
         
2291 2291
         EEH_Template::display_template($template, $template_args);
2292 2292
     }
@@ -2315,14 +2315,14 @@  discard block
 block discarded – undo
2315 2315
         if ( ! empty($fields)) {
2316 2316
             //yup there be fields
2317 2317
             foreach ($fields as $field => $config) {
2318
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2318
+                $field_id = $this->_message_template_group->messenger().'_'.$field;
2319 2319
                 $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2320 2320
                 $default  = isset($config['default']) ? $config['default'] : '';
2321 2321
                 $default  = isset($config['value']) ? $config['value'] : $default;
2322 2322
                 
2323 2323
                 // if type is hidden and the value is empty
2324 2324
                 // something may have gone wrong so let's correct with the defaults
2325
-                $fix              = $config['input'] === 'hidden'
2325
+                $fix = $config['input'] === 'hidden'
2326 2326
                                     && isset($existing[$field])
2327 2327
                                     && empty($existing[$field])
2328 2328
                     ? $default
@@ -2332,7 +2332,7 @@  discard block
 block discarded – undo
2332 2332
                     : $fix;
2333 2333
                 
2334 2334
                 $template_form_fields[$field_id] = array(
2335
-                    'name'       => 'test_settings_fld[' . $field . ']',
2335
+                    'name'       => 'test_settings_fld['.$field.']',
2336 2336
                     'label'      => $config['label'],
2337 2337
                     'input'      => $config['input'],
2338 2338
                     'type'       => $config['type'],
@@ -2400,7 +2400,7 @@  discard block
 block discarded – undo
2400 2400
         );
2401 2401
         
2402 2402
         return EEH_Template::display_template(
2403
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2403
+            EE_MSG_TEMPLATE_PATH.'shortcode_selector_skeleton.template.php',
2404 2404
             $template_args,
2405 2405
             true
2406 2406
         );
@@ -2425,7 +2425,7 @@  discard block
 block discarded – undo
2425 2425
         //$messenger = $this->_message_template_group->messenger_obj();
2426 2426
         //now let's set the content depending on the status of the shortcodes array
2427 2427
         if (empty($shortcodes)) {
2428
-            $content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2428
+            $content = '<p>'.esc_html__('There are no valid shortcodes available', 'event_espresso').'</p>';
2429 2429
             echo $content;
2430 2430
         } else {
2431 2431
             //$alt = 0;
@@ -2562,7 +2562,7 @@  discard block
 block discarded – undo
2562 2562
                     <?php
2563 2563
                 }
2564 2564
                 //setup nonce_url
2565
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2565
+                wp_nonce_field($args['action'].'_nonce', $args['action'].'_nonce', false);
2566 2566
                 ?>
2567 2567
                 <select name="context">
2568 2568
                     <?php
@@ -2663,7 +2663,7 @@  discard block
 block discarded – undo
2663 2663
         $context      = ucwords(str_replace('_', ' ', $context_slug));
2664 2664
         
2665 2665
         $item_desc = $messenger_label && $message_type_label
2666
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2666
+            ? $messenger_label.' '.$message_type_label.' '.$context.' '
2667 2667
             : '';
2668 2668
         $item_desc .= 'Message Template';
2669 2669
         $query_args  = array();
@@ -2736,9 +2736,9 @@  discard block
 block discarded – undo
2736 2736
                             'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2737 2737
                         );
2738 2738
                         //if they aren't allowed to use all JS, restrict them to just posty-y tags
2739
-                        if (! current_user_can('unfiltered_html')){
2740
-                            if (is_array($set_column_values['MTP_content'])){
2741
-                                 foreach($set_column_values['MTP_content'] as $key => $value) {
2739
+                        if ( ! current_user_can('unfiltered_html')) {
2740
+                            if (is_array($set_column_values['MTP_content'])) {
2741
+                                 foreach ($set_column_values['MTP_content'] as $key => $value) {
2742 2742
                                      //remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2743 2743
                                      //only removes slashes from double-quotes, so attributes using single quotes always
2744 2744
                                      //appear invalid.) But currently the models expect slashed data, so after wp_kses
@@ -2787,7 +2787,7 @@  discard block
 block discarded – undo
2787 2787
                                 //default setup for it.
2788 2788
                                 //@link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2789 2789
                                 $updated = $MTP->insert($message_template_fields);
2790
-                                if (! $updated || is_wp_error($updated)) {
2790
+                                if ( ! $updated || is_wp_error($updated)) {
2791 2791
                                     EE_Error::add_error(
2792 2792
                                         sprintf(
2793 2793
                                             esc_html__('%s field could not be updated.', 'event_espresso'),
@@ -3148,7 +3148,7 @@  discard block
 block discarded – undo
3148 3148
             : 'email';
3149 3149
         
3150 3150
         //let's setup the messenger tabs
3151
-        $this->_template_args['admin_page_header']         = EEH_Tabbed_Content::tab_text_links(
3151
+        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3152 3152
             $this->_m_mt_settings['messenger_tabs'],
3153 3153
             'messenger_links',
3154 3154
             '|',
@@ -3216,10 +3216,10 @@  discard block
 block discarded – undo
3216 3216
                 
3217 3217
                 $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
3218 3218
                     'label'    => ucwords($message_type->label['singular']),
3219
-                    'class'    => 'message-type-' . $a_or_i,
3220
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3221
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3222
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3219
+                    'class'    => 'message-type-'.$a_or_i,
3220
+                    'slug_id'  => $message_type->name.'-messagetype-'.$messenger->name,
3221
+                    'mt_nonce' => wp_create_nonce($message_type->name.'_nonce'),
3222
+                    'href'     => 'espresso_'.$message_type->name.'_message_type_settings',
3223 3223
                     'title'    => $a_or_i === 'active'
3224 3224
                         ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3225 3225
                         : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
@@ -3255,9 +3255,9 @@  discard block
 block discarded – undo
3255 3255
             $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3256 3256
             
3257 3257
             foreach ($fields as $fldname => $fldprops) {
3258
-                $field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3258
+                $field_id                       = $messenger->name.'-'.$message_type->name.'-'.$fldname;
3259 3259
                 $template_form_field[$field_id] = array(
3260
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3260
+                    'name'       => 'message_type_settings['.$fldname.']',
3261 3261
                     'label'      => $fldprops['label'],
3262 3262
                     'input'      => $fldprops['field_type'],
3263 3263
                     'type'       => $fldprops['value_type'],
@@ -3308,12 +3308,12 @@  discard block
 block discarded – undo
3308 3308
             $settings_template_args['hidden_fields'],
3309 3309
             'array'
3310 3310
         );
3311
-        $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields'])
3311
+        $settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3312 3312
             ? ' hidden'
3313 3313
             : '';
3314 3314
         
3315 3315
         
3316
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3316
+        $template = EE_MSG_TEMPLATE_PATH.'ee_msg_mt_settings_content.template.php';
3317 3317
         $content  = EEH_Template::display_template($template, $settings_template_args, true);
3318 3318
         
3319 3319
         return $content;
@@ -3348,11 +3348,11 @@  discard block
 block discarded – undo
3348 3348
                 )
3349 3349
                     ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
3350 3350
                     : '';
3351
-                $m_boxes[$messenger . '_a_box']         = sprintf(
3351
+                $m_boxes[$messenger.'_a_box'] = sprintf(
3352 3352
                     esc_html__('%s Settings', 'event_espresso'),
3353 3353
                     $tab_array['label']
3354 3354
                 );
3355
-                $m_template_args[$messenger . '_a_box'] = array(
3355
+                $m_template_args[$messenger.'_a_box'] = array(
3356 3356
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3357 3357
                     'inactive_message_types' => isset(
3358 3358
                         $this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
@@ -3368,8 +3368,8 @@  discard block
 block discarded – undo
3368 3368
                 // message type meta boxes
3369 3369
                 // (which is really just the inactive container for each messenger
3370 3370
                 // showing inactive message types for that messenger)
3371
-                $mt_boxes[$messenger . '_i_box']         = esc_html__('Inactive Message Types', 'event_espresso');
3372
-                $mt_template_args[$messenger . '_i_box'] = array(
3371
+                $mt_boxes[$messenger.'_i_box']         = esc_html__('Inactive Message Types', 'event_espresso');
3372
+                $mt_template_args[$messenger.'_i_box'] = array(
3373 3373
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3374 3374
                     'inactive_message_types' => isset(
3375 3375
                         $this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
@@ -3387,14 +3387,14 @@  discard block
 block discarded – undo
3387 3387
         
3388 3388
         
3389 3389
         //register messenger metaboxes
3390
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3390
+        $m_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_mt_meta_box.template.php';
3391 3391
         foreach ($m_boxes as $box => $label) {
3392 3392
             $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
3393 3393
             $msgr          = str_replace('_a_box', '', $box);
3394 3394
             add_meta_box(
3395
-                'espresso_' . $msgr . '_settings',
3395
+                'espresso_'.$msgr.'_settings',
3396 3396
                 $label,
3397
-                function ($post, $metabox) {
3397
+                function($post, $metabox) {
3398 3398
                     echo EEH_Template::display_template(
3399 3399
                             $metabox["args"]["template_path"],
3400 3400
                             $metabox["args"]["template_args"],
@@ -3409,17 +3409,17 @@  discard block
 block discarded – undo
3409 3409
         }
3410 3410
         
3411 3411
         //register message type metaboxes
3412
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3412
+        $mt_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_meta_box.template.php';
3413 3413
         foreach ($mt_boxes as $box => $label) {
3414 3414
             $callback_args = array(
3415 3415
                 'template_path' => $mt_template_path,
3416 3416
                 'template_args' => $mt_template_args[$box]
3417 3417
             );
3418
-            $mt            = str_replace('_i_box', '', $box);
3418
+            $mt = str_replace('_i_box', '', $box);
3419 3419
             add_meta_box(
3420
-                'espresso_' . $mt . '_inactive_mts',
3420
+                'espresso_'.$mt.'_inactive_mts',
3421 3421
                 $label,
3422
-                function ($post, $metabox) {
3422
+                function($post, $metabox) {
3423 3423
                     echo EEH_Template::display_template(
3424 3424
                             $metabox["args"]["template_path"],
3425 3425
                             $metabox["args"]["template_args"],
@@ -3566,7 +3566,7 @@  discard block
 block discarded – undo
3566 3566
             if ($form->is_valid()) {
3567 3567
                 $valid_data = $form->valid_data();
3568 3568
                 foreach ($valid_data as $property => $value) {
3569
-                    $setter = 'set_' . $property;
3569
+                    $setter = 'set_'.$property;
3570 3570
                     if (method_exists($network_config, $setter)) {
3571 3571
                         $network_config->{$setter}($value);
3572 3572
                     } else if (
@@ -3601,8 +3601,8 @@  discard block
 block discarded – undo
3601 3601
      */
3602 3602
     protected function _get_mt_tabs($tab_array)
3603 3603
     {
3604
-        $tab_array = (array)$tab_array;
3605
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3604
+        $tab_array = (array) $tab_array;
3605
+        $template  = EE_MSG_TEMPLATE_PATH.'ee_msg_details_mt_settings_tab_item.template.php';
3606 3606
         $tabs      = '';
3607 3607
         
3608 3608
         foreach ($tab_array as $tab) {
@@ -3635,9 +3635,9 @@  discard block
 block discarded – undo
3635 3635
             $existing_settings = $messenger->get_existing_admin_settings();
3636 3636
             
3637 3637
             foreach ($fields as $fldname => $fldprops) {
3638
-                $field_id                       = $messenger->name . '-' . $fldname;
3638
+                $field_id                       = $messenger->name.'-'.$fldname;
3639 3639
                 $template_form_field[$field_id] = array(
3640
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3640
+                    'name'       => 'messenger_settings['.$field_id.']',
3641 3641
                     'label'      => $fldprops['label'],
3642 3642
                     'input'      => $fldprops['field_type'],
3643 3643
                     'type'       => $fldprops['value_type'],
@@ -3672,7 +3672,7 @@  discard block
 block discarded – undo
3672 3672
         //make sure any active message types that are existing are included in the hidden fields
3673 3673
         if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3674 3674
             foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3675
-                $settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3675
+                $settings_template_args['hidden_fields']['messenger_settings[message_types]['.$mt.']'] = array(
3676 3676
                     'type'  => 'hidden',
3677 3677
                     'value' => $mt
3678 3678
                 );
@@ -3701,9 +3701,9 @@  discard block
 block discarded – undo
3701 3701
         
3702 3702
         
3703 3703
         $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3704
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3704
+        $settings_template_args['nonce']         = wp_create_nonce('activate_'.$messenger->name.'_toggle_nonce');
3705 3705
         $settings_template_args['on_off_status'] = $active ? true : false;
3706
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3706
+        $template                                = EE_MSG_TEMPLATE_PATH.'ee_msg_m_settings_content.template.php';
3707 3707
         $content                                 = EEH_Template::display_template(
3708 3708
             $template,
3709 3709
             $settings_template_args,
@@ -3743,7 +3743,7 @@  discard block
 block discarded – undo
3743 3743
         $nonce     = isset($this->_req_data['activate_nonce'])
3744 3744
             ? sanitize_text_field($this->_req_data['activate_nonce'])
3745 3745
             : '';
3746
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3746
+        $nonce_ref = 'activate_'.$this->_req_data['messenger'].'_toggle_nonce';
3747 3747
         
3748 3748
         $this->_verify_nonce($nonce, $nonce_ref);
3749 3749
         
@@ -3859,7 +3859,7 @@  discard block
 block discarded – undo
3859 3859
         
3860 3860
         //do a nonce check here since we're not arriving via a normal route
3861 3861
         $nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3862
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3862
+        $nonce_ref = $this->_req_data['message_type'].'_nonce';
3863 3863
         
3864 3864
         $this->_verify_nonce($nonce, $nonce_ref);
3865 3865
         
@@ -4220,7 +4220,7 @@  discard block
 block discarded – undo
4220 4220
         $message_type = $message_types[$this->_req_data['message_type']];
4221 4221
         $messenger    = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4222 4222
         
4223
-        $content                         = $this->_message_type_settings_content(
4223
+        $content = $this->_message_type_settings_content(
4224 4224
             $message_type,
4225 4225
             $messenger,
4226 4226
             true
Please login to merge, or discard this patch.
Indentation   +4081 added lines, -4081 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
 use EventEspresso\core\exceptions\InvalidInterfaceException;
6 6
 
7 7
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
8
-    exit('NO direct script access allowed');
8
+	exit('NO direct script access allowed');
9 9
 }
10 10
 
11 11
 /**
@@ -23,2554 +23,2554 @@  discard block
 block discarded – undo
23 23
 class Messages_Admin_Page extends EE_Admin_Page
24 24
 {
25 25
     
26
-    /**
27
-     * @type EE_Message_Resource_Manager $_message_resource_manager
28
-     */
29
-    protected $_message_resource_manager;
26
+	/**
27
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
28
+	 */
29
+	protected $_message_resource_manager;
30 30
     
31
-    /**
32
-     * @type string $_active_message_type_name
33
-     */
34
-    protected $_active_message_type_name = '';
31
+	/**
32
+	 * @type string $_active_message_type_name
33
+	 */
34
+	protected $_active_message_type_name = '';
35 35
     
36
-    /**
37
-     * @type EE_messenger $_active_messenger
38
-     */
39
-    protected $_active_messenger;
40
-    protected $_activate_state;
41
-    protected $_activate_meta_box_type;
42
-    protected $_current_message_meta_box;
43
-    protected $_current_message_meta_box_object;
44
-    protected $_context_switcher;
45
-    protected $_shortcodes = array();
46
-    protected $_active_messengers = array();
47
-    protected $_active_message_types = array();
36
+	/**
37
+	 * @type EE_messenger $_active_messenger
38
+	 */
39
+	protected $_active_messenger;
40
+	protected $_activate_state;
41
+	protected $_activate_meta_box_type;
42
+	protected $_current_message_meta_box;
43
+	protected $_current_message_meta_box_object;
44
+	protected $_context_switcher;
45
+	protected $_shortcodes = array();
46
+	protected $_active_messengers = array();
47
+	protected $_active_message_types = array();
48 48
     
49
-    /**
50
-     * @var EE_Message_Template_Group $_message_template_group
51
-     */
52
-    protected $_message_template_group;
53
-    protected $_m_mt_settings = array();
49
+	/**
50
+	 * @var EE_Message_Template_Group $_message_template_group
51
+	 */
52
+	protected $_message_template_group;
53
+	protected $_m_mt_settings = array();
54 54
     
55 55
     
56
-    /**
57
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
58
-     * IF there is no group then it gets automatically set to the Default template pack.
59
-     *
60
-     * @since 4.5.0
61
-     *
62
-     * @var EE_Messages_Template_Pack
63
-     */
64
-    protected $_template_pack;
56
+	/**
57
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
58
+	 * IF there is no group then it gets automatically set to the Default template pack.
59
+	 *
60
+	 * @since 4.5.0
61
+	 *
62
+	 * @var EE_Messages_Template_Pack
63
+	 */
64
+	protected $_template_pack;
65 65
     
66 66
     
67
-    /**
68
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
69
-     * group is.  If there is no group then it automatically gets set to default.
70
-     *
71
-     * @since 4.5.0
72
-     *
73
-     * @var string
74
-     */
75
-    protected $_variation;
67
+	/**
68
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
69
+	 * group is.  If there is no group then it automatically gets set to default.
70
+	 *
71
+	 * @since 4.5.0
72
+	 *
73
+	 * @var string
74
+	 */
75
+	protected $_variation;
76 76
 
77 77
 
78
-    /**
79
-     * @param bool $routing
80
-     * @throws EE_Error
81
-     */
82
-    public function __construct($routing = true)
83
-    {
84
-        //make sure messages autoloader is running
85
-        EED_Messages::set_autoloaders();
86
-        parent::__construct($routing);
87
-    }
78
+	/**
79
+	 * @param bool $routing
80
+	 * @throws EE_Error
81
+	 */
82
+	public function __construct($routing = true)
83
+	{
84
+		//make sure messages autoloader is running
85
+		EED_Messages::set_autoloaders();
86
+		parent::__construct($routing);
87
+	}
88 88
     
89 89
     
90
-    protected function _init_page_props()
91
-    {
92
-        $this->page_slug        = EE_MSG_PG_SLUG;
93
-        $this->page_label       = esc_html__('Messages Settings', 'event_espresso');
94
-        $this->_admin_base_url  = EE_MSG_ADMIN_URL;
95
-        $this->_admin_base_path = EE_MSG_ADMIN;
96
-        
97
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
98
-        
99
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
100
-        $this->_load_message_resource_manager();
101
-    }
90
+	protected function _init_page_props()
91
+	{
92
+		$this->page_slug        = EE_MSG_PG_SLUG;
93
+		$this->page_label       = esc_html__('Messages Settings', 'event_espresso');
94
+		$this->_admin_base_url  = EE_MSG_ADMIN_URL;
95
+		$this->_admin_base_path = EE_MSG_ADMIN;
96
+        
97
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
98
+        
99
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
100
+		$this->_load_message_resource_manager();
101
+	}
102 102
 
103 103
 
104
-    /**
105
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
106
-     *
107
-     * @throws EE_Error
108
-     * @throws InvalidDataTypeException
109
-     * @throws InvalidInterfaceException
110
-     * @throws InvalidArgumentException
111
-     * @throws ReflectionException
112
-     */
113
-    protected function _load_message_resource_manager()
114
-    {
115
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
116
-    }
104
+	/**
105
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
106
+	 *
107
+	 * @throws EE_Error
108
+	 * @throws InvalidDataTypeException
109
+	 * @throws InvalidInterfaceException
110
+	 * @throws InvalidArgumentException
111
+	 * @throws ReflectionException
112
+	 */
113
+	protected function _load_message_resource_manager()
114
+	{
115
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
116
+	}
117 117
 
118 118
 
119
-    /**
120
-     * @deprecated 4.9.9.rc.014
121
-     * @return array
122
-     * @throws EE_Error
123
-     * @throws InvalidArgumentException
124
-     * @throws InvalidDataTypeException
125
-     * @throws InvalidInterfaceException
126
-     */
127
-    public function get_messengers_for_list_table()
128
-    {
129
-        EE_Error::doing_it_wrong(
130
-            __METHOD__,
131
-            sprintf(
132
-                esc_html__(
133
-                    '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',
134
-                    'event_espresso'
135
-                ),
136
-                'Messages_Admin_Page::get_messengers_select_input()'
137
-            ),
138
-            '4.9.9.rc.014'
139
-        );
140
-        
141
-        $m_values          = array();
142
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
143
-        //setup messengers for selects
144
-        $i = 1;
145
-        foreach ($active_messengers as $active_messenger) {
146
-            if ($active_messenger instanceof EE_Message) {
147
-                $m_values[$i]['id']   = $active_messenger->messenger();
148
-                $m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
149
-                $i++;
150
-            }
151
-        }
152
-        
153
-        return $m_values;
154
-    }
119
+	/**
120
+	 * @deprecated 4.9.9.rc.014
121
+	 * @return array
122
+	 * @throws EE_Error
123
+	 * @throws InvalidArgumentException
124
+	 * @throws InvalidDataTypeException
125
+	 * @throws InvalidInterfaceException
126
+	 */
127
+	public function get_messengers_for_list_table()
128
+	{
129
+		EE_Error::doing_it_wrong(
130
+			__METHOD__,
131
+			sprintf(
132
+				esc_html__(
133
+					'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',
134
+					'event_espresso'
135
+				),
136
+				'Messages_Admin_Page::get_messengers_select_input()'
137
+			),
138
+			'4.9.9.rc.014'
139
+		);
140
+        
141
+		$m_values          = array();
142
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
143
+		//setup messengers for selects
144
+		$i = 1;
145
+		foreach ($active_messengers as $active_messenger) {
146
+			if ($active_messenger instanceof EE_Message) {
147
+				$m_values[$i]['id']   = $active_messenger->messenger();
148
+				$m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
149
+				$i++;
150
+			}
151
+		}
152
+        
153
+		return $m_values;
154
+	}
155 155
 
156 156
 
157
-    /**
158
-     * @deprecated 4.9.9.rc.014
159
-     * @return array
160
-     * @throws EE_Error
161
-     * @throws InvalidArgumentException
162
-     * @throws InvalidDataTypeException
163
-     * @throws InvalidInterfaceException
164
-     */
165
-    public function get_message_types_for_list_table()
166
-    {
167
-        EE_Error::doing_it_wrong(
168
-            __METHOD__,
169
-            sprintf(
170
-                esc_html__(
171
-                    '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',
172
-                    'event_espresso'
173
-                ),
174
-                'Messages_Admin_Page::get_message_types_select_input()'
175
-            ),
176
-            '4.9.9.rc.014'
177
-        );
178
-        
179
-        $mt_values       = array();
180
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
181
-        $i               = 1;
182
-        foreach ($active_messages as $active_message) {
183
-            if ($active_message instanceof EE_Message) {
184
-                $mt_values[$i]['id']   = $active_message->message_type();
185
-                $mt_values[$i]['text'] = ucwords($active_message->message_type_label());
186
-                $i++;
187
-            }
188
-        }
189
-        
190
-        return $mt_values;
191
-    }
157
+	/**
158
+	 * @deprecated 4.9.9.rc.014
159
+	 * @return array
160
+	 * @throws EE_Error
161
+	 * @throws InvalidArgumentException
162
+	 * @throws InvalidDataTypeException
163
+	 * @throws InvalidInterfaceException
164
+	 */
165
+	public function get_message_types_for_list_table()
166
+	{
167
+		EE_Error::doing_it_wrong(
168
+			__METHOD__,
169
+			sprintf(
170
+				esc_html__(
171
+					'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',
172
+					'event_espresso'
173
+				),
174
+				'Messages_Admin_Page::get_message_types_select_input()'
175
+			),
176
+			'4.9.9.rc.014'
177
+		);
178
+        
179
+		$mt_values       = array();
180
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
181
+		$i               = 1;
182
+		foreach ($active_messages as $active_message) {
183
+			if ($active_message instanceof EE_Message) {
184
+				$mt_values[$i]['id']   = $active_message->message_type();
185
+				$mt_values[$i]['text'] = ucwords($active_message->message_type_label());
186
+				$i++;
187
+			}
188
+		}
189
+        
190
+		return $mt_values;
191
+	}
192 192
 
193 193
 
194
-    /**
195
-     * @deprecated 4.9.9.rc.014
196
-     * @return array
197
-     * @throws EE_Error
198
-     * @throws InvalidArgumentException
199
-     * @throws InvalidDataTypeException
200
-     * @throws InvalidInterfaceException
201
-     */
202
-    public function get_contexts_for_message_types_for_list_table()
203
-    {
204
-        EE_Error::doing_it_wrong(
205
-            __METHOD__,
206
-            sprintf(
207
-                esc_html__(
208
-                    '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',
209
-                    'event_espresso'
210
-                ),
211
-                'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
212
-            ),
213
-            '4.9.9.rc.014'
214
-        );
215
-        
216
-        $contexts                = array();
217
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
218
-        foreach ($active_message_contexts as $active_message) {
219
-            if ($active_message instanceof EE_Message) {
220
-                $message_type = $active_message->message_type_object();
221
-                if ($message_type instanceof EE_message_type) {
222
-                    $message_type_contexts = $message_type->get_contexts();
223
-                    foreach ($message_type_contexts as $context => $context_details) {
224
-                        $contexts[$context] = $context_details['label'];
225
-                    }
226
-                }
227
-            }
228
-        }
229
-        
230
-        return $contexts;
231
-    }
194
+	/**
195
+	 * @deprecated 4.9.9.rc.014
196
+	 * @return array
197
+	 * @throws EE_Error
198
+	 * @throws InvalidArgumentException
199
+	 * @throws InvalidDataTypeException
200
+	 * @throws InvalidInterfaceException
201
+	 */
202
+	public function get_contexts_for_message_types_for_list_table()
203
+	{
204
+		EE_Error::doing_it_wrong(
205
+			__METHOD__,
206
+			sprintf(
207
+				esc_html__(
208
+					'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',
209
+					'event_espresso'
210
+				),
211
+				'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
212
+			),
213
+			'4.9.9.rc.014'
214
+		);
215
+        
216
+		$contexts                = array();
217
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
218
+		foreach ($active_message_contexts as $active_message) {
219
+			if ($active_message instanceof EE_Message) {
220
+				$message_type = $active_message->message_type_object();
221
+				if ($message_type instanceof EE_message_type) {
222
+					$message_type_contexts = $message_type->get_contexts();
223
+					foreach ($message_type_contexts as $context => $context_details) {
224
+						$contexts[$context] = $context_details['label'];
225
+					}
226
+				}
227
+			}
228
+		}
229
+        
230
+		return $contexts;
231
+	}
232 232
 
233 233
 
234
-    /**
235
-     * Generate select input with provided messenger options array.
236
-     *
237
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
238
-     *                                 labels.
239
-     * @return string
240
-     * @throws EE_Error
241
-     */
242
-    public function get_messengers_select_input($messenger_options)
243
-    {
244
-        //if empty or just one value then just return an empty string
245
-        if (empty($messenger_options)
246
-            || ! is_array($messenger_options)
247
-            || count($messenger_options) === 1
248
-        ) {
249
-            return '';
250
-        }
251
-        //merge in default
252
-        $messenger_options = array_merge(
253
-            array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
254
-            $messenger_options
255
-        );
256
-        $input             = new EE_Select_Input(
257
-            $messenger_options,
258
-            array(
259
-                'html_name'  => 'ee_messenger_filter_by',
260
-                'html_id'    => 'ee_messenger_filter_by',
261
-                'html_class' => 'wide',
262
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
263
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
264
-                    : 'none_selected'
265
-            )
266
-        );
267
-        
268
-        return $input->get_html_for_input();
269
-    }
234
+	/**
235
+	 * Generate select input with provided messenger options array.
236
+	 *
237
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
238
+	 *                                 labels.
239
+	 * @return string
240
+	 * @throws EE_Error
241
+	 */
242
+	public function get_messengers_select_input($messenger_options)
243
+	{
244
+		//if empty or just one value then just return an empty string
245
+		if (empty($messenger_options)
246
+			|| ! is_array($messenger_options)
247
+			|| count($messenger_options) === 1
248
+		) {
249
+			return '';
250
+		}
251
+		//merge in default
252
+		$messenger_options = array_merge(
253
+			array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
254
+			$messenger_options
255
+		);
256
+		$input             = new EE_Select_Input(
257
+			$messenger_options,
258
+			array(
259
+				'html_name'  => 'ee_messenger_filter_by',
260
+				'html_id'    => 'ee_messenger_filter_by',
261
+				'html_class' => 'wide',
262
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
263
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
264
+					: 'none_selected'
265
+			)
266
+		);
267
+        
268
+		return $input->get_html_for_input();
269
+	}
270 270
 
271 271
 
272
-    /**
273
-     * Generate select input with provided message type options array.
274
-     *
275
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
276
-     *                                    message type labels
277
-     * @return string
278
-     * @throws EE_Error
279
-     */
280
-    public function get_message_types_select_input($message_type_options)
281
-    {
282
-        //if empty or count of options is 1 then just return an empty string
283
-        if (empty($message_type_options)
284
-            || ! is_array($message_type_options)
285
-            || count($message_type_options) === 1
286
-        ) {
287
-            return '';
288
-        }
289
-        //merge in default
290
-        $message_type_options = array_merge(
291
-            array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
292
-            $message_type_options
293
-        );
294
-        $input                = new EE_Select_Input(
295
-            $message_type_options,
296
-            array(
297
-                'html_name'  => 'ee_message_type_filter_by',
298
-                'html_id'    => 'ee_message_type_filter_by',
299
-                'html_class' => 'wide',
300
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
301
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
302
-                    : 'none_selected',
303
-            )
304
-        );
305
-        
306
-        return $input->get_html_for_input();
307
-    }
272
+	/**
273
+	 * Generate select input with provided message type options array.
274
+	 *
275
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
276
+	 *                                    message type labels
277
+	 * @return string
278
+	 * @throws EE_Error
279
+	 */
280
+	public function get_message_types_select_input($message_type_options)
281
+	{
282
+		//if empty or count of options is 1 then just return an empty string
283
+		if (empty($message_type_options)
284
+			|| ! is_array($message_type_options)
285
+			|| count($message_type_options) === 1
286
+		) {
287
+			return '';
288
+		}
289
+		//merge in default
290
+		$message_type_options = array_merge(
291
+			array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
292
+			$message_type_options
293
+		);
294
+		$input                = new EE_Select_Input(
295
+			$message_type_options,
296
+			array(
297
+				'html_name'  => 'ee_message_type_filter_by',
298
+				'html_id'    => 'ee_message_type_filter_by',
299
+				'html_class' => 'wide',
300
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
301
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
302
+					: 'none_selected',
303
+			)
304
+		);
305
+        
306
+		return $input->get_html_for_input();
307
+	}
308 308
 
309 309
 
310
-    /**
311
-     * Generate select input with provide message type contexts array.
312
-     *
313
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
314
-     *                               context label.
315
-     * @return string
316
-     * @throws EE_Error
317
-     */
318
-    public function get_contexts_for_message_types_select_input($context_options)
319
-    {
320
-        //if empty or count of options is one then just return empty string
321
-        if (empty($context_options)
322
-            || ! is_array($context_options)
323
-            || count($context_options) === 1
324
-        ) {
325
-            return '';
326
-        }
327
-        //merge in default
328
-        $context_options = array_merge(
329
-            array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
330
-            $context_options
331
-        );
332
-        $input           = new EE_Select_Input(
333
-            $context_options,
334
-            array(
335
-                'html_name'  => 'ee_context_filter_by',
336
-                'html_id'    => 'ee_context_filter_by',
337
-                'html_class' => 'wide',
338
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
339
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
340
-                    : 'none_selected',
341
-            )
342
-        );
343
-        
344
-        return $input->get_html_for_input();
345
-    }
310
+	/**
311
+	 * Generate select input with provide message type contexts array.
312
+	 *
313
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
314
+	 *                               context label.
315
+	 * @return string
316
+	 * @throws EE_Error
317
+	 */
318
+	public function get_contexts_for_message_types_select_input($context_options)
319
+	{
320
+		//if empty or count of options is one then just return empty string
321
+		if (empty($context_options)
322
+			|| ! is_array($context_options)
323
+			|| count($context_options) === 1
324
+		) {
325
+			return '';
326
+		}
327
+		//merge in default
328
+		$context_options = array_merge(
329
+			array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
330
+			$context_options
331
+		);
332
+		$input           = new EE_Select_Input(
333
+			$context_options,
334
+			array(
335
+				'html_name'  => 'ee_context_filter_by',
336
+				'html_id'    => 'ee_context_filter_by',
337
+				'html_class' => 'wide',
338
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
339
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
340
+					: 'none_selected',
341
+			)
342
+		);
343
+        
344
+		return $input->get_html_for_input();
345
+	}
346 346
     
347 347
     
348
-    protected function _ajax_hooks()
349
-    {
350
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
351
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
352
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
353
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
354
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
355
-        add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
356
-    }
348
+	protected function _ajax_hooks()
349
+	{
350
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
351
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
352
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
353
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
354
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
355
+		add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
356
+	}
357 357
     
358 358
     
359
-    protected function _define_page_props()
360
-    {
361
-        $this->_admin_page_title = $this->page_label;
362
-        $this->_labels           = array(
363
-            'buttons'    => array(
364
-                'add'    => esc_html__('Add New Message Template', 'event_espresso'),
365
-                'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
366
-                'delete' => esc_html__('Delete Message Template', 'event_espresso')
367
-            ),
368
-            'publishbox' => esc_html__('Update Actions', 'event_espresso')
369
-        );
370
-    }
359
+	protected function _define_page_props()
360
+	{
361
+		$this->_admin_page_title = $this->page_label;
362
+		$this->_labels           = array(
363
+			'buttons'    => array(
364
+				'add'    => esc_html__('Add New Message Template', 'event_espresso'),
365
+				'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
366
+				'delete' => esc_html__('Delete Message Template', 'event_espresso')
367
+			),
368
+			'publishbox' => esc_html__('Update Actions', 'event_espresso')
369
+		);
370
+	}
371 371
     
372 372
     
373
-    /**
374
-     *        an array for storing key => value pairs of request actions and their corresponding methods
375
-     * @access protected
376
-     * @return void
377
-     */
378
-    protected function _set_page_routes()
379
-    {
380
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
381
-            ? $this->_req_data['GRP_ID']
382
-            : 0;
383
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
384
-            ? $this->_req_data['id']
385
-            : $grp_id;
386
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
387
-            ? $this->_req_data['MSG_ID']
388
-            : 0;
389
-        
390
-        $this->_page_routes = array(
391
-            'default'                          => array(
392
-                'func'       => '_message_queue_list_table',
393
-                'capability' => 'ee_read_global_messages'
394
-            ),
395
-            'global_mtps'                      => array(
396
-                'func'       => '_ee_default_messages_overview_list_table',
397
-                'capability' => 'ee_read_global_messages'
398
-            ),
399
-            'custom_mtps'                      => array(
400
-                'func'       => '_custom_mtps_preview',
401
-                'capability' => 'ee_read_messages'
402
-            ),
403
-            'add_new_message_template'         => array(
404
-                'func'       => '_add_message_template',
405
-                'capability' => 'ee_edit_messages',
406
-                'noheader'   => true
407
-            ),
408
-            'edit_message_template'            => array(
409
-                'func'       => '_edit_message_template',
410
-                'capability' => 'ee_edit_message',
411
-                'obj_id'     => $grp_id
412
-            ),
413
-            'preview_message'                  => array(
414
-                'func'               => '_preview_message',
415
-                'capability'         => 'ee_read_message',
416
-                'obj_id'             => $grp_id,
417
-                'noheader'           => true,
418
-                'headers_sent_route' => 'display_preview_message'
419
-            ),
420
-            'display_preview_message'          => array(
421
-                'func'       => '_display_preview_message',
422
-                'capability' => 'ee_read_message',
423
-                'obj_id'     => $grp_id
424
-            ),
425
-            'insert_message_template'          => array(
426
-                'func'       => '_insert_or_update_message_template',
427
-                'capability' => 'ee_edit_messages',
428
-                'args'       => array('new_template' => true),
429
-                'noheader'   => true
430
-            ),
431
-            'update_message_template'          => array(
432
-                'func'       => '_insert_or_update_message_template',
433
-                'capability' => 'ee_edit_message',
434
-                'obj_id'     => $grp_id,
435
-                'args'       => array('new_template' => false),
436
-                'noheader'   => true
437
-            ),
438
-            'trash_message_template'           => array(
439
-                'func'       => '_trash_or_restore_message_template',
440
-                'capability' => 'ee_delete_message',
441
-                'obj_id'     => $grp_id,
442
-                'args'       => array('trash' => true, 'all' => true),
443
-                'noheader'   => true
444
-            ),
445
-            'trash_message_template_context'   => array(
446
-                'func'       => '_trash_or_restore_message_template',
447
-                'capability' => 'ee_delete_message',
448
-                'obj_id'     => $grp_id,
449
-                'args'       => array('trash' => true),
450
-                'noheader'   => true
451
-            ),
452
-            'restore_message_template'         => array(
453
-                'func'       => '_trash_or_restore_message_template',
454
-                'capability' => 'ee_delete_message',
455
-                'obj_id'     => $grp_id,
456
-                'args'       => array('trash' => false, 'all' => true),
457
-                'noheader'   => true
458
-            ),
459
-            'restore_message_template_context' => array(
460
-                'func'       => '_trash_or_restore_message_template',
461
-                'capability' => 'ee_delete_message',
462
-                'obj_id'     => $grp_id,
463
-                'args'       => array('trash' => false),
464
-                'noheader'   => true
465
-            ),
466
-            'delete_message_template'          => array(
467
-                'func'       => '_delete_message_template',
468
-                'capability' => 'ee_delete_message',
469
-                'obj_id'     => $grp_id,
470
-                'noheader'   => true
471
-            ),
472
-            'reset_to_default'                 => array(
473
-                'func'       => '_reset_to_default_template',
474
-                'capability' => 'ee_edit_message',
475
-                'obj_id'     => $grp_id,
476
-                'noheader'   => true
477
-            ),
478
-            'settings'                         => array(
479
-                'func'       => '_settings',
480
-                'capability' => 'manage_options'
481
-            ),
482
-            'update_global_settings'           => array(
483
-                'func'       => '_update_global_settings',
484
-                'capability' => 'manage_options',
485
-                'noheader'   => true
486
-            ),
487
-            'generate_now'                     => array(
488
-                'func'       => '_generate_now',
489
-                'capability' => 'ee_send_message',
490
-                'noheader'   => true
491
-            ),
492
-            'generate_and_send_now'            => array(
493
-                'func'       => '_generate_and_send_now',
494
-                'capability' => 'ee_send_message',
495
-                'noheader'   => true
496
-            ),
497
-            'queue_for_resending'              => array(
498
-                'func'       => '_queue_for_resending',
499
-                'capability' => 'ee_send_message',
500
-                'noheader'   => true
501
-            ),
502
-            'send_now'                         => array(
503
-                'func'       => '_send_now',
504
-                'capability' => 'ee_send_message',
505
-                'noheader'   => true
506
-            ),
507
-            'delete_ee_message'                => array(
508
-                'func'       => '_delete_ee_messages',
509
-                'capability' => 'ee_delete_messages',
510
-                'noheader'   => true
511
-            ),
512
-            'delete_ee_messages'               => array(
513
-                'func'       => '_delete_ee_messages',
514
-                'capability' => 'ee_delete_messages',
515
-                'noheader'   => true,
516
-                'obj_id'     => $msg_id
517
-            )
518
-        );
519
-    }
373
+	/**
374
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
375
+	 * @access protected
376
+	 * @return void
377
+	 */
378
+	protected function _set_page_routes()
379
+	{
380
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
381
+			? $this->_req_data['GRP_ID']
382
+			: 0;
383
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
384
+			? $this->_req_data['id']
385
+			: $grp_id;
386
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
387
+			? $this->_req_data['MSG_ID']
388
+			: 0;
389
+        
390
+		$this->_page_routes = array(
391
+			'default'                          => array(
392
+				'func'       => '_message_queue_list_table',
393
+				'capability' => 'ee_read_global_messages'
394
+			),
395
+			'global_mtps'                      => array(
396
+				'func'       => '_ee_default_messages_overview_list_table',
397
+				'capability' => 'ee_read_global_messages'
398
+			),
399
+			'custom_mtps'                      => array(
400
+				'func'       => '_custom_mtps_preview',
401
+				'capability' => 'ee_read_messages'
402
+			),
403
+			'add_new_message_template'         => array(
404
+				'func'       => '_add_message_template',
405
+				'capability' => 'ee_edit_messages',
406
+				'noheader'   => true
407
+			),
408
+			'edit_message_template'            => array(
409
+				'func'       => '_edit_message_template',
410
+				'capability' => 'ee_edit_message',
411
+				'obj_id'     => $grp_id
412
+			),
413
+			'preview_message'                  => array(
414
+				'func'               => '_preview_message',
415
+				'capability'         => 'ee_read_message',
416
+				'obj_id'             => $grp_id,
417
+				'noheader'           => true,
418
+				'headers_sent_route' => 'display_preview_message'
419
+			),
420
+			'display_preview_message'          => array(
421
+				'func'       => '_display_preview_message',
422
+				'capability' => 'ee_read_message',
423
+				'obj_id'     => $grp_id
424
+			),
425
+			'insert_message_template'          => array(
426
+				'func'       => '_insert_or_update_message_template',
427
+				'capability' => 'ee_edit_messages',
428
+				'args'       => array('new_template' => true),
429
+				'noheader'   => true
430
+			),
431
+			'update_message_template'          => array(
432
+				'func'       => '_insert_or_update_message_template',
433
+				'capability' => 'ee_edit_message',
434
+				'obj_id'     => $grp_id,
435
+				'args'       => array('new_template' => false),
436
+				'noheader'   => true
437
+			),
438
+			'trash_message_template'           => array(
439
+				'func'       => '_trash_or_restore_message_template',
440
+				'capability' => 'ee_delete_message',
441
+				'obj_id'     => $grp_id,
442
+				'args'       => array('trash' => true, 'all' => true),
443
+				'noheader'   => true
444
+			),
445
+			'trash_message_template_context'   => array(
446
+				'func'       => '_trash_or_restore_message_template',
447
+				'capability' => 'ee_delete_message',
448
+				'obj_id'     => $grp_id,
449
+				'args'       => array('trash' => true),
450
+				'noheader'   => true
451
+			),
452
+			'restore_message_template'         => array(
453
+				'func'       => '_trash_or_restore_message_template',
454
+				'capability' => 'ee_delete_message',
455
+				'obj_id'     => $grp_id,
456
+				'args'       => array('trash' => false, 'all' => true),
457
+				'noheader'   => true
458
+			),
459
+			'restore_message_template_context' => array(
460
+				'func'       => '_trash_or_restore_message_template',
461
+				'capability' => 'ee_delete_message',
462
+				'obj_id'     => $grp_id,
463
+				'args'       => array('trash' => false),
464
+				'noheader'   => true
465
+			),
466
+			'delete_message_template'          => array(
467
+				'func'       => '_delete_message_template',
468
+				'capability' => 'ee_delete_message',
469
+				'obj_id'     => $grp_id,
470
+				'noheader'   => true
471
+			),
472
+			'reset_to_default'                 => array(
473
+				'func'       => '_reset_to_default_template',
474
+				'capability' => 'ee_edit_message',
475
+				'obj_id'     => $grp_id,
476
+				'noheader'   => true
477
+			),
478
+			'settings'                         => array(
479
+				'func'       => '_settings',
480
+				'capability' => 'manage_options'
481
+			),
482
+			'update_global_settings'           => array(
483
+				'func'       => '_update_global_settings',
484
+				'capability' => 'manage_options',
485
+				'noheader'   => true
486
+			),
487
+			'generate_now'                     => array(
488
+				'func'       => '_generate_now',
489
+				'capability' => 'ee_send_message',
490
+				'noheader'   => true
491
+			),
492
+			'generate_and_send_now'            => array(
493
+				'func'       => '_generate_and_send_now',
494
+				'capability' => 'ee_send_message',
495
+				'noheader'   => true
496
+			),
497
+			'queue_for_resending'              => array(
498
+				'func'       => '_queue_for_resending',
499
+				'capability' => 'ee_send_message',
500
+				'noheader'   => true
501
+			),
502
+			'send_now'                         => array(
503
+				'func'       => '_send_now',
504
+				'capability' => 'ee_send_message',
505
+				'noheader'   => true
506
+			),
507
+			'delete_ee_message'                => array(
508
+				'func'       => '_delete_ee_messages',
509
+				'capability' => 'ee_delete_messages',
510
+				'noheader'   => true
511
+			),
512
+			'delete_ee_messages'               => array(
513
+				'func'       => '_delete_ee_messages',
514
+				'capability' => 'ee_delete_messages',
515
+				'noheader'   => true,
516
+				'obj_id'     => $msg_id
517
+			)
518
+		);
519
+	}
520 520
     
521 521
     
522
-    protected function _set_page_config()
523
-    {
524
-        $this->_page_config = array(
525
-            'default'                  => array(
526
-                'nav'           => array(
527
-                    'label' => esc_html__('Message Activity', 'event_espresso'),
528
-                    'order' => 10
529
-                ),
530
-                'list_table'    => 'EE_Message_List_Table',
531
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
532
-                'require_nonce' => false
533
-            ),
534
-            'global_mtps'              => array(
535
-                'nav'           => array(
536
-                    'label' => esc_html__('Default Message Templates', 'event_espresso'),
537
-                    'order' => 20
538
-                ),
539
-                'list_table'    => 'Messages_Template_List_Table',
540
-                'help_tabs'     => array(
541
-                    'messages_overview_help_tab'                                => array(
542
-                        'title'    => esc_html__('Messages Overview', 'event_espresso'),
543
-                        'filename' => 'messages_overview'
544
-                    ),
545
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
546
-                        'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
547
-                        'filename' => 'messages_overview_table_column_headings'
548
-                    ),
549
-                    'messages_overview_messages_filters_help_tab'               => array(
550
-                        'title'    => esc_html__('Message Filters', 'event_espresso'),
551
-                        'filename' => 'messages_overview_filters'
552
-                    ),
553
-                    'messages_overview_messages_views_help_tab'                 => array(
554
-                        'title'    => esc_html__('Message Views', 'event_espresso'),
555
-                        'filename' => 'messages_overview_views'
556
-                    ),
557
-                    'message_overview_message_types_help_tab'                   => array(
558
-                        'title'    => esc_html__('Message Types', 'event_espresso'),
559
-                        'filename' => 'messages_overview_types'
560
-                    ),
561
-                    'messages_overview_messengers_help_tab'                     => array(
562
-                        'title'    => esc_html__('Messengers', 'event_espresso'),
563
-                        'filename' => 'messages_overview_messengers',
564
-                    ),
565
-                ),
566
-                'help_tour'     => array('Messages_Overview_Help_Tour'),
567
-                'require_nonce' => false
568
-            ),
569
-            'custom_mtps'              => array(
570
-                'nav'           => array(
571
-                    'label' => esc_html__('Custom Message Templates', 'event_espresso'),
572
-                    'order' => 30
573
-                ),
574
-                'help_tabs'     => array(),
575
-                'help_tour'     => array(),
576
-                'require_nonce' => false
577
-            ),
578
-            'add_new_message_template' => array(
579
-                'nav'           => array(
580
-                    'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
581
-                    'order'      => 5,
582
-                    'persistent' => false
583
-                ),
584
-                'require_nonce' => false
585
-            ),
586
-            'edit_message_template'    => array(
587
-                'labels'        => array(
588
-                    'buttons'    => array(
589
-                        'reset' => esc_html__('Reset Templates'),
590
-                    ),
591
-                    'publishbox' => esc_html__('Update Actions', 'event_espresso')
592
-                ),
593
-                'nav'           => array(
594
-                    'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
595
-                    'order'      => 5,
596
-                    'persistent' => false,
597
-                    'url'        => ''
598
-                ),
599
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
600
-                'has_metaboxes' => true,
601
-                'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
602
-                'help_tabs'     => array(
603
-                    'edit_message_template'       => array(
604
-                        'title'    => esc_html__('Message Template Editor', 'event_espresso'),
605
-                        'callback' => 'edit_message_template_help_tab'
606
-                    ),
607
-                    'message_templates_help_tab'  => array(
608
-                        'title'    => esc_html__('Message Templates', 'event_espresso'),
609
-                        'filename' => 'messages_templates'
610
-                    ),
611
-                    'message_template_shortcodes' => array(
612
-                        'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
613
-                        'callback' => 'message_template_shortcodes_help_tab'
614
-                    ),
615
-                    'message_preview_help_tab'    => array(
616
-                        'title'    => esc_html__('Message Preview', 'event_espresso'),
617
-                        'filename' => 'messages_preview'
618
-                    ),
619
-                    'messages_overview_other_help_tab'                          => array(
620
-                        'title'    => esc_html__('Messages Other', 'event_espresso'),
621
-                        'filename' => 'messages_overview_other',
622
-                    ),
623
-                ),
624
-                'require_nonce' => false
625
-            ),
626
-            'display_preview_message'  => array(
627
-                'nav'           => array(
628
-                    'label'      => esc_html__('Message Preview', 'event_espresso'),
629
-                    'order'      => 5,
630
-                    'url'        => '',
631
-                    'persistent' => false
632
-                ),
633
-                'help_tabs'     => array(
634
-                    'preview_message' => array(
635
-                        'title'    => esc_html__('About Previews', 'event_espresso'),
636
-                        'callback' => 'preview_message_help_tab'
637
-                    )
638
-                ),
639
-                'require_nonce' => false
640
-            ),
641
-            'settings'                 => array(
642
-                'nav'           => array(
643
-                    'label' => esc_html__('Settings', 'event_espresso'),
644
-                    'order' => 40
645
-                ),
646
-                'metaboxes'     => array('_messages_settings_metaboxes'),
647
-                'help_tabs'     => array(
648
-                    'messages_settings_help_tab'               => array(
649
-                        'title'    => esc_html__('Messages Settings', 'event_espresso'),
650
-                        'filename' => 'messages_settings'
651
-                    ),
652
-                    'messages_settings_message_types_help_tab' => array(
653
-                        'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
654
-                        'filename' => 'messages_settings_message_types'
655
-                    ),
656
-                    'messages_settings_messengers_help_tab'    => array(
657
-                        'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
658
-                        'filename' => 'messages_settings_messengers'
659
-                    ),
660
-                ),
661
-                'help_tour'     => array('Messages_Settings_Help_Tour'),
662
-                'require_nonce' => false
663
-            )
664
-        );
665
-    }
522
+	protected function _set_page_config()
523
+	{
524
+		$this->_page_config = array(
525
+			'default'                  => array(
526
+				'nav'           => array(
527
+					'label' => esc_html__('Message Activity', 'event_espresso'),
528
+					'order' => 10
529
+				),
530
+				'list_table'    => 'EE_Message_List_Table',
531
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
532
+				'require_nonce' => false
533
+			),
534
+			'global_mtps'              => array(
535
+				'nav'           => array(
536
+					'label' => esc_html__('Default Message Templates', 'event_espresso'),
537
+					'order' => 20
538
+				),
539
+				'list_table'    => 'Messages_Template_List_Table',
540
+				'help_tabs'     => array(
541
+					'messages_overview_help_tab'                                => array(
542
+						'title'    => esc_html__('Messages Overview', 'event_espresso'),
543
+						'filename' => 'messages_overview'
544
+					),
545
+					'messages_overview_messages_table_column_headings_help_tab' => array(
546
+						'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
547
+						'filename' => 'messages_overview_table_column_headings'
548
+					),
549
+					'messages_overview_messages_filters_help_tab'               => array(
550
+						'title'    => esc_html__('Message Filters', 'event_espresso'),
551
+						'filename' => 'messages_overview_filters'
552
+					),
553
+					'messages_overview_messages_views_help_tab'                 => array(
554
+						'title'    => esc_html__('Message Views', 'event_espresso'),
555
+						'filename' => 'messages_overview_views'
556
+					),
557
+					'message_overview_message_types_help_tab'                   => array(
558
+						'title'    => esc_html__('Message Types', 'event_espresso'),
559
+						'filename' => 'messages_overview_types'
560
+					),
561
+					'messages_overview_messengers_help_tab'                     => array(
562
+						'title'    => esc_html__('Messengers', 'event_espresso'),
563
+						'filename' => 'messages_overview_messengers',
564
+					),
565
+				),
566
+				'help_tour'     => array('Messages_Overview_Help_Tour'),
567
+				'require_nonce' => false
568
+			),
569
+			'custom_mtps'              => array(
570
+				'nav'           => array(
571
+					'label' => esc_html__('Custom Message Templates', 'event_espresso'),
572
+					'order' => 30
573
+				),
574
+				'help_tabs'     => array(),
575
+				'help_tour'     => array(),
576
+				'require_nonce' => false
577
+			),
578
+			'add_new_message_template' => array(
579
+				'nav'           => array(
580
+					'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
581
+					'order'      => 5,
582
+					'persistent' => false
583
+				),
584
+				'require_nonce' => false
585
+			),
586
+			'edit_message_template'    => array(
587
+				'labels'        => array(
588
+					'buttons'    => array(
589
+						'reset' => esc_html__('Reset Templates'),
590
+					),
591
+					'publishbox' => esc_html__('Update Actions', 'event_espresso')
592
+				),
593
+				'nav'           => array(
594
+					'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
595
+					'order'      => 5,
596
+					'persistent' => false,
597
+					'url'        => ''
598
+				),
599
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
600
+				'has_metaboxes' => true,
601
+				'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
602
+				'help_tabs'     => array(
603
+					'edit_message_template'       => array(
604
+						'title'    => esc_html__('Message Template Editor', 'event_espresso'),
605
+						'callback' => 'edit_message_template_help_tab'
606
+					),
607
+					'message_templates_help_tab'  => array(
608
+						'title'    => esc_html__('Message Templates', 'event_espresso'),
609
+						'filename' => 'messages_templates'
610
+					),
611
+					'message_template_shortcodes' => array(
612
+						'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
613
+						'callback' => 'message_template_shortcodes_help_tab'
614
+					),
615
+					'message_preview_help_tab'    => array(
616
+						'title'    => esc_html__('Message Preview', 'event_espresso'),
617
+						'filename' => 'messages_preview'
618
+					),
619
+					'messages_overview_other_help_tab'                          => array(
620
+						'title'    => esc_html__('Messages Other', 'event_espresso'),
621
+						'filename' => 'messages_overview_other',
622
+					),
623
+				),
624
+				'require_nonce' => false
625
+			),
626
+			'display_preview_message'  => array(
627
+				'nav'           => array(
628
+					'label'      => esc_html__('Message Preview', 'event_espresso'),
629
+					'order'      => 5,
630
+					'url'        => '',
631
+					'persistent' => false
632
+				),
633
+				'help_tabs'     => array(
634
+					'preview_message' => array(
635
+						'title'    => esc_html__('About Previews', 'event_espresso'),
636
+						'callback' => 'preview_message_help_tab'
637
+					)
638
+				),
639
+				'require_nonce' => false
640
+			),
641
+			'settings'                 => array(
642
+				'nav'           => array(
643
+					'label' => esc_html__('Settings', 'event_espresso'),
644
+					'order' => 40
645
+				),
646
+				'metaboxes'     => array('_messages_settings_metaboxes'),
647
+				'help_tabs'     => array(
648
+					'messages_settings_help_tab'               => array(
649
+						'title'    => esc_html__('Messages Settings', 'event_espresso'),
650
+						'filename' => 'messages_settings'
651
+					),
652
+					'messages_settings_message_types_help_tab' => array(
653
+						'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
654
+						'filename' => 'messages_settings_message_types'
655
+					),
656
+					'messages_settings_messengers_help_tab'    => array(
657
+						'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
658
+						'filename' => 'messages_settings_messengers'
659
+					),
660
+				),
661
+				'help_tour'     => array('Messages_Settings_Help_Tour'),
662
+				'require_nonce' => false
663
+			)
664
+		);
665
+	}
666 666
     
667 667
     
668
-    protected function _add_screen_options()
669
-    {
670
-        //todo
671
-    }
668
+	protected function _add_screen_options()
669
+	{
670
+		//todo
671
+	}
672 672
     
673 673
     
674
-    protected function _add_screen_options_global_mtps()
675
-    {
676
-        /**
677
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
678
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
679
-         */
680
-        $page_title              = $this->_admin_page_title;
681
-        $this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
682
-        $this->_per_page_screen_option();
683
-        $this->_admin_page_title = $page_title;
684
-    }
674
+	protected function _add_screen_options_global_mtps()
675
+	{
676
+		/**
677
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
678
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
679
+		 */
680
+		$page_title              = $this->_admin_page_title;
681
+		$this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
682
+		$this->_per_page_screen_option();
683
+		$this->_admin_page_title = $page_title;
684
+	}
685 685
     
686 686
     
687
-    protected function _add_screen_options_default()
688
-    {
689
-        $this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
690
-        $this->_per_page_screen_option();
691
-    }
687
+	protected function _add_screen_options_default()
688
+	{
689
+		$this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
690
+		$this->_per_page_screen_option();
691
+	}
692 692
     
693 693
     
694
-    //none of the below group are currently used for Messages
695
-    protected function _add_feature_pointers()
696
-    {
697
-    }
694
+	//none of the below group are currently used for Messages
695
+	protected function _add_feature_pointers()
696
+	{
697
+	}
698 698
     
699
-    public function admin_init()
700
-    {
701
-    }
699
+	public function admin_init()
700
+	{
701
+	}
702 702
     
703
-    public function admin_notices()
704
-    {
705
-    }
703
+	public function admin_notices()
704
+	{
705
+	}
706 706
     
707
-    public function admin_footer_scripts()
708
-    {
709
-    }
707
+	public function admin_footer_scripts()
708
+	{
709
+	}
710 710
     
711 711
     
712
-    public function messages_help_tab()
713
-    {
714
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
715
-    }
712
+	public function messages_help_tab()
713
+	{
714
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
715
+	}
716 716
     
717 717
     
718
-    public function messengers_help_tab()
719
-    {
720
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
721
-    }
718
+	public function messengers_help_tab()
719
+	{
720
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
721
+	}
722 722
     
723 723
     
724
-    public function message_types_help_tab()
725
-    {
726
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
727
-    }
724
+	public function message_types_help_tab()
725
+	{
726
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
727
+	}
728 728
     
729 729
     
730
-    public function messages_overview_help_tab()
731
-    {
732
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
733
-    }
730
+	public function messages_overview_help_tab()
731
+	{
732
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
733
+	}
734 734
     
735 735
     
736
-    public function message_templates_help_tab()
737
-    {
738
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
739
-    }
736
+	public function message_templates_help_tab()
737
+	{
738
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
739
+	}
740 740
     
741 741
     
742
-    public function edit_message_template_help_tab()
743
-    {
744
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
745
-                        . esc_attr__('Editor Title', 'event_espresso')
746
-                        . '" />';
747
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
748
-                        . esc_attr__('Context Switcher and Preview', 'event_espresso')
749
-                        . '" />';
750
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
751
-                        . esc_attr__('Message Template Form Fields', 'event_espresso')
752
-                        . '" />';
753
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
754
-                        . esc_attr__('Shortcodes Metabox', 'event_espresso')
755
-                        . '" />';
756
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
757
-                        . esc_attr__('Publish Metabox', 'event_espresso')
758
-                        . '" />';
759
-        EEH_Template::display_template(
760
-            EE_MSG_TEMPLATE_PATH  . 'ee_msg_messages_templates_editor_help_tab.template.php',
761
-            $args
762
-        );
763
-    }
742
+	public function edit_message_template_help_tab()
743
+	{
744
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
745
+						. esc_attr__('Editor Title', 'event_espresso')
746
+						. '" />';
747
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
748
+						. esc_attr__('Context Switcher and Preview', 'event_espresso')
749
+						. '" />';
750
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
751
+						. esc_attr__('Message Template Form Fields', 'event_espresso')
752
+						. '" />';
753
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
754
+						. esc_attr__('Shortcodes Metabox', 'event_espresso')
755
+						. '" />';
756
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
757
+						. esc_attr__('Publish Metabox', 'event_espresso')
758
+						. '" />';
759
+		EEH_Template::display_template(
760
+			EE_MSG_TEMPLATE_PATH  . 'ee_msg_messages_templates_editor_help_tab.template.php',
761
+			$args
762
+		);
763
+	}
764 764
     
765 765
     
766
-    public function message_template_shortcodes_help_tab()
767
-    {
768
-        $this->_set_shortcodes();
769
-        $args['shortcodes'] = $this->_shortcodes;
770
-        EEH_Template::display_template(
771
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
772
-            $args
773
-        );
774
-    }
766
+	public function message_template_shortcodes_help_tab()
767
+	{
768
+		$this->_set_shortcodes();
769
+		$args['shortcodes'] = $this->_shortcodes;
770
+		EEH_Template::display_template(
771
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
772
+			$args
773
+		);
774
+	}
775 775
     
776 776
     
777
-    public function preview_message_help_tab()
778
-    {
779
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
780
-    }
777
+	public function preview_message_help_tab()
778
+	{
779
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
780
+	}
781 781
     
782 782
     
783
-    public function settings_help_tab()
784
-    {
785
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
786
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
787
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
788
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
789
-        $args['img3'] = '<div class="switch">'
790
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
791
-                        . ' type="checkbox" checked="checked">'
792
-                        . '<label for="ee-on-off-toggle-on"></label>'
793
-                        . '</div>';
794
-        $args['img4'] = '<div class="switch">'
795
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
796
-                        . ' type="checkbox">'
797
-                        . '<label for="ee-on-off-toggle-on"></label>'
798
-                        . '</div>';
799
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
800
-    }
783
+	public function settings_help_tab()
784
+	{
785
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
786
+						. '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
787
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
788
+						. '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
789
+		$args['img3'] = '<div class="switch">'
790
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
791
+						. ' type="checkbox" checked="checked">'
792
+						. '<label for="ee-on-off-toggle-on"></label>'
793
+						. '</div>';
794
+		$args['img4'] = '<div class="switch">'
795
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
796
+						. ' type="checkbox">'
797
+						. '<label for="ee-on-off-toggle-on"></label>'
798
+						. '</div>';
799
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
800
+	}
801 801
     
802 802
     
803
-    public function load_scripts_styles()
804
-    {
805
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
806
-        wp_enqueue_style('espresso_ee_msg');
807
-        
808
-        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
-            array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
810
-        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
811
-            array('ee-dialog'), EVENT_ESPRESSO_VERSION);
812
-    }
803
+	public function load_scripts_styles()
804
+	{
805
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
806
+		wp_enqueue_style('espresso_ee_msg');
807
+        
808
+		wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
+			array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
810
+		wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
811
+			array('ee-dialog'), EVENT_ESPRESSO_VERSION);
812
+	}
813 813
     
814 814
     
815
-    public function load_scripts_styles_default()
816
-    {
817
-        wp_enqueue_script('ee-msg-list-table-js');
818
-    }
815
+	public function load_scripts_styles_default()
816
+	{
817
+		wp_enqueue_script('ee-msg-list-table-js');
818
+	}
819 819
     
820 820
     
821
-    public function wp_editor_css($mce_css)
822
-    {
823
-        //if we're on the edit_message_template route
824
-        if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
825
-            $message_type_name = $this->_active_message_type_name;
821
+	public function wp_editor_css($mce_css)
822
+	{
823
+		//if we're on the edit_message_template route
824
+		if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
825
+			$message_type_name = $this->_active_message_type_name;
826 826
             
827
-            //we're going to REPLACE the existing mce css
828
-            //we need to get the css file location from the active messenger
829
-            $mce_css = $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true,
830
-                'wpeditor', $this->_variation);
831
-        }
832
-        
833
-        return $mce_css;
834
-    }
827
+			//we're going to REPLACE the existing mce css
828
+			//we need to get the css file location from the active messenger
829
+			$mce_css = $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true,
830
+				'wpeditor', $this->_variation);
831
+		}
832
+        
833
+		return $mce_css;
834
+	}
835 835
     
836 836
     
837
-    public function load_scripts_styles_edit_message_template()
838
-    {
839
-        
840
-        $this->_set_shortcodes();
841
-        
842
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
843
-            esc_html__(
844
-                '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.',
845
-                'event_espresso'
846
-            ),
847
-            $this->_message_template_group->messenger_obj()->label['singular'],
848
-            $this->_message_template_group->message_type_obj()->label['singular']
849
-        );
850
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
851
-            '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?',
852
-            'event_espresso'
853
-        );
854
-        EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
855
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
856
-            'event_espresso'
857
-        );
858
-        
859
-        wp_register_script(
860
-            'ee_msgs_edit_js',
861
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
862
-            array('jquery'),
863
-            EVENT_ESPRESSO_VERSION
864
-        );
865
-        
866
-        wp_enqueue_script('ee_admin_js');
867
-        wp_enqueue_script('ee_msgs_edit_js');
868
-        
869
-        //add in special css for tiny_mce
870
-        add_filter('mce_css', array($this, 'wp_editor_css'));
871
-    }
837
+	public function load_scripts_styles_edit_message_template()
838
+	{
839
+        
840
+		$this->_set_shortcodes();
841
+        
842
+		EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
843
+			esc_html__(
844
+				'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.',
845
+				'event_espresso'
846
+			),
847
+			$this->_message_template_group->messenger_obj()->label['singular'],
848
+			$this->_message_template_group->message_type_obj()->label['singular']
849
+		);
850
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
851
+			'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?',
852
+			'event_espresso'
853
+		);
854
+		EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
855
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
856
+			'event_espresso'
857
+		);
858
+        
859
+		wp_register_script(
860
+			'ee_msgs_edit_js',
861
+			EE_MSG_ASSETS_URL . 'ee_message_editor.js',
862
+			array('jquery'),
863
+			EVENT_ESPRESSO_VERSION
864
+		);
865
+        
866
+		wp_enqueue_script('ee_admin_js');
867
+		wp_enqueue_script('ee_msgs_edit_js');
868
+        
869
+		//add in special css for tiny_mce
870
+		add_filter('mce_css', array($this, 'wp_editor_css'));
871
+	}
872 872
     
873 873
     
874
-    public function load_scripts_styles_display_preview_message()
875
-    {
876
-        
877
-        $this->_set_message_template_group();
878
-        
879
-        if (isset($this->_req_data['messenger'])) {
880
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
881
-                $this->_req_data['messenger']
882
-            );
883
-        }
884
-        
885
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
886
-        
887
-        
888
-        wp_enqueue_style('espresso_preview_css',
889
-            $this->_active_messenger->get_variation(
890
-                $this->_template_pack,
891
-                $message_type_name,
892
-                true,
893
-                'preview',
894
-                $this->_variation
895
-            )
896
-        );
897
-    }
874
+	public function load_scripts_styles_display_preview_message()
875
+	{
876
+        
877
+		$this->_set_message_template_group();
878
+        
879
+		if (isset($this->_req_data['messenger'])) {
880
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
881
+				$this->_req_data['messenger']
882
+			);
883
+		}
884
+        
885
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
886
+        
887
+        
888
+		wp_enqueue_style('espresso_preview_css',
889
+			$this->_active_messenger->get_variation(
890
+				$this->_template_pack,
891
+				$message_type_name,
892
+				true,
893
+				'preview',
894
+				$this->_variation
895
+			)
896
+		);
897
+	}
898 898
     
899 899
     
900
-    public function load_scripts_styles_settings()
901
-    {
902
-        wp_register_style(
903
-            'ee-message-settings',
904
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
905
-            array(),
906
-            EVENT_ESPRESSO_VERSION
907
-        );
908
-        wp_enqueue_style('ee-text-links');
909
-        wp_enqueue_style('ee-message-settings');
910
-        wp_enqueue_script('ee-messages-settings');
911
-    }
900
+	public function load_scripts_styles_settings()
901
+	{
902
+		wp_register_style(
903
+			'ee-message-settings',
904
+			EE_MSG_ASSETS_URL . 'ee_message_settings.css',
905
+			array(),
906
+			EVENT_ESPRESSO_VERSION
907
+		);
908
+		wp_enqueue_style('ee-text-links');
909
+		wp_enqueue_style('ee-message-settings');
910
+		wp_enqueue_script('ee-messages-settings');
911
+	}
912 912
     
913 913
     
914
-    /**
915
-     * set views array for List Table
916
-     */
917
-    public function _set_list_table_views_global_mtps()
918
-    {
919
-        $this->_views = array(
920
-            'in_use' => array(
921
-                'slug'        => 'in_use',
922
-                'label'       => esc_html__('In Use', 'event_espresso'),
923
-                'count'       => 0,
924
-            )
925
-        );
926
-    }
914
+	/**
915
+	 * set views array for List Table
916
+	 */
917
+	public function _set_list_table_views_global_mtps()
918
+	{
919
+		$this->_views = array(
920
+			'in_use' => array(
921
+				'slug'        => 'in_use',
922
+				'label'       => esc_html__('In Use', 'event_espresso'),
923
+				'count'       => 0,
924
+			)
925
+		);
926
+	}
927 927
 
928 928
 
929
-    /**
930
-     * Set views array for the Custom Template List Table
931
-     */
932
-    public function _set_list_table_views_custom_mtps()
933
-    {
934
-        $this->_set_list_table_views_global_mtps();
935
-        $this->_views['in_use']['bulk_action'] = array(
936
-                'trash_message_template' => esc_html__('Move to Trash', 'event_espresso')
937
-        );
938
-    }
929
+	/**
930
+	 * Set views array for the Custom Template List Table
931
+	 */
932
+	public function _set_list_table_views_custom_mtps()
933
+	{
934
+		$this->_set_list_table_views_global_mtps();
935
+		$this->_views['in_use']['bulk_action'] = array(
936
+				'trash_message_template' => esc_html__('Move to Trash', 'event_espresso')
937
+		);
938
+	}
939 939
 
940 940
 
941
-    /**
942
-     * set views array for message queue list table
943
-     *
944
-     * @throws InvalidDataTypeException
945
-     * @throws InvalidInterfaceException
946
-     * @throws InvalidArgumentException
947
-     * @throws EE_Error
948
-     * @throws ReflectionException
949
-     */
950
-    public function _set_list_table_views_default()
951
-    {
952
-        EE_Registry::instance()->load_helper('Template');
953
-        
954
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
955
-            'ee_send_message',
956
-            'message_list_table_bulk_actions'
957
-        )
958
-            ? array(
959
-                'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
960
-                'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
961
-                'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
962
-                'send_now'              => esc_html__('Send Now', 'event_espresso')
963
-            )
964
-            : array();
965
-        
966
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
967
-            'ee_delete_messages',
968
-            'message_list_table_bulk_actions'
969
-        )
970
-            ? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
971
-            : array();
972
-        
973
-        
974
-        $this->_views = array(
975
-            'all' => array(
976
-                'slug'        => 'all',
977
-                'label'       => esc_html__('All', 'event_espresso'),
978
-                'count'       => 0,
979
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action)
980
-            )
981
-        );
982
-        
983
-        
984
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
985
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
986
-                continue;
987
-            }
988
-            $status_bulk_actions = $common_bulk_actions;
989
-            //unset bulk actions not applying to status
990
-            if (! empty($status_bulk_actions)) {
991
-                switch ($status) {
992
-                    case EEM_Message::status_idle:
993
-                    case EEM_Message::status_resend:
994
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
995
-                        break;
941
+	/**
942
+	 * set views array for message queue list table
943
+	 *
944
+	 * @throws InvalidDataTypeException
945
+	 * @throws InvalidInterfaceException
946
+	 * @throws InvalidArgumentException
947
+	 * @throws EE_Error
948
+	 * @throws ReflectionException
949
+	 */
950
+	public function _set_list_table_views_default()
951
+	{
952
+		EE_Registry::instance()->load_helper('Template');
953
+        
954
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
955
+			'ee_send_message',
956
+			'message_list_table_bulk_actions'
957
+		)
958
+			? array(
959
+				'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
960
+				'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
961
+				'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
962
+				'send_now'              => esc_html__('Send Now', 'event_espresso')
963
+			)
964
+			: array();
965
+        
966
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
967
+			'ee_delete_messages',
968
+			'message_list_table_bulk_actions'
969
+		)
970
+			? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
971
+			: array();
972
+        
973
+        
974
+		$this->_views = array(
975
+			'all' => array(
976
+				'slug'        => 'all',
977
+				'label'       => esc_html__('All', 'event_espresso'),
978
+				'count'       => 0,
979
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action)
980
+			)
981
+		);
982
+        
983
+        
984
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
985
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
986
+				continue;
987
+			}
988
+			$status_bulk_actions = $common_bulk_actions;
989
+			//unset bulk actions not applying to status
990
+			if (! empty($status_bulk_actions)) {
991
+				switch ($status) {
992
+					case EEM_Message::status_idle:
993
+					case EEM_Message::status_resend:
994
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
995
+						break;
996 996
                     
997
-                    case EEM_Message::status_failed:
998
-                    case EEM_Message::status_debug_only:
999
-                    case EEM_Message::status_messenger_executing:
1000
-                        $status_bulk_actions = array();
1001
-                        break;
997
+					case EEM_Message::status_failed:
998
+					case EEM_Message::status_debug_only:
999
+					case EEM_Message::status_messenger_executing:
1000
+						$status_bulk_actions = array();
1001
+						break;
1002 1002
                     
1003
-                    case EEM_Message::status_incomplete:
1004
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1005
-                        break;
1003
+					case EEM_Message::status_incomplete:
1004
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1005
+						break;
1006 1006
                     
1007
-                    case EEM_Message::status_retry:
1008
-                    case EEM_Message::status_sent:
1009
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1010
-                        break;
1011
-                }
1012
-            }
1007
+					case EEM_Message::status_retry:
1008
+					case EEM_Message::status_sent:
1009
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1010
+						break;
1011
+				}
1012
+			}
1013 1013
 
1014
-            //skip adding messenger executing status to views because it will be included with the Failed view.
1015
-            if ( $status === EEM_Message::status_messenger_executing ) {
1016
-                continue;
1017
-            }
1014
+			//skip adding messenger executing status to views because it will be included with the Failed view.
1015
+			if ( $status === EEM_Message::status_messenger_executing ) {
1016
+				continue;
1017
+			}
1018 1018
             
1019
-            $this->_views[strtolower($status)] = array(
1020
-                'slug'        => strtolower($status),
1021
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1022
-                'count'       => 0,
1023
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action)
1024
-            );
1025
-        }
1026
-    }
1019
+			$this->_views[strtolower($status)] = array(
1020
+				'slug'        => strtolower($status),
1021
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1022
+				'count'       => 0,
1023
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action)
1024
+			);
1025
+		}
1026
+	}
1027 1027
     
1028 1028
     
1029
-    protected function _ee_default_messages_overview_list_table()
1030
-    {
1031
-        $this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1032
-        $this->display_admin_list_table_page_with_no_sidebar();
1033
-    }
1029
+	protected function _ee_default_messages_overview_list_table()
1030
+	{
1031
+		$this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1032
+		$this->display_admin_list_table_page_with_no_sidebar();
1033
+	}
1034 1034
     
1035 1035
     
1036
-    protected function _message_queue_list_table()
1037
-    {
1038
-        $this->_search_btn_label                   = esc_html__('Message Activity', 'event_espresso');
1039
-        $this->_template_args['per_column']        = 6;
1040
-        $this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
1041
-        $this->_template_args['before_list_table'] = '<h3>'
1042
-                                                     . EEM_Message::instance()->get_pretty_label_for_results()
1043
-                                                     . '</h3>';
1044
-        $this->display_admin_list_table_page_with_no_sidebar();
1045
-    }
1036
+	protected function _message_queue_list_table()
1037
+	{
1038
+		$this->_search_btn_label                   = esc_html__('Message Activity', 'event_espresso');
1039
+		$this->_template_args['per_column']        = 6;
1040
+		$this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
1041
+		$this->_template_args['before_list_table'] = '<h3>'
1042
+													 . EEM_Message::instance()->get_pretty_label_for_results()
1043
+													 . '</h3>';
1044
+		$this->display_admin_list_table_page_with_no_sidebar();
1045
+	}
1046 1046
     
1047 1047
     
1048
-    protected function _message_legend_items()
1049
-    {
1050
-        
1051
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
1052
-        $action_items       = array();
1053
-        
1054
-        foreach ($action_css_classes as $action_item => $action_details) {
1055
-            if ($action_item === 'see_notifications_for') {
1056
-                continue;
1057
-            }
1058
-            $action_items[$action_item] = array(
1059
-                'class' => $action_details['css_class'],
1060
-                'desc'  => $action_details['label']
1061
-            );
1062
-        }
1063
-        
1064
-        /** @type array $status_items status legend setup */
1065
-        $status_items = array(
1066
-            'sent_status'       => array(
1067
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1068
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
1069
-            ),
1070
-            'idle_status'       => array(
1071
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1072
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
1073
-            ),
1074
-            'failed_status'     => array(
1075
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1076
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
1077
-            ),
1078
-            'messenger_executing_status' => array(
1079
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1080
-                'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
1081
-            ),
1082
-            'resend_status'     => array(
1083
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1084
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
1085
-            ),
1086
-            'incomplete_status' => array(
1087
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1088
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
1089
-            ),
1090
-            'retry_status'      => array(
1091
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1092
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
1093
-            )
1094
-        );
1095
-        if (EEM_Message::debug()) {
1096
-            $status_items['debug_only_status'] = array(
1097
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1098
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1099
-            );
1100
-        }
1101
-        
1102
-        return array_merge($action_items, $status_items);
1103
-    }
1048
+	protected function _message_legend_items()
1049
+	{
1050
+        
1051
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
1052
+		$action_items       = array();
1053
+        
1054
+		foreach ($action_css_classes as $action_item => $action_details) {
1055
+			if ($action_item === 'see_notifications_for') {
1056
+				continue;
1057
+			}
1058
+			$action_items[$action_item] = array(
1059
+				'class' => $action_details['css_class'],
1060
+				'desc'  => $action_details['label']
1061
+			);
1062
+		}
1063
+        
1064
+		/** @type array $status_items status legend setup */
1065
+		$status_items = array(
1066
+			'sent_status'       => array(
1067
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1068
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
1069
+			),
1070
+			'idle_status'       => array(
1071
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1072
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
1073
+			),
1074
+			'failed_status'     => array(
1075
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1076
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
1077
+			),
1078
+			'messenger_executing_status' => array(
1079
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1080
+				'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
1081
+			),
1082
+			'resend_status'     => array(
1083
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1084
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
1085
+			),
1086
+			'incomplete_status' => array(
1087
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1088
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
1089
+			),
1090
+			'retry_status'      => array(
1091
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1092
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
1093
+			)
1094
+		);
1095
+		if (EEM_Message::debug()) {
1096
+			$status_items['debug_only_status'] = array(
1097
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1098
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1099
+			);
1100
+		}
1101
+        
1102
+		return array_merge($action_items, $status_items);
1103
+	}
1104 1104
     
1105 1105
     
1106
-    protected function _custom_mtps_preview()
1107
-    {
1108
-        $this->_admin_page_title              = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1109
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1110
-            . ' alt="' . esc_attr__('Preview Custom Message Templates screenshot', 'event_espresso') . '" />';
1111
-        $this->_template_args['preview_text'] = '<strong>'
1112
-            . esc_html__(
1113
-                '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.',
1114
-                'event_espresso'
1115
-            )
1116
-            . '</strong>';
1106
+	protected function _custom_mtps_preview()
1107
+	{
1108
+		$this->_admin_page_title              = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1109
+		$this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1110
+			. ' alt="' . esc_attr__('Preview Custom Message Templates screenshot', 'event_espresso') . '" />';
1111
+		$this->_template_args['preview_text'] = '<strong>'
1112
+			. esc_html__(
1113
+				'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.',
1114
+				'event_espresso'
1115
+			)
1116
+			. '</strong>';
1117 1117
 
1118
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1119
-    }
1118
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1119
+	}
1120 1120
 
1121 1121
 
1122
-    /**
1123
-     * get_message_templates
1124
-     * This gets all the message templates for listing on the overview list.
1125
-     *
1126
-     * @access public
1127
-     * @param int    $perpage the amount of templates groups to show per page
1128
-     * @param string $type    the current _view we're getting templates for
1129
-     * @param bool   $count   return count?
1130
-     * @param bool   $all     disregard any paging info (get all data);
1131
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1132
-     * @return array
1133
-     * @throws EE_Error
1134
-     * @throws InvalidArgumentException
1135
-     * @throws InvalidDataTypeException
1136
-     * @throws InvalidInterfaceException
1137
-     */
1138
-    public function get_message_templates(
1139
-        $perpage = 10,
1140
-        $type = 'in_use',
1141
-        $count = false,
1142
-        $all = false,
1143
-        $global = true)
1144
-    {
1145
-        
1146
-        $MTP = EEM_Message_Template_Group::instance();
1147
-        
1148
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1149
-        $orderby                    = $this->_req_data['orderby'];
1150
-        
1151
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1152
-            ? $this->_req_data['order']
1153
-            : 'ASC';
1154
-        
1155
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1156
-            ? $this->_req_data['paged']
1157
-            : 1;
1158
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1159
-            ? $this->_req_data['perpage']
1160
-            : $perpage;
1161
-        
1162
-        $offset = ($current_page - 1) * $per_page;
1163
-        $limit  = $all ? null : array($offset, $per_page);
1164
-        
1165
-        
1166
-        //options will match what is in the _views array property
1167
-        switch ($type) {
1168
-            case 'in_use':
1169
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1170
-                break;
1171
-            default:
1172
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1173
-        }
1174
-        
1175
-        return $templates;
1176
-    }
1122
+	/**
1123
+	 * get_message_templates
1124
+	 * This gets all the message templates for listing on the overview list.
1125
+	 *
1126
+	 * @access public
1127
+	 * @param int    $perpage the amount of templates groups to show per page
1128
+	 * @param string $type    the current _view we're getting templates for
1129
+	 * @param bool   $count   return count?
1130
+	 * @param bool   $all     disregard any paging info (get all data);
1131
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1132
+	 * @return array
1133
+	 * @throws EE_Error
1134
+	 * @throws InvalidArgumentException
1135
+	 * @throws InvalidDataTypeException
1136
+	 * @throws InvalidInterfaceException
1137
+	 */
1138
+	public function get_message_templates(
1139
+		$perpage = 10,
1140
+		$type = 'in_use',
1141
+		$count = false,
1142
+		$all = false,
1143
+		$global = true)
1144
+	{
1145
+        
1146
+		$MTP = EEM_Message_Template_Group::instance();
1147
+        
1148
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1149
+		$orderby                    = $this->_req_data['orderby'];
1150
+        
1151
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1152
+			? $this->_req_data['order']
1153
+			: 'ASC';
1154
+        
1155
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1156
+			? $this->_req_data['paged']
1157
+			: 1;
1158
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1159
+			? $this->_req_data['perpage']
1160
+			: $perpage;
1161
+        
1162
+		$offset = ($current_page - 1) * $per_page;
1163
+		$limit  = $all ? null : array($offset, $per_page);
1164
+        
1165
+        
1166
+		//options will match what is in the _views array property
1167
+		switch ($type) {
1168
+			case 'in_use':
1169
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1170
+				break;
1171
+			default:
1172
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1173
+		}
1174
+        
1175
+		return $templates;
1176
+	}
1177 1177
     
1178 1178
     
1179
-    /**
1180
-     * filters etc might need a list of installed message_types
1181
-     * @return array an array of message type objects
1182
-     */
1183
-    public function get_installed_message_types()
1184
-    {
1185
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1186
-        $installed               = array();
1187
-        
1188
-        foreach ($installed_message_types as $message_type) {
1189
-            $installed[$message_type->name] = $message_type;
1190
-        }
1191
-        
1192
-        return $installed;
1193
-    }
1179
+	/**
1180
+	 * filters etc might need a list of installed message_types
1181
+	 * @return array an array of message type objects
1182
+	 */
1183
+	public function get_installed_message_types()
1184
+	{
1185
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1186
+		$installed               = array();
1187
+        
1188
+		foreach ($installed_message_types as $message_type) {
1189
+			$installed[$message_type->name] = $message_type;
1190
+		}
1191
+        
1192
+		return $installed;
1193
+	}
1194 1194
     
1195 1195
     
1196
-    /**
1197
-     * _add_message_template
1198
-     *
1199
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1200
-     *
1201
-     * @param string $message_type
1202
-     * @param string $messenger
1203
-     * @param string $GRP_ID
1204
-     *
1205
-     * @throws EE_error
1206
-     */
1207
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1208
-    {
1209
-        //set values override any request data
1210
-        $message_type = ! empty($message_type) ? $message_type : '';
1211
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1212
-            ? $this->_req_data['message_type']
1213
-            : $message_type;
1214
-        
1215
-        $messenger = ! empty($messenger) ? $messenger : '';
1216
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1217
-            ? $this->_req_data['messenger']
1218
-            : $messenger;
1219
-        
1220
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1221
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1222
-        
1223
-        //we need messenger and message type.  They should be coming from the event editor. If not here then return error
1224
-        if (empty($message_type) || empty($messenger)) {
1225
-            throw new EE_Error(
1226
-                esc_html__(
1227
-                    'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1228
-                    'event_espresso'
1229
-                )
1230
-            );
1231
-        }
1232
-        
1233
-        //we need the GRP_ID for the template being used as the base for the new template
1234
-        if (empty($GRP_ID)) {
1235
-            throw new EE_Error(
1236
-                esc_html__(
1237
-                    'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1238
-                    'event_espresso'
1239
-                )
1240
-            );
1241
-        }
1242
-        
1243
-        //let's just make sure the template gets generated!
1244
-        
1245
-        //we need to reassign some variables for what the insert is expecting
1246
-        $this->_req_data['MTP_messenger']    = $messenger;
1247
-        $this->_req_data['MTP_message_type'] = $message_type;
1248
-        $this->_req_data['GRP_ID']           = $GRP_ID;
1249
-        $this->_insert_or_update_message_template(true);
1250
-    }
1196
+	/**
1197
+	 * _add_message_template
1198
+	 *
1199
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1200
+	 *
1201
+	 * @param string $message_type
1202
+	 * @param string $messenger
1203
+	 * @param string $GRP_ID
1204
+	 *
1205
+	 * @throws EE_error
1206
+	 */
1207
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1208
+	{
1209
+		//set values override any request data
1210
+		$message_type = ! empty($message_type) ? $message_type : '';
1211
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1212
+			? $this->_req_data['message_type']
1213
+			: $message_type;
1214
+        
1215
+		$messenger = ! empty($messenger) ? $messenger : '';
1216
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1217
+			? $this->_req_data['messenger']
1218
+			: $messenger;
1219
+        
1220
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1221
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1222
+        
1223
+		//we need messenger and message type.  They should be coming from the event editor. If not here then return error
1224
+		if (empty($message_type) || empty($messenger)) {
1225
+			throw new EE_Error(
1226
+				esc_html__(
1227
+					'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1228
+					'event_espresso'
1229
+				)
1230
+			);
1231
+		}
1232
+        
1233
+		//we need the GRP_ID for the template being used as the base for the new template
1234
+		if (empty($GRP_ID)) {
1235
+			throw new EE_Error(
1236
+				esc_html__(
1237
+					'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1238
+					'event_espresso'
1239
+				)
1240
+			);
1241
+		}
1242
+        
1243
+		//let's just make sure the template gets generated!
1244
+        
1245
+		//we need to reassign some variables for what the insert is expecting
1246
+		$this->_req_data['MTP_messenger']    = $messenger;
1247
+		$this->_req_data['MTP_message_type'] = $message_type;
1248
+		$this->_req_data['GRP_ID']           = $GRP_ID;
1249
+		$this->_insert_or_update_message_template(true);
1250
+	}
1251 1251
 
1252 1252
 
1253
-    /**
1254
-     * public wrapper for the _add_message_template method
1255
-     *
1256
-     * @param string $message_type     message type slug
1257
-     * @param string $messenger        messenger slug
1258
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1259
-     *                                 off of.
1260
-     * @throws EE_error
1261
-     */
1262
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1263
-    {
1264
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1265
-    }
1253
+	/**
1254
+	 * public wrapper for the _add_message_template method
1255
+	 *
1256
+	 * @param string $message_type     message type slug
1257
+	 * @param string $messenger        messenger slug
1258
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1259
+	 *                                 off of.
1260
+	 * @throws EE_error
1261
+	 */
1262
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1263
+	{
1264
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1265
+	}
1266 1266
 
1267 1267
 
1268
-    /**
1269
-     * _edit_message_template
1270
-     *
1271
-     * @access protected
1272
-     * @return void
1273
-     * @throws InvalidIdentifierException
1274
-     * @throws DomainException
1275
-     * @throws EE_Error
1276
-     * @throws InvalidArgumentException
1277
-     * @throws ReflectionException
1278
-     * @throws InvalidDataTypeException
1279
-     * @throws InvalidInterfaceException
1280
-     */
1281
-    protected function _edit_message_template()
1282
-    {
1283
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1284
-        $template_fields = '';
1285
-        $sidebar_fields  = '';
1286
-        //we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1287
-        // valid html in the templates.
1288
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1289
-        
1290
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1291
-            ? absint($this->_req_data['id'])
1292
-            : false;
1293
-        
1294
-        $this->_set_shortcodes(); //this also sets the _message_template property.
1295
-        $message_template_group = $this->_message_template_group;
1296
-        $c_label                = $message_template_group->context_label();
1297
-        $c_config               = $message_template_group->contexts_config();
1298
-        
1299
-        reset($c_config);
1300
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1301
-            ? strtolower($this->_req_data['context'])
1302
-            : key($c_config);
1303
-        
1304
-        
1305
-        if (empty($GRP_ID)) {
1306
-            $action = 'insert_message_template';
1307
-            $edit_message_template_form_url = add_query_arg(
1308
-                array('action' => $action, 'noheader' => true),
1309
-                EE_MSG_ADMIN_URL
1310
-            );
1311
-        } else {
1312
-            $action = 'update_message_template';
1313
-            $edit_message_template_form_url = add_query_arg(
1314
-                array('action' => $action, 'noheader' => true),
1315
-                EE_MSG_ADMIN_URL
1316
-            );
1317
-        }
1318
-        
1319
-        //set active messenger for this view
1320
-        $this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1321
-            $message_template_group->messenger()
1322
-        );
1323
-        $this->_active_message_type_name = $message_template_group->message_type();
1324
-        
1325
-        
1326
-        //Do we have any validation errors?
1327
-        $validators = $this->_get_transient();
1328
-        $v_fields   = ! empty($validators) ? array_keys($validators) : array();
1329
-        
1330
-        
1331
-        //we need to assemble the title from Various details
1332
-        $context_label = sprintf(
1333
-            esc_html__('(%s %s)', 'event_espresso'),
1334
-            $c_config[$context]['label'],
1335
-            ucwords($c_label['label'])
1336
-        );
1337
-        
1338
-        $title = sprintf(
1339
-            esc_html__(' %s %s Template %s', 'event_espresso'),
1340
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1341
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1342
-            $context_label
1343
-        );
1344
-        
1345
-        $this->_template_args['GRP_ID']           = $GRP_ID;
1346
-        $this->_template_args['message_template'] = $message_template_group;
1347
-        $this->_template_args['is_extra_fields']  = false;
1348
-        
1349
-        
1350
-        //let's get EEH_MSG_Template so we can get template form fields
1351
-        $template_field_structure = EEH_MSG_Template::get_fields(
1352
-            $message_template_group->messenger(),
1353
-            $message_template_group->message_type()
1354
-        );
1355
-        
1356
-        if ( ! $template_field_structure) {
1357
-            $template_field_structure = false;
1358
-            $template_fields          = esc_html__(
1359
-                'There was an error in assembling the fields for this display (you should see an error message)',
1360
-                'event_espresso'
1361
-            );
1362
-        }
1363
-        
1364
-        
1365
-        $message_templates = $message_template_group->context_templates();
1366
-        
1367
-        
1368
-        //if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1369
-        // will get handled in the "extra" array.
1370
-        if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1371
-            foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1372
-                unset($template_field_structure[$context][$reference_field]);
1373
-            }
1374
-        }
1375
-        
1376
-        //let's loop through the template_field_structure and actually assemble the input fields!
1377
-        if ( ! empty($template_field_structure)) {
1378
-            foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1379
-                //if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1380
-                // the extra array and reset them.
1381
-                if ($template_field === 'extra') {
1382
-                    $this->_template_args['is_extra_fields'] = true;
1383
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1384
-                        $message_template = $message_templates[$context][$reference_field];
1385
-                        $content          = $message_template instanceof EE_Message_Template
1386
-                            ? $message_template->get('MTP_content')
1387
-                            : '';
1388
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1389
-                            //let's verify if we need this extra field via the shortcodes parameter.
1390
-                            $continue = false;
1391
-                            if (isset($extra_array['shortcodes_required'])) {
1392
-                                foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1393
-                                    if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1394
-                                        $continue = true;
1395
-                                    }
1396
-                                }
1397
-                                if ($continue) {
1398
-                                    continue;
1399
-                                }
1400
-                            }
1268
+	/**
1269
+	 * _edit_message_template
1270
+	 *
1271
+	 * @access protected
1272
+	 * @return void
1273
+	 * @throws InvalidIdentifierException
1274
+	 * @throws DomainException
1275
+	 * @throws EE_Error
1276
+	 * @throws InvalidArgumentException
1277
+	 * @throws ReflectionException
1278
+	 * @throws InvalidDataTypeException
1279
+	 * @throws InvalidInterfaceException
1280
+	 */
1281
+	protected function _edit_message_template()
1282
+	{
1283
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1284
+		$template_fields = '';
1285
+		$sidebar_fields  = '';
1286
+		//we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1287
+		// valid html in the templates.
1288
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1289
+        
1290
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1291
+			? absint($this->_req_data['id'])
1292
+			: false;
1293
+        
1294
+		$this->_set_shortcodes(); //this also sets the _message_template property.
1295
+		$message_template_group = $this->_message_template_group;
1296
+		$c_label                = $message_template_group->context_label();
1297
+		$c_config               = $message_template_group->contexts_config();
1298
+        
1299
+		reset($c_config);
1300
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1301
+			? strtolower($this->_req_data['context'])
1302
+			: key($c_config);
1303
+        
1304
+        
1305
+		if (empty($GRP_ID)) {
1306
+			$action = 'insert_message_template';
1307
+			$edit_message_template_form_url = add_query_arg(
1308
+				array('action' => $action, 'noheader' => true),
1309
+				EE_MSG_ADMIN_URL
1310
+			);
1311
+		} else {
1312
+			$action = 'update_message_template';
1313
+			$edit_message_template_form_url = add_query_arg(
1314
+				array('action' => $action, 'noheader' => true),
1315
+				EE_MSG_ADMIN_URL
1316
+			);
1317
+		}
1318
+        
1319
+		//set active messenger for this view
1320
+		$this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1321
+			$message_template_group->messenger()
1322
+		);
1323
+		$this->_active_message_type_name = $message_template_group->message_type();
1324
+        
1325
+        
1326
+		//Do we have any validation errors?
1327
+		$validators = $this->_get_transient();
1328
+		$v_fields   = ! empty($validators) ? array_keys($validators) : array();
1329
+        
1330
+        
1331
+		//we need to assemble the title from Various details
1332
+		$context_label = sprintf(
1333
+			esc_html__('(%s %s)', 'event_espresso'),
1334
+			$c_config[$context]['label'],
1335
+			ucwords($c_label['label'])
1336
+		);
1337
+        
1338
+		$title = sprintf(
1339
+			esc_html__(' %s %s Template %s', 'event_espresso'),
1340
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1341
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1342
+			$context_label
1343
+		);
1344
+        
1345
+		$this->_template_args['GRP_ID']           = $GRP_ID;
1346
+		$this->_template_args['message_template'] = $message_template_group;
1347
+		$this->_template_args['is_extra_fields']  = false;
1348
+        
1349
+        
1350
+		//let's get EEH_MSG_Template so we can get template form fields
1351
+		$template_field_structure = EEH_MSG_Template::get_fields(
1352
+			$message_template_group->messenger(),
1353
+			$message_template_group->message_type()
1354
+		);
1355
+        
1356
+		if ( ! $template_field_structure) {
1357
+			$template_field_structure = false;
1358
+			$template_fields          = esc_html__(
1359
+				'There was an error in assembling the fields for this display (you should see an error message)',
1360
+				'event_espresso'
1361
+			);
1362
+		}
1363
+        
1364
+        
1365
+		$message_templates = $message_template_group->context_templates();
1366
+        
1367
+        
1368
+		//if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1369
+		// will get handled in the "extra" array.
1370
+		if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1371
+			foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1372
+				unset($template_field_structure[$context][$reference_field]);
1373
+			}
1374
+		}
1375
+        
1376
+		//let's loop through the template_field_structure and actually assemble the input fields!
1377
+		if ( ! empty($template_field_structure)) {
1378
+			foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1379
+				//if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1380
+				// the extra array and reset them.
1381
+				if ($template_field === 'extra') {
1382
+					$this->_template_args['is_extra_fields'] = true;
1383
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1384
+						$message_template = $message_templates[$context][$reference_field];
1385
+						$content          = $message_template instanceof EE_Message_Template
1386
+							? $message_template->get('MTP_content')
1387
+							: '';
1388
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1389
+							//let's verify if we need this extra field via the shortcodes parameter.
1390
+							$continue = false;
1391
+							if (isset($extra_array['shortcodes_required'])) {
1392
+								foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1393
+									if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1394
+										$continue = true;
1395
+									}
1396
+								}
1397
+								if ($continue) {
1398
+									continue;
1399
+								}
1400
+							}
1401 1401
                             
1402
-                            $field_id                                = $reference_field
1403
-                                                                       . '-'
1404
-                                                                       . $extra_field
1405
-                                                                       . '-content';
1406
-                            $template_form_fields[$field_id]         = $extra_array;
1407
-                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields['
1408
-                                                                       . $reference_field
1409
-                                                                       . '][content]['
1410
-                                                                       . $extra_field . ']';
1411
-                            $css_class                               = isset($extra_array['css_class'])
1412
-                                ? $extra_array['css_class']
1413
-                                : '';
1402
+							$field_id                                = $reference_field
1403
+																	   . '-'
1404
+																	   . $extra_field
1405
+																	   . '-content';
1406
+							$template_form_fields[$field_id]         = $extra_array;
1407
+							$template_form_fields[$field_id]['name'] = 'MTP_template_fields['
1408
+																	   . $reference_field
1409
+																	   . '][content]['
1410
+																	   . $extra_field . ']';
1411
+							$css_class                               = isset($extra_array['css_class'])
1412
+								? $extra_array['css_class']
1413
+								: '';
1414 1414
                             
1415
-                            $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1416
-                                && in_array($extra_field, $v_fields, true)
1417
-                                &&
1418
-                                (
1419
-                                    is_array($validators[$extra_field])
1420
-                                    && isset($validators[$extra_field]['msg'])
1421
-                                )
1422
-                                ? 'validate-error ' . $css_class
1423
-                                : $css_class;
1415
+							$template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1416
+								&& in_array($extra_field, $v_fields, true)
1417
+								&&
1418
+								(
1419
+									is_array($validators[$extra_field])
1420
+									&& isset($validators[$extra_field]['msg'])
1421
+								)
1422
+								? 'validate-error ' . $css_class
1423
+								: $css_class;
1424 1424
                             
1425
-                            $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1426
-                                                                        && isset($content[$extra_field])
1427
-                                ? $content[$extra_field]
1428
-                                : '';
1425
+							$template_form_fields[$field_id]['value'] = ! empty($message_templates)
1426
+																		&& isset($content[$extra_field])
1427
+								? $content[$extra_field]
1428
+								: '';
1429 1429
                             
1430
-                            //do we have a validation error?  if we do then let's use that value instead
1431
-                            $template_form_fields[$field_id]['value'] = isset($validators[$extra_field])
1432
-                                ? $validators[$extra_field]['value']
1433
-                                : $template_form_fields[$field_id]['value'];
1430
+							//do we have a validation error?  if we do then let's use that value instead
1431
+							$template_form_fields[$field_id]['value'] = isset($validators[$extra_field])
1432
+								? $validators[$extra_field]['value']
1433
+								: $template_form_fields[$field_id]['value'];
1434 1434
                             
1435 1435
                             
1436
-                            $template_form_fields[$field_id]['db-col'] = 'MTP_content';
1436
+							$template_form_fields[$field_id]['db-col'] = 'MTP_content';
1437 1437
                             
1438
-                            //shortcode selector
1439
-                            $field_name_to_use                                 = $extra_field === 'main'
1440
-                                ? 'content'
1441
-                                : $extra_field;
1442
-                            $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1443
-                                $field_name_to_use,
1444
-                                $field_id
1445
-                            );
1438
+							//shortcode selector
1439
+							$field_name_to_use                                 = $extra_field === 'main'
1440
+								? 'content'
1441
+								: $extra_field;
1442
+							$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1443
+								$field_name_to_use,
1444
+								$field_id
1445
+							);
1446 1446
                             
1447
-                            if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1448
-                                //we want to decode the entities
1449
-                                $template_form_fields[$field_id]['value'] = $template_form_fields[$field_id]['value'];
1447
+							if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1448
+								//we want to decode the entities
1449
+								$template_form_fields[$field_id]['value'] = $template_form_fields[$field_id]['value'];
1450 1450
                                 
1451
-                            }/**/
1452
-                        }
1453
-                        $templatefield_MTP_id          = $reference_field . '-MTP_ID';
1454
-                        $templatefield_templatename_id = $reference_field . '-name';
1451
+							}/**/
1452
+						}
1453
+						$templatefield_MTP_id          = $reference_field . '-MTP_ID';
1454
+						$templatefield_templatename_id = $reference_field . '-name';
1455 1455
                         
1456
-                        $template_form_fields[$templatefield_MTP_id] = array(
1457
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1458
-                            'label'      => null,
1459
-                            'input'      => 'hidden',
1460
-                            'type'       => 'int',
1461
-                            'required'   => false,
1462
-                            'validation' => false,
1463
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1464
-                            'css_class'  => '',
1465
-                            'format'     => '%d',
1466
-                            'db-col'     => 'MTP_ID'
1467
-                        );
1456
+						$template_form_fields[$templatefield_MTP_id] = array(
1457
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1458
+							'label'      => null,
1459
+							'input'      => 'hidden',
1460
+							'type'       => 'int',
1461
+							'required'   => false,
1462
+							'validation' => false,
1463
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1464
+							'css_class'  => '',
1465
+							'format'     => '%d',
1466
+							'db-col'     => 'MTP_ID'
1467
+						);
1468 1468
                         
1469
-                        $template_form_fields[$templatefield_templatename_id] = array(
1470
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1471
-                            'label'      => null,
1472
-                            'input'      => 'hidden',
1473
-                            'type'       => 'string',
1474
-                            'required'   => false,
1475
-                            'validation' => true,
1476
-                            'value'      => $reference_field,
1477
-                            'css_class'  => '',
1478
-                            'format'     => '%s',
1479
-                            'db-col'     => 'MTP_template_field'
1480
-                        );
1481
-                    }
1482
-                    continue; //skip the next stuff, we got the necessary fields here for this dataset.
1483
-                } else {
1484
-                    $field_id                                 = $template_field . '-content';
1485
-                    $template_form_fields[$field_id]          = $field_setup_array;
1486
-                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1487
-                    $message_template                         = isset($message_templates[$context][$template_field])
1488
-                        ? $message_templates[$context][$template_field]
1489
-                        : null;
1490
-                    $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1491
-                                                                && is_array($message_templates[$context])
1492
-                                                                && $message_template instanceof EE_Message_Template
1493
-                        ? $message_template->get('MTP_content')
1494
-                        : '';
1469
+						$template_form_fields[$templatefield_templatename_id] = array(
1470
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1471
+							'label'      => null,
1472
+							'input'      => 'hidden',
1473
+							'type'       => 'string',
1474
+							'required'   => false,
1475
+							'validation' => true,
1476
+							'value'      => $reference_field,
1477
+							'css_class'  => '',
1478
+							'format'     => '%s',
1479
+							'db-col'     => 'MTP_template_field'
1480
+						);
1481
+					}
1482
+					continue; //skip the next stuff, we got the necessary fields here for this dataset.
1483
+				} else {
1484
+					$field_id                                 = $template_field . '-content';
1485
+					$template_form_fields[$field_id]          = $field_setup_array;
1486
+					$template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1487
+					$message_template                         = isset($message_templates[$context][$template_field])
1488
+						? $message_templates[$context][$template_field]
1489
+						: null;
1490
+					$template_form_fields[$field_id]['value'] = ! empty($message_templates)
1491
+																&& is_array($message_templates[$context])
1492
+																&& $message_template instanceof EE_Message_Template
1493
+						? $message_template->get('MTP_content')
1494
+						: '';
1495 1495
                     
1496
-                    //do we have a validator error for this field?  if we do then we'll use that value instead
1497
-                    $template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1498
-                        ? $validators[$template_field]['value']
1499
-                        : $template_form_fields[$field_id]['value'];
1496
+					//do we have a validator error for this field?  if we do then we'll use that value instead
1497
+					$template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1498
+						? $validators[$template_field]['value']
1499
+						: $template_form_fields[$field_id]['value'];
1500 1500
                     
1501 1501
                     
1502
-                    $template_form_fields[$field_id]['db-col']    = 'MTP_content';
1503
-                    $css_class                                    = isset($field_setup_array['css_class'])
1504
-                        ? $field_setup_array['css_class']
1505
-                        : '';
1506
-                    $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1507
-                                                                    && in_array($template_field, $v_fields, true)
1508
-                                                                    && isset($validators[$template_field]['msg'])
1509
-                        ? 'validate-error ' . $css_class
1510
-                        : $css_class;
1502
+					$template_form_fields[$field_id]['db-col']    = 'MTP_content';
1503
+					$css_class                                    = isset($field_setup_array['css_class'])
1504
+						? $field_setup_array['css_class']
1505
+						: '';
1506
+					$template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1507
+																	&& in_array($template_field, $v_fields, true)
1508
+																	&& isset($validators[$template_field]['msg'])
1509
+						? 'validate-error ' . $css_class
1510
+						: $css_class;
1511 1511
                     
1512
-                    //shortcode selector
1513
-                    $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1514
-                        $template_field, $field_id
1515
-                    );
1516
-                }
1512
+					//shortcode selector
1513
+					$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1514
+						$template_field, $field_id
1515
+					);
1516
+				}
1517 1517
                 
1518
-                //k took care of content field(s) now let's take care of others.
1518
+				//k took care of content field(s) now let's take care of others.
1519 1519
                 
1520
-                $templatefield_MTP_id                = $template_field . '-MTP_ID';
1521
-                $templatefield_field_templatename_id = $template_field . '-name';
1520
+				$templatefield_MTP_id                = $template_field . '-MTP_ID';
1521
+				$templatefield_field_templatename_id = $template_field . '-name';
1522 1522
                 
1523
-                //foreach template field there are actually two form fields created
1524
-                $template_form_fields[$templatefield_MTP_id] = array(
1525
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1526
-                    'label'      => null,
1527
-                    'input'      => 'hidden',
1528
-                    'type'       => 'int',
1529
-                    'required'   => false,
1530
-                    'validation' => true,
1531
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1532
-                    'css_class'  => '',
1533
-                    'format'     => '%d',
1534
-                    'db-col'     => 'MTP_ID'
1535
-                );
1523
+				//foreach template field there are actually two form fields created
1524
+				$template_form_fields[$templatefield_MTP_id] = array(
1525
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1526
+					'label'      => null,
1527
+					'input'      => 'hidden',
1528
+					'type'       => 'int',
1529
+					'required'   => false,
1530
+					'validation' => true,
1531
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1532
+					'css_class'  => '',
1533
+					'format'     => '%d',
1534
+					'db-col'     => 'MTP_ID'
1535
+				);
1536 1536
                 
1537
-                $template_form_fields[$templatefield_field_templatename_id] = array(
1538
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1539
-                    'label'      => null,
1540
-                    'input'      => 'hidden',
1541
-                    'type'       => 'string',
1542
-                    'required'   => false,
1543
-                    'validation' => true,
1544
-                    'value'      => $template_field,
1545
-                    'css_class'  => '',
1546
-                    'format'     => '%s',
1547
-                    'db-col'     => 'MTP_template_field'
1548
-                );
1537
+				$template_form_fields[$templatefield_field_templatename_id] = array(
1538
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1539
+					'label'      => null,
1540
+					'input'      => 'hidden',
1541
+					'type'       => 'string',
1542
+					'required'   => false,
1543
+					'validation' => true,
1544
+					'value'      => $template_field,
1545
+					'css_class'  => '',
1546
+					'format'     => '%s',
1547
+					'db-col'     => 'MTP_template_field'
1548
+				);
1549 1549
                 
1550
-            }
1550
+			}
1551 1551
             
1552
-            //add other fields
1553
-            $template_form_fields['ee-msg-current-context'] = array(
1554
-                'name'       => 'MTP_context',
1555
-                'label'      => null,
1556
-                'input'      => 'hidden',
1557
-                'type'       => 'string',
1558
-                'required'   => false,
1559
-                'validation' => true,
1560
-                'value'      => $context,
1561
-                'css_class'  => '',
1562
-                'format'     => '%s',
1563
-                'db-col'     => 'MTP_context'
1564
-            );
1552
+			//add other fields
1553
+			$template_form_fields['ee-msg-current-context'] = array(
1554
+				'name'       => 'MTP_context',
1555
+				'label'      => null,
1556
+				'input'      => 'hidden',
1557
+				'type'       => 'string',
1558
+				'required'   => false,
1559
+				'validation' => true,
1560
+				'value'      => $context,
1561
+				'css_class'  => '',
1562
+				'format'     => '%s',
1563
+				'db-col'     => 'MTP_context'
1564
+			);
1565 1565
             
1566
-            $template_form_fields['ee-msg-grp-id'] = array(
1567
-                'name'       => 'GRP_ID',
1568
-                'label'      => null,
1569
-                'input'      => 'hidden',
1570
-                'type'       => 'int',
1571
-                'required'   => false,
1572
-                'validation' => true,
1573
-                'value'      => $GRP_ID,
1574
-                'css_class'  => '',
1575
-                'format'     => '%d',
1576
-                'db-col'     => 'GRP_ID'
1577
-            );
1566
+			$template_form_fields['ee-msg-grp-id'] = array(
1567
+				'name'       => 'GRP_ID',
1568
+				'label'      => null,
1569
+				'input'      => 'hidden',
1570
+				'type'       => 'int',
1571
+				'required'   => false,
1572
+				'validation' => true,
1573
+				'value'      => $GRP_ID,
1574
+				'css_class'  => '',
1575
+				'format'     => '%d',
1576
+				'db-col'     => 'GRP_ID'
1577
+			);
1578 1578
             
1579
-            $template_form_fields['ee-msg-messenger'] = array(
1580
-                'name'       => 'MTP_messenger',
1581
-                'label'      => null,
1582
-                'input'      => 'hidden',
1583
-                'type'       => 'string',
1584
-                'required'   => false,
1585
-                'validation' => true,
1586
-                'value'      => $message_template_group->messenger(),
1587
-                'css_class'  => '',
1588
-                'format'     => '%s',
1589
-                'db-col'     => 'MTP_messenger'
1590
-            );
1579
+			$template_form_fields['ee-msg-messenger'] = array(
1580
+				'name'       => 'MTP_messenger',
1581
+				'label'      => null,
1582
+				'input'      => 'hidden',
1583
+				'type'       => 'string',
1584
+				'required'   => false,
1585
+				'validation' => true,
1586
+				'value'      => $message_template_group->messenger(),
1587
+				'css_class'  => '',
1588
+				'format'     => '%s',
1589
+				'db-col'     => 'MTP_messenger'
1590
+			);
1591 1591
             
1592
-            $template_form_fields['ee-msg-message-type'] = array(
1593
-                'name'       => 'MTP_message_type',
1594
-                'label'      => null,
1595
-                'input'      => 'hidden',
1596
-                'type'       => 'string',
1597
-                'required'   => false,
1598
-                'validation' => true,
1599
-                'value'      => $message_template_group->message_type(),
1600
-                'css_class'  => '',
1601
-                'format'     => '%s',
1602
-                'db-col'     => 'MTP_message_type'
1603
-            );
1592
+			$template_form_fields['ee-msg-message-type'] = array(
1593
+				'name'       => 'MTP_message_type',
1594
+				'label'      => null,
1595
+				'input'      => 'hidden',
1596
+				'type'       => 'string',
1597
+				'required'   => false,
1598
+				'validation' => true,
1599
+				'value'      => $message_template_group->message_type(),
1600
+				'css_class'  => '',
1601
+				'format'     => '%s',
1602
+				'db-col'     => 'MTP_message_type'
1603
+			);
1604 1604
             
1605
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1606
-                'name'       => 'MTP_is_global',
1607
-                'label'      => esc_html__('Global Template', 'event_espresso'),
1608
-                'input'      => 'hidden',
1609
-                'type'       => 'int',
1610
-                'required'   => false,
1611
-                'validation' => true,
1612
-                'value'      => $message_template_group->get('MTP_is_global'),
1613
-                'css_class'  => '',
1614
-                'format'     => '%d',
1615
-                'db-col'     => 'MTP_is_global'
1616
-            );
1605
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1606
+				'name'       => 'MTP_is_global',
1607
+				'label'      => esc_html__('Global Template', 'event_espresso'),
1608
+				'input'      => 'hidden',
1609
+				'type'       => 'int',
1610
+				'required'   => false,
1611
+				'validation' => true,
1612
+				'value'      => $message_template_group->get('MTP_is_global'),
1613
+				'css_class'  => '',
1614
+				'format'     => '%d',
1615
+				'db-col'     => 'MTP_is_global'
1616
+			);
1617 1617
             
1618
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1619
-                'name'       => 'MTP_is_override',
1620
-                'label'      => esc_html__('Override all custom', 'event_espresso'),
1621
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1622
-                'type'       => 'int',
1623
-                'required'   => false,
1624
-                'validation' => true,
1625
-                'value'      => $message_template_group->get('MTP_is_override'),
1626
-                'css_class'  => '',
1627
-                'format'     => '%d',
1628
-                'db-col'     => 'MTP_is_override'
1629
-            );
1618
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1619
+				'name'       => 'MTP_is_override',
1620
+				'label'      => esc_html__('Override all custom', 'event_espresso'),
1621
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1622
+				'type'       => 'int',
1623
+				'required'   => false,
1624
+				'validation' => true,
1625
+				'value'      => $message_template_group->get('MTP_is_override'),
1626
+				'css_class'  => '',
1627
+				'format'     => '%d',
1628
+				'db-col'     => 'MTP_is_override'
1629
+			);
1630 1630
             
1631
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1632
-                'name'       => 'MTP_is_active',
1633
-                'label'      => esc_html__('Active Template', 'event_espresso'),
1634
-                'input'      => 'hidden',
1635
-                'type'       => 'int',
1636
-                'required'   => false,
1637
-                'validation' => true,
1638
-                'value'      => $message_template_group->is_active(),
1639
-                'css_class'  => '',
1640
-                'format'     => '%d',
1641
-                'db-col'     => 'MTP_is_active'
1642
-            );
1631
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1632
+				'name'       => 'MTP_is_active',
1633
+				'label'      => esc_html__('Active Template', 'event_espresso'),
1634
+				'input'      => 'hidden',
1635
+				'type'       => 'int',
1636
+				'required'   => false,
1637
+				'validation' => true,
1638
+				'value'      => $message_template_group->is_active(),
1639
+				'css_class'  => '',
1640
+				'format'     => '%d',
1641
+				'db-col'     => 'MTP_is_active'
1642
+			);
1643 1643
             
1644
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1645
-                'name'       => 'MTP_deleted',
1646
-                'label'      => null,
1647
-                'input'      => 'hidden',
1648
-                'type'       => 'int',
1649
-                'required'   => false,
1650
-                'validation' => true,
1651
-                'value'      => $message_template_group->get('MTP_deleted'),
1652
-                'css_class'  => '',
1653
-                'format'     => '%d',
1654
-                'db-col'     => 'MTP_deleted'
1655
-            );
1656
-            $sidebar_form_fields['ee-msg-author']  = array(
1657
-                'name'       => 'MTP_user_id',
1658
-                'label'      => esc_html__('Author', 'event_espresso'),
1659
-                'input'      => 'hidden',
1660
-                'type'       => 'int',
1661
-                'required'   => false,
1662
-                'validation' => false,
1663
-                'value'      => $message_template_group->user(),
1664
-                'format'     => '%d',
1665
-                'db-col'     => 'MTP_user_id'
1666
-            );
1644
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1645
+				'name'       => 'MTP_deleted',
1646
+				'label'      => null,
1647
+				'input'      => 'hidden',
1648
+				'type'       => 'int',
1649
+				'required'   => false,
1650
+				'validation' => true,
1651
+				'value'      => $message_template_group->get('MTP_deleted'),
1652
+				'css_class'  => '',
1653
+				'format'     => '%d',
1654
+				'db-col'     => 'MTP_deleted'
1655
+			);
1656
+			$sidebar_form_fields['ee-msg-author']  = array(
1657
+				'name'       => 'MTP_user_id',
1658
+				'label'      => esc_html__('Author', 'event_espresso'),
1659
+				'input'      => 'hidden',
1660
+				'type'       => 'int',
1661
+				'required'   => false,
1662
+				'validation' => false,
1663
+				'value'      => $message_template_group->user(),
1664
+				'format'     => '%d',
1665
+				'db-col'     => 'MTP_user_id'
1666
+			);
1667 1667
             
1668
-            $sidebar_form_fields['ee-msg-route'] = array(
1669
-                'name'  => 'action',
1670
-                'input' => 'hidden',
1671
-                'type'  => 'string',
1672
-                'value' => $action
1673
-            );
1668
+			$sidebar_form_fields['ee-msg-route'] = array(
1669
+				'name'  => 'action',
1670
+				'input' => 'hidden',
1671
+				'type'  => 'string',
1672
+				'value' => $action
1673
+			);
1674 1674
             
1675
-            $sidebar_form_fields['ee-msg-id']        = array(
1676
-                'name'  => 'id',
1677
-                'input' => 'hidden',
1678
-                'type'  => 'int',
1679
-                'value' => $GRP_ID
1680
-            );
1681
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1682
-                'name'  => $action . '_nonce',
1683
-                'input' => 'hidden',
1684
-                'type'  => 'string',
1685
-                'value' => wp_create_nonce($action . '_nonce')
1686
-            );
1675
+			$sidebar_form_fields['ee-msg-id']        = array(
1676
+				'name'  => 'id',
1677
+				'input' => 'hidden',
1678
+				'type'  => 'int',
1679
+				'value' => $GRP_ID
1680
+			);
1681
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1682
+				'name'  => $action . '_nonce',
1683
+				'input' => 'hidden',
1684
+				'type'  => 'string',
1685
+				'value' => wp_create_nonce($action . '_nonce')
1686
+			);
1687 1687
             
1688
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1689
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1690
-                    'name'  => 'template_switch',
1691
-                    'input' => 'hidden',
1692
-                    'type'  => 'int',
1693
-                    'value' => 1
1694
-                );
1695
-            }
1688
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1689
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1690
+					'name'  => 'template_switch',
1691
+					'input' => 'hidden',
1692
+					'type'  => 'int',
1693
+					'value' => 1
1694
+				);
1695
+			}
1696 1696
             
1697 1697
             
1698
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1699
-            $sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1698
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1699
+			$sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1700 1700
             
1701 1701
             
1702
-        } //end if ( !empty($template_field_structure) )
1703
-        
1704
-        //set extra content for publish box
1705
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1706
-        $this->_set_publish_post_box_vars(
1707
-            'id',
1708
-            $GRP_ID,
1709
-            false,
1710
-            add_query_arg(
1711
-                array('action' => 'global_mtps'),
1712
-                $this->_admin_base_url
1713
-            )
1714
-        );
1715
-        
1716
-        //add preview button
1717
-        $preview_url    = parent::add_query_args_and_nonce(
1718
-            array(
1719
-                'message_type' => $message_template_group->message_type(),
1720
-                'messenger'    => $message_template_group->messenger(),
1721
-                'context'      => $context,
1722
-                'GRP_ID'       => $GRP_ID,
1723
-                'action'       => 'preview_message'
1724
-            ),
1725
-            $this->_admin_base_url
1726
-        );
1727
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1728
-                          . esc_html__('Preview', 'event_espresso')
1729
-                          . '</a>';
1730
-        
1731
-        
1732
-        //setup context switcher
1733
-        $context_switcher_args = array(
1734
-            'page'    => 'espresso_messages',
1735
-            'action'  => 'edit_message_template',
1736
-            'id'      => $GRP_ID,
1737
-            'context' => $context,
1738
-            'extra'   => $preview_button
1739
-        );
1740
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1741
-        
1742
-        
1743
-        //main box
1744
-        $this->_template_args['template_fields']                         = $template_fields;
1745
-        $this->_template_args['sidebar_box_id']                          = 'details';
1746
-        $this->_template_args['action']                                  = $action;
1747
-        $this->_template_args['context']                                 = $context;
1748
-        $this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1749
-        $this->_template_args['learn_more_about_message_templates_link'] =
1750
-            $this->_learn_more_about_message_templates_link();
1751
-        
1752
-        
1753
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1754
-        $this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1755
-            $message_template_group,
1756
-            $context,
1757
-            $context_label
1758
-        );
1759
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1760
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1761
-        
1762
-        $this->_template_path = $this->_template_args['GRP_ID']
1763
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1764
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1765
-        
1766
-        //send along EE_Message_Template_Group object for further template use.
1767
-        $this->_template_args['MTP'] = $message_template_group;
1768
-        
1769
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1770
-            $this->_template_path,
1771
-            $this->_template_args,
1772
-            true
1773
-        );
1774
-        
1775
-        
1776
-        //finally, let's set the admin_page title
1777
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1778
-        
1779
-        
1780
-        //we need to take care of setting the shortcodes property for use elsewhere.
1781
-        $this->_set_shortcodes();
1782
-        
1783
-        
1784
-        //final template wrapper
1785
-        $this->display_admin_page_with_sidebar();
1786
-    }
1702
+		} //end if ( !empty($template_field_structure) )
1703
+        
1704
+		//set extra content for publish box
1705
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1706
+		$this->_set_publish_post_box_vars(
1707
+			'id',
1708
+			$GRP_ID,
1709
+			false,
1710
+			add_query_arg(
1711
+				array('action' => 'global_mtps'),
1712
+				$this->_admin_base_url
1713
+			)
1714
+		);
1715
+        
1716
+		//add preview button
1717
+		$preview_url    = parent::add_query_args_and_nonce(
1718
+			array(
1719
+				'message_type' => $message_template_group->message_type(),
1720
+				'messenger'    => $message_template_group->messenger(),
1721
+				'context'      => $context,
1722
+				'GRP_ID'       => $GRP_ID,
1723
+				'action'       => 'preview_message'
1724
+			),
1725
+			$this->_admin_base_url
1726
+		);
1727
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1728
+						  . esc_html__('Preview', 'event_espresso')
1729
+						  . '</a>';
1730
+        
1731
+        
1732
+		//setup context switcher
1733
+		$context_switcher_args = array(
1734
+			'page'    => 'espresso_messages',
1735
+			'action'  => 'edit_message_template',
1736
+			'id'      => $GRP_ID,
1737
+			'context' => $context,
1738
+			'extra'   => $preview_button
1739
+		);
1740
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1741
+        
1742
+        
1743
+		//main box
1744
+		$this->_template_args['template_fields']                         = $template_fields;
1745
+		$this->_template_args['sidebar_box_id']                          = 'details';
1746
+		$this->_template_args['action']                                  = $action;
1747
+		$this->_template_args['context']                                 = $context;
1748
+		$this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1749
+		$this->_template_args['learn_more_about_message_templates_link'] =
1750
+			$this->_learn_more_about_message_templates_link();
1751
+        
1752
+        
1753
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1754
+		$this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1755
+			$message_template_group,
1756
+			$context,
1757
+			$context_label
1758
+		);
1759
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1760
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1761
+        
1762
+		$this->_template_path = $this->_template_args['GRP_ID']
1763
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1764
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1765
+        
1766
+		//send along EE_Message_Template_Group object for further template use.
1767
+		$this->_template_args['MTP'] = $message_template_group;
1768
+        
1769
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1770
+			$this->_template_path,
1771
+			$this->_template_args,
1772
+			true
1773
+		);
1774
+        
1775
+        
1776
+		//finally, let's set the admin_page title
1777
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1778
+        
1779
+        
1780
+		//we need to take care of setting the shortcodes property for use elsewhere.
1781
+		$this->_set_shortcodes();
1782
+        
1783
+        
1784
+		//final template wrapper
1785
+		$this->display_admin_page_with_sidebar();
1786
+	}
1787 1787
     
1788 1788
     
1789
-    public function filter_tinymce_init($mceInit, $editor_id)
1790
-    {
1791
-        return $mceInit;
1792
-    }
1789
+	public function filter_tinymce_init($mceInit, $editor_id)
1790
+	{
1791
+		return $mceInit;
1792
+	}
1793 1793
     
1794 1794
     
1795
-    public function add_context_switcher()
1796
-    {
1797
-        return $this->_context_switcher;
1798
-    }
1795
+	public function add_context_switcher()
1796
+	{
1797
+		return $this->_context_switcher;
1798
+	}
1799 1799
 
1800 1800
 
1801
-    /**
1802
-     * Adds the activation/deactivation toggle for the message template context.
1803
-     *
1804
-     * @param EE_Message_Template_Group $message_template_group
1805
-     * @param string                    $context
1806
-     * @param string                    $context_label
1807
-     * @return string
1808
-     * @throws DomainException
1809
-     * @throws EE_Error
1810
-     * @throws InvalidIdentifierException
1811
-     */
1812
-    protected function add_active_context_element(
1813
-        EE_Message_Template_Group $message_template_group,
1814
-        $context,
1815
-        $context_label
1816
-    ) {
1817
-        $template_args = array(
1818
-            'context' => $context,
1819
-            'nonce' => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1820
-            'is_active' => $message_template_group->is_context_active($context),
1821
-            'on_off_action' => $message_template_group->is_context_active($context)
1822
-                ? 'context-off'
1823
-                : 'context-on',
1824
-            'context_label' => str_replace(array('(', ')'), '', $context_label),
1825
-            'message_template_group_id' => $message_template_group->ID()
1826
-        );
1827
-        return EEH_Template::display_template(
1828
-          EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1829
-          $template_args,
1830
-          true
1831
-        );
1832
-    }
1801
+	/**
1802
+	 * Adds the activation/deactivation toggle for the message template context.
1803
+	 *
1804
+	 * @param EE_Message_Template_Group $message_template_group
1805
+	 * @param string                    $context
1806
+	 * @param string                    $context_label
1807
+	 * @return string
1808
+	 * @throws DomainException
1809
+	 * @throws EE_Error
1810
+	 * @throws InvalidIdentifierException
1811
+	 */
1812
+	protected function add_active_context_element(
1813
+		EE_Message_Template_Group $message_template_group,
1814
+		$context,
1815
+		$context_label
1816
+	) {
1817
+		$template_args = array(
1818
+			'context' => $context,
1819
+			'nonce' => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1820
+			'is_active' => $message_template_group->is_context_active($context),
1821
+			'on_off_action' => $message_template_group->is_context_active($context)
1822
+				? 'context-off'
1823
+				: 'context-on',
1824
+			'context_label' => str_replace(array('(', ')'), '', $context_label),
1825
+			'message_template_group_id' => $message_template_group->ID()
1826
+		);
1827
+		return EEH_Template::display_template(
1828
+		  EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1829
+		  $template_args,
1830
+		  true
1831
+		);
1832
+	}
1833 1833
 
1834 1834
 
1835
-    /**
1836
-     * Ajax callback for `toggle_context_template` ajax action.
1837
-     * Handles toggling the message context on or off.
1838
-     * @throws EE_Error
1839
-     * @throws InvalidArgumentException
1840
-     * @throws InvalidDataTypeException
1841
-     * @throws InvalidIdentifierException
1842
-     * @throws InvalidInterfaceException
1843
-     */
1844
-    public function toggle_context_template()
1845
-    {
1846
-        $success = true;
1847
-        //check for required data
1848
-        if (!isset(
1849
-            $this->_req_data['message_template_group_id'],
1850
-            $this->_req_data['context'],
1851
-            $this->_req_data['status']
1852
-        )) {
1853
-            EE_Error::add_error(
1854
-                esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1855
-                __FILE__,
1856
-                __FUNCTION__,
1857
-                __LINE__
1858
-            );
1859
-            $success = false;
1860
-        }
1835
+	/**
1836
+	 * Ajax callback for `toggle_context_template` ajax action.
1837
+	 * Handles toggling the message context on or off.
1838
+	 * @throws EE_Error
1839
+	 * @throws InvalidArgumentException
1840
+	 * @throws InvalidDataTypeException
1841
+	 * @throws InvalidIdentifierException
1842
+	 * @throws InvalidInterfaceException
1843
+	 */
1844
+	public function toggle_context_template()
1845
+	{
1846
+		$success = true;
1847
+		//check for required data
1848
+		if (!isset(
1849
+			$this->_req_data['message_template_group_id'],
1850
+			$this->_req_data['context'],
1851
+			$this->_req_data['status']
1852
+		)) {
1853
+			EE_Error::add_error(
1854
+				esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1855
+				__FILE__,
1856
+				__FUNCTION__,
1857
+				__LINE__
1858
+			);
1859
+			$success = false;
1860
+		}
1861 1861
 
1862
-        $nonce = isset($this->_req_data['toggle_context_nonce'])
1863
-            ? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1864
-            : '';
1865
-        $nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1866
-        $this->_verify_nonce($nonce, $nonce_ref);
1867
-        $status = $this->_req_data['status'];
1868
-        if ($status !== 'off' && $status !=='on') {
1869
-            EE_Error::add_error(
1870
-                sprintf(
1871
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1872
-                    $this->_req_data['status']
1873
-                ),
1874
-                __FILE__,
1875
-                __FUNCTION__,
1876
-                __LINE__
1877
-            );
1878
-            $success = false;
1879
-        }
1880
-        $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1881
-            $this->_req_data['message_template_group_id']
1882
-        );
1883
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1884
-            EE_Error::add_error(
1885
-                sprintf(
1886
-                    esc_html__(
1887
-                        'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1888
-                        'event_espresso'
1889
-                    ),
1890
-                    $this->_req_data['message_template_group_id'],
1891
-                    'EE_Message_Template_Group'
1892
-                ),
1893
-                __FILE__,
1894
-                __FUNCTION__,
1895
-                __LINE__
1896
-            );
1897
-            $success = false;
1898
-        }
1899
-        if ($success) {
1900
-            $success = $status === 'off'
1901
-                ? $message_template_group->deactivate_context($this->_req_data['context'])
1902
-                : $message_template_group->activate_context($this->_req_data['context']);
1903
-        }
1904
-        $this->_template_args['success'] = $success;
1905
-        $this->_return_json();
1906
-    }
1862
+		$nonce = isset($this->_req_data['toggle_context_nonce'])
1863
+			? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1864
+			: '';
1865
+		$nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1866
+		$this->_verify_nonce($nonce, $nonce_ref);
1867
+		$status = $this->_req_data['status'];
1868
+		if ($status !== 'off' && $status !=='on') {
1869
+			EE_Error::add_error(
1870
+				sprintf(
1871
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1872
+					$this->_req_data['status']
1873
+				),
1874
+				__FILE__,
1875
+				__FUNCTION__,
1876
+				__LINE__
1877
+			);
1878
+			$success = false;
1879
+		}
1880
+		$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1881
+			$this->_req_data['message_template_group_id']
1882
+		);
1883
+		if (! $message_template_group instanceof EE_Message_Template_Group) {
1884
+			EE_Error::add_error(
1885
+				sprintf(
1886
+					esc_html__(
1887
+						'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1888
+						'event_espresso'
1889
+					),
1890
+					$this->_req_data['message_template_group_id'],
1891
+					'EE_Message_Template_Group'
1892
+				),
1893
+				__FILE__,
1894
+				__FUNCTION__,
1895
+				__LINE__
1896
+			);
1897
+			$success = false;
1898
+		}
1899
+		if ($success) {
1900
+			$success = $status === 'off'
1901
+				? $message_template_group->deactivate_context($this->_req_data['context'])
1902
+				: $message_template_group->activate_context($this->_req_data['context']);
1903
+		}
1904
+		$this->_template_args['success'] = $success;
1905
+		$this->_return_json();
1906
+	}
1907 1907
 
1908 1908
 
1909 1909
     
1910
-    public function _add_form_element_before()
1911
-    {
1912
-        return '<form method="post" action="'
1913
-               . $this->_template_args["edit_message_template_form_url"]
1914
-               . '" id="ee-msg-edit-frm">';
1915
-    }
1910
+	public function _add_form_element_before()
1911
+	{
1912
+		return '<form method="post" action="'
1913
+			   . $this->_template_args["edit_message_template_form_url"]
1914
+			   . '" id="ee-msg-edit-frm">';
1915
+	}
1916 1916
     
1917
-    public function _add_form_element_after()
1918
-    {
1919
-        return '</form>';
1920
-    }
1917
+	public function _add_form_element_after()
1918
+	{
1919
+		return '</form>';
1920
+	}
1921 1921
 
1922 1922
 
1923
-    /**
1924
-     * This executes switching the template pack for a message template.
1925
-     *
1926
-     * @since 4.5.0
1927
-     * @throws EE_Error
1928
-     * @throws InvalidDataTypeException
1929
-     * @throws InvalidInterfaceException
1930
-     * @throws InvalidArgumentException
1931
-     * @throws ReflectionException
1932
-     */
1933
-    public function switch_template_pack()
1934
-    {
1935
-        $GRP_ID        = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1936
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1937
-        
1938
-        //verify we have needed values.
1939
-        if (empty($GRP_ID) || empty($template_pack)) {
1940
-            $this->_template_args['error'] = true;
1941
-            EE_Error::add_error(
1942
-                esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1943
-                __FILE__,
1944
-                __FUNCTION__,
1945
-                __LINE__
1946
-            );
1947
-        } else {
1948
-            //get template, set the new template_pack and then reset to default
1949
-            /** @type EE_Message_Template_Group $message_template_group */
1950
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1923
+	/**
1924
+	 * This executes switching the template pack for a message template.
1925
+	 *
1926
+	 * @since 4.5.0
1927
+	 * @throws EE_Error
1928
+	 * @throws InvalidDataTypeException
1929
+	 * @throws InvalidInterfaceException
1930
+	 * @throws InvalidArgumentException
1931
+	 * @throws ReflectionException
1932
+	 */
1933
+	public function switch_template_pack()
1934
+	{
1935
+		$GRP_ID        = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1936
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1937
+        
1938
+		//verify we have needed values.
1939
+		if (empty($GRP_ID) || empty($template_pack)) {
1940
+			$this->_template_args['error'] = true;
1941
+			EE_Error::add_error(
1942
+				esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1943
+				__FILE__,
1944
+				__FUNCTION__,
1945
+				__LINE__
1946
+			);
1947
+		} else {
1948
+			//get template, set the new template_pack and then reset to default
1949
+			/** @type EE_Message_Template_Group $message_template_group */
1950
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1951 1951
             
1952
-            $message_template_group->set_template_pack_name($template_pack);
1953
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1954
-            $this->_req_data['mt']   = $message_template_group->message_type();
1952
+			$message_template_group->set_template_pack_name($template_pack);
1953
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1954
+			$this->_req_data['mt']   = $message_template_group->message_type();
1955 1955
             
1956
-            $query_args = $this->_reset_to_default_template();
1956
+			$query_args = $this->_reset_to_default_template();
1957 1957
             
1958
-            if (empty($query_args['id'])) {
1959
-                EE_Error::add_error(
1960
-                    esc_html__(
1961
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1962
-                        'event_espresso'
1963
-                    ),
1964
-                    __FILE__,
1965
-                    __FUNCTION__,
1966
-                    __LINE__
1967
-                );
1968
-                $this->_template_args['error'] = true;
1969
-            } else {
1970
-                $template_label       = $message_template_group->get_template_pack()->label;
1971
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1972
-                EE_Error::add_success(
1973
-                    sprintf(
1974
-                        esc_html__(
1975
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1976
-                            'event_espresso'
1977
-                        ),
1978
-                        $template_label,
1979
-                        $template_pack_labels->template_pack
1980
-                    )
1981
-                );
1982
-                //generate the redirect url for js.
1983
-                $url                                          = self::add_query_args_and_nonce($query_args,
1984
-                    $this->_admin_base_url);
1985
-                $this->_template_args['data']['redirect_url'] = $url;
1986
-                $this->_template_args['success']              = true;
1987
-            }
1958
+			if (empty($query_args['id'])) {
1959
+				EE_Error::add_error(
1960
+					esc_html__(
1961
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1962
+						'event_espresso'
1963
+					),
1964
+					__FILE__,
1965
+					__FUNCTION__,
1966
+					__LINE__
1967
+				);
1968
+				$this->_template_args['error'] = true;
1969
+			} else {
1970
+				$template_label       = $message_template_group->get_template_pack()->label;
1971
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1972
+				EE_Error::add_success(
1973
+					sprintf(
1974
+						esc_html__(
1975
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1976
+							'event_espresso'
1977
+						),
1978
+						$template_label,
1979
+						$template_pack_labels->template_pack
1980
+					)
1981
+				);
1982
+				//generate the redirect url for js.
1983
+				$url                                          = self::add_query_args_and_nonce($query_args,
1984
+					$this->_admin_base_url);
1985
+				$this->_template_args['data']['redirect_url'] = $url;
1986
+				$this->_template_args['success']              = true;
1987
+			}
1988 1988
             
1989
-            $this->_return_json();
1989
+			$this->_return_json();
1990 1990
             
1991
-        }
1992
-    }
1991
+		}
1992
+	}
1993 1993
 
1994 1994
 
1995
-    /**
1996
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
1997
-     * they want.
1998
-     *
1999
-     * @access protected
2000
-     * @return array|null
2001
-     * @throws EE_Error
2002
-     * @throws InvalidArgumentException
2003
-     * @throws InvalidDataTypeException
2004
-     * @throws InvalidInterfaceException
2005
-     */
2006
-    protected function _reset_to_default_template()
2007
-    {
2008
-        
2009
-        $templates = array();
2010
-        $GRP_ID    = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2011
-        //we need to make sure we've got the info we need.
2012
-        if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2013
-            EE_Error::add_error(
2014
-                esc_html__(
2015
-                    '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.',
2016
-                    'event_espresso'
2017
-                ),
2018
-                __FILE__, __FUNCTION__, __LINE__
2019
-            );
2020
-        }
2021
-        
2022
-        // all templates will be reset to whatever the defaults are
2023
-        // for the global template matching the messenger and message type.
2024
-        $success = ! empty($GRP_ID) ? true : false;
2025
-        
2026
-        if ($success) {
1995
+	/**
1996
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
1997
+	 * they want.
1998
+	 *
1999
+	 * @access protected
2000
+	 * @return array|null
2001
+	 * @throws EE_Error
2002
+	 * @throws InvalidArgumentException
2003
+	 * @throws InvalidDataTypeException
2004
+	 * @throws InvalidInterfaceException
2005
+	 */
2006
+	protected function _reset_to_default_template()
2007
+	{
2008
+        
2009
+		$templates = array();
2010
+		$GRP_ID    = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2011
+		//we need to make sure we've got the info we need.
2012
+		if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2013
+			EE_Error::add_error(
2014
+				esc_html__(
2015
+					'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.',
2016
+					'event_espresso'
2017
+				),
2018
+				__FILE__, __FUNCTION__, __LINE__
2019
+			);
2020
+		}
2021
+        
2022
+		// all templates will be reset to whatever the defaults are
2023
+		// for the global template matching the messenger and message type.
2024
+		$success = ! empty($GRP_ID) ? true : false;
2025
+        
2026
+		if ($success) {
2027 2027
             
2028
-            //let's first determine if the incoming template is a global template,
2029
-            // if it isn't then we need to get the global template matching messenger and message type.
2030
-            //$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2028
+			//let's first determine if the incoming template is a global template,
2029
+			// if it isn't then we need to get the global template matching messenger and message type.
2030
+			//$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2031 2031
             
2032 2032
             
2033
-            //note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2034
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
2033
+			//note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2034
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
2035 2035
             
2036
-            if ($success) {
2037
-                // if successfully deleted, lets generate the new ones.
2038
-                // Note. We set GLOBAL to true, because resets on ANY template
2039
-                // will use the related global template defaults for regeneration.
2040
-                // This means that if a custom template is reset it resets to whatever the related global template is.
2041
-                // HOWEVER, we DO keep the template pack and template variation set
2042
-                // for the current custom template when resetting.
2043
-                $templates = $this->_generate_new_templates(
2044
-                    $this->_req_data['msgr'],
2045
-                    $this->_req_data['mt'],
2046
-                    $GRP_ID,
2047
-                    true
2048
-                );
2049
-            }
2036
+			if ($success) {
2037
+				// if successfully deleted, lets generate the new ones.
2038
+				// Note. We set GLOBAL to true, because resets on ANY template
2039
+				// will use the related global template defaults for regeneration.
2040
+				// This means that if a custom template is reset it resets to whatever the related global template is.
2041
+				// HOWEVER, we DO keep the template pack and template variation set
2042
+				// for the current custom template when resetting.
2043
+				$templates = $this->_generate_new_templates(
2044
+					$this->_req_data['msgr'],
2045
+					$this->_req_data['mt'],
2046
+					$GRP_ID,
2047
+					true
2048
+				);
2049
+			}
2050 2050
             
2051
-        }
2052
-        
2053
-        //any error messages?
2054
-        if ( ! $success) {
2055
-            EE_Error::add_error(
2056
-                esc_html__('Something went wrong with deleting existing templates. Unable to reset to default',
2057
-                    'event_espresso'),
2058
-                __FILE__, __FUNCTION__, __LINE__
2059
-            );
2060
-        }
2061
-        
2062
-        //all good, let's add a success message!
2063
-        if ($success && ! empty($templates)) {
2064
-            //the info for the template we generated is the first element in the returned array
2065
-            // $templates = $templates[0];
2066
-            EE_Error::overwrite_success();
2067
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2068
-        }
2069
-        
2070
-        
2071
-        $query_args = array(
2072
-            'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
2073
-            'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
2074
-            'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps'
2075
-        );
2076
-        
2077
-        //if called via ajax then we return query args otherwise redirect
2078
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2079
-            return $query_args;
2080
-        } else {
2081
-            $this->_redirect_after_action(false, '', '', $query_args, true);
2051
+		}
2052
+        
2053
+		//any error messages?
2054
+		if ( ! $success) {
2055
+			EE_Error::add_error(
2056
+				esc_html__('Something went wrong with deleting existing templates. Unable to reset to default',
2057
+					'event_espresso'),
2058
+				__FILE__, __FUNCTION__, __LINE__
2059
+			);
2060
+		}
2061
+        
2062
+		//all good, let's add a success message!
2063
+		if ($success && ! empty($templates)) {
2064
+			//the info for the template we generated is the first element in the returned array
2065
+			// $templates = $templates[0];
2066
+			EE_Error::overwrite_success();
2067
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2068
+		}
2069
+        
2070
+        
2071
+		$query_args = array(
2072
+			'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
2073
+			'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
2074
+			'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps'
2075
+		);
2076
+        
2077
+		//if called via ajax then we return query args otherwise redirect
2078
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2079
+			return $query_args;
2080
+		} else {
2081
+			$this->_redirect_after_action(false, '', '', $query_args, true);
2082 2082
 
2083
-            return null;
2084
-        }
2085
-    }
2083
+			return null;
2084
+		}
2085
+	}
2086 2086
 
2087 2087
 
2088
-    /**
2089
-     * Retrieve and set the message preview for display.
2090
-     *
2091
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2092
-     * @return string
2093
-     * @throws ReflectionException
2094
-     * @throws EE_Error
2095
-     * @throws InvalidArgumentException
2096
-     * @throws InvalidDataTypeException
2097
-     * @throws InvalidInterfaceException
2098
-     */
2099
-    public function _preview_message($send = false)
2100
-    {
2101
-        //first make sure we've got the necessary parameters
2102
-        if (
2103
-        ! isset(
2104
-            $this->_req_data['message_type'],
2105
-            $this->_req_data['messenger'],
2106
-            $this->_req_data['messenger'],
2107
-            $this->_req_data['GRP_ID']
2108
-        )
2109
-        ) {
2110
-            EE_Error::add_error(
2111
-                esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2112
-                __FILE__, __FUNCTION__, __LINE__
2113
-            );
2114
-        }
2115
-        
2116
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2117
-        
2118
-        
2119
-        //get the preview!
2120
-        $preview = EED_Messages::preview_message($this->_req_data['message_type'], $this->_req_data['context'],
2121
-            $this->_req_data['messenger'], $send);
2122
-        
2123
-        if ($send) {
2124
-            return $preview;
2125
-        }
2126
-        
2127
-        //let's add a button to go back to the edit view
2128
-        $query_args             = array(
2129
-            'id'      => $this->_req_data['GRP_ID'],
2130
-            'context' => $this->_req_data['context'],
2131
-            'action'  => 'edit_message_template'
2132
-        );
2133
-        $go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2134
-        $preview_button         = '<a href="'
2135
-                                  . $go_back_url
2136
-                                  . '" class="button-secondary messages-preview-go-back-button">'
2137
-                                  . esc_html__('Go Back to Edit', 'event_espresso')
2138
-                                  . '</a>';
2139
-        $message_types          = $this->get_installed_message_types();
2140
-        $active_messenger       = $this->_message_resource_manager->get_active_messenger(
2141
-                $this->_req_data['messenger']
2142
-        );
2143
-        $active_messenger_label = $active_messenger instanceof EE_messenger
2144
-            ? ucwords($active_messenger->label['singular'])
2145
-            : esc_html__('Unknown Messenger', 'event_espresso');
2146
-        //let's provide a helpful title for context
2147
-        $preview_title = sprintf(
2148
-            esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2149
-            $active_messenger_label,
2150
-            ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
2151
-        );
2152
-        //setup display of preview.
2153
-        $this->_admin_page_title                    = $preview_title;
2154
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2155
-        $this->_template_args['data']['force_json'] = true;
2156
-        
2157
-        return '';
2158
-    }
2088
+	/**
2089
+	 * Retrieve and set the message preview for display.
2090
+	 *
2091
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2092
+	 * @return string
2093
+	 * @throws ReflectionException
2094
+	 * @throws EE_Error
2095
+	 * @throws InvalidArgumentException
2096
+	 * @throws InvalidDataTypeException
2097
+	 * @throws InvalidInterfaceException
2098
+	 */
2099
+	public function _preview_message($send = false)
2100
+	{
2101
+		//first make sure we've got the necessary parameters
2102
+		if (
2103
+		! isset(
2104
+			$this->_req_data['message_type'],
2105
+			$this->_req_data['messenger'],
2106
+			$this->_req_data['messenger'],
2107
+			$this->_req_data['GRP_ID']
2108
+		)
2109
+		) {
2110
+			EE_Error::add_error(
2111
+				esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2112
+				__FILE__, __FUNCTION__, __LINE__
2113
+			);
2114
+		}
2115
+        
2116
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2117
+        
2118
+        
2119
+		//get the preview!
2120
+		$preview = EED_Messages::preview_message($this->_req_data['message_type'], $this->_req_data['context'],
2121
+			$this->_req_data['messenger'], $send);
2122
+        
2123
+		if ($send) {
2124
+			return $preview;
2125
+		}
2126
+        
2127
+		//let's add a button to go back to the edit view
2128
+		$query_args             = array(
2129
+			'id'      => $this->_req_data['GRP_ID'],
2130
+			'context' => $this->_req_data['context'],
2131
+			'action'  => 'edit_message_template'
2132
+		);
2133
+		$go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2134
+		$preview_button         = '<a href="'
2135
+								  . $go_back_url
2136
+								  . '" class="button-secondary messages-preview-go-back-button">'
2137
+								  . esc_html__('Go Back to Edit', 'event_espresso')
2138
+								  . '</a>';
2139
+		$message_types          = $this->get_installed_message_types();
2140
+		$active_messenger       = $this->_message_resource_manager->get_active_messenger(
2141
+				$this->_req_data['messenger']
2142
+		);
2143
+		$active_messenger_label = $active_messenger instanceof EE_messenger
2144
+			? ucwords($active_messenger->label['singular'])
2145
+			: esc_html__('Unknown Messenger', 'event_espresso');
2146
+		//let's provide a helpful title for context
2147
+		$preview_title = sprintf(
2148
+			esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2149
+			$active_messenger_label,
2150
+			ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
2151
+		);
2152
+		//setup display of preview.
2153
+		$this->_admin_page_title                    = $preview_title;
2154
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2155
+		$this->_template_args['data']['force_json'] = true;
2156
+        
2157
+		return '';
2158
+	}
2159 2159
     
2160 2160
     
2161
-    /**
2162
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2163
-     * gets called automatically.
2164
-     *
2165
-     * @since 4.5.0
2166
-     *
2167
-     * @return string
2168
-     */
2169
-    protected function _display_preview_message()
2170
-    {
2171
-        $this->display_admin_page_with_no_sidebar();
2172
-    }
2161
+	/**
2162
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2163
+	 * gets called automatically.
2164
+	 *
2165
+	 * @since 4.5.0
2166
+	 *
2167
+	 * @return string
2168
+	 */
2169
+	protected function _display_preview_message()
2170
+	{
2171
+		$this->display_admin_page_with_no_sidebar();
2172
+	}
2173 2173
     
2174 2174
     
2175
-    /**
2176
-     * registers metaboxes that should show up on the "edit_message_template" page
2177
-     *
2178
-     * @access protected
2179
-     * @return void
2180
-     */
2181
-    protected function _register_edit_meta_boxes()
2182
-    {
2183
-        add_meta_box(
2184
-            'mtp_valid_shortcodes',
2185
-            esc_html__('Valid Shortcodes', 'event_espresso'),
2186
-            array($this, 'shortcode_meta_box'),
2187
-            $this->_current_screen->id,
2188
-            'side',
2189
-            'default');
2190
-        add_meta_box(
2191
-            'mtp_extra_actions',
2192
-            esc_html__('Extra Actions', 'event_espresso'),
2193
-            array($this, 'extra_actions_meta_box'),
2194
-            $this->_current_screen->id,
2195
-            'side',
2196
-            'high'
2197
-        );
2198
-        add_meta_box(
2199
-            'mtp_templates',
2200
-            esc_html__('Template Styles', 'event_espresso'),
2201
-            array($this, 'template_pack_meta_box'),
2202
-            $this->_current_screen->id,
2203
-            'side',
2204
-            'high'
2205
-        );
2206
-    }
2175
+	/**
2176
+	 * registers metaboxes that should show up on the "edit_message_template" page
2177
+	 *
2178
+	 * @access protected
2179
+	 * @return void
2180
+	 */
2181
+	protected function _register_edit_meta_boxes()
2182
+	{
2183
+		add_meta_box(
2184
+			'mtp_valid_shortcodes',
2185
+			esc_html__('Valid Shortcodes', 'event_espresso'),
2186
+			array($this, 'shortcode_meta_box'),
2187
+			$this->_current_screen->id,
2188
+			'side',
2189
+			'default');
2190
+		add_meta_box(
2191
+			'mtp_extra_actions',
2192
+			esc_html__('Extra Actions', 'event_espresso'),
2193
+			array($this, 'extra_actions_meta_box'),
2194
+			$this->_current_screen->id,
2195
+			'side',
2196
+			'high'
2197
+		);
2198
+		add_meta_box(
2199
+			'mtp_templates',
2200
+			esc_html__('Template Styles', 'event_espresso'),
2201
+			array($this, 'template_pack_meta_box'),
2202
+			$this->_current_screen->id,
2203
+			'side',
2204
+			'high'
2205
+		);
2206
+	}
2207 2207
 
2208 2208
 
2209
-    /**
2210
-     * metabox content for all template pack and variation selection.
2211
-     *
2212
-     * @since 4.5.0
2213
-     * @return string
2214
-     * @throws DomainException
2215
-     * @throws EE_Error
2216
-     * @throws InvalidArgumentException
2217
-     * @throws ReflectionException
2218
-     * @throws InvalidDataTypeException
2219
-     * @throws InvalidInterfaceException
2220
-     */
2221
-    public function template_pack_meta_box()
2222
-    {
2223
-        $this->_set_message_template_group();
2224
-        
2225
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
2226
-        
2227
-        $tp_select_values = array();
2228
-        
2229
-        foreach ($tp_collection as $tp) {
2230
-            //only include template packs that support this messenger and message type!
2231
-            $supports = $tp->get_supports();
2232
-            if (
2233
-                ! isset($supports[$this->_message_template_group->messenger()])
2234
-                || ! in_array(
2235
-                    $this->_message_template_group->message_type(),
2236
-                    $supports[$this->_message_template_group->messenger()],
2237
-                    true
2238
-                )
2239
-            ) {
2240
-                //not supported
2241
-                continue;
2242
-            }
2209
+	/**
2210
+	 * metabox content for all template pack and variation selection.
2211
+	 *
2212
+	 * @since 4.5.0
2213
+	 * @return string
2214
+	 * @throws DomainException
2215
+	 * @throws EE_Error
2216
+	 * @throws InvalidArgumentException
2217
+	 * @throws ReflectionException
2218
+	 * @throws InvalidDataTypeException
2219
+	 * @throws InvalidInterfaceException
2220
+	 */
2221
+	public function template_pack_meta_box()
2222
+	{
2223
+		$this->_set_message_template_group();
2224
+        
2225
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
2226
+        
2227
+		$tp_select_values = array();
2228
+        
2229
+		foreach ($tp_collection as $tp) {
2230
+			//only include template packs that support this messenger and message type!
2231
+			$supports = $tp->get_supports();
2232
+			if (
2233
+				! isset($supports[$this->_message_template_group->messenger()])
2234
+				|| ! in_array(
2235
+					$this->_message_template_group->message_type(),
2236
+					$supports[$this->_message_template_group->messenger()],
2237
+					true
2238
+				)
2239
+			) {
2240
+				//not supported
2241
+				continue;
2242
+			}
2243 2243
             
2244
-            $tp_select_values[] = array(
2245
-                'text' => $tp->label,
2246
-                'id'   => $tp->dbref
2247
-            );
2248
-        }
2249
-        
2250
-        //if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2251
-        // the default template pack.  This still allows for the odd template pack to override.
2252
-        if (empty($tp_select_values)) {
2253
-            $tp_select_values[] = array(
2254
-                'text' => esc_html__('Default', 'event_espresso'),
2255
-                'id'   => 'default'
2256
-            );
2257
-        }
2258
-        
2259
-        //setup variation select values for the currently selected template.
2260
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
2261
-            $this->_message_template_group->messenger(),
2262
-            $this->_message_template_group->message_type()
2263
-        );
2264
-        $variations_select_values = array();
2265
-        foreach ($variations as $variation => $label) {
2266
-            $variations_select_values[] = array(
2267
-                'text' => $label,
2268
-                'id'   => $variation
2269
-            );
2270
-        }
2271
-        
2272
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2273
-        
2274
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
2275
-            'MTP_template_pack',
2276
-            $tp_select_values,
2277
-            $this->_message_template_group->get_template_pack_name()
2278
-        );
2279
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
2280
-            'MTP_template_variation',
2281
-            $variations_select_values,
2282
-            $this->_message_template_group->get_template_pack_variation()
2283
-        );
2284
-        $template_args['template_pack_label']            = $template_pack_labels->template_pack;
2285
-        $template_args['template_variation_label']       = $template_pack_labels->template_variation;
2286
-        $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
2287
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2288
-        
2289
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2290
-        
2291
-        EEH_Template::display_template($template, $template_args);
2292
-    }
2244
+			$tp_select_values[] = array(
2245
+				'text' => $tp->label,
2246
+				'id'   => $tp->dbref
2247
+			);
2248
+		}
2249
+        
2250
+		//if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2251
+		// the default template pack.  This still allows for the odd template pack to override.
2252
+		if (empty($tp_select_values)) {
2253
+			$tp_select_values[] = array(
2254
+				'text' => esc_html__('Default', 'event_espresso'),
2255
+				'id'   => 'default'
2256
+			);
2257
+		}
2258
+        
2259
+		//setup variation select values for the currently selected template.
2260
+		$variations               = $this->_message_template_group->get_template_pack()->get_variations(
2261
+			$this->_message_template_group->messenger(),
2262
+			$this->_message_template_group->message_type()
2263
+		);
2264
+		$variations_select_values = array();
2265
+		foreach ($variations as $variation => $label) {
2266
+			$variations_select_values[] = array(
2267
+				'text' => $label,
2268
+				'id'   => $variation
2269
+			);
2270
+		}
2271
+        
2272
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2273
+        
2274
+		$template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
2275
+			'MTP_template_pack',
2276
+			$tp_select_values,
2277
+			$this->_message_template_group->get_template_pack_name()
2278
+		);
2279
+		$template_args['variations_selector']            = EEH_Form_Fields::select_input(
2280
+			'MTP_template_variation',
2281
+			$variations_select_values,
2282
+			$this->_message_template_group->get_template_pack_variation()
2283
+		);
2284
+		$template_args['template_pack_label']            = $template_pack_labels->template_pack;
2285
+		$template_args['template_variation_label']       = $template_pack_labels->template_variation;
2286
+		$template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
2287
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2288
+        
2289
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2290
+        
2291
+		EEH_Template::display_template($template, $template_args);
2292
+	}
2293 2293
     
2294 2294
     
2295
-    /**
2296
-     * This meta box holds any extra actions related to Message Templates
2297
-     * For now, this includes Resetting templates to defaults and sending a test email.
2298
-     *
2299
-     * @access  public
2300
-     * @return void
2301
-     * @throws EE_Error
2302
-     */
2303
-    public function extra_actions_meta_box()
2304
-    {
2305
-        $template_form_fields = array();
2306
-        
2307
-        $extra_args = array(
2308
-            'msgr'   => $this->_message_template_group->messenger(),
2309
-            'mt'     => $this->_message_template_group->message_type(),
2310
-            'GRP_ID' => $this->_message_template_group->GRP_ID()
2311
-        );
2312
-        //first we need to see if there are any fields
2313
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2314
-        
2315
-        if ( ! empty($fields)) {
2316
-            //yup there be fields
2317
-            foreach ($fields as $field => $config) {
2318
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2319
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2320
-                $default  = isset($config['default']) ? $config['default'] : '';
2321
-                $default  = isset($config['value']) ? $config['value'] : $default;
2295
+	/**
2296
+	 * This meta box holds any extra actions related to Message Templates
2297
+	 * For now, this includes Resetting templates to defaults and sending a test email.
2298
+	 *
2299
+	 * @access  public
2300
+	 * @return void
2301
+	 * @throws EE_Error
2302
+	 */
2303
+	public function extra_actions_meta_box()
2304
+	{
2305
+		$template_form_fields = array();
2306
+        
2307
+		$extra_args = array(
2308
+			'msgr'   => $this->_message_template_group->messenger(),
2309
+			'mt'     => $this->_message_template_group->message_type(),
2310
+			'GRP_ID' => $this->_message_template_group->GRP_ID()
2311
+		);
2312
+		//first we need to see if there are any fields
2313
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2314
+        
2315
+		if ( ! empty($fields)) {
2316
+			//yup there be fields
2317
+			foreach ($fields as $field => $config) {
2318
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2319
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2320
+				$default  = isset($config['default']) ? $config['default'] : '';
2321
+				$default  = isset($config['value']) ? $config['value'] : $default;
2322 2322
                 
2323
-                // if type is hidden and the value is empty
2324
-                // something may have gone wrong so let's correct with the defaults
2325
-                $fix              = $config['input'] === 'hidden'
2326
-                                    && isset($existing[$field])
2327
-                                    && empty($existing[$field])
2328
-                    ? $default
2329
-                    : '';
2330
-                $existing[$field] = isset($existing[$field]) && empty($fix)
2331
-                    ? $existing[$field]
2332
-                    : $fix;
2323
+				// if type is hidden and the value is empty
2324
+				// something may have gone wrong so let's correct with the defaults
2325
+				$fix              = $config['input'] === 'hidden'
2326
+									&& isset($existing[$field])
2327
+									&& empty($existing[$field])
2328
+					? $default
2329
+					: '';
2330
+				$existing[$field] = isset($existing[$field]) && empty($fix)
2331
+					? $existing[$field]
2332
+					: $fix;
2333 2333
                 
2334
-                $template_form_fields[$field_id] = array(
2335
-                    'name'       => 'test_settings_fld[' . $field . ']',
2336
-                    'label'      => $config['label'],
2337
-                    'input'      => $config['input'],
2338
-                    'type'       => $config['type'],
2339
-                    'required'   => $config['required'],
2340
-                    'validation' => $config['validation'],
2341
-                    'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2342
-                    'css_class'  => $config['css_class'],
2343
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2344
-                    'default'    => $default,
2345
-                    'format'     => $config['format']
2346
-                );
2347
-            }
2348
-        }
2349
-        
2350
-        $test_settings_fields = ! empty($template_form_fields)
2351
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2352
-            : '';
2353
-        
2354
-        $test_settings_html = '';
2355
-        //print out $test_settings_fields
2356
-        if ( ! empty($test_settings_fields)) {
2357
-            echo $test_settings_fields;
2358
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2359
-            $test_settings_html .= 'name="test_button" value="';
2360
-            $test_settings_html .= esc_html__('Test Send', 'event_espresso');
2361
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2362
-        }
2363
-        
2364
-        //and button
2365
-        $test_settings_html .= '<p>'
2366
-                               . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2367
-                               . '</p>';
2368
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2369
-        $test_settings_html .= $this->get_action_link_or_button(
2370
-            'reset_to_default',
2371
-            'reset',
2372
-            $extra_args,
2373
-            'button-primary reset-default-button'
2374
-        );
2375
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2376
-        echo $test_settings_html;
2377
-    }
2334
+				$template_form_fields[$field_id] = array(
2335
+					'name'       => 'test_settings_fld[' . $field . ']',
2336
+					'label'      => $config['label'],
2337
+					'input'      => $config['input'],
2338
+					'type'       => $config['type'],
2339
+					'required'   => $config['required'],
2340
+					'validation' => $config['validation'],
2341
+					'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2342
+					'css_class'  => $config['css_class'],
2343
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2344
+					'default'    => $default,
2345
+					'format'     => $config['format']
2346
+				);
2347
+			}
2348
+		}
2349
+        
2350
+		$test_settings_fields = ! empty($template_form_fields)
2351
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2352
+			: '';
2353
+        
2354
+		$test_settings_html = '';
2355
+		//print out $test_settings_fields
2356
+		if ( ! empty($test_settings_fields)) {
2357
+			echo $test_settings_fields;
2358
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2359
+			$test_settings_html .= 'name="test_button" value="';
2360
+			$test_settings_html .= esc_html__('Test Send', 'event_espresso');
2361
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2362
+		}
2363
+        
2364
+		//and button
2365
+		$test_settings_html .= '<p>'
2366
+							   . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2367
+							   . '</p>';
2368
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2369
+		$test_settings_html .= $this->get_action_link_or_button(
2370
+			'reset_to_default',
2371
+			'reset',
2372
+			$extra_args,
2373
+			'button-primary reset-default-button'
2374
+		);
2375
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2376
+		echo $test_settings_html;
2377
+	}
2378 2378
 
2379 2379
 
2380
-    /**
2381
-     * This returns the shortcode selector skeleton for a given context and field.
2382
-     *
2383
-     * @since 4.9.rc.000
2384
-     * @param string $field           The name of the field retrieving shortcodes for.
2385
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2386
-     * @return string
2387
-     * @throws DomainException
2388
-     * @throws EE_Error
2389
-     * @throws InvalidArgumentException
2390
-     * @throws ReflectionException
2391
-     * @throws InvalidDataTypeException
2392
-     * @throws InvalidInterfaceException
2393
-     */
2394
-    protected function _get_shortcode_selector($field, $linked_input_id)
2395
-    {
2396
-        $template_args = array(
2397
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2398
-            'fieldname'       => $field,
2399
-            'linked_input_id' => $linked_input_id
2400
-        );
2401
-        
2402
-        return EEH_Template::display_template(
2403
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2404
-            $template_args,
2405
-            true
2406
-        );
2407
-    }
2380
+	/**
2381
+	 * This returns the shortcode selector skeleton for a given context and field.
2382
+	 *
2383
+	 * @since 4.9.rc.000
2384
+	 * @param string $field           The name of the field retrieving shortcodes for.
2385
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2386
+	 * @return string
2387
+	 * @throws DomainException
2388
+	 * @throws EE_Error
2389
+	 * @throws InvalidArgumentException
2390
+	 * @throws ReflectionException
2391
+	 * @throws InvalidDataTypeException
2392
+	 * @throws InvalidInterfaceException
2393
+	 */
2394
+	protected function _get_shortcode_selector($field, $linked_input_id)
2395
+	{
2396
+		$template_args = array(
2397
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2398
+			'fieldname'       => $field,
2399
+			'linked_input_id' => $linked_input_id
2400
+		);
2401
+        
2402
+		return EEH_Template::display_template(
2403
+			EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2404
+			$template_args,
2405
+			true
2406
+		);
2407
+	}
2408 2408
 
2409 2409
 
2410
-    /**
2411
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2412
-     * page)
2413
-     *
2414
-     * @access public
2415
-     * @return void
2416
-     * @throws EE_Error
2417
-     * @throws InvalidArgumentException
2418
-     * @throws ReflectionException
2419
-     * @throws InvalidDataTypeException
2420
-     * @throws InvalidInterfaceException
2421
-     */
2422
-    public function shortcode_meta_box()
2423
-    {
2424
-        $shortcodes = $this->_get_shortcodes(array(), false); //just make sure shortcodes property is set
2425
-        //$messenger = $this->_message_template_group->messenger_obj();
2426
-        //now let's set the content depending on the status of the shortcodes array
2427
-        if (empty($shortcodes)) {
2428
-            $content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2429
-            echo $content;
2430
-        } else {
2431
-            //$alt = 0;
2432
-            ?>
2410
+	/**
2411
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2412
+	 * page)
2413
+	 *
2414
+	 * @access public
2415
+	 * @return void
2416
+	 * @throws EE_Error
2417
+	 * @throws InvalidArgumentException
2418
+	 * @throws ReflectionException
2419
+	 * @throws InvalidDataTypeException
2420
+	 * @throws InvalidInterfaceException
2421
+	 */
2422
+	public function shortcode_meta_box()
2423
+	{
2424
+		$shortcodes = $this->_get_shortcodes(array(), false); //just make sure shortcodes property is set
2425
+		//$messenger = $this->_message_template_group->messenger_obj();
2426
+		//now let's set the content depending on the status of the shortcodes array
2427
+		if (empty($shortcodes)) {
2428
+			$content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2429
+			echo $content;
2430
+		} else {
2431
+			//$alt = 0;
2432
+			?>
2433 2433
             <div style="float:right; margin-top:10px"><?php echo $this->_get_help_tab_link('message_template_shortcodes'); ?></div>
2434 2434
             <p class="small-text"><?php printf(
2435
-                    esc_html__(
2436
-                        'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2437
-                        'event_espresso'
2438
-                    ),
2439
-                    '<span class="dashicons dashicons-menu"></span>'
2440
-                ); ?></p>
2435
+					esc_html__(
2436
+						'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2437
+						'event_espresso'
2438
+					),
2439
+					'<span class="dashicons dashicons-menu"></span>'
2440
+				); ?></p>
2441 2441
             <?php
2442
-        }
2442
+		}
2443 2443
         
2444 2444
         
2445
-    }
2445
+	}
2446 2446
 
2447 2447
 
2448
-    /**
2449
-     * used to set the $_shortcodes property for when its needed elsewhere.
2450
-     *
2451
-     * @access protected
2452
-     * @return void
2453
-     * @throws EE_Error
2454
-     * @throws InvalidArgumentException
2455
-     * @throws ReflectionException
2456
-     * @throws InvalidDataTypeException
2457
-     * @throws InvalidInterfaceException
2458
-     */
2459
-    protected function _set_shortcodes()
2460
-    {
2461
-        
2462
-        //no need to run this if the property is already set
2463
-        if ( ! empty($this->_shortcodes)) {
2464
-            return;
2465
-        }
2466
-        
2467
-        $this->_shortcodes = $this->_get_shortcodes();
2468
-    }
2448
+	/**
2449
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2450
+	 *
2451
+	 * @access protected
2452
+	 * @return void
2453
+	 * @throws EE_Error
2454
+	 * @throws InvalidArgumentException
2455
+	 * @throws ReflectionException
2456
+	 * @throws InvalidDataTypeException
2457
+	 * @throws InvalidInterfaceException
2458
+	 */
2459
+	protected function _set_shortcodes()
2460
+	{
2461
+        
2462
+		//no need to run this if the property is already set
2463
+		if ( ! empty($this->_shortcodes)) {
2464
+			return;
2465
+		}
2466
+        
2467
+		$this->_shortcodes = $this->_get_shortcodes();
2468
+	}
2469 2469
 
2470 2470
 
2471
-    /**
2472
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2473
-     * property)
2474
-     *
2475
-     * @access  protected
2476
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2477
-     *                         for. Defaults to all (for the given context)
2478
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2479
-     * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2480
-     *                         true just an array of shortcode/label pairs.
2481
-     * @throws EE_Error
2482
-     * @throws InvalidArgumentException
2483
-     * @throws ReflectionException
2484
-     * @throws InvalidDataTypeException
2485
-     * @throws InvalidInterfaceException
2486
-     */
2487
-    protected function _get_shortcodes($fields = array(), $merged = true)
2488
-    {
2489
-        $this->_set_message_template_group();
2490
-        
2491
-        //we need the messenger and message template to retrieve the valid shortcodes array.
2492
-        $GRP_ID  = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2493
-            ? absint($this->_req_data['id'])
2494
-            : false;
2495
-        $context = isset($this->_req_data['context'])
2496
-            ? $this->_req_data['context']
2497
-            : key($this->_message_template_group->contexts_config());
2498
-        
2499
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2500
-    }
2471
+	/**
2472
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2473
+	 * property)
2474
+	 *
2475
+	 * @access  protected
2476
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2477
+	 *                         for. Defaults to all (for the given context)
2478
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2479
+	 * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2480
+	 *                         true just an array of shortcode/label pairs.
2481
+	 * @throws EE_Error
2482
+	 * @throws InvalidArgumentException
2483
+	 * @throws ReflectionException
2484
+	 * @throws InvalidDataTypeException
2485
+	 * @throws InvalidInterfaceException
2486
+	 */
2487
+	protected function _get_shortcodes($fields = array(), $merged = true)
2488
+	{
2489
+		$this->_set_message_template_group();
2490
+        
2491
+		//we need the messenger and message template to retrieve the valid shortcodes array.
2492
+		$GRP_ID  = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2493
+			? absint($this->_req_data['id'])
2494
+			: false;
2495
+		$context = isset($this->_req_data['context'])
2496
+			? $this->_req_data['context']
2497
+			: key($this->_message_template_group->contexts_config());
2498
+        
2499
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2500
+	}
2501 2501
 
2502 2502
 
2503
-    /**
2504
-     * This sets the _message_template property (containing the called message_template object)
2505
-     *
2506
-     * @access protected
2507
-     * @return void
2508
-     * @throws EE_Error
2509
-     * @throws InvalidArgumentException
2510
-     * @throws ReflectionException
2511
-     * @throws InvalidDataTypeException
2512
-     * @throws InvalidInterfaceException
2513
-     */
2514
-    protected function _set_message_template_group()
2515
-    {
2516
-        
2517
-        if ( ! empty($this->_message_template_group)) {
2518
-            return;
2519
-        } //get out if this is already set.
2520
-        
2521
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2522
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2523
-        
2524
-        //let's get the message templates
2525
-        $MTP = EEM_Message_Template_Group::instance();
2526
-        
2527
-        if (empty($GRP_ID)) {
2528
-            $this->_message_template_group = $MTP->create_default_object();
2529
-        } else {
2530
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2531
-        }
2532
-        
2533
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2534
-        $this->_variation     = $this->_message_template_group->get_template_pack_variation();
2535
-        
2536
-    }
2503
+	/**
2504
+	 * This sets the _message_template property (containing the called message_template object)
2505
+	 *
2506
+	 * @access protected
2507
+	 * @return void
2508
+	 * @throws EE_Error
2509
+	 * @throws InvalidArgumentException
2510
+	 * @throws ReflectionException
2511
+	 * @throws InvalidDataTypeException
2512
+	 * @throws InvalidInterfaceException
2513
+	 */
2514
+	protected function _set_message_template_group()
2515
+	{
2516
+        
2517
+		if ( ! empty($this->_message_template_group)) {
2518
+			return;
2519
+		} //get out if this is already set.
2520
+        
2521
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2522
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2523
+        
2524
+		//let's get the message templates
2525
+		$MTP = EEM_Message_Template_Group::instance();
2526
+        
2527
+		if (empty($GRP_ID)) {
2528
+			$this->_message_template_group = $MTP->create_default_object();
2529
+		} else {
2530
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2531
+		}
2532
+        
2533
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2534
+		$this->_variation     = $this->_message_template_group->get_template_pack_variation();
2535
+        
2536
+	}
2537 2537
 
2538 2538
 
2539
-    /**
2540
-     * sets up a context switcher for edit forms
2541
-     *
2542
-     * @access  protected
2543
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2544
-     * @param array                      $args                  various things the context switcher needs.
2545
-     * @throws EE_Error
2546
-     */
2547
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2548
-    {
2549
-        $context_details = $template_group_object->contexts_config();
2550
-        $context_label   = $template_group_object->context_label();
2551
-        ob_start();
2552
-        ?>
2539
+	/**
2540
+	 * sets up a context switcher for edit forms
2541
+	 *
2542
+	 * @access  protected
2543
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2544
+	 * @param array                      $args                  various things the context switcher needs.
2545
+	 * @throws EE_Error
2546
+	 */
2547
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2548
+	{
2549
+		$context_details = $template_group_object->contexts_config();
2550
+		$context_label   = $template_group_object->context_label();
2551
+		ob_start();
2552
+		?>
2553 2553
         <div class="ee-msg-switcher-container">
2554 2554
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2555 2555
                 <?php
2556
-                foreach ($args as $name => $value) {
2557
-                    if ($name === 'context' || empty($value) || $name === 'extra') {
2558
-                        continue;
2559
-                    }
2560
-                    ?>
2556
+				foreach ($args as $name => $value) {
2557
+					if ($name === 'context' || empty($value) || $name === 'extra') {
2558
+						continue;
2559
+					}
2560
+					?>
2561 2561
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2562 2562
                     <?php
2563
-                }
2564
-                //setup nonce_url
2565
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2566
-                ?>
2563
+				}
2564
+				//setup nonce_url
2565
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2566
+				?>
2567 2567
                 <select name="context">
2568 2568
                     <?php
2569
-                    $context_templates = $template_group_object->context_templates();
2570
-                    if (is_array($context_templates)) :
2571
-                        foreach ($context_templates as $context => $template_fields) :
2572
-                            $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2573
-                            ?>
2569
+					$context_templates = $template_group_object->context_templates();
2570
+					if (is_array($context_templates)) :
2571
+						foreach ($context_templates as $context => $template_fields) :
2572
+							$checked = ($context === $args['context']) ? 'selected="selected"' : '';
2573
+							?>
2574 2574
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2575 2575
                                 <?php echo $context_details[$context]['label']; ?>
2576 2576
                             </option>
@@ -2583,1863 +2583,1863 @@  discard block
 block discarded – undo
2583 2583
             <?php echo $args['extra']; ?>
2584 2584
         </div> <!-- end .ee-msg-switcher-container -->
2585 2585
         <?php
2586
-        $output = ob_get_contents();
2587
-        ob_clean();
2588
-        $this->_context_switcher = $output;
2589
-    }
2586
+		$output = ob_get_contents();
2587
+		ob_clean();
2588
+		$this->_context_switcher = $output;
2589
+	}
2590 2590
     
2591 2591
     
2592
-    /**
2593
-     * utility for sanitizing new values coming in.
2594
-     * Note: this is only used when updating a context.
2595
-     *
2596
-     * @access protected
2597
-     *
2598
-     * @param int $index This helps us know which template field to select from the request array.
2599
-     *
2600
-     * @return array
2601
-     */
2602
-    protected function _set_message_template_column_values($index)
2603
-    {
2604
-        if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2605
-            foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2606
-                $this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2607
-            }
2608
-        }
2609
-        
2610
-        
2611
-        $set_column_values = array(
2612
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2613
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2614
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2615
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2616
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2617
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2618
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2619
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2620
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2621
-                ? absint($this->_req_data['MTP_is_global'])
2622
-                : 0,
2623
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2624
-                ? absint($this->_req_data['MTP_is_override'])
2625
-                : 0,
2626
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2627
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active'])
2628
-        );
2629
-        
2630
-        
2631
-        return $set_column_values;
2632
-    }
2592
+	/**
2593
+	 * utility for sanitizing new values coming in.
2594
+	 * Note: this is only used when updating a context.
2595
+	 *
2596
+	 * @access protected
2597
+	 *
2598
+	 * @param int $index This helps us know which template field to select from the request array.
2599
+	 *
2600
+	 * @return array
2601
+	 */
2602
+	protected function _set_message_template_column_values($index)
2603
+	{
2604
+		if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2605
+			foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2606
+				$this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2607
+			}
2608
+		}
2609
+        
2610
+        
2611
+		$set_column_values = array(
2612
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2613
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2614
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2615
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2616
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2617
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2618
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2619
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2620
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2621
+				? absint($this->_req_data['MTP_is_global'])
2622
+				: 0,
2623
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2624
+				? absint($this->_req_data['MTP_is_override'])
2625
+				: 0,
2626
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2627
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active'])
2628
+		);
2629
+        
2630
+        
2631
+		return $set_column_values;
2632
+	}
2633 2633
     
2634 2634
     
2635
-    protected function _insert_or_update_message_template($new = false)
2636
-    {
2637
-        
2638
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2639
-        $success  = 0;
2640
-        $override = false;
2641
-        
2642
-        //setup notices description
2643
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2644
-        
2645
-        //need the message type and messenger objects to be able to use the labels for the notices
2646
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2647
-        $messenger_label  = $messenger_object instanceof EE_messenger
2648
-            ? ucwords($messenger_object->label['singular'])
2649
-            : '';
2650
-        
2651
-        $message_type_slug   = ! empty($this->_req_data['MTP_message_type'])
2652
-            ? $this->_req_data['MTP_message_type']
2653
-            : '';
2654
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2655
-        
2656
-        $message_type_label = $message_type_object instanceof EE_message_type
2657
-            ? ucwords($message_type_object->label['singular'])
2658
-            : '';
2659
-        
2660
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2661
-            ? $this->_req_data['MTP_context']
2662
-            : '';
2663
-        $context      = ucwords(str_replace('_', ' ', $context_slug));
2664
-        
2665
-        $item_desc = $messenger_label && $message_type_label
2666
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2667
-            : '';
2668
-        $item_desc .= 'Message Template';
2669
-        $query_args  = array();
2670
-        $edit_array  = array();
2671
-        $action_desc = '';
2672
-        
2673
-        //if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2674
-        // user to edit.
2675
-        if ($new) {
2676
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2677
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2678
-                if (empty($edit_array)) {
2679
-                    $success = 0;
2680
-                } else {
2681
-                    $success    = 1;
2682
-                    $edit_array = $edit_array[0];
2683
-                    $query_args = array(
2684
-                        'id'      => $edit_array['GRP_ID'],
2685
-                        'context' => $edit_array['MTP_context'],
2686
-                        'action'  => 'edit_message_template'
2687
-                    );
2688
-                }
2689
-            }
2690
-            $action_desc = 'created';
2691
-        } else {
2692
-            $MTPG = EEM_Message_Template_Group::instance();
2693
-            $MTP  = EEM_Message_Template::instance();
2635
+	protected function _insert_or_update_message_template($new = false)
2636
+	{
2637
+        
2638
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2639
+		$success  = 0;
2640
+		$override = false;
2641
+        
2642
+		//setup notices description
2643
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2644
+        
2645
+		//need the message type and messenger objects to be able to use the labels for the notices
2646
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2647
+		$messenger_label  = $messenger_object instanceof EE_messenger
2648
+			? ucwords($messenger_object->label['singular'])
2649
+			: '';
2650
+        
2651
+		$message_type_slug   = ! empty($this->_req_data['MTP_message_type'])
2652
+			? $this->_req_data['MTP_message_type']
2653
+			: '';
2654
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2655
+        
2656
+		$message_type_label = $message_type_object instanceof EE_message_type
2657
+			? ucwords($message_type_object->label['singular'])
2658
+			: '';
2659
+        
2660
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2661
+			? $this->_req_data['MTP_context']
2662
+			: '';
2663
+		$context      = ucwords(str_replace('_', ' ', $context_slug));
2664
+        
2665
+		$item_desc = $messenger_label && $message_type_label
2666
+			? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2667
+			: '';
2668
+		$item_desc .= 'Message Template';
2669
+		$query_args  = array();
2670
+		$edit_array  = array();
2671
+		$action_desc = '';
2672
+        
2673
+		//if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2674
+		// user to edit.
2675
+		if ($new) {
2676
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2677
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2678
+				if (empty($edit_array)) {
2679
+					$success = 0;
2680
+				} else {
2681
+					$success    = 1;
2682
+					$edit_array = $edit_array[0];
2683
+					$query_args = array(
2684
+						'id'      => $edit_array['GRP_ID'],
2685
+						'context' => $edit_array['MTP_context'],
2686
+						'action'  => 'edit_message_template'
2687
+					);
2688
+				}
2689
+			}
2690
+			$action_desc = 'created';
2691
+		} else {
2692
+			$MTPG = EEM_Message_Template_Group::instance();
2693
+			$MTP  = EEM_Message_Template::instance();
2694 2694
             
2695 2695
             
2696
-            //run update for each template field in displayed context
2697
-            if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2698
-                EE_Error::add_error(
2699
-                    esc_html__(
2700
-                        'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2701
-                        'event_espresso'
2702
-                    ),
2703
-                    __FILE__,
2704
-                    __FUNCTION__,
2705
-                    __LINE__
2706
-                );
2707
-                $success = 0;
2696
+			//run update for each template field in displayed context
2697
+			if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2698
+				EE_Error::add_error(
2699
+					esc_html__(
2700
+						'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2701
+						'event_espresso'
2702
+					),
2703
+					__FILE__,
2704
+					__FUNCTION__,
2705
+					__LINE__
2706
+				);
2707
+				$success = 0;
2708 2708
                 
2709
-            } else {
2710
-                //first validate all fields!
2711
-                $validates = $MTPG->validate($this->_req_data['MTP_template_fields'], $context_slug, $messenger_slug,
2712
-                    $message_type_slug);
2709
+			} else {
2710
+				//first validate all fields!
2711
+				$validates = $MTPG->validate($this->_req_data['MTP_template_fields'], $context_slug, $messenger_slug,
2712
+					$message_type_slug);
2713 2713
                 
2714
-                //if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2715
-                // appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2716
-                //  WE need to make sure there is no actual error messages in validates.
2717
-                if (is_array($validates) && ! empty($validates)) {
2718
-                    //add the transient so when the form loads we know which fields to highlight
2719
-                    $this->_add_transient('edit_message_template', $validates);
2714
+				//if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2715
+				// appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2716
+				//  WE need to make sure there is no actual error messages in validates.
2717
+				if (is_array($validates) && ! empty($validates)) {
2718
+					//add the transient so when the form loads we know which fields to highlight
2719
+					$this->_add_transient('edit_message_template', $validates);
2720 2720
                     
2721
-                    $success = 0;
2721
+					$success = 0;
2722 2722
                     
2723
-                    //setup notices
2724
-                    foreach ($validates as $field => $error) {
2725
-                        if (isset($error['msg'])) {
2726
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2727
-                        }
2728
-                    }
2723
+					//setup notices
2724
+					foreach ($validates as $field => $error) {
2725
+						if (isset($error['msg'])) {
2726
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2727
+						}
2728
+					}
2729 2729
                     
2730
-                } else {
2731
-                    $set_column_values = array();
2732
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2733
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2730
+				} else {
2731
+					$set_column_values = array();
2732
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2733
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2734 2734
                         
2735
-                        $where_cols_n_values = array(
2736
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2737
-                        );
2738
-                        //if they aren't allowed to use all JS, restrict them to just posty-y tags
2739
-                        if (! current_user_can('unfiltered_html')){
2740
-                            if (is_array($set_column_values['MTP_content'])){
2741
-                                 foreach($set_column_values['MTP_content'] as $key => $value) {
2742
-                                     //remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2743
-                                     //only removes slashes from double-quotes, so attributes using single quotes always
2744
-                                     //appear invalid.) But currently the models expect slashed data, so after wp_kses
2745
-                                     //runs we need to re-slash the data. Sheesh. See
2746
-                                     //https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2747
-                                     $set_column_values['MTP_content'][$key] = addslashes(
2748
-                                             wp_kses(
2749
-                                                 stripslashes($value),
2750
-                                                 wp_kses_allowed_html('post')
2751
-                                             )
2752
-                                     );
2753
-                                 }
2754
-                            } else {
2755
-                                $set_column_values['MTP_content'] = wp_kses(
2756
-                                    $set_column_values['MTP_content'],
2757
-                                    wp_kses_allowed_html('post')
2758
-                                );
2759
-                            }
2760
-                        }
2761
-                        $message_template_fields = array(
2762
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2763
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2764
-                            'MTP_context'        => $set_column_values['MTP_context'],
2765
-                            'MTP_content'        => $set_column_values['MTP_content']
2766
-                        );
2767
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2768
-                            if ($updated === false) {
2769
-                                EE_Error::add_error(
2770
-                                    sprintf(
2771
-                                        esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2772
-                                        $template_field
2773
-                                    ),
2774
-                                    __FILE__,
2775
-                                    __FUNCTION__,
2776
-                                    __LINE__
2777
-                                );
2778
-                            } else {
2779
-                                $success = 1;
2780
-                            }
2781
-                        } else {
2782
-                            //only do this logic if we don't have a MTP_ID for this field
2783
-                            if (empty($this->_req_data['MTP_template_fields'][$template_field]['MTP_ID'])) {
2784
-                                //this has already been through the template field validator and sanitized, so it will be
2785
-                                //safe to insert this field.  Why insert?  This typically happens when we introduce a new
2786
-                                //message template field in a messenger/message type and existing users don't have the
2787
-                                //default setup for it.
2788
-                                //@link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2789
-                                $updated = $MTP->insert($message_template_fields);
2790
-                                if (! $updated || is_wp_error($updated)) {
2791
-                                    EE_Error::add_error(
2792
-                                        sprintf(
2793
-                                            esc_html__('%s field could not be updated.', 'event_espresso'),
2794
-                                            $template_field
2795
-                                        ),
2796
-                                        __FILE__,
2797
-                                        __FUNCTION__,
2798
-                                        __LINE__
2799
-                                    );
2800
-                                    $success = 0;
2801
-                                } else {
2802
-                                    $success = 1;
2803
-                                }
2804
-                            }
2805
-                        }
2806
-                        $action_desc = 'updated';
2807
-                    }
2735
+						$where_cols_n_values = array(
2736
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2737
+						);
2738
+						//if they aren't allowed to use all JS, restrict them to just posty-y tags
2739
+						if (! current_user_can('unfiltered_html')){
2740
+							if (is_array($set_column_values['MTP_content'])){
2741
+								 foreach($set_column_values['MTP_content'] as $key => $value) {
2742
+									 //remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2743
+									 //only removes slashes from double-quotes, so attributes using single quotes always
2744
+									 //appear invalid.) But currently the models expect slashed data, so after wp_kses
2745
+									 //runs we need to re-slash the data. Sheesh. See
2746
+									 //https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2747
+									 $set_column_values['MTP_content'][$key] = addslashes(
2748
+											 wp_kses(
2749
+												 stripslashes($value),
2750
+												 wp_kses_allowed_html('post')
2751
+											 )
2752
+									 );
2753
+								 }
2754
+							} else {
2755
+								$set_column_values['MTP_content'] = wp_kses(
2756
+									$set_column_values['MTP_content'],
2757
+									wp_kses_allowed_html('post')
2758
+								);
2759
+							}
2760
+						}
2761
+						$message_template_fields = array(
2762
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2763
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2764
+							'MTP_context'        => $set_column_values['MTP_context'],
2765
+							'MTP_content'        => $set_column_values['MTP_content']
2766
+						);
2767
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2768
+							if ($updated === false) {
2769
+								EE_Error::add_error(
2770
+									sprintf(
2771
+										esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2772
+										$template_field
2773
+									),
2774
+									__FILE__,
2775
+									__FUNCTION__,
2776
+									__LINE__
2777
+								);
2778
+							} else {
2779
+								$success = 1;
2780
+							}
2781
+						} else {
2782
+							//only do this logic if we don't have a MTP_ID for this field
2783
+							if (empty($this->_req_data['MTP_template_fields'][$template_field]['MTP_ID'])) {
2784
+								//this has already been through the template field validator and sanitized, so it will be
2785
+								//safe to insert this field.  Why insert?  This typically happens when we introduce a new
2786
+								//message template field in a messenger/message type and existing users don't have the
2787
+								//default setup for it.
2788
+								//@link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2789
+								$updated = $MTP->insert($message_template_fields);
2790
+								if (! $updated || is_wp_error($updated)) {
2791
+									EE_Error::add_error(
2792
+										sprintf(
2793
+											esc_html__('%s field could not be updated.', 'event_espresso'),
2794
+											$template_field
2795
+										),
2796
+										__FILE__,
2797
+										__FUNCTION__,
2798
+										__LINE__
2799
+									);
2800
+									$success = 0;
2801
+								} else {
2802
+									$success = 1;
2803
+								}
2804
+							}
2805
+						}
2806
+						$action_desc = 'updated';
2807
+					}
2808 2808
                     
2809
-                    //we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2810
-                    $mtpg_fields = array(
2811
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2812
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2813
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2814
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2815
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2816
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2817
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2818
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2819
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2820
-                            : '',
2821
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2822
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2823
-                            : ''
2824
-                    );
2809
+					//we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2810
+					$mtpg_fields = array(
2811
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2812
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2813
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2814
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2815
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2816
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2817
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2818
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2819
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2820
+							: '',
2821
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2822
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2823
+							: ''
2824
+					);
2825 2825
                     
2826
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2827
-                    $updated    = $MTPG->update($mtpg_fields, array($mtpg_where));
2826
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2827
+					$updated    = $MTPG->update($mtpg_fields, array($mtpg_where));
2828 2828
                     
2829
-                    if ($updated === false) {
2830
-                        EE_Error::add_error(
2831
-                            sprintf(
2832
-                                esc_html__(
2833
-                                    'The Message Template Group (%d) was NOT updated for some reason',
2834
-                                    'event_espresso'
2835
-                                ),
2836
-                                $set_column_values['GRP_ID']
2837
-                            ),
2838
-                            __FILE__,
2839
-                            __FUNCTION__,
2840
-                            __LINE__
2841
-                        );
2842
-                    } else {
2843
-                        //k now we need to ensure the template_pack and template_variation fields are set.
2844
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2845
-                            ? $this->_req_data['MTP_template_pack']
2846
-                            : 'default';
2829
+					if ($updated === false) {
2830
+						EE_Error::add_error(
2831
+							sprintf(
2832
+								esc_html__(
2833
+									'The Message Template Group (%d) was NOT updated for some reason',
2834
+									'event_espresso'
2835
+								),
2836
+								$set_column_values['GRP_ID']
2837
+							),
2838
+							__FILE__,
2839
+							__FUNCTION__,
2840
+							__LINE__
2841
+						);
2842
+					} else {
2843
+						//k now we need to ensure the template_pack and template_variation fields are set.
2844
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2845
+							? $this->_req_data['MTP_template_pack']
2846
+							: 'default';
2847 2847
                         
2848
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2849
-                            ? $this->_req_data['MTP_template_variation']
2850
-                            : 'default';
2848
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2849
+							? $this->_req_data['MTP_template_variation']
2850
+							: 'default';
2851 2851
                         
2852
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2853
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2854
-                            $mtpg_obj->set_template_pack_name($template_pack);
2855
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2856
-                        }
2857
-                        $success = 1;
2858
-                    }
2859
-                }
2860
-            }
2852
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2853
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2854
+							$mtpg_obj->set_template_pack_name($template_pack);
2855
+							$mtpg_obj->set_template_pack_variation($template_variation);
2856
+						}
2857
+						$success = 1;
2858
+					}
2859
+				}
2860
+			}
2861 2861
             
2862
-        }
2863
-        
2864
-        //we return things differently if doing ajax
2865
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2866
-            $this->_template_args['success'] = $success;
2867
-            $this->_template_args['error']   = ! $success ? true : false;
2868
-            $this->_template_args['content'] = '';
2869
-            $this->_template_args['data']    = array(
2870
-                'grpID'        => $edit_array['GRP_ID'],
2871
-                'templateName' => $edit_array['template_name']
2872
-            );
2873
-            if ($success) {
2874
-                EE_Error::overwrite_success();
2875
-                EE_Error::add_success(
2876
-                    esc_html__(
2877
-                        '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.',
2878
-                        'event_espresso'
2879
-                    )
2880
-                );
2881
-            }
2862
+		}
2863
+        
2864
+		//we return things differently if doing ajax
2865
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2866
+			$this->_template_args['success'] = $success;
2867
+			$this->_template_args['error']   = ! $success ? true : false;
2868
+			$this->_template_args['content'] = '';
2869
+			$this->_template_args['data']    = array(
2870
+				'grpID'        => $edit_array['GRP_ID'],
2871
+				'templateName' => $edit_array['template_name']
2872
+			);
2873
+			if ($success) {
2874
+				EE_Error::overwrite_success();
2875
+				EE_Error::add_success(
2876
+					esc_html__(
2877
+						'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.',
2878
+						'event_espresso'
2879
+					)
2880
+				);
2881
+			}
2882 2882
             
2883
-            $this->_return_json();
2884
-        }
2885
-        
2886
-        
2887
-        //was a test send triggered?
2888
-        if (isset($this->_req_data['test_button'])) {
2889
-            EE_Error::overwrite_success();
2890
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2891
-            $override = true;
2892
-        }
2893
-        
2894
-        if (empty($query_args)) {
2895
-            $query_args = array(
2896
-                'id'      => $this->_req_data['GRP_ID'],
2897
-                'context' => $context_slug,
2898
-                'action'  => 'edit_message_template'
2899
-            );
2900
-        }
2901
-        
2902
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2903
-    }
2883
+			$this->_return_json();
2884
+		}
2885
+        
2886
+        
2887
+		//was a test send triggered?
2888
+		if (isset($this->_req_data['test_button'])) {
2889
+			EE_Error::overwrite_success();
2890
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2891
+			$override = true;
2892
+		}
2893
+        
2894
+		if (empty($query_args)) {
2895
+			$query_args = array(
2896
+				'id'      => $this->_req_data['GRP_ID'],
2897
+				'context' => $context_slug,
2898
+				'action'  => 'edit_message_template'
2899
+			);
2900
+		}
2901
+        
2902
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2903
+	}
2904 2904
 
2905 2905
 
2906
-    /**
2907
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
2908
-     *
2909
-     * @param  string $context      what context being tested
2910
-     * @param  string $messenger    messenger being tested
2911
-     * @param  string $message_type message type being tested
2912
-     * @throws EE_Error
2913
-     * @throws InvalidArgumentException
2914
-     * @throws InvalidDataTypeException
2915
-     * @throws InvalidInterfaceException
2916
-     */
2917
-    protected function _do_test_send($context, $messenger, $message_type)
2918
-    {
2919
-        //set things up for preview
2920
-        $this->_req_data['messenger']    = $messenger;
2921
-        $this->_req_data['message_type'] = $message_type;
2922
-        $this->_req_data['context']      = $context;
2923
-        $this->_req_data['GRP_ID']       = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2924
-        $active_messenger                = $this->_message_resource_manager->get_active_messenger($messenger);
2925
-        
2926
-        //let's save any existing fields that might be required by the messenger
2927
-        if (
2928
-            isset($this->_req_data['test_settings_fld'])
2929
-            && $active_messenger instanceof EE_messenger
2930
-            && apply_filters(
2931
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2932
-                true,
2933
-                $this->_req_data['test_settings_fld'],
2934
-                $active_messenger
2935
-            )
2936
-        ) {
2937
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2938
-        }
2939
-        
2940
-        $success = $this->_preview_message(true);
2941
-        
2942
-        if ($success) {
2943
-            EE_Error::add_success(__('Test message sent', 'event_espresso'));
2944
-        } else {
2945
-            EE_Error::add_error(
2946
-                esc_html__('The test message was not sent', 'event_espresso'),
2947
-                __FILE__,
2948
-                __FUNCTION__,
2949
-                __LINE__
2950
-            );
2951
-        }
2952
-    }
2906
+	/**
2907
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
2908
+	 *
2909
+	 * @param  string $context      what context being tested
2910
+	 * @param  string $messenger    messenger being tested
2911
+	 * @param  string $message_type message type being tested
2912
+	 * @throws EE_Error
2913
+	 * @throws InvalidArgumentException
2914
+	 * @throws InvalidDataTypeException
2915
+	 * @throws InvalidInterfaceException
2916
+	 */
2917
+	protected function _do_test_send($context, $messenger, $message_type)
2918
+	{
2919
+		//set things up for preview
2920
+		$this->_req_data['messenger']    = $messenger;
2921
+		$this->_req_data['message_type'] = $message_type;
2922
+		$this->_req_data['context']      = $context;
2923
+		$this->_req_data['GRP_ID']       = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2924
+		$active_messenger                = $this->_message_resource_manager->get_active_messenger($messenger);
2925
+        
2926
+		//let's save any existing fields that might be required by the messenger
2927
+		if (
2928
+			isset($this->_req_data['test_settings_fld'])
2929
+			&& $active_messenger instanceof EE_messenger
2930
+			&& apply_filters(
2931
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2932
+				true,
2933
+				$this->_req_data['test_settings_fld'],
2934
+				$active_messenger
2935
+			)
2936
+		) {
2937
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2938
+		}
2939
+        
2940
+		$success = $this->_preview_message(true);
2941
+        
2942
+		if ($success) {
2943
+			EE_Error::add_success(__('Test message sent', 'event_espresso'));
2944
+		} else {
2945
+			EE_Error::add_error(
2946
+				esc_html__('The test message was not sent', 'event_espresso'),
2947
+				__FILE__,
2948
+				__FUNCTION__,
2949
+				__LINE__
2950
+			);
2951
+		}
2952
+	}
2953 2953
     
2954 2954
     
2955
-    /**
2956
-     * _generate_new_templates
2957
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
2958
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
2959
-     * for the event.
2960
-     *
2961
-     *
2962
-     * @param  string $messenger     the messenger we are generating templates for
2963
-     * @param array   $message_types array of message types that the templates are generated for.
2964
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
2965
-     *                               indicate the message_template_group being used as the base.
2966
-     *
2967
-     * @param bool    $global
2968
-     *
2969
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
2970
-     *                               encountering problems.
2971
-     * @throws EE_Error
2972
-     */
2973
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
2974
-    {
2975
-        
2976
-        //if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
2977
-        // just don't generate any templates.
2978
-        if (empty($message_types)) {
2979
-            return true;
2980
-        }
2981
-        
2982
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
2983
-    }
2955
+	/**
2956
+	 * _generate_new_templates
2957
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
2958
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
2959
+	 * for the event.
2960
+	 *
2961
+	 *
2962
+	 * @param  string $messenger     the messenger we are generating templates for
2963
+	 * @param array   $message_types array of message types that the templates are generated for.
2964
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
2965
+	 *                               indicate the message_template_group being used as the base.
2966
+	 *
2967
+	 * @param bool    $global
2968
+	 *
2969
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
2970
+	 *                               encountering problems.
2971
+	 * @throws EE_Error
2972
+	 */
2973
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
2974
+	{
2975
+        
2976
+		//if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
2977
+		// just don't generate any templates.
2978
+		if (empty($message_types)) {
2979
+			return true;
2980
+		}
2981
+        
2982
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
2983
+	}
2984 2984
 
2985 2985
 
2986
-    /**
2987
-     * [_trash_or_restore_message_template]
2988
-     *
2989
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
2990
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
2991
-     *                        an individual context (FALSE).
2992
-     * @return void
2993
-     * @throws EE_Error
2994
-     * @throws InvalidArgumentException
2995
-     * @throws InvalidDataTypeException
2996
-     * @throws InvalidInterfaceException
2997
-     */
2998
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
2999
-    {
3000
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3001
-        $MTP = EEM_Message_Template_Group::instance();
3002
-        
3003
-        $success = 1;
3004
-        
3005
-        //incoming GRP_IDs
3006
-        if ($all) {
3007
-            //Checkboxes
3008
-            if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3009
-                //if array has more than one element then success message should be plural.
3010
-                //todo: what about nonce?
3011
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2986
+	/**
2987
+	 * [_trash_or_restore_message_template]
2988
+	 *
2989
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
2990
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
2991
+	 *                        an individual context (FALSE).
2992
+	 * @return void
2993
+	 * @throws EE_Error
2994
+	 * @throws InvalidArgumentException
2995
+	 * @throws InvalidDataTypeException
2996
+	 * @throws InvalidInterfaceException
2997
+	 */
2998
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
2999
+	{
3000
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3001
+		$MTP = EEM_Message_Template_Group::instance();
3002
+        
3003
+		$success = 1;
3004
+        
3005
+		//incoming GRP_IDs
3006
+		if ($all) {
3007
+			//Checkboxes
3008
+			if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3009
+				//if array has more than one element then success message should be plural.
3010
+				//todo: what about nonce?
3011
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3012 3012
                 
3013
-                //cycle through checkboxes
3014
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3015
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3016
-                    if ( ! $trashed_or_restored) {
3017
-                        $success = 0;
3018
-                    }
3019
-                }
3020
-            } else {
3021
-                //grab single GRP_ID and handle
3022
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3023
-                if ( ! empty($GRP_ID)) {
3024
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3025
-                    if ( ! $trashed_or_restored) {
3026
-                        $success = 0;
3027
-                    }
3028
-                } else {
3029
-                    $success = 0;
3030
-                }
3031
-            }
3013
+				//cycle through checkboxes
3014
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3015
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3016
+					if ( ! $trashed_or_restored) {
3017
+						$success = 0;
3018
+					}
3019
+				}
3020
+			} else {
3021
+				//grab single GRP_ID and handle
3022
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3023
+				if ( ! empty($GRP_ID)) {
3024
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3025
+					if ( ! $trashed_or_restored) {
3026
+						$success = 0;
3027
+					}
3028
+				} else {
3029
+					$success = 0;
3030
+				}
3031
+			}
3032 3032
             
3033
-        }
3033
+		}
3034 3034
         
3035
-        $action_desc = $trash
3036
-            ? esc_html__('moved to the trash', 'event_espresso')
3037
-            : esc_html__('restored', 'event_espresso');
3035
+		$action_desc = $trash
3036
+			? esc_html__('moved to the trash', 'event_espresso')
3037
+			: esc_html__('restored', 'event_espresso');
3038 3038
         
3039
-        $action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched') : $action_desc;
3039
+		$action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched') : $action_desc;
3040 3040
         
3041
-        $item_desc = $all ? _n('Message Template Group', 'Message Template Groups', $success,
3042
-            'event_espresso') : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3041
+		$item_desc = $all ? _n('Message Template Group', 'Message Template Groups', $success,
3042
+			'event_espresso') : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3043 3043
         
3044
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n('template', 'templates', $success,
3045
-            'event_espresso') : $item_desc;
3044
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n('template', 'templates', $success,
3045
+			'event_espresso') : $item_desc;
3046 3046
         
3047
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
3047
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
3048 3048
         
3049
-    }
3049
+	}
3050 3050
 
3051 3051
 
3052
-    /**
3053
-     * [_delete_message_template]
3054
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3055
-     *
3056
-     * @return void
3057
-     * @throws EE_Error
3058
-     * @throws InvalidArgumentException
3059
-     * @throws InvalidDataTypeException
3060
-     * @throws InvalidInterfaceException
3061
-     */
3062
-    protected function _delete_message_template()
3063
-    {
3064
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3065
-        
3066
-        //checkboxes
3067
-        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3068
-            //if array has more than one element then success message should be plural
3069
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3052
+	/**
3053
+	 * [_delete_message_template]
3054
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3055
+	 *
3056
+	 * @return void
3057
+	 * @throws EE_Error
3058
+	 * @throws InvalidArgumentException
3059
+	 * @throws InvalidDataTypeException
3060
+	 * @throws InvalidInterfaceException
3061
+	 */
3062
+	protected function _delete_message_template()
3063
+	{
3064
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3065
+        
3066
+		//checkboxes
3067
+		if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3068
+			//if array has more than one element then success message should be plural
3069
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3070 3070
             
3071
-            //cycle through bulk action checkboxes
3072
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3073
-                $success = $this->_delete_mtp_permanently($GRP_ID);
3074
-            }
3075
-        } else {
3076
-            //grab single grp_id and delete
3077
-            $GRP_ID  = absint($this->_req_data['id']);
3078
-            $success = $this->_delete_mtp_permanently($GRP_ID);
3079
-        }
3080
-        
3081
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3082
-        
3083
-    }
3071
+			//cycle through bulk action checkboxes
3072
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3073
+				$success = $this->_delete_mtp_permanently($GRP_ID);
3074
+			}
3075
+		} else {
3076
+			//grab single grp_id and delete
3077
+			$GRP_ID  = absint($this->_req_data['id']);
3078
+			$success = $this->_delete_mtp_permanently($GRP_ID);
3079
+		}
3080
+        
3081
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3082
+        
3083
+	}
3084 3084
 
3085 3085
 
3086
-    /**
3087
-     * helper for permanently deleting a mtP group and all related message_templates
3088
-     *
3089
-     * @param  int  $GRP_ID        The group being deleted
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.
3092
-     * @throws EE_Error
3093
-     * @throws InvalidArgumentException
3094
-     * @throws InvalidDataTypeException
3095
-     * @throws InvalidInterfaceException
3096
-     */
3097
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3098
-    {
3099
-        $success = 1;
3100
-        $MTPG    = EEM_Message_Template_Group::instance();
3101
-        //first let's GET this group
3102
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
3103
-        //then delete permanently all the related Message Templates
3104
-        $deleted = $MTG->delete_related_permanently('Message_Template');
3105
-        
3106
-        if ($deleted === 0) {
3107
-            $success = 0;
3108
-        }
3109
-        
3110
-        //now delete permanently this particular group
3111
-        
3112
-        if ($include_group && ! $MTG->delete_permanently()) {
3113
-            $success = 0;
3114
-        }
3115
-        
3116
-        return $success;
3117
-    }
3086
+	/**
3087
+	 * helper for permanently deleting a mtP group and all related message_templates
3088
+	 *
3089
+	 * @param  int  $GRP_ID        The group being deleted
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.
3092
+	 * @throws EE_Error
3093
+	 * @throws InvalidArgumentException
3094
+	 * @throws InvalidDataTypeException
3095
+	 * @throws InvalidInterfaceException
3096
+	 */
3097
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3098
+	{
3099
+		$success = 1;
3100
+		$MTPG    = EEM_Message_Template_Group::instance();
3101
+		//first let's GET this group
3102
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
3103
+		//then delete permanently all the related Message Templates
3104
+		$deleted = $MTG->delete_related_permanently('Message_Template');
3105
+        
3106
+		if ($deleted === 0) {
3107
+			$success = 0;
3108
+		}
3109
+        
3110
+		//now delete permanently this particular group
3111
+        
3112
+		if ($include_group && ! $MTG->delete_permanently()) {
3113
+			$success = 0;
3114
+		}
3115
+        
3116
+		return $success;
3117
+	}
3118 3118
     
3119 3119
     
3120
-    /**
3121
-     *    _learn_more_about_message_templates_link
3122
-     * @access protected
3123
-     * @return string
3124
-     */
3125
-    protected function _learn_more_about_message_templates_link()
3126
-    {
3127
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3128
-               . esc_html__('learn more about how message templates works', 'event_espresso')
3129
-               . '</a>';
3130
-    }
3120
+	/**
3121
+	 *    _learn_more_about_message_templates_link
3122
+	 * @access protected
3123
+	 * @return string
3124
+	 */
3125
+	protected function _learn_more_about_message_templates_link()
3126
+	{
3127
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3128
+			   . esc_html__('learn more about how message templates works', 'event_espresso')
3129
+			   . '</a>';
3130
+	}
3131 3131
 
3132 3132
 
3133
-    /**
3134
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3135
-     * ajax and other routes.
3136
-     *
3137
-     * @return void
3138
-     * @throws DomainException
3139
-     */
3140
-    protected function _settings()
3141
-    {
3142
-        
3143
-        
3144
-        $this->_set_m_mt_settings();
3145
-        
3146
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3147
-            ? $this->_req_data['selected_messenger']
3148
-            : 'email';
3149
-        
3150
-        //let's setup the messenger tabs
3151
-        $this->_template_args['admin_page_header']         = EEH_Tabbed_Content::tab_text_links(
3152
-            $this->_m_mt_settings['messenger_tabs'],
3153
-            'messenger_links',
3154
-            '|',
3155
-            $selected_messenger
3156
-        );
3157
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3158
-        $this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
3159
-        
3160
-        $this->display_admin_page_with_sidebar();
3161
-        
3162
-    }
3133
+	/**
3134
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3135
+	 * ajax and other routes.
3136
+	 *
3137
+	 * @return void
3138
+	 * @throws DomainException
3139
+	 */
3140
+	protected function _settings()
3141
+	{
3142
+        
3143
+        
3144
+		$this->_set_m_mt_settings();
3145
+        
3146
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3147
+			? $this->_req_data['selected_messenger']
3148
+			: 'email';
3149
+        
3150
+		//let's setup the messenger tabs
3151
+		$this->_template_args['admin_page_header']         = EEH_Tabbed_Content::tab_text_links(
3152
+			$this->_m_mt_settings['messenger_tabs'],
3153
+			'messenger_links',
3154
+			'|',
3155
+			$selected_messenger
3156
+		);
3157
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3158
+		$this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
3159
+        
3160
+		$this->display_admin_page_with_sidebar();
3161
+        
3162
+	}
3163 3163
 
3164 3164
 
3165
-    /**
3166
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3167
-     *
3168
-     * @access protected
3169
-     * @return void
3170
-     * @throws DomainException
3171
-     */
3172
-    protected function _set_m_mt_settings()
3173
-    {
3174
-        //first if this is already set then lets get out no need to regenerate data.
3175
-        if ( ! empty($this->_m_mt_settings)) {
3176
-            return;
3177
-        }
3178
-        
3179
-        //get all installed messengers and message_types
3180
-        /** @type EE_messenger[] $messengers */
3181
-        $messengers = $this->_message_resource_manager->installed_messengers();
3182
-        /** @type EE_message_type[] $message_types */
3183
-        $message_types = $this->_message_resource_manager->installed_message_types();
3184
-        
3185
-        
3186
-        //assemble the array for the _tab_text_links helper
3187
-        
3188
-        foreach ($messengers as $messenger) {
3189
-            $this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
3190
-                'label' => ucwords($messenger->label['singular']),
3191
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3192
-                    ? 'messenger-active'
3193
-                    : '',
3194
-                'href'  => $messenger->name,
3195
-                'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3196
-                'slug'  => $messenger->name,
3197
-                'obj'   => $messenger
3198
-            );
3165
+	/**
3166
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3167
+	 *
3168
+	 * @access protected
3169
+	 * @return void
3170
+	 * @throws DomainException
3171
+	 */
3172
+	protected function _set_m_mt_settings()
3173
+	{
3174
+		//first if this is already set then lets get out no need to regenerate data.
3175
+		if ( ! empty($this->_m_mt_settings)) {
3176
+			return;
3177
+		}
3178
+        
3179
+		//get all installed messengers and message_types
3180
+		/** @type EE_messenger[] $messengers */
3181
+		$messengers = $this->_message_resource_manager->installed_messengers();
3182
+		/** @type EE_message_type[] $message_types */
3183
+		$message_types = $this->_message_resource_manager->installed_message_types();
3184
+        
3185
+        
3186
+		//assemble the array for the _tab_text_links helper
3187
+        
3188
+		foreach ($messengers as $messenger) {
3189
+			$this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
3190
+				'label' => ucwords($messenger->label['singular']),
3191
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3192
+					? 'messenger-active'
3193
+					: '',
3194
+				'href'  => $messenger->name,
3195
+				'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3196
+				'slug'  => $messenger->name,
3197
+				'obj'   => $messenger
3198
+			);
3199 3199
             
3200 3200
             
3201
-            $message_types_for_messenger = $messenger->get_valid_message_types();
3201
+			$message_types_for_messenger = $messenger->get_valid_message_types();
3202 3202
             
3203
-            foreach ($message_types as $message_type) {
3204
-                //first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3205
-                // it shouldn't show in either the inactive OR active metabox.
3206
-                if ( ! in_array($message_type->name, $message_types_for_messenger, true)) {
3207
-                    continue;
3208
-                }
3203
+			foreach ($message_types as $message_type) {
3204
+				//first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3205
+				// it shouldn't show in either the inactive OR active metabox.
3206
+				if ( ! in_array($message_type->name, $message_types_for_messenger, true)) {
3207
+					continue;
3208
+				}
3209 3209
                 
3210
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3211
-                    $messenger->name,
3212
-                    $message_type->name
3213
-                )
3214
-                    ? 'active'
3215
-                    : 'inactive';
3210
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3211
+					$messenger->name,
3212
+					$message_type->name
3213
+				)
3214
+					? 'active'
3215
+					: 'inactive';
3216 3216
                 
3217
-                $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
3218
-                    'label'    => ucwords($message_type->label['singular']),
3219
-                    'class'    => 'message-type-' . $a_or_i,
3220
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3221
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3222
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3223
-                    'title'    => $a_or_i === 'active'
3224
-                        ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3225
-                        : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3226
-                    'content'  => $a_or_i === 'active'
3227
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
3228
-                        : $this->_message_type_settings_content($message_type, $messenger),
3229
-                    'slug'     => $message_type->name,
3230
-                    'active'   => $a_or_i === 'active',
3231
-                    'obj'      => $message_type
3232
-                );
3233
-            }
3234
-        }
3235
-    }
3217
+				$this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
3218
+					'label'    => ucwords($message_type->label['singular']),
3219
+					'class'    => 'message-type-' . $a_or_i,
3220
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3221
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3222
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3223
+					'title'    => $a_or_i === 'active'
3224
+						? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3225
+						: esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3226
+					'content'  => $a_or_i === 'active'
3227
+						? $this->_message_type_settings_content($message_type, $messenger, true)
3228
+						: $this->_message_type_settings_content($message_type, $messenger),
3229
+					'slug'     => $message_type->name,
3230
+					'active'   => $a_or_i === 'active',
3231
+					'obj'      => $message_type
3232
+				);
3233
+			}
3234
+		}
3235
+	}
3236 3236
 
3237 3237
 
3238
-    /**
3239
-     * This just prepares the content for the message type settings
3240
-     *
3241
-     * @param  EE_message_type  $message_type The message type object
3242
-     * @param  EE_messenger  $messenger    The messenger object
3243
-     * @param  boolean $active       Whether the message type is active or not
3244
-     * @return string html output for the content
3245
-     * @throws DomainException
3246
-     */
3247
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
3248
-    {
3249
-        //get message type fields
3250
-        $fields                                         = $message_type->get_admin_settings_fields();
3251
-        $settings_template_args['template_form_fields'] = '';
3252
-        
3253
-        if ( ! empty($fields) && $active) {
3238
+	/**
3239
+	 * This just prepares the content for the message type settings
3240
+	 *
3241
+	 * @param  EE_message_type  $message_type The message type object
3242
+	 * @param  EE_messenger  $messenger    The messenger object
3243
+	 * @param  boolean $active       Whether the message type is active or not
3244
+	 * @return string html output for the content
3245
+	 * @throws DomainException
3246
+	 */
3247
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
3248
+	{
3249
+		//get message type fields
3250
+		$fields                                         = $message_type->get_admin_settings_fields();
3251
+		$settings_template_args['template_form_fields'] = '';
3252
+        
3253
+		if ( ! empty($fields) && $active) {
3254 3254
             
3255
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3255
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3256 3256
             
3257
-            foreach ($fields as $fldname => $fldprops) {
3258
-                $field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3259
-                $template_form_field[$field_id] = array(
3260
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3261
-                    'label'      => $fldprops['label'],
3262
-                    'input'      => $fldprops['field_type'],
3263
-                    'type'       => $fldprops['value_type'],
3264
-                    'required'   => $fldprops['required'],
3265
-                    'validation' => $fldprops['validation'],
3266
-                    'value'      => isset($existing_settings[$fldname])
3267
-                        ? $existing_settings[$fldname]
3268
-                        : $fldprops['default'],
3269
-                    'options'    => isset($fldprops['options'])
3270
-                        ? $fldprops['options']
3271
-                        : array(),
3272
-                    'default'    => isset($existing_settings[$fldname])
3273
-                        ? $existing_settings[$fldname]
3274
-                        : $fldprops['default'],
3275
-                    'css_class'  => 'no-drag',
3276
-                    'format'     => $fldprops['format']
3277
-                );
3278
-            }
3257
+			foreach ($fields as $fldname => $fldprops) {
3258
+				$field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3259
+				$template_form_field[$field_id] = array(
3260
+					'name'       => 'message_type_settings[' . $fldname . ']',
3261
+					'label'      => $fldprops['label'],
3262
+					'input'      => $fldprops['field_type'],
3263
+					'type'       => $fldprops['value_type'],
3264
+					'required'   => $fldprops['required'],
3265
+					'validation' => $fldprops['validation'],
3266
+					'value'      => isset($existing_settings[$fldname])
3267
+						? $existing_settings[$fldname]
3268
+						: $fldprops['default'],
3269
+					'options'    => isset($fldprops['options'])
3270
+						? $fldprops['options']
3271
+						: array(),
3272
+					'default'    => isset($existing_settings[$fldname])
3273
+						? $existing_settings[$fldname]
3274
+						: $fldprops['default'],
3275
+					'css_class'  => 'no-drag',
3276
+					'format'     => $fldprops['format']
3277
+				);
3278
+			}
3279 3279
             
3280 3280
             
3281
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3282
-                ? $this->_generate_admin_form_fields(
3283
-                    $template_form_field,
3284
-                    'string',
3285
-                    'ee_mt_activate_form'
3286
-                )
3287
-                : '';
3288
-        }
3289
-        
3290
-        $settings_template_args['description'] = $message_type->description;
3291
-        //we also need some hidden fields
3292
-        $settings_template_args['hidden_fields'] = array(
3293
-            'message_type_settings[messenger]'    => array(
3294
-                'type'  => 'hidden',
3295
-                'value' => $messenger->name
3296
-            ),
3297
-            'message_type_settings[message_type]' => array(
3298
-                'type'  => 'hidden',
3299
-                'value' => $message_type->name
3300
-            ),
3301
-            'type'                                => array(
3302
-                'type'  => 'hidden',
3303
-                'value' => 'message_type'
3304
-            )
3305
-        );
3306
-        
3307
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3308
-            $settings_template_args['hidden_fields'],
3309
-            'array'
3310
-        );
3311
-        $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields'])
3312
-            ? ' hidden'
3313
-            : '';
3314
-        
3315
-        
3316
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3317
-        $content  = EEH_Template::display_template($template, $settings_template_args, true);
3318
-        
3319
-        return $content;
3320
-    }
3281
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3282
+				? $this->_generate_admin_form_fields(
3283
+					$template_form_field,
3284
+					'string',
3285
+					'ee_mt_activate_form'
3286
+				)
3287
+				: '';
3288
+		}
3289
+        
3290
+		$settings_template_args['description'] = $message_type->description;
3291
+		//we also need some hidden fields
3292
+		$settings_template_args['hidden_fields'] = array(
3293
+			'message_type_settings[messenger]'    => array(
3294
+				'type'  => 'hidden',
3295
+				'value' => $messenger->name
3296
+			),
3297
+			'message_type_settings[message_type]' => array(
3298
+				'type'  => 'hidden',
3299
+				'value' => $message_type->name
3300
+			),
3301
+			'type'                                => array(
3302
+				'type'  => 'hidden',
3303
+				'value' => 'message_type'
3304
+			)
3305
+		);
3306
+        
3307
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3308
+			$settings_template_args['hidden_fields'],
3309
+			'array'
3310
+		);
3311
+		$settings_template_args['show_form']     = empty($settings_template_args['template_form_fields'])
3312
+			? ' hidden'
3313
+			: '';
3314
+        
3315
+        
3316
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3317
+		$content  = EEH_Template::display_template($template, $settings_template_args, true);
3318
+        
3319
+		return $content;
3320
+	}
3321 3321
 
3322 3322
 
3323
-    /**
3324
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
3325
-     *
3326
-     * @access protected
3327
-     * @return void
3328
-     * @throws DomainException
3329
-     */
3330
-    protected function _messages_settings_metaboxes()
3331
-    {
3332
-        $this->_set_m_mt_settings();
3333
-        $m_boxes         = $mt_boxes = array();
3334
-        $m_template_args = $mt_template_args = array();
3335
-        
3336
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3337
-            ? $this->_req_data['selected_messenger']
3338
-            : 'email';
3339
-        
3340
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
3341
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3342
-                $hide_on_message  = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3343
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3344
-                //messenger meta boxes
3345
-                $active                                 = $selected_messenger === $messenger;
3346
-                $active_mt_tabs                         = isset(
3347
-                    $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
3348
-                )
3349
-                    ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
3350
-                    : '';
3351
-                $m_boxes[$messenger . '_a_box']         = sprintf(
3352
-                    esc_html__('%s Settings', 'event_espresso'),
3353
-                    $tab_array['label']
3354
-                );
3355
-                $m_template_args[$messenger . '_a_box'] = array(
3356
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3357
-                    'inactive_message_types' => isset(
3358
-                        $this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
3359
-                    )
3360
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
3361
-                        : '',
3362
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3363
-                    'hidden'                 => $active ? '' : ' hidden',
3364
-                    'hide_on_message'        => $hide_on_message,
3365
-                    'messenger'              => $messenger,
3366
-                    'active'                 => $active
3367
-                );
3368
-                // message type meta boxes
3369
-                // (which is really just the inactive container for each messenger
3370
-                // showing inactive message types for that messenger)
3371
-                $mt_boxes[$messenger . '_i_box']         = esc_html__('Inactive Message Types', 'event_espresso');
3372
-                $mt_template_args[$messenger . '_i_box'] = array(
3373
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3374
-                    'inactive_message_types' => isset(
3375
-                        $this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
3376
-                    )
3377
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
3378
-                        : '',
3379
-                    'hidden'                 => $active ? '' : ' hidden',
3380
-                    'hide_on_message'        => $hide_on_message,
3381
-                    'hide_off_message'       => $hide_off_message,
3382
-                    'messenger'              => $messenger,
3383
-                    'active'                 => $active
3384
-                );
3385
-            }
3386
-        }
3387
-        
3388
-        
3389
-        //register messenger metaboxes
3390
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3391
-        foreach ($m_boxes as $box => $label) {
3392
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
3393
-            $msgr          = str_replace('_a_box', '', $box);
3394
-            add_meta_box(
3395
-                'espresso_' . $msgr . '_settings',
3396
-                $label,
3397
-                function ($post, $metabox) {
3398
-                    echo EEH_Template::display_template(
3399
-                            $metabox["args"]["template_path"],
3400
-                            $metabox["args"]["template_args"],
3401
-                            true
3402
-                    );
3403
-                },
3404
-                $this->_current_screen->id,
3405
-                'normal',
3406
-                'high',
3407
-                $callback_args
3408
-            );
3409
-        }
3410
-        
3411
-        //register message type metaboxes
3412
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3413
-        foreach ($mt_boxes as $box => $label) {
3414
-            $callback_args = array(
3415
-                'template_path' => $mt_template_path,
3416
-                'template_args' => $mt_template_args[$box]
3417
-            );
3418
-            $mt            = str_replace('_i_box', '', $box);
3419
-            add_meta_box(
3420
-                'espresso_' . $mt . '_inactive_mts',
3421
-                $label,
3422
-                function ($post, $metabox) {
3423
-                    echo EEH_Template::display_template(
3424
-                            $metabox["args"]["template_path"],
3425
-                            $metabox["args"]["template_args"],
3426
-                            true
3427
-                    );
3428
-                },
3429
-                $this->_current_screen->id,
3430
-                'side',
3431
-                'high',
3432
-                $callback_args
3433
-            );
3434
-        }
3435
-        
3436
-        //register metabox for global messages settings but only when on the main site.  On single site installs this
3437
-        // will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3438
-        if (is_main_site()) {
3439
-            add_meta_box(
3440
-                'espresso_global_message_settings',
3441
-                esc_html__('Global Message Settings', 'event_espresso'),
3442
-                array($this, 'global_messages_settings_metabox_content'),
3443
-                $this->_current_screen->id,
3444
-                'normal',
3445
-                'low',
3446
-                array()
3447
-            );
3448
-        }
3449
-        
3450
-    }
3323
+	/**
3324
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
3325
+	 *
3326
+	 * @access protected
3327
+	 * @return void
3328
+	 * @throws DomainException
3329
+	 */
3330
+	protected function _messages_settings_metaboxes()
3331
+	{
3332
+		$this->_set_m_mt_settings();
3333
+		$m_boxes         = $mt_boxes = array();
3334
+		$m_template_args = $mt_template_args = array();
3335
+        
3336
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3337
+			? $this->_req_data['selected_messenger']
3338
+			: 'email';
3339
+        
3340
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
3341
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3342
+				$hide_on_message  = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3343
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3344
+				//messenger meta boxes
3345
+				$active                                 = $selected_messenger === $messenger;
3346
+				$active_mt_tabs                         = isset(
3347
+					$this->_m_mt_settings['message_type_tabs'][$messenger]['active']
3348
+				)
3349
+					? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
3350
+					: '';
3351
+				$m_boxes[$messenger . '_a_box']         = sprintf(
3352
+					esc_html__('%s Settings', 'event_espresso'),
3353
+					$tab_array['label']
3354
+				);
3355
+				$m_template_args[$messenger . '_a_box'] = array(
3356
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3357
+					'inactive_message_types' => isset(
3358
+						$this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
3359
+					)
3360
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
3361
+						: '',
3362
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3363
+					'hidden'                 => $active ? '' : ' hidden',
3364
+					'hide_on_message'        => $hide_on_message,
3365
+					'messenger'              => $messenger,
3366
+					'active'                 => $active
3367
+				);
3368
+				// message type meta boxes
3369
+				// (which is really just the inactive container for each messenger
3370
+				// showing inactive message types for that messenger)
3371
+				$mt_boxes[$messenger . '_i_box']         = esc_html__('Inactive Message Types', 'event_espresso');
3372
+				$mt_template_args[$messenger . '_i_box'] = array(
3373
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3374
+					'inactive_message_types' => isset(
3375
+						$this->_m_mt_settings['message_type_tabs'][$messenger]['inactive']
3376
+					)
3377
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
3378
+						: '',
3379
+					'hidden'                 => $active ? '' : ' hidden',
3380
+					'hide_on_message'        => $hide_on_message,
3381
+					'hide_off_message'       => $hide_off_message,
3382
+					'messenger'              => $messenger,
3383
+					'active'                 => $active
3384
+				);
3385
+			}
3386
+		}
3387
+        
3388
+        
3389
+		//register messenger metaboxes
3390
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3391
+		foreach ($m_boxes as $box => $label) {
3392
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
3393
+			$msgr          = str_replace('_a_box', '', $box);
3394
+			add_meta_box(
3395
+				'espresso_' . $msgr . '_settings',
3396
+				$label,
3397
+				function ($post, $metabox) {
3398
+					echo EEH_Template::display_template(
3399
+							$metabox["args"]["template_path"],
3400
+							$metabox["args"]["template_args"],
3401
+							true
3402
+					);
3403
+				},
3404
+				$this->_current_screen->id,
3405
+				'normal',
3406
+				'high',
3407
+				$callback_args
3408
+			);
3409
+		}
3410
+        
3411
+		//register message type metaboxes
3412
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3413
+		foreach ($mt_boxes as $box => $label) {
3414
+			$callback_args = array(
3415
+				'template_path' => $mt_template_path,
3416
+				'template_args' => $mt_template_args[$box]
3417
+			);
3418
+			$mt            = str_replace('_i_box', '', $box);
3419
+			add_meta_box(
3420
+				'espresso_' . $mt . '_inactive_mts',
3421
+				$label,
3422
+				function ($post, $metabox) {
3423
+					echo EEH_Template::display_template(
3424
+							$metabox["args"]["template_path"],
3425
+							$metabox["args"]["template_args"],
3426
+							true
3427
+					);
3428
+				},
3429
+				$this->_current_screen->id,
3430
+				'side',
3431
+				'high',
3432
+				$callback_args
3433
+			);
3434
+		}
3435
+        
3436
+		//register metabox for global messages settings but only when on the main site.  On single site installs this
3437
+		// will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3438
+		if (is_main_site()) {
3439
+			add_meta_box(
3440
+				'espresso_global_message_settings',
3441
+				esc_html__('Global Message Settings', 'event_espresso'),
3442
+				array($this, 'global_messages_settings_metabox_content'),
3443
+				$this->_current_screen->id,
3444
+				'normal',
3445
+				'low',
3446
+				array()
3447
+			);
3448
+		}
3449
+        
3450
+	}
3451 3451
 
3452 3452
 
3453
-    /**
3454
-     *  This generates the content for the global messages settings metabox.
3455
-     *
3456
-     * @return string
3457
-     * @throws EE_Error
3458
-     * @throws InvalidArgumentException
3459
-     * @throws ReflectionException
3460
-     * @throws InvalidDataTypeException
3461
-     * @throws InvalidInterfaceException
3462
-     */
3463
-    public function global_messages_settings_metabox_content()
3464
-    {
3465
-        $form = $this->_generate_global_settings_form();
3466
-        echo $form->form_open(
3467
-                $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3468
-                'POST'
3469
-            )
3470
-             . $form->get_html()
3471
-             . $form->form_close();
3472
-    }
3453
+	/**
3454
+	 *  This generates the content for the global messages settings metabox.
3455
+	 *
3456
+	 * @return string
3457
+	 * @throws EE_Error
3458
+	 * @throws InvalidArgumentException
3459
+	 * @throws ReflectionException
3460
+	 * @throws InvalidDataTypeException
3461
+	 * @throws InvalidInterfaceException
3462
+	 */
3463
+	public function global_messages_settings_metabox_content()
3464
+	{
3465
+		$form = $this->_generate_global_settings_form();
3466
+		echo $form->form_open(
3467
+				$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3468
+				'POST'
3469
+			)
3470
+			 . $form->get_html()
3471
+			 . $form->form_close();
3472
+	}
3473 3473
 
3474 3474
 
3475
-    /**
3476
-     * This generates and returns the form object for the global messages settings.
3477
-     *
3478
-     * @return EE_Form_Section_Proper
3479
-     * @throws EE_Error
3480
-     * @throws InvalidArgumentException
3481
-     * @throws ReflectionException
3482
-     * @throws InvalidDataTypeException
3483
-     * @throws InvalidInterfaceException
3484
-     */
3485
-    protected function _generate_global_settings_form()
3486
-    {
3487
-        EE_Registry::instance()->load_helper('HTML');
3488
-        /** @var EE_Network_Core_Config $network_config */
3489
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3490
-        
3491
-        return new EE_Form_Section_Proper(
3492
-            array(
3493
-                'name'            => 'global_messages_settings',
3494
-                'html_id'         => 'global_messages_settings',
3495
-                'html_class'      => 'form-table',
3496
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3497
-                'subsections'     => apply_filters(
3498
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3499
-                    array(
3500
-                        'do_messages_on_same_request' => new EE_Select_Input(
3501
-                            array(
3502
-                                true  => esc_html__("On the same request", "event_espresso"),
3503
-                                false => esc_html__("On a separate request", "event_espresso")
3504
-                            ),
3505
-                            array(
3506
-                                'default'         => $network_config->do_messages_on_same_request,
3507
-                                'html_label_text' => esc_html__(
3508
-                                    'Generate and send all messages:',
3509
-                                    'event_espresso'
3510
-                                ),
3511
-                                'html_help_text'  => esc_html__(
3512
-                                    '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.',
3513
-                                    'event_espresso'
3514
-                                ),
3515
-                            )
3516
-                        ),
3517
-                        'delete_threshold' => new EE_Select_Input(
3518
-                            array(
3519
-                                0 => esc_html__('Forever', 'event_espresso'),
3520
-                                3 => esc_html__('3 Months', 'event_espresso'),
3521
-                                6 => esc_html__('6 Months', 'event_espresso'),
3522
-                                9 => esc_html__('9 Months', 'event_espresso'),
3523
-                                12 => esc_html__('12 Months', 'event_espresso'),
3524
-                                24 => esc_html__('24 Months', 'event_espresso'),
3525
-                                36 => esc_html__('36 Months', 'event_espresso')
3526
-                            ),
3527
-                            array(
3528
-                                'default' => EE_Registry::instance()->CFG->messages->delete_threshold,
3529
-                                'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3530
-                                'html_help_text' => esc_html__(
3531
-                                    'You can control how long a record of processed messages is kept via this option.',
3532
-                                    'event_espresso'
3533
-                                ),
3534
-                            )
3535
-                        ),
3536
-                        'update_settings'             => new EE_Submit_Input(
3537
-                            array(
3538
-                                'default'         => esc_html__('Update', 'event_espresso'),
3539
-                                'html_label_text' => '&nbsp'
3540
-                            )
3541
-                        )
3542
-                    )
3543
-                )
3544
-            )
3545
-        );
3546
-    }
3475
+	/**
3476
+	 * This generates and returns the form object for the global messages settings.
3477
+	 *
3478
+	 * @return EE_Form_Section_Proper
3479
+	 * @throws EE_Error
3480
+	 * @throws InvalidArgumentException
3481
+	 * @throws ReflectionException
3482
+	 * @throws InvalidDataTypeException
3483
+	 * @throws InvalidInterfaceException
3484
+	 */
3485
+	protected function _generate_global_settings_form()
3486
+	{
3487
+		EE_Registry::instance()->load_helper('HTML');
3488
+		/** @var EE_Network_Core_Config $network_config */
3489
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3490
+        
3491
+		return new EE_Form_Section_Proper(
3492
+			array(
3493
+				'name'            => 'global_messages_settings',
3494
+				'html_id'         => 'global_messages_settings',
3495
+				'html_class'      => 'form-table',
3496
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3497
+				'subsections'     => apply_filters(
3498
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3499
+					array(
3500
+						'do_messages_on_same_request' => new EE_Select_Input(
3501
+							array(
3502
+								true  => esc_html__("On the same request", "event_espresso"),
3503
+								false => esc_html__("On a separate request", "event_espresso")
3504
+							),
3505
+							array(
3506
+								'default'         => $network_config->do_messages_on_same_request,
3507
+								'html_label_text' => esc_html__(
3508
+									'Generate and send all messages:',
3509
+									'event_espresso'
3510
+								),
3511
+								'html_help_text'  => esc_html__(
3512
+									'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.',
3513
+									'event_espresso'
3514
+								),
3515
+							)
3516
+						),
3517
+						'delete_threshold' => new EE_Select_Input(
3518
+							array(
3519
+								0 => esc_html__('Forever', 'event_espresso'),
3520
+								3 => esc_html__('3 Months', 'event_espresso'),
3521
+								6 => esc_html__('6 Months', 'event_espresso'),
3522
+								9 => esc_html__('9 Months', 'event_espresso'),
3523
+								12 => esc_html__('12 Months', 'event_espresso'),
3524
+								24 => esc_html__('24 Months', 'event_espresso'),
3525
+								36 => esc_html__('36 Months', 'event_espresso')
3526
+							),
3527
+							array(
3528
+								'default' => EE_Registry::instance()->CFG->messages->delete_threshold,
3529
+								'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3530
+								'html_help_text' => esc_html__(
3531
+									'You can control how long a record of processed messages is kept via this option.',
3532
+									'event_espresso'
3533
+								),
3534
+							)
3535
+						),
3536
+						'update_settings'             => new EE_Submit_Input(
3537
+							array(
3538
+								'default'         => esc_html__('Update', 'event_espresso'),
3539
+								'html_label_text' => '&nbsp'
3540
+							)
3541
+						)
3542
+					)
3543
+				)
3544
+			)
3545
+		);
3546
+	}
3547 3547
 
3548 3548
 
3549
-    /**
3550
-     * This handles updating the global settings set on the admin page.
3551
-     *
3552
-     * @throws EE_Error
3553
-     * @throws InvalidDataTypeException
3554
-     * @throws InvalidInterfaceException
3555
-     * @throws InvalidArgumentException
3556
-     * @throws ReflectionException
3557
-     */
3558
-    protected function _update_global_settings()
3559
-    {
3560
-        /** @var EE_Network_Core_Config $network_config */
3561
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3562
-        $messages_config = EE_Registry::instance()->CFG->messages;
3563
-        $form           = $this->_generate_global_settings_form();
3564
-        if ($form->was_submitted()) {
3565
-            $form->receive_form_submission();
3566
-            if ($form->is_valid()) {
3567
-                $valid_data = $form->valid_data();
3568
-                foreach ($valid_data as $property => $value) {
3569
-                    $setter = 'set_' . $property;
3570
-                    if (method_exists($network_config, $setter)) {
3571
-                        $network_config->{$setter}($value);
3572
-                    } else if (
3573
-                        property_exists($network_config, $property)
3574
-                        && $network_config->{$property} !== $value
3575
-                    ) {
3576
-                        $network_config->{$property} = $value;
3577
-                    } else if (
3578
-                        property_exists($messages_config, $property)
3579
-                        && $messages_config->{$property} !== $value
3580
-                    ) {
3581
-                        $messages_config->{$property} = $value;
3582
-                    }
3583
-                }
3584
-                //only update if the form submission was valid!
3585
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3586
-                EE_Registry::instance()->CFG->update_espresso_config();
3587
-                EE_Error::overwrite_success();
3588
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3589
-            }
3590
-        }
3591
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3592
-    }
3549
+	/**
3550
+	 * This handles updating the global settings set on the admin page.
3551
+	 *
3552
+	 * @throws EE_Error
3553
+	 * @throws InvalidDataTypeException
3554
+	 * @throws InvalidInterfaceException
3555
+	 * @throws InvalidArgumentException
3556
+	 * @throws ReflectionException
3557
+	 */
3558
+	protected function _update_global_settings()
3559
+	{
3560
+		/** @var EE_Network_Core_Config $network_config */
3561
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3562
+		$messages_config = EE_Registry::instance()->CFG->messages;
3563
+		$form           = $this->_generate_global_settings_form();
3564
+		if ($form->was_submitted()) {
3565
+			$form->receive_form_submission();
3566
+			if ($form->is_valid()) {
3567
+				$valid_data = $form->valid_data();
3568
+				foreach ($valid_data as $property => $value) {
3569
+					$setter = 'set_' . $property;
3570
+					if (method_exists($network_config, $setter)) {
3571
+						$network_config->{$setter}($value);
3572
+					} else if (
3573
+						property_exists($network_config, $property)
3574
+						&& $network_config->{$property} !== $value
3575
+					) {
3576
+						$network_config->{$property} = $value;
3577
+					} else if (
3578
+						property_exists($messages_config, $property)
3579
+						&& $messages_config->{$property} !== $value
3580
+					) {
3581
+						$messages_config->{$property} = $value;
3582
+					}
3583
+				}
3584
+				//only update if the form submission was valid!
3585
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3586
+				EE_Registry::instance()->CFG->update_espresso_config();
3587
+				EE_Error::overwrite_success();
3588
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3589
+			}
3590
+		}
3591
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3592
+	}
3593 3593
 
3594 3594
 
3595
-    /**
3596
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3597
-     *
3598
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3599
-     * @return string html formatted tabs
3600
-     * @throws DomainException
3601
-     */
3602
-    protected function _get_mt_tabs($tab_array)
3603
-    {
3604
-        $tab_array = (array)$tab_array;
3605
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3606
-        $tabs      = '';
3607
-        
3608
-        foreach ($tab_array as $tab) {
3609
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3610
-        }
3611
-        
3612
-        return $tabs;
3613
-    }
3595
+	/**
3596
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3597
+	 *
3598
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3599
+	 * @return string html formatted tabs
3600
+	 * @throws DomainException
3601
+	 */
3602
+	protected function _get_mt_tabs($tab_array)
3603
+	{
3604
+		$tab_array = (array)$tab_array;
3605
+		$template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3606
+		$tabs      = '';
3607
+        
3608
+		foreach ($tab_array as $tab) {
3609
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3610
+		}
3611
+        
3612
+		return $tabs;
3613
+	}
3614 3614
 
3615 3615
 
3616
-    /**
3617
-     * This prepares the content of the messenger meta box admin settings
3618
-     *
3619
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3620
-     * @return string html formatted content
3621
-     * @throws DomainException
3622
-     */
3623
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3624
-    {
3616
+	/**
3617
+	 * This prepares the content of the messenger meta box admin settings
3618
+	 *
3619
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3620
+	 * @return string html formatted content
3621
+	 * @throws DomainException
3622
+	 */
3623
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3624
+	{
3625 3625
         
3626
-        $fields                                         = $messenger->get_admin_settings_fields();
3627
-        $settings_template_args['template_form_fields'] = '';
3626
+		$fields                                         = $messenger->get_admin_settings_fields();
3627
+		$settings_template_args['template_form_fields'] = '';
3628 3628
         
3629
-        //is $messenger active?
3630
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3629
+		//is $messenger active?
3630
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3631 3631
         
3632 3632
         
3633
-        if ( ! empty($fields)) {
3633
+		if ( ! empty($fields)) {
3634 3634
             
3635
-            $existing_settings = $messenger->get_existing_admin_settings();
3635
+			$existing_settings = $messenger->get_existing_admin_settings();
3636 3636
             
3637
-            foreach ($fields as $fldname => $fldprops) {
3638
-                $field_id                       = $messenger->name . '-' . $fldname;
3639
-                $template_form_field[$field_id] = array(
3640
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3641
-                    'label'      => $fldprops['label'],
3642
-                    'input'      => $fldprops['field_type'],
3643
-                    'type'       => $fldprops['value_type'],
3644
-                    'required'   => $fldprops['required'],
3645
-                    'validation' => $fldprops['validation'],
3646
-                    'value'      => isset($existing_settings[$field_id])
3647
-                        ? $existing_settings[$field_id]
3648
-                        : $fldprops['default'],
3649
-                    'css_class'  => '',
3650
-                    'format'     => $fldprops['format']
3651
-                );
3652
-            }
3637
+			foreach ($fields as $fldname => $fldprops) {
3638
+				$field_id                       = $messenger->name . '-' . $fldname;
3639
+				$template_form_field[$field_id] = array(
3640
+					'name'       => 'messenger_settings[' . $field_id . ']',
3641
+					'label'      => $fldprops['label'],
3642
+					'input'      => $fldprops['field_type'],
3643
+					'type'       => $fldprops['value_type'],
3644
+					'required'   => $fldprops['required'],
3645
+					'validation' => $fldprops['validation'],
3646
+					'value'      => isset($existing_settings[$field_id])
3647
+						? $existing_settings[$field_id]
3648
+						: $fldprops['default'],
3649
+					'css_class'  => '',
3650
+					'format'     => $fldprops['format']
3651
+				);
3652
+			}
3653 3653
             
3654 3654
             
3655
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3656
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3657
-                : '';
3658
-        }
3659
-        
3660
-        //we also need some hidden fields
3661
-        $settings_template_args['hidden_fields'] = array(
3662
-            'messenger_settings[messenger]' => array(
3663
-                'type'  => 'hidden',
3664
-                'value' => $messenger->name
3665
-            ),
3666
-            'type'                          => array(
3667
-                'type'  => 'hidden',
3668
-                'value' => 'messenger'
3669
-            )
3670
-        );
3671
-        
3672
-        //make sure any active message types that are existing are included in the hidden fields
3673
-        if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3674
-            foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3675
-                $settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3676
-                    'type'  => 'hidden',
3677
-                    'value' => $mt
3678
-                );
3679
-            }
3680
-        }
3681
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3682
-            $settings_template_args['hidden_fields'],
3683
-            'array'
3684
-        );
3685
-        $active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3686
-        
3687
-        $settings_template_args['messenger']           = $messenger->name;
3688
-        $settings_template_args['description']         = $messenger->description;
3689
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3690
-        
3691
-        
3692
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3693
-            $messenger->name
3694
-        )
3695
-            ? $settings_template_args['show_hide_edit_form']
3696
-            : ' hidden';
3697
-        
3698
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3699
-            ? ' hidden'
3700
-            : $settings_template_args['show_hide_edit_form'];
3701
-        
3702
-        
3703
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3704
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3705
-        $settings_template_args['on_off_status'] = $active ? true : false;
3706
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3707
-        $content                                 = EEH_Template::display_template(
3708
-            $template,
3709
-            $settings_template_args,
3710
-            true
3711
-        );
3712
-        
3713
-        return $content;
3714
-    }
3655
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3656
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3657
+				: '';
3658
+		}
3659
+        
3660
+		//we also need some hidden fields
3661
+		$settings_template_args['hidden_fields'] = array(
3662
+			'messenger_settings[messenger]' => array(
3663
+				'type'  => 'hidden',
3664
+				'value' => $messenger->name
3665
+			),
3666
+			'type'                          => array(
3667
+				'type'  => 'hidden',
3668
+				'value' => 'messenger'
3669
+			)
3670
+		);
3671
+        
3672
+		//make sure any active message types that are existing are included in the hidden fields
3673
+		if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3674
+			foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3675
+				$settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3676
+					'type'  => 'hidden',
3677
+					'value' => $mt
3678
+				);
3679
+			}
3680
+		}
3681
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3682
+			$settings_template_args['hidden_fields'],
3683
+			'array'
3684
+		);
3685
+		$active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3686
+        
3687
+		$settings_template_args['messenger']           = $messenger->name;
3688
+		$settings_template_args['description']         = $messenger->description;
3689
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3690
+        
3691
+        
3692
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3693
+			$messenger->name
3694
+		)
3695
+			? $settings_template_args['show_hide_edit_form']
3696
+			: ' hidden';
3697
+        
3698
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3699
+			? ' hidden'
3700
+			: $settings_template_args['show_hide_edit_form'];
3701
+        
3702
+        
3703
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3704
+		$settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3705
+		$settings_template_args['on_off_status'] = $active ? true : false;
3706
+		$template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3707
+		$content                                 = EEH_Template::display_template(
3708
+			$template,
3709
+			$settings_template_args,
3710
+			true
3711
+		);
3712
+        
3713
+		return $content;
3714
+	}
3715 3715
 
3716 3716
 
3717
-    /**
3718
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3719
-     *
3720
-     * @throws DomainException
3721
-     * @throws EE_Error
3722
-     * @throws InvalidDataTypeException
3723
-     * @throws InvalidInterfaceException
3724
-     * @throws InvalidArgumentException
3725
-     * @throws ReflectionException
3726
-     */
3727
-    public function activate_messenger_toggle()
3728
-    {
3729
-        $success = true;
3730
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3731
-        //let's check that we have required data
3732
-        if ( ! isset($this->_req_data['messenger'])) {
3733
-            EE_Error::add_error(
3734
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3735
-                __FILE__,
3736
-                __FUNCTION__,
3737
-                __LINE__
3738
-            );
3739
-            $success = false;
3740
-        }
3741
-        
3742
-        //do a nonce check here since we're not arriving via a normal route
3743
-        $nonce     = isset($this->_req_data['activate_nonce'])
3744
-            ? sanitize_text_field($this->_req_data['activate_nonce'])
3745
-            : '';
3746
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3747
-        
3748
-        $this->_verify_nonce($nonce, $nonce_ref);
3749
-        
3750
-        
3751
-        if ( ! isset($this->_req_data['status'])) {
3752
-            EE_Error::add_error(
3753
-                esc_html__(
3754
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3755
-                    'event_espresso'
3756
-                ),
3757
-                __FILE__,
3758
-                __FUNCTION__,
3759
-                __LINE__
3760
-            );
3761
-            $success = false;
3762
-        }
3763
-        
3764
-        //do check to verify we have a valid status.
3765
-        $status = $this->_req_data['status'];
3766
-        
3767
-        if ($status !== 'off' && $status !== 'on') {
3768
-            EE_Error::add_error(
3769
-                sprintf(
3770
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3771
-                    $this->_req_data['status']
3772
-                ),
3773
-                __FILE__,
3774
-                __FUNCTION__,
3775
-                __LINE__
3776
-            );
3777
-            $success = false;
3778
-        }
3779
-        
3780
-        if ($success) {
3781
-            //made it here?  Stop dawdling then!!
3782
-            $success = $status === 'off'
3783
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3784
-                : $this->_activate_messenger($this->_req_data['messenger']);
3785
-        }
3786
-        
3787
-        $this->_template_args['success'] = $success;
3788
-        
3789
-        //no special instructions so let's just do the json return (which should automatically do all the special stuff).
3790
-        $this->_return_json();
3791
-        
3792
-    }
3717
+	/**
3718
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3719
+	 *
3720
+	 * @throws DomainException
3721
+	 * @throws EE_Error
3722
+	 * @throws InvalidDataTypeException
3723
+	 * @throws InvalidInterfaceException
3724
+	 * @throws InvalidArgumentException
3725
+	 * @throws ReflectionException
3726
+	 */
3727
+	public function activate_messenger_toggle()
3728
+	{
3729
+		$success = true;
3730
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3731
+		//let's check that we have required data
3732
+		if ( ! isset($this->_req_data['messenger'])) {
3733
+			EE_Error::add_error(
3734
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3735
+				__FILE__,
3736
+				__FUNCTION__,
3737
+				__LINE__
3738
+			);
3739
+			$success = false;
3740
+		}
3741
+        
3742
+		//do a nonce check here since we're not arriving via a normal route
3743
+		$nonce     = isset($this->_req_data['activate_nonce'])
3744
+			? sanitize_text_field($this->_req_data['activate_nonce'])
3745
+			: '';
3746
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3747
+        
3748
+		$this->_verify_nonce($nonce, $nonce_ref);
3749
+        
3750
+        
3751
+		if ( ! isset($this->_req_data['status'])) {
3752
+			EE_Error::add_error(
3753
+				esc_html__(
3754
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3755
+					'event_espresso'
3756
+				),
3757
+				__FILE__,
3758
+				__FUNCTION__,
3759
+				__LINE__
3760
+			);
3761
+			$success = false;
3762
+		}
3763
+        
3764
+		//do check to verify we have a valid status.
3765
+		$status = $this->_req_data['status'];
3766
+        
3767
+		if ($status !== 'off' && $status !== 'on') {
3768
+			EE_Error::add_error(
3769
+				sprintf(
3770
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3771
+					$this->_req_data['status']
3772
+				),
3773
+				__FILE__,
3774
+				__FUNCTION__,
3775
+				__LINE__
3776
+			);
3777
+			$success = false;
3778
+		}
3779
+        
3780
+		if ($success) {
3781
+			//made it here?  Stop dawdling then!!
3782
+			$success = $status === 'off'
3783
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3784
+				: $this->_activate_messenger($this->_req_data['messenger']);
3785
+		}
3786
+        
3787
+		$this->_template_args['success'] = $success;
3788
+        
3789
+		//no special instructions so let's just do the json return (which should automatically do all the special stuff).
3790
+		$this->_return_json();
3791
+        
3792
+	}
3793 3793
 
3794 3794
 
3795
-    /**
3796
-     * used by ajax from the messages settings page to activate|deactivate a message type
3797
-     *
3798
-     * @throws DomainException
3799
-     * @throws EE_Error
3800
-     * @throws ReflectionException
3801
-     * @throws InvalidDataTypeException
3802
-     * @throws InvalidInterfaceException
3803
-     * @throws InvalidArgumentException
3804
-     */
3805
-    public function activate_mt_toggle()
3806
-    {
3807
-        $success = true;
3808
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3809
-        
3810
-        //let's make sure we have the necessary data
3811
-        if ( ! isset($this->_req_data['message_type'])) {
3812
-            EE_Error::add_error(
3813
-                esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3814
-                __FILE__,
3815
-                __FUNCTION__,
3816
-                __LINE__
3817
-            );
3818
-            $success = false;
3819
-        }
3820
-        
3821
-        if ( ! isset($this->_req_data['messenger'])) {
3822
-            EE_Error::add_error(
3823
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3824
-                __FILE__,
3825
-                __FUNCTION__,
3826
-                __LINE__
3827
-            );
3828
-            $success = false;
3829
-        }
3830
-        
3831
-        if ( ! isset($this->_req_data['status'])) {
3832
-            EE_Error::add_error(
3833
-                esc_html__('Messenger status needed to know whether activation or deactivation is happening. No status is given',
3834
-                    'event_espresso'),
3835
-                __FILE__,
3836
-                __FUNCTION__,
3837
-                __LINE__
3838
-            );
3839
-            $success = false;
3840
-        }
3841
-        
3842
-        
3843
-        //do check to verify we have a valid status.
3844
-        $status = $this->_req_data['status'];
3845
-        
3846
-        if ($status !== 'activate' && $status !== 'deactivate') {
3847
-            EE_Error::add_error(
3848
-                sprintf(
3849
-                    esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3850
-                    $this->_req_data['status']
3851
-                ),
3852
-                __FILE__,
3853
-                __FUNCTION__,
3854
-                __LINE__
3855
-            );
3856
-            $success = false;
3857
-        }
3858
-        
3859
-        
3860
-        //do a nonce check here since we're not arriving via a normal route
3861
-        $nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3862
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3863
-        
3864
-        $this->_verify_nonce($nonce, $nonce_ref);
3865
-        
3866
-        if ($success) {
3867
-            //made it here? um, what are you waiting for then?
3868
-            $success = $status === 'deactivate'
3869
-                ? $this->_deactivate_message_type_for_messenger(
3870
-                    $this->_req_data['messenger'],
3871
-                    $this->_req_data['message_type']
3872
-                )
3873
-                : $this->_activate_message_type_for_messenger(
3874
-                    $this->_req_data['messenger'],
3875
-                    $this->_req_data['message_type']
3876
-                );
3877
-        }
3878
-        
3879
-        $this->_template_args['success'] = $success;
3880
-        $this->_return_json();
3881
-    }
3795
+	/**
3796
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3797
+	 *
3798
+	 * @throws DomainException
3799
+	 * @throws EE_Error
3800
+	 * @throws ReflectionException
3801
+	 * @throws InvalidDataTypeException
3802
+	 * @throws InvalidInterfaceException
3803
+	 * @throws InvalidArgumentException
3804
+	 */
3805
+	public function activate_mt_toggle()
3806
+	{
3807
+		$success = true;
3808
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3809
+        
3810
+		//let's make sure we have the necessary data
3811
+		if ( ! isset($this->_req_data['message_type'])) {
3812
+			EE_Error::add_error(
3813
+				esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3814
+				__FILE__,
3815
+				__FUNCTION__,
3816
+				__LINE__
3817
+			);
3818
+			$success = false;
3819
+		}
3820
+        
3821
+		if ( ! isset($this->_req_data['messenger'])) {
3822
+			EE_Error::add_error(
3823
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3824
+				__FILE__,
3825
+				__FUNCTION__,
3826
+				__LINE__
3827
+			);
3828
+			$success = false;
3829
+		}
3830
+        
3831
+		if ( ! isset($this->_req_data['status'])) {
3832
+			EE_Error::add_error(
3833
+				esc_html__('Messenger status needed to know whether activation or deactivation is happening. No status is given',
3834
+					'event_espresso'),
3835
+				__FILE__,
3836
+				__FUNCTION__,
3837
+				__LINE__
3838
+			);
3839
+			$success = false;
3840
+		}
3841
+        
3842
+        
3843
+		//do check to verify we have a valid status.
3844
+		$status = $this->_req_data['status'];
3845
+        
3846
+		if ($status !== 'activate' && $status !== 'deactivate') {
3847
+			EE_Error::add_error(
3848
+				sprintf(
3849
+					esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3850
+					$this->_req_data['status']
3851
+				),
3852
+				__FILE__,
3853
+				__FUNCTION__,
3854
+				__LINE__
3855
+			);
3856
+			$success = false;
3857
+		}
3858
+        
3859
+        
3860
+		//do a nonce check here since we're not arriving via a normal route
3861
+		$nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3862
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3863
+        
3864
+		$this->_verify_nonce($nonce, $nonce_ref);
3865
+        
3866
+		if ($success) {
3867
+			//made it here? um, what are you waiting for then?
3868
+			$success = $status === 'deactivate'
3869
+				? $this->_deactivate_message_type_for_messenger(
3870
+					$this->_req_data['messenger'],
3871
+					$this->_req_data['message_type']
3872
+				)
3873
+				: $this->_activate_message_type_for_messenger(
3874
+					$this->_req_data['messenger'],
3875
+					$this->_req_data['message_type']
3876
+				);
3877
+		}
3878
+        
3879
+		$this->_template_args['success'] = $success;
3880
+		$this->_return_json();
3881
+	}
3882 3882
 
3883 3883
 
3884
-    /**
3885
-     * Takes care of processing activating a messenger and preparing the appropriate response.
3886
-     *
3887
-     * @param string $messenger_name The name of the messenger being activated
3888
-     * @return bool
3889
-     * @throws DomainException
3890
-     * @throws EE_Error
3891
-     * @throws InvalidArgumentException
3892
-     * @throws ReflectionException
3893
-     * @throws InvalidDataTypeException
3894
-     * @throws InvalidInterfaceException
3895
-     */
3896
-    protected function _activate_messenger($messenger_name)
3897
-    {
3898
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3899
-        $active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3900
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger
3901
-            ? $active_messenger->get_default_message_types()
3902
-            : array();
3903
-        
3904
-        //ensure is active
3905
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3906
-        
3907
-        //set response_data for reload
3908
-        foreach ($message_types_to_activate as $message_type_name) {
3909
-            /** @var EE_message_type $message_type */
3910
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3911
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger(
3912
-                    $messenger_name,
3913
-                    $message_type_name
3914
-                )
3915
-                && $message_type instanceof EE_message_type
3916
-            ) {
3917
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
3918
-                if ($message_type->get_admin_settings_fields()) {
3919
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
3920
-                }
3921
-            }
3922
-        }
3923
-        
3924
-        //add success message for activating messenger
3925
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3926
-        
3927
-    }
3884
+	/**
3885
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
3886
+	 *
3887
+	 * @param string $messenger_name The name of the messenger being activated
3888
+	 * @return bool
3889
+	 * @throws DomainException
3890
+	 * @throws EE_Error
3891
+	 * @throws InvalidArgumentException
3892
+	 * @throws ReflectionException
3893
+	 * @throws InvalidDataTypeException
3894
+	 * @throws InvalidInterfaceException
3895
+	 */
3896
+	protected function _activate_messenger($messenger_name)
3897
+	{
3898
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3899
+		$active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3900
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger
3901
+			? $active_messenger->get_default_message_types()
3902
+			: array();
3903
+        
3904
+		//ensure is active
3905
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3906
+        
3907
+		//set response_data for reload
3908
+		foreach ($message_types_to_activate as $message_type_name) {
3909
+			/** @var EE_message_type $message_type */
3910
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3911
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger(
3912
+					$messenger_name,
3913
+					$message_type_name
3914
+				)
3915
+				&& $message_type instanceof EE_message_type
3916
+			) {
3917
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
3918
+				if ($message_type->get_admin_settings_fields()) {
3919
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
3920
+				}
3921
+			}
3922
+		}
3923
+        
3924
+		//add success message for activating messenger
3925
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3926
+        
3927
+	}
3928 3928
 
3929 3929
 
3930
-    /**
3931
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
3932
-     *
3933
-     * @param string $messenger_name The name of the messenger being activated
3934
-     * @return bool
3935
-     * @throws DomainException
3936
-     * @throws EE_Error
3937
-     * @throws InvalidArgumentException
3938
-     * @throws ReflectionException
3939
-     * @throws InvalidDataTypeException
3940
-     * @throws InvalidInterfaceException
3941
-     */
3942
-    protected function _deactivate_messenger($messenger_name)
3943
-    {
3944
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3945
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3946
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
3947
-        
3948
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
3949
-    }
3930
+	/**
3931
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
3932
+	 *
3933
+	 * @param string $messenger_name The name of the messenger being activated
3934
+	 * @return bool
3935
+	 * @throws DomainException
3936
+	 * @throws EE_Error
3937
+	 * @throws InvalidArgumentException
3938
+	 * @throws ReflectionException
3939
+	 * @throws InvalidDataTypeException
3940
+	 * @throws InvalidInterfaceException
3941
+	 */
3942
+	protected function _deactivate_messenger($messenger_name)
3943
+	{
3944
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3945
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3946
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
3947
+        
3948
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
3949
+	}
3950 3950
 
3951 3951
 
3952
-    /**
3953
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
3954
-     *
3955
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
3956
-     * @param string $message_type_name The name of the message type being activated for the messenger
3957
-     * @return bool
3958
-     * @throws DomainException
3959
-     * @throws EE_Error
3960
-     * @throws InvalidArgumentException
3961
-     * @throws ReflectionException
3962
-     * @throws InvalidDataTypeException
3963
-     * @throws InvalidInterfaceException
3964
-     */
3965
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
3966
-    {
3967
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3968
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3969
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3970
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
3971
-        
3972
-        //ensure is active
3973
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
3974
-        
3975
-        //set response for load
3976
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3977
-            $message_type_name)
3978
-        ) {
3979
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
3980
-            if ($message_type_to_activate->get_admin_settings_fields()) {
3981
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
3982
-            }
3983
-        }
3984
-        
3985
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger,
3986
-            $message_type_to_activate);
3987
-    }
3952
+	/**
3953
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
3954
+	 *
3955
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
3956
+	 * @param string $message_type_name The name of the message type being activated for the messenger
3957
+	 * @return bool
3958
+	 * @throws DomainException
3959
+	 * @throws EE_Error
3960
+	 * @throws InvalidArgumentException
3961
+	 * @throws ReflectionException
3962
+	 * @throws InvalidDataTypeException
3963
+	 * @throws InvalidInterfaceException
3964
+	 */
3965
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
3966
+	{
3967
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3968
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3969
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3970
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
3971
+        
3972
+		//ensure is active
3973
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
3974
+        
3975
+		//set response for load
3976
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3977
+			$message_type_name)
3978
+		) {
3979
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
3980
+			if ($message_type_to_activate->get_admin_settings_fields()) {
3981
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
3982
+			}
3983
+		}
3984
+        
3985
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger,
3986
+			$message_type_to_activate);
3987
+	}
3988 3988
 
3989 3989
 
3990
-    /**
3991
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
3992
-     *
3993
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
3994
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
3995
-     * @return bool
3996
-     * @throws DomainException
3997
-     * @throws EE_Error
3998
-     * @throws InvalidArgumentException
3999
-     * @throws ReflectionException
4000
-     * @throws InvalidDataTypeException
4001
-     * @throws InvalidInterfaceException
4002
-     */
4003
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4004
-    {
4005
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4006
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4007
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4008
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4009
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4010
-        
4011
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger,
4012
-            $message_type_to_deactivate);
4013
-    }
3990
+	/**
3991
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
3992
+	 *
3993
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
3994
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
3995
+	 * @return bool
3996
+	 * @throws DomainException
3997
+	 * @throws EE_Error
3998
+	 * @throws InvalidArgumentException
3999
+	 * @throws ReflectionException
4000
+	 * @throws InvalidDataTypeException
4001
+	 * @throws InvalidInterfaceException
4002
+	 */
4003
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4004
+	{
4005
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4006
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4007
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4008
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4009
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4010
+        
4011
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger,
4012
+			$message_type_to_deactivate);
4013
+	}
4014 4014
     
4015 4015
     
4016
-    /**
4017
-     * This just initializes the defaults for activating messenger and message type responses.
4018
-     */
4019
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
4020
-    {
4021
-        $this->_template_args['data']['active_mts'] = array();
4022
-        $this->_template_args['data']['mt_reload']  = array();
4023
-    }
4016
+	/**
4017
+	 * This just initializes the defaults for activating messenger and message type responses.
4018
+	 */
4019
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
4020
+	{
4021
+		$this->_template_args['data']['active_mts'] = array();
4022
+		$this->_template_args['data']['mt_reload']  = array();
4023
+	}
4024 4024
 
4025 4025
 
4026
-    /**
4027
-     * Setup appropriate response for activating a messenger and/or message types
4028
-     *
4029
-     * @param EE_messenger         $messenger
4030
-     * @param EE_message_type|null $message_type
4031
-     * @return bool
4032
-     * @throws DomainException
4033
-     * @throws EE_Error
4034
-     * @throws InvalidArgumentException
4035
-     * @throws ReflectionException
4036
-     * @throws InvalidDataTypeException
4037
-     * @throws InvalidInterfaceException
4038
-     */
4039
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
4040
-        $messenger,
4041
-        EE_Message_Type $message_type = null
4042
-    ) {
4043
-        //if $messenger isn't a valid messenger object then get out.
4044
-        if ( ! $messenger instanceof EE_Messenger) {
4045
-            EE_Error::add_error(
4046
-                esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4047
-                __FILE__,
4048
-                __FUNCTION__,
4049
-                __LINE__
4050
-            );
4026
+	/**
4027
+	 * Setup appropriate response for activating a messenger and/or message types
4028
+	 *
4029
+	 * @param EE_messenger         $messenger
4030
+	 * @param EE_message_type|null $message_type
4031
+	 * @return bool
4032
+	 * @throws DomainException
4033
+	 * @throws EE_Error
4034
+	 * @throws InvalidArgumentException
4035
+	 * @throws ReflectionException
4036
+	 * @throws InvalidDataTypeException
4037
+	 * @throws InvalidInterfaceException
4038
+	 */
4039
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
4040
+		$messenger,
4041
+		EE_Message_Type $message_type = null
4042
+	) {
4043
+		//if $messenger isn't a valid messenger object then get out.
4044
+		if ( ! $messenger instanceof EE_Messenger) {
4045
+			EE_Error::add_error(
4046
+				esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4047
+				__FILE__,
4048
+				__FUNCTION__,
4049
+				__LINE__
4050
+			);
4051 4051
             
4052
-            return false;
4053
-        }
4054
-        //activated
4055
-        if ($this->_template_args['data']['active_mts']) {
4056
-            EE_Error::overwrite_success();
4057
-            //activated a message type with the messenger
4058
-            if ($message_type instanceof EE_message_type) {
4059
-                EE_Error::add_success(
4060
-                    sprintf(
4061
-                        esc_html__('%s message type has been successfully activated with the %s messenger', 'event_espresso'),
4062
-                        ucwords($message_type->label['singular']),
4063
-                        ucwords($messenger->label['singular'])
4064
-                    )
4065
-                );
4052
+			return false;
4053
+		}
4054
+		//activated
4055
+		if ($this->_template_args['data']['active_mts']) {
4056
+			EE_Error::overwrite_success();
4057
+			//activated a message type with the messenger
4058
+			if ($message_type instanceof EE_message_type) {
4059
+				EE_Error::add_success(
4060
+					sprintf(
4061
+						esc_html__('%s message type has been successfully activated with the %s messenger', 'event_espresso'),
4062
+						ucwords($message_type->label['singular']),
4063
+						ucwords($messenger->label['singular'])
4064
+					)
4065
+				);
4066 4066
                 
4067
-                //if message type was invoice then let's make sure we activate the invoice payment method.
4068
-                if ($message_type->name === 'invoice') {
4069
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
4070
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4071
-                    if ($pm instanceof EE_Payment_Method) {
4072
-                        EE_Error::add_attention(
4073
-                            esc_html__(
4074
-                                '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.',
4075
-                                'event_espresso'
4076
-                            )
4077
-                        );
4078
-                    }
4079
-                }
4080
-                //just toggles the entire messenger
4081
-            } else {
4082
-                EE_Error::add_success(
4083
-                    sprintf(
4084
-                        esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4085
-                        ucwords($messenger->label['singular'])
4086
-                    )
4087
-                );
4088
-            }
4067
+				//if message type was invoice then let's make sure we activate the invoice payment method.
4068
+				if ($message_type->name === 'invoice') {
4069
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
4070
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4071
+					if ($pm instanceof EE_Payment_Method) {
4072
+						EE_Error::add_attention(
4073
+							esc_html__(
4074
+								'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.',
4075
+								'event_espresso'
4076
+							)
4077
+						);
4078
+					}
4079
+				}
4080
+				//just toggles the entire messenger
4081
+			} else {
4082
+				EE_Error::add_success(
4083
+					sprintf(
4084
+						esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4085
+						ucwords($messenger->label['singular'])
4086
+					)
4087
+				);
4088
+			}
4089 4089
             
4090
-            return true;
4090
+			return true;
4091 4091
             
4092
-            //possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4093
-            //message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4094
-            //in which case we just give a success message for the messenger being successfully activated.
4095
-        } else {
4096
-            if ( ! $messenger->get_default_message_types()) {
4097
-                //messenger doesn't have any default message types so still a success.
4098
-                EE_Error::add_success(
4099
-                    sprintf(
4100
-                        esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4101
-                        ucwords($messenger->label['singular'])
4102
-                    )
4103
-                );
4092
+			//possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4093
+			//message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4094
+			//in which case we just give a success message for the messenger being successfully activated.
4095
+		} else {
4096
+			if ( ! $messenger->get_default_message_types()) {
4097
+				//messenger doesn't have any default message types so still a success.
4098
+				EE_Error::add_success(
4099
+					sprintf(
4100
+						esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4101
+						ucwords($messenger->label['singular'])
4102
+					)
4103
+				);
4104 4104
                 
4105
-                return true;
4106
-            } else {
4107
-                EE_Error::add_error(
4108
-                    $message_type instanceof EE_message_type
4109
-                        ? sprintf(
4110
-                        esc_html__('%s message type was not successfully activated with the %s messenger', 'event_espresso'),
4111
-                        ucwords($message_type->label['singular']),
4112
-                        ucwords($messenger->label['singular'])
4113
-                    )
4114
-                        : sprintf(
4115
-                        esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4116
-                        ucwords($messenger->label['singular'])
4117
-                    ),
4118
-                    __FILE__,
4119
-                    __FUNCTION__,
4120
-                    __LINE__
4121
-                );
4105
+				return true;
4106
+			} else {
4107
+				EE_Error::add_error(
4108
+					$message_type instanceof EE_message_type
4109
+						? sprintf(
4110
+						esc_html__('%s message type was not successfully activated with the %s messenger', 'event_espresso'),
4111
+						ucwords($message_type->label['singular']),
4112
+						ucwords($messenger->label['singular'])
4113
+					)
4114
+						: sprintf(
4115
+						esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4116
+						ucwords($messenger->label['singular'])
4117
+					),
4118
+					__FILE__,
4119
+					__FUNCTION__,
4120
+					__LINE__
4121
+				);
4122 4122
                 
4123
-                return false;
4124
-            }
4125
-        }
4126
-    }
4123
+				return false;
4124
+			}
4125
+		}
4126
+	}
4127 4127
 
4128 4128
 
4129
-    /**
4130
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
4131
-     *
4132
-     * @param EE_messenger         $messenger
4133
-     * @param EE_message_type|null $message_type
4134
-     * @return bool
4135
-     * @throws DomainException
4136
-     * @throws EE_Error
4137
-     * @throws InvalidArgumentException
4138
-     * @throws ReflectionException
4139
-     * @throws InvalidDataTypeException
4140
-     * @throws InvalidInterfaceException
4141
-     */
4142
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4143
-        $messenger,
4144
-        EE_message_type $message_type = null
4145
-    ) {
4146
-        EE_Error::overwrite_success();
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 deactivated is not a valid messenger', 'event_espresso'),
4152
-                __FILE__,
4153
-                __FUNCTION__,
4154
-                __LINE__
4155
-            );
4129
+	/**
4130
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
4131
+	 *
4132
+	 * @param EE_messenger         $messenger
4133
+	 * @param EE_message_type|null $message_type
4134
+	 * @return bool
4135
+	 * @throws DomainException
4136
+	 * @throws EE_Error
4137
+	 * @throws InvalidArgumentException
4138
+	 * @throws ReflectionException
4139
+	 * @throws InvalidDataTypeException
4140
+	 * @throws InvalidInterfaceException
4141
+	 */
4142
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4143
+		$messenger,
4144
+		EE_message_type $message_type = null
4145
+	) {
4146
+		EE_Error::overwrite_success();
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 deactivated is not a valid messenger', 'event_espresso'),
4152
+				__FILE__,
4153
+				__FUNCTION__,
4154
+				__LINE__
4155
+			);
4156 4156
             
4157
-            return false;
4158
-        }
4159
-        
4160
-        if ($message_type instanceof EE_message_type) {
4161
-            $message_type_name = $message_type->name;
4162
-            EE_Error::add_success(
4163
-                sprintf(
4164
-                    esc_html__('%s message type has been successfully deactivated for the %s messenger.', 'event_espresso'),
4165
-                    ucwords($message_type->label['singular']),
4166
-                    ucwords($messenger->label['singular'])
4167
-                )
4168
-            );
4169
-        } else {
4170
-            $message_type_name = '';
4171
-            EE_Error::add_success(
4172
-                sprintf(
4173
-                    esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4174
-                    ucwords($messenger->label['singular'])
4175
-                )
4176
-            );
4177
-        }
4178
-        
4179
-        //if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4180
-        if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4181
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
4182
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4183
-            if ($count_updated > 0) {
4184
-                $msg = $message_type_name === 'invoice'
4185
-                    ? esc_html__(
4186
-                        '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.',
4187
-                        'event_espresso'
4188
-                    )
4189
-                    : esc_html__(
4190
-                        '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.',
4191
-                        'event_espresso'
4192
-                    );
4193
-                EE_Error::add_attention($msg);
4194
-            }
4195
-        }
4196
-        
4197
-        return true;
4198
-    }
4157
+			return false;
4158
+		}
4159
+        
4160
+		if ($message_type instanceof EE_message_type) {
4161
+			$message_type_name = $message_type->name;
4162
+			EE_Error::add_success(
4163
+				sprintf(
4164
+					esc_html__('%s message type has been successfully deactivated for the %s messenger.', 'event_espresso'),
4165
+					ucwords($message_type->label['singular']),
4166
+					ucwords($messenger->label['singular'])
4167
+				)
4168
+			);
4169
+		} else {
4170
+			$message_type_name = '';
4171
+			EE_Error::add_success(
4172
+				sprintf(
4173
+					esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4174
+					ucwords($messenger->label['singular'])
4175
+				)
4176
+			);
4177
+		}
4178
+        
4179
+		//if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4180
+		if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4181
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
4182
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4183
+			if ($count_updated > 0) {
4184
+				$msg = $message_type_name === 'invoice'
4185
+					? esc_html__(
4186
+						'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.',
4187
+						'event_espresso'
4188
+					)
4189
+					: esc_html__(
4190
+						'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.',
4191
+						'event_espresso'
4192
+					);
4193
+				EE_Error::add_attention($msg);
4194
+			}
4195
+		}
4196
+        
4197
+		return true;
4198
+	}
4199 4199
 
4200 4200
 
4201
-    /**
4202
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4203
-     *
4204
-     * @throws DomainException
4205
-     */
4206
-    public function update_mt_form()
4207
-    {
4208
-        if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4209
-            EE_Error::add_error(
4210
-                esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4211
-                __FILE__,
4212
-                __FUNCTION__,
4213
-                __LINE__
4214
-            );
4215
-            $this->_return_json();
4216
-        }
4217
-        
4218
-        $message_types = $this->get_installed_message_types();
4219
-        
4220
-        $message_type = $message_types[$this->_req_data['message_type']];
4221
-        $messenger    = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4222
-        
4223
-        $content                         = $this->_message_type_settings_content(
4224
-            $message_type,
4225
-            $messenger,
4226
-            true
4227
-        );
4228
-        $this->_template_args['success'] = true;
4229
-        $this->_template_args['content'] = $content;
4230
-        $this->_return_json();
4231
-    }
4201
+	/**
4202
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4203
+	 *
4204
+	 * @throws DomainException
4205
+	 */
4206
+	public function update_mt_form()
4207
+	{
4208
+		if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4209
+			EE_Error::add_error(
4210
+				esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4211
+				__FILE__,
4212
+				__FUNCTION__,
4213
+				__LINE__
4214
+			);
4215
+			$this->_return_json();
4216
+		}
4217
+        
4218
+		$message_types = $this->get_installed_message_types();
4219
+        
4220
+		$message_type = $message_types[$this->_req_data['message_type']];
4221
+		$messenger    = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4222
+        
4223
+		$content                         = $this->_message_type_settings_content(
4224
+			$message_type,
4225
+			$messenger,
4226
+			true
4227
+		);
4228
+		$this->_template_args['success'] = true;
4229
+		$this->_template_args['content'] = $content;
4230
+		$this->_return_json();
4231
+	}
4232 4232
     
4233 4233
     
4234
-    /**
4235
-     * this handles saving the settings for a messenger or message type
4236
-     *
4237
-     */
4238
-    public function save_settings()
4239
-    {
4240
-        if ( ! isset($this->_req_data['type'])) {
4241
-            EE_Error::add_error(
4242
-                esc_html__(
4243
-                    'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4244
-                    'event_espresso'
4245
-                ),
4246
-                __FILE__,
4247
-                __FUNCTION__,
4248
-                __LINE__
4249
-            );
4250
-            $this->_template_args['error'] = true;
4251
-            $this->_return_json();
4252
-        }
4253
-        
4254
-        
4255
-        if ($this->_req_data['type'] === 'messenger') {
4256
-            //this should be an array.
4257
-            $settings  = $this->_req_data['messenger_settings'];
4258
-            $messenger = $settings['messenger'];
4259
-            //let's setup the settings data
4260
-            foreach ($settings as $key => $value) {
4261
-                switch ($key) {
4262
-                    case 'messenger' :
4263
-                        unset($settings['messenger']);
4264
-                        break;
4265
-                    case 'message_types' :
4266
-                        unset($settings['message_types']);
4267
-                        break;
4268
-                    default :
4269
-                        $settings[$key] = $value;
4270
-                        break;
4271
-                }
4272
-            }
4273
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4274
-        } elseif ($this->_req_data['type'] === 'message_type') {
4275
-            $settings     = $this->_req_data['message_type_settings'];
4276
-            $messenger    = $settings['messenger'];
4277
-            $message_type = $settings['message_type'];
4234
+	/**
4235
+	 * this handles saving the settings for a messenger or message type
4236
+	 *
4237
+	 */
4238
+	public function save_settings()
4239
+	{
4240
+		if ( ! isset($this->_req_data['type'])) {
4241
+			EE_Error::add_error(
4242
+				esc_html__(
4243
+					'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4244
+					'event_espresso'
4245
+				),
4246
+				__FILE__,
4247
+				__FUNCTION__,
4248
+				__LINE__
4249
+			);
4250
+			$this->_template_args['error'] = true;
4251
+			$this->_return_json();
4252
+		}
4253
+        
4254
+        
4255
+		if ($this->_req_data['type'] === 'messenger') {
4256
+			//this should be an array.
4257
+			$settings  = $this->_req_data['messenger_settings'];
4258
+			$messenger = $settings['messenger'];
4259
+			//let's setup the settings data
4260
+			foreach ($settings as $key => $value) {
4261
+				switch ($key) {
4262
+					case 'messenger' :
4263
+						unset($settings['messenger']);
4264
+						break;
4265
+					case 'message_types' :
4266
+						unset($settings['message_types']);
4267
+						break;
4268
+					default :
4269
+						$settings[$key] = $value;
4270
+						break;
4271
+				}
4272
+			}
4273
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4274
+		} elseif ($this->_req_data['type'] === 'message_type') {
4275
+			$settings     = $this->_req_data['message_type_settings'];
4276
+			$messenger    = $settings['messenger'];
4277
+			$message_type = $settings['message_type'];
4278 4278
             
4279
-            foreach ($settings as $key => $value) {
4280
-                switch ($key) {
4281
-                    case 'messenger' :
4282
-                        unset($settings['messenger']);
4283
-                        break;
4284
-                    case 'message_type' :
4285
-                        unset($settings['message_type']);
4286
-                        break;
4287
-                    default :
4288
-                        $settings[$key] = $value;
4289
-                        break;
4290
-                }
4291
-            }
4279
+			foreach ($settings as $key => $value) {
4280
+				switch ($key) {
4281
+					case 'messenger' :
4282
+						unset($settings['messenger']);
4283
+						break;
4284
+					case 'message_type' :
4285
+						unset($settings['message_type']);
4286
+						break;
4287
+					default :
4288
+						$settings[$key] = $value;
4289
+						break;
4290
+				}
4291
+			}
4292 4292
             
4293
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4294
-        }
4295
-        
4296
-        //okay we should have the data all setup.  Now we just update!
4297
-        $success = $this->_message_resource_manager->update_active_messengers_option();
4298
-        
4299
-        if ($success) {
4300
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
4301
-        } else {
4302
-            EE_Error::add_error(
4303
-                esc_html__(
4304
-                    'Settings did not get updated',
4305
-                    'event_espresso'
4306
-                ),
4307
-                __FILE__,
4308
-                __FUNCTION__,
4309
-                __LINE__
4310
-            );
4311
-        }
4312
-        
4313
-        $this->_template_args['success'] = $success;
4314
-        $this->_return_json();
4315
-    }
4293
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4294
+		}
4295
+        
4296
+		//okay we should have the data all setup.  Now we just update!
4297
+		$success = $this->_message_resource_manager->update_active_messengers_option();
4298
+        
4299
+		if ($success) {
4300
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
4301
+		} else {
4302
+			EE_Error::add_error(
4303
+				esc_html__(
4304
+					'Settings did not get updated',
4305
+					'event_espresso'
4306
+				),
4307
+				__FILE__,
4308
+				__FUNCTION__,
4309
+				__LINE__
4310
+			);
4311
+		}
4312
+        
4313
+		$this->_template_args['success'] = $success;
4314
+		$this->_return_json();
4315
+	}
4316 4316
     
4317 4317
     
4318 4318
     
4319 4319
     
4320
-    /**  EE MESSAGE PROCESSING ACTIONS **/
4320
+	/**  EE MESSAGE PROCESSING ACTIONS **/
4321 4321
 
4322 4322
 
4323
-    /**
4324
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4325
-     * However, this does not send immediately, it just queues for sending.
4326
-     *
4327
-     * @since 4.9.0
4328
-     * @throws EE_Error
4329
-     * @throws InvalidDataTypeException
4330
-     * @throws InvalidInterfaceException
4331
-     * @throws InvalidArgumentException
4332
-     * @throws ReflectionException
4333
-     */
4334
-    protected function _generate_now()
4335
-    {
4336
-        EED_Messages::generate_now($this->_get_msg_ids_from_request());
4337
-        $this->_redirect_after_action(false, '', '', array(), true);
4338
-    }
4323
+	/**
4324
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4325
+	 * However, this does not send immediately, it just queues for sending.
4326
+	 *
4327
+	 * @since 4.9.0
4328
+	 * @throws EE_Error
4329
+	 * @throws InvalidDataTypeException
4330
+	 * @throws InvalidInterfaceException
4331
+	 * @throws InvalidArgumentException
4332
+	 * @throws ReflectionException
4333
+	 */
4334
+	protected function _generate_now()
4335
+	{
4336
+		EED_Messages::generate_now($this->_get_msg_ids_from_request());
4337
+		$this->_redirect_after_action(false, '', '', array(), true);
4338
+	}
4339 4339
 
4340 4340
 
4341
-    /**
4342
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4343
-     * are EEM_Message::status_resend or EEM_Message::status_idle
4344
-     *
4345
-     * @since 4.9.0
4346
-     * @throws EE_Error
4347
-     * @throws InvalidDataTypeException
4348
-     * @throws InvalidInterfaceException
4349
-     * @throws InvalidArgumentException
4350
-     * @throws ReflectionException
4351
-     */
4352
-    protected function _generate_and_send_now()
4353
-    {
4354
-        EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4355
-        $this->_redirect_after_action(false, '', '', array(), true);
4356
-    }
4341
+	/**
4342
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4343
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
4344
+	 *
4345
+	 * @since 4.9.0
4346
+	 * @throws EE_Error
4347
+	 * @throws InvalidDataTypeException
4348
+	 * @throws InvalidInterfaceException
4349
+	 * @throws InvalidArgumentException
4350
+	 * @throws ReflectionException
4351
+	 */
4352
+	protected function _generate_and_send_now()
4353
+	{
4354
+		EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4355
+		$this->_redirect_after_action(false, '', '', array(), true);
4356
+	}
4357 4357
 
4358 4358
 
4359
-    /**
4360
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4361
-     *
4362
-     * @since 4.9.0
4363
-     * @throws EE_Error
4364
-     * @throws InvalidDataTypeException
4365
-     * @throws InvalidInterfaceException
4366
-     * @throws InvalidArgumentException
4367
-     * @throws ReflectionException
4368
-     */
4369
-    protected function _queue_for_resending()
4370
-    {
4371
-        EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4372
-        $this->_redirect_after_action(false, '', '', array(), true);
4373
-    }
4359
+	/**
4360
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4361
+	 *
4362
+	 * @since 4.9.0
4363
+	 * @throws EE_Error
4364
+	 * @throws InvalidDataTypeException
4365
+	 * @throws InvalidInterfaceException
4366
+	 * @throws InvalidArgumentException
4367
+	 * @throws ReflectionException
4368
+	 */
4369
+	protected function _queue_for_resending()
4370
+	{
4371
+		EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4372
+		$this->_redirect_after_action(false, '', '', array(), true);
4373
+	}
4374 4374
 
4375 4375
 
4376
-    /**
4377
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4378
-     *
4379
-     * @since 4.9.0
4380
-     * @throws EE_Error
4381
-     * @throws InvalidDataTypeException
4382
-     * @throws InvalidInterfaceException
4383
-     * @throws InvalidArgumentException
4384
-     * @throws ReflectionException
4385
-     */
4386
-    protected function _send_now()
4387
-    {
4388
-        EED_Messages::send_now($this->_get_msg_ids_from_request());
4389
-        $this->_redirect_after_action(false, '', '', array(), true);
4390
-    }
4376
+	/**
4377
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4378
+	 *
4379
+	 * @since 4.9.0
4380
+	 * @throws EE_Error
4381
+	 * @throws InvalidDataTypeException
4382
+	 * @throws InvalidInterfaceException
4383
+	 * @throws InvalidArgumentException
4384
+	 * @throws ReflectionException
4385
+	 */
4386
+	protected function _send_now()
4387
+	{
4388
+		EED_Messages::send_now($this->_get_msg_ids_from_request());
4389
+		$this->_redirect_after_action(false, '', '', array(), true);
4390
+	}
4391 4391
 
4392 4392
 
4393
-    /**
4394
-     * Deletes EE_messages for IDs in the request.
4395
-     *
4396
-     * @since 4.9.0
4397
-     * @throws EE_Error
4398
-     * @throws InvalidDataTypeException
4399
-     * @throws InvalidInterfaceException
4400
-     * @throws InvalidArgumentException
4401
-     */
4402
-    protected function _delete_ee_messages()
4403
-    {
4404
-        $msg_ids       = $this->_get_msg_ids_from_request();
4405
-        $deleted_count = 0;
4406
-        foreach ($msg_ids as $msg_id) {
4407
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4408
-                $deleted_count++;
4409
-            }
4410
-        }
4411
-        if ($deleted_count) {
4412
-            EE_Error::add_success(esc_html(_n('Message successfully deleted', 'Messages successfully deleted', $deleted_count, 'event_espresso')));
4413
-            $this->_redirect_after_action(
4414
-                false,
4415
-                '',
4416
-                '',
4417
-                array(),
4418
-                true
4419
-            );
4420
-        } else {
4421
-            EE_Error::add_error(
4422
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4423
-                __FILE__, __FUNCTION__, __LINE__
4424
-            );
4425
-            $this->_redirect_after_action(false, '', '', array(), true);
4426
-        }
4427
-    }
4393
+	/**
4394
+	 * Deletes EE_messages for IDs in the request.
4395
+	 *
4396
+	 * @since 4.9.0
4397
+	 * @throws EE_Error
4398
+	 * @throws InvalidDataTypeException
4399
+	 * @throws InvalidInterfaceException
4400
+	 * @throws InvalidArgumentException
4401
+	 */
4402
+	protected function _delete_ee_messages()
4403
+	{
4404
+		$msg_ids       = $this->_get_msg_ids_from_request();
4405
+		$deleted_count = 0;
4406
+		foreach ($msg_ids as $msg_id) {
4407
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4408
+				$deleted_count++;
4409
+			}
4410
+		}
4411
+		if ($deleted_count) {
4412
+			EE_Error::add_success(esc_html(_n('Message successfully deleted', 'Messages successfully deleted', $deleted_count, 'event_espresso')));
4413
+			$this->_redirect_after_action(
4414
+				false,
4415
+				'',
4416
+				'',
4417
+				array(),
4418
+				true
4419
+			);
4420
+		} else {
4421
+			EE_Error::add_error(
4422
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4423
+				__FILE__, __FUNCTION__, __LINE__
4424
+			);
4425
+			$this->_redirect_after_action(false, '', '', array(), true);
4426
+		}
4427
+	}
4428 4428
     
4429 4429
     
4430
-    /**
4431
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4432
-     * @since 4.9.0
4433
-     * @return array
4434
-     */
4435
-    protected function _get_msg_ids_from_request()
4436
-    {
4437
-        if ( ! isset($this->_req_data['MSG_ID'])) {
4438
-            return array();
4439
-        }
4440
-        
4441
-        return is_array($this->_req_data['MSG_ID'])
4442
-            ? array_keys($this->_req_data['MSG_ID'])
4443
-            : array($this->_req_data['MSG_ID']);
4444
-    }
4430
+	/**
4431
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4432
+	 * @since 4.9.0
4433
+	 * @return array
4434
+	 */
4435
+	protected function _get_msg_ids_from_request()
4436
+	{
4437
+		if ( ! isset($this->_req_data['MSG_ID'])) {
4438
+			return array();
4439
+		}
4440
+        
4441
+		return is_array($this->_req_data['MSG_ID'])
4442
+			? array_keys($this->_req_data['MSG_ID'])
4443
+			: array($this->_req_data['MSG_ID']);
4444
+	}
4445 4445
 }
Please login to merge, or discard this patch.
core/domain/entities/notifications/PersistentAdminNotice.php 2 patches
Indentation   +323 added lines, -323 removed lines patch added patch discarded remove patch
@@ -28,332 +28,332 @@
 block discarded – undo
28 28
 class PersistentAdminNotice implements RequiresCapCheckInterface
29 29
 {
30 30
 
31
-    /**
32
-     * @var string $name
33
-     */
34
-    protected $name = '';
35
-
36
-    /**
37
-     * @var string $message
38
-     */
39
-    protected $message = '';
40
-
41
-    /**
42
-     * @var boolean $force_update
43
-     */
44
-    protected $force_update = false;
45
-
46
-    /**
47
-     * @var string $capability
48
-     */
49
-    protected $capability = 'manage_options';
50
-
51
-    /**
52
-     * @var string $cap_context
53
-     */
54
-    protected $cap_context = 'view persistent admin notice';
55
-
56
-    /**
57
-     * @var boolean $dismissed
58
-     */
59
-    protected $dismissed = false;
60
-
61
-    /**
62
-     * @var CapCheckInterface $cap_check
63
-     */
64
-    protected $cap_check;
65
-
66
-    /**
67
-     * if true, then this notice will be deleted from the database
68
-     *
69
-     * @var boolean $purge
70
-     */
71
-    protected $purge = false;
72
-
73
-    /**
74
-     * gets set to true if notice is successfully registered with the PersistentAdminNoticeManager
75
-     * if false, and WP_DEBUG is on, then an exception will be thrown in the admin footer
76
-     *
77
-     * @var boolean $registered
78
-     */
79
-    private $registered = false;
80
-
81
-
82
-
83
-    /**
84
-     * PersistentAdminNotice constructor
85
-     *
86
-     * @param string $name         [required] the name, or key of the Persistent Admin Notice to be stored
87
-     * @param string $message      [required] the message to be stored persistently until dismissed
88
-     * @param bool   $force_update enforce the reappearance of a persistent message
89
-     * @param string $capability   user capability required to view this notice
90
-     * @param string $cap_context  description for why the cap check is being performed
91
-     * @param bool   $dismissed    whether or not the user has already dismissed/viewed this notice
92
-     * @throws InvalidDataTypeException
93
-     */
94
-    public function __construct(
95
-        $name,
96
-        $message,
97
-        $force_update = false,
98
-        $capability = 'manage_options',
99
-        $cap_context = 'view persistent admin notice',
100
-        $dismissed = false
101
-    ) {
102
-        $this->setName($name);
103
-        $this->setMessage($message);
104
-        $this->setForceUpdate($force_update);
105
-        $this->setCapability($capability);
106
-        $this->setCapContext($cap_context);
107
-        $this->setDismissed($dismissed);
108
-        add_action(
109
-            'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
110
-            array($this, 'registerPersistentAdminNotice')
111
-        );
112
-        add_action('shutdown', array($this, 'confirmRegistered'), 999);
113
-    }
114
-
115
-
116
-
117
-    /**
118
-     * @return string
119
-     */
120
-    public function getName()
121
-    {
122
-        return $this->name;
123
-    }
124
-
125
-
126
-
127
-    /**
128
-     * @param string $name
129
-     * @throws InvalidDataTypeException
130
-     */
131
-    private function setName($name)
132
-    {
133
-        if (! is_string($name)) {
134
-            throw new InvalidDataTypeException('$name', $name, 'string');
135
-        }
136
-        $this->name = sanitize_key($name);
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * @return string
143
-     */
144
-    public function getMessage()
145
-    {
146
-        return $this->message;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * @param string $message
153
-     * @throws InvalidDataTypeException
154
-     */
155
-    private function setMessage($message)
156
-    {
157
-        if (! is_string($message)) {
158
-            throw new InvalidDataTypeException('$message', $message, 'string');
159
-        }
160
-        global $allowedtags;
161
-        $allowedtags['br'] = array();
162
-        $this->message     = wp_kses($message, $allowedtags);
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * @return bool
169
-     */
170
-    public function getForceUpdate()
171
-    {
172
-        return $this->force_update;
173
-    }
174
-
175
-
176
-
177
-    /**
178
-     * @param bool $force_update
179
-     */
180
-    private function setForceUpdate($force_update)
181
-    {
182
-        $this->force_update = filter_var($force_update, FILTER_VALIDATE_BOOLEAN);
183
-    }
184
-
185
-
186
-
187
-    /**
188
-     * @return string
189
-     */
190
-    public function getCapability()
191
-    {
192
-        return $this->capability;
193
-    }
194
-
195
-
196
-
197
-    /**
198
-     * @param string $capability
199
-     * @throws InvalidDataTypeException
200
-     */
201
-    private function setCapability($capability)
202
-    {
203
-        if (! is_string($capability)) {
204
-            throw new InvalidDataTypeException('$capability', $capability, 'string');
205
-        }
206
-        $this->capability = ! empty($capability) ? $capability : 'manage_options';
207
-    }
31
+	/**
32
+	 * @var string $name
33
+	 */
34
+	protected $name = '';
35
+
36
+	/**
37
+	 * @var string $message
38
+	 */
39
+	protected $message = '';
40
+
41
+	/**
42
+	 * @var boolean $force_update
43
+	 */
44
+	protected $force_update = false;
45
+
46
+	/**
47
+	 * @var string $capability
48
+	 */
49
+	protected $capability = 'manage_options';
50
+
51
+	/**
52
+	 * @var string $cap_context
53
+	 */
54
+	protected $cap_context = 'view persistent admin notice';
55
+
56
+	/**
57
+	 * @var boolean $dismissed
58
+	 */
59
+	protected $dismissed = false;
60
+
61
+	/**
62
+	 * @var CapCheckInterface $cap_check
63
+	 */
64
+	protected $cap_check;
65
+
66
+	/**
67
+	 * if true, then this notice will be deleted from the database
68
+	 *
69
+	 * @var boolean $purge
70
+	 */
71
+	protected $purge = false;
72
+
73
+	/**
74
+	 * gets set to true if notice is successfully registered with the PersistentAdminNoticeManager
75
+	 * if false, and WP_DEBUG is on, then an exception will be thrown in the admin footer
76
+	 *
77
+	 * @var boolean $registered
78
+	 */
79
+	private $registered = false;
80
+
81
+
82
+
83
+	/**
84
+	 * PersistentAdminNotice constructor
85
+	 *
86
+	 * @param string $name         [required] the name, or key of the Persistent Admin Notice to be stored
87
+	 * @param string $message      [required] the message to be stored persistently until dismissed
88
+	 * @param bool   $force_update enforce the reappearance of a persistent message
89
+	 * @param string $capability   user capability required to view this notice
90
+	 * @param string $cap_context  description for why the cap check is being performed
91
+	 * @param bool   $dismissed    whether or not the user has already dismissed/viewed this notice
92
+	 * @throws InvalidDataTypeException
93
+	 */
94
+	public function __construct(
95
+		$name,
96
+		$message,
97
+		$force_update = false,
98
+		$capability = 'manage_options',
99
+		$cap_context = 'view persistent admin notice',
100
+		$dismissed = false
101
+	) {
102
+		$this->setName($name);
103
+		$this->setMessage($message);
104
+		$this->setForceUpdate($force_update);
105
+		$this->setCapability($capability);
106
+		$this->setCapContext($cap_context);
107
+		$this->setDismissed($dismissed);
108
+		add_action(
109
+			'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
110
+			array($this, 'registerPersistentAdminNotice')
111
+		);
112
+		add_action('shutdown', array($this, 'confirmRegistered'), 999);
113
+	}
114
+
115
+
116
+
117
+	/**
118
+	 * @return string
119
+	 */
120
+	public function getName()
121
+	{
122
+		return $this->name;
123
+	}
124
+
125
+
126
+
127
+	/**
128
+	 * @param string $name
129
+	 * @throws InvalidDataTypeException
130
+	 */
131
+	private function setName($name)
132
+	{
133
+		if (! is_string($name)) {
134
+			throw new InvalidDataTypeException('$name', $name, 'string');
135
+		}
136
+		$this->name = sanitize_key($name);
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * @return string
143
+	 */
144
+	public function getMessage()
145
+	{
146
+		return $this->message;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * @param string $message
153
+	 * @throws InvalidDataTypeException
154
+	 */
155
+	private function setMessage($message)
156
+	{
157
+		if (! is_string($message)) {
158
+			throw new InvalidDataTypeException('$message', $message, 'string');
159
+		}
160
+		global $allowedtags;
161
+		$allowedtags['br'] = array();
162
+		$this->message     = wp_kses($message, $allowedtags);
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * @return bool
169
+	 */
170
+	public function getForceUpdate()
171
+	{
172
+		return $this->force_update;
173
+	}
174
+
175
+
176
+
177
+	/**
178
+	 * @param bool $force_update
179
+	 */
180
+	private function setForceUpdate($force_update)
181
+	{
182
+		$this->force_update = filter_var($force_update, FILTER_VALIDATE_BOOLEAN);
183
+	}
184
+
185
+
186
+
187
+	/**
188
+	 * @return string
189
+	 */
190
+	public function getCapability()
191
+	{
192
+		return $this->capability;
193
+	}
194
+
195
+
196
+
197
+	/**
198
+	 * @param string $capability
199
+	 * @throws InvalidDataTypeException
200
+	 */
201
+	private function setCapability($capability)
202
+	{
203
+		if (! is_string($capability)) {
204
+			throw new InvalidDataTypeException('$capability', $capability, 'string');
205
+		}
206
+		$this->capability = ! empty($capability) ? $capability : 'manage_options';
207
+	}
208 208
 
209 209
 
210 210
 
211
-    /**
212
-     * @return string
213
-     */
214
-    public function getCapContext()
215
-    {
216
-        return $this->cap_context;
217
-    }
218
-
219
-
220
-
221
-    /**
222
-     * @param string $cap_context
223
-     * @throws InvalidDataTypeException
224
-     */
225
-    private function setCapContext($cap_context)
226
-    {
227
-        if (! is_string($cap_context)) {
228
-            throw new InvalidDataTypeException('$cap_context', $cap_context, 'string');
229
-        }
230
-        $this->cap_context = ! empty($cap_context) ? $cap_context : 'view persistent admin notice';
231
-    }
232
-
233
-
234
-
235
-    /**
236
-     * @return bool
237
-     */
238
-    public function getDismissed()
239
-    {
240
-        return $this->dismissed;
241
-    }
242
-
243
-
244
-
245
-    /**
246
-     * @param bool $dismissed
247
-     */
248
-    public function setDismissed($dismissed)
249
-    {
250
-        $this->dismissed = filter_var($dismissed, FILTER_VALIDATE_BOOLEAN);
251
-    }
252
-
253
-
254
-
255
-    /**
256
-     * @return CapCheckInterface
257
-     * @throws InvalidDataTypeException
258
-     */
259
-    public function getCapCheck()
260
-    {
261
-        if (! $this->cap_check instanceof CapCheckInterface) {
262
-            $this->setCapCheck(
263
-                new CapCheck(
264
-                    $this->capability,
265
-                    $this->cap_context
266
-                )
267
-            );
268
-        }
269
-        return $this->cap_check;
270
-    }
271
-
272
-
273
-
274
-    /**
275
-     * @param CapCheckInterface $cap_check
276
-     */
277
-    private function setCapCheck(CapCheckInterface $cap_check)
278
-    {
279
-        $this->cap_check = $cap_check;
280
-    }
281
-
282
-
283
-
284
-    /**
285
-     * @return bool
286
-     */
287
-    public function getPurge()
288
-    {
289
-        return $this->purge;
290
-    }
291
-
292
-
293
-
294
-    /**
295
-     * @param bool $purge
296
-     */
297
-    public function setPurge($purge)
298
-    {
299
-        $this->purge = filter_var($purge, FILTER_VALIDATE_BOOLEAN);
300
-    }
301
-
302
-
303
-
304
-    /**
305
-     * given a valid PersistentAdminNotice Collection,
306
-     * this notice will be added if it is not already found in the collection (using its name as the identifier)
307
-     * if an existing notice is found that has already been dismissed,
308
-     * but we are overriding with a forced update, then we will toggle its dismissed state,
309
-     * so that the notice is displayed again
310
-     *
311
-     * @param Collection $persistent_admin_notice_collection
312
-     * @throws InvalidEntityException
313
-     */
314
-    public function registerPersistentAdminNotice(Collection $persistent_admin_notice_collection)
315
-    {
316
-        if ($this->registered) {
317
-            return;
318
-        }
319
-        // first check if this notice has already been added to the collection
320
-        if ($persistent_admin_notice_collection->has($this->name)) {
321
-            /** @var PersistentAdminNotice $existing */
322
-            $existing = $persistent_admin_notice_collection->get($this->name);
323
-            // we don't need to add it again (we can't actually)
324
-            // but if it has already been dismissed, and we are overriding with a forced update
325
-            if ($existing->getDismissed() && $this->getForceUpdate()) {
326
-                // then toggle the notice's dismissed state to true
327
-                // so that it gets displayed again
328
-                $existing->setDismissed(false);
329
-                // and make sure the message is set
330
-                $existing->setMessage($this->message);
331
-            }
332
-        } else {
333
-            $persistent_admin_notice_collection->add($this, $this->name);
334
-        }
335
-        $this->registered = true;
336
-    }
337
-
338
-
339
-
340
-    /**
341
-     * @throws Exception
342
-     */
343
-    public function confirmRegistered()
344
-    {
345
-        if (! $this->registered && WP_DEBUG) {
346
-            throw new DomainException(
347
-                sprintf(
348
-                    esc_html__(
349
-                        'The "%1$s" PersistentAdminNotice was not successfully registered. Please ensure that it is being created prior to either the "admin_notices" or "network_admin_notices" hooks being triggered.',
350
-                        'event_espresso'
351
-                    ),
352
-                    $this->name
353
-                )
354
-            );
355
-        }
356
-    }
211
+	/**
212
+	 * @return string
213
+	 */
214
+	public function getCapContext()
215
+	{
216
+		return $this->cap_context;
217
+	}
218
+
219
+
220
+
221
+	/**
222
+	 * @param string $cap_context
223
+	 * @throws InvalidDataTypeException
224
+	 */
225
+	private function setCapContext($cap_context)
226
+	{
227
+		if (! is_string($cap_context)) {
228
+			throw new InvalidDataTypeException('$cap_context', $cap_context, 'string');
229
+		}
230
+		$this->cap_context = ! empty($cap_context) ? $cap_context : 'view persistent admin notice';
231
+	}
232
+
233
+
234
+
235
+	/**
236
+	 * @return bool
237
+	 */
238
+	public function getDismissed()
239
+	{
240
+		return $this->dismissed;
241
+	}
242
+
243
+
244
+
245
+	/**
246
+	 * @param bool $dismissed
247
+	 */
248
+	public function setDismissed($dismissed)
249
+	{
250
+		$this->dismissed = filter_var($dismissed, FILTER_VALIDATE_BOOLEAN);
251
+	}
252
+
253
+
254
+
255
+	/**
256
+	 * @return CapCheckInterface
257
+	 * @throws InvalidDataTypeException
258
+	 */
259
+	public function getCapCheck()
260
+	{
261
+		if (! $this->cap_check instanceof CapCheckInterface) {
262
+			$this->setCapCheck(
263
+				new CapCheck(
264
+					$this->capability,
265
+					$this->cap_context
266
+				)
267
+			);
268
+		}
269
+		return $this->cap_check;
270
+	}
271
+
272
+
273
+
274
+	/**
275
+	 * @param CapCheckInterface $cap_check
276
+	 */
277
+	private function setCapCheck(CapCheckInterface $cap_check)
278
+	{
279
+		$this->cap_check = $cap_check;
280
+	}
281
+
282
+
283
+
284
+	/**
285
+	 * @return bool
286
+	 */
287
+	public function getPurge()
288
+	{
289
+		return $this->purge;
290
+	}
291
+
292
+
293
+
294
+	/**
295
+	 * @param bool $purge
296
+	 */
297
+	public function setPurge($purge)
298
+	{
299
+		$this->purge = filter_var($purge, FILTER_VALIDATE_BOOLEAN);
300
+	}
301
+
302
+
303
+
304
+	/**
305
+	 * given a valid PersistentAdminNotice Collection,
306
+	 * this notice will be added if it is not already found in the collection (using its name as the identifier)
307
+	 * if an existing notice is found that has already been dismissed,
308
+	 * but we are overriding with a forced update, then we will toggle its dismissed state,
309
+	 * so that the notice is displayed again
310
+	 *
311
+	 * @param Collection $persistent_admin_notice_collection
312
+	 * @throws InvalidEntityException
313
+	 */
314
+	public function registerPersistentAdminNotice(Collection $persistent_admin_notice_collection)
315
+	{
316
+		if ($this->registered) {
317
+			return;
318
+		}
319
+		// first check if this notice has already been added to the collection
320
+		if ($persistent_admin_notice_collection->has($this->name)) {
321
+			/** @var PersistentAdminNotice $existing */
322
+			$existing = $persistent_admin_notice_collection->get($this->name);
323
+			// we don't need to add it again (we can't actually)
324
+			// but if it has already been dismissed, and we are overriding with a forced update
325
+			if ($existing->getDismissed() && $this->getForceUpdate()) {
326
+				// then toggle the notice's dismissed state to true
327
+				// so that it gets displayed again
328
+				$existing->setDismissed(false);
329
+				// and make sure the message is set
330
+				$existing->setMessage($this->message);
331
+			}
332
+		} else {
333
+			$persistent_admin_notice_collection->add($this, $this->name);
334
+		}
335
+		$this->registered = true;
336
+	}
337
+
338
+
339
+
340
+	/**
341
+	 * @throws Exception
342
+	 */
343
+	public function confirmRegistered()
344
+	{
345
+		if (! $this->registered && WP_DEBUG) {
346
+			throw new DomainException(
347
+				sprintf(
348
+					esc_html__(
349
+						'The "%1$s" PersistentAdminNotice was not successfully registered. Please ensure that it is being created prior to either the "admin_notices" or "network_admin_notices" hooks being triggered.',
350
+						'event_espresso'
351
+					),
352
+					$this->name
353
+				)
354
+			);
355
+		}
356
+	}
357 357
 
358 358
 
359 359
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
      */
131 131
     private function setName($name)
132 132
     {
133
-        if (! is_string($name)) {
133
+        if ( ! is_string($name)) {
134 134
             throw new InvalidDataTypeException('$name', $name, 'string');
135 135
         }
136 136
         $this->name = sanitize_key($name);
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
      */
155 155
     private function setMessage($message)
156 156
     {
157
-        if (! is_string($message)) {
157
+        if ( ! is_string($message)) {
158 158
             throw new InvalidDataTypeException('$message', $message, 'string');
159 159
         }
160 160
         global $allowedtags;
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
      */
201 201
     private function setCapability($capability)
202 202
     {
203
-        if (! is_string($capability)) {
203
+        if ( ! is_string($capability)) {
204 204
             throw new InvalidDataTypeException('$capability', $capability, 'string');
205 205
         }
206 206
         $this->capability = ! empty($capability) ? $capability : 'manage_options';
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
      */
225 225
     private function setCapContext($cap_context)
226 226
     {
227
-        if (! is_string($cap_context)) {
227
+        if ( ! is_string($cap_context)) {
228 228
             throw new InvalidDataTypeException('$cap_context', $cap_context, 'string');
229 229
         }
230 230
         $this->cap_context = ! empty($cap_context) ? $cap_context : 'view persistent admin notice';
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
      */
259 259
     public function getCapCheck()
260 260
     {
261
-        if (! $this->cap_check instanceof CapCheckInterface) {
261
+        if ( ! $this->cap_check instanceof CapCheckInterface) {
262 262
             $this->setCapCheck(
263 263
                 new CapCheck(
264 264
                     $this->capability,
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
      */
343 343
     public function confirmRegistered()
344 344
     {
345
-        if (! $this->registered && WP_DEBUG) {
345
+        if ( ! $this->registered && WP_DEBUG) {
346 346
             throw new DomainException(
347 347
                 sprintf(
348 348
                     esc_html__(
Please login to merge, or discard this patch.
espresso.php 2 patches
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
  * @since       4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
41
+    if ( ! function_exists('espresso_duplicate_plugin_error')) {
42 42
         /**
43 43
          *    espresso_duplicate_plugin_error
44 44
          *    displays if more than one version of EE is activated at the same time
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
 
64 64
 } else {
65 65
     define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
66
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67 67
         /**
68 68
          * espresso_minimum_php_version_error
69 69
          * @return void
@@ -126,13 +126,13 @@  discard block
 block discarded – undo
126 126
                 return;
127 127
             }
128 128
             // load debugging tools
129
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
130
-                require_once   EE_HELPERS . 'EEH_Debug_Tools.helper.php';
129
+            if (WP_DEBUG === true && is_readable(EE_HELPERS.'EEH_Debug_Tools.helper.php')) {
130
+                require_once   EE_HELPERS.'EEH_Debug_Tools.helper.php';
131 131
                 \EEH_Debug_Tools::instance();
132 132
             }
133 133
             // load error handling
134
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
135
-                require_once EE_CORE . 'EE_Error.core.php';
134
+            if (is_readable(EE_CORE.'EE_Error.core.php')) {
135
+                require_once EE_CORE.'EE_Error.core.php';
136 136
             } else {
137 137
                 wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
138 138
             }
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
             if (is_readable($full_path_to_file)) {
153 153
                 require_once $full_path_to_file;
154 154
             } else {
155
-                throw new \EE_Error (
155
+                throw new \EE_Error(
156 156
                     sprintf(
157 157
                         esc_html__(
158 158
                             'The %s class file could not be located or is not readable due to file permissions.',
@@ -178,47 +178,47 @@  discard block
 block discarded – undo
178 178
          */
179 179
         function bootstrap_espresso()
180 180
         {
181
-            require_once __DIR__ . '/core/espresso_definitions.php';
181
+            require_once __DIR__.'/core/espresso_definitions.php';
182 182
             try {
183 183
                 espresso_load_error_handling();
184 184
                 espresso_load_required(
185 185
                     'EEH_Base',
186
-                    EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php'
186
+                    EE_CORE.'helpers'.DS.'EEH_Base.helper.php'
187 187
                 );
188 188
                 espresso_load_required(
189 189
                     'EEH_File',
190
-                    EE_CORE . 'interfaces' . DS . 'EEHI_File.interface.php'
190
+                    EE_CORE.'interfaces'.DS.'EEHI_File.interface.php'
191 191
                 );
192 192
                 espresso_load_required(
193 193
                     'EEH_File',
194
-                    EE_CORE . 'helpers' . DS . 'EEH_File.helper.php'
194
+                    EE_CORE.'helpers'.DS.'EEH_File.helper.php'
195 195
                 );
196 196
                 espresso_load_required(
197 197
                     'EEH_Array',
198
-                    EE_CORE . 'helpers' . DS . 'EEH_Array.helper.php'
198
+                    EE_CORE.'helpers'.DS.'EEH_Array.helper.php'
199 199
                 );
200 200
                 // instantiate and configure PSR4 autoloader
201 201
                 espresso_load_required(
202 202
                     'Psr4Autoloader',
203
-                    EE_CORE . 'Psr4Autoloader.php'
203
+                    EE_CORE.'Psr4Autoloader.php'
204 204
                 );
205 205
                 espresso_load_required(
206 206
                     'EE_Psr4AutoloaderInit',
207
-                    EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
207
+                    EE_CORE.'EE_Psr4AutoloaderInit.core.php'
208 208
                 );
209 209
                 $AutoloaderInit = new EE_Psr4AutoloaderInit();
210 210
                 $AutoloaderInit->initializeAutoloader();
211 211
                 espresso_load_required(
212 212
                     'EE_Request',
213
-                    EE_CORE . 'request_stack' . DS . 'EE_Request.core.php'
213
+                    EE_CORE.'request_stack'.DS.'EE_Request.core.php'
214 214
                 );
215 215
                 espresso_load_required(
216 216
                     'EE_Response',
217
-                    EE_CORE . 'request_stack' . DS . 'EE_Response.core.php'
217
+                    EE_CORE.'request_stack'.DS.'EE_Response.core.php'
218 218
                 );
219 219
                 espresso_load_required(
220 220
                     'EE_Bootstrap',
221
-                    EE_CORE . 'EE_Bootstrap.core.php'
221
+                    EE_CORE.'EE_Bootstrap.core.php'
222 222
                 );
223 223
                 // bootstrap EE and the request stack
224 224
                 new EE_Bootstrap(
@@ -226,14 +226,14 @@  discard block
 block discarded – undo
226 226
                     new EE_Response()
227 227
                 );
228 228
             } catch (Exception $e) {
229
-                require_once EE_CORE . 'exceptions' . DS . 'ExceptionStackTraceDisplay.php';
229
+                require_once EE_CORE.'exceptions'.DS.'ExceptionStackTraceDisplay.php';
230 230
                 new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
231 231
             }
232 232
         }
233 233
         bootstrap_espresso();
234 234
     }
235 235
 }
236
-if (! function_exists('espresso_deactivate_plugin')) {
236
+if ( ! function_exists('espresso_deactivate_plugin')) {
237 237
     /**
238 238
      *    deactivate_plugin
239 239
      * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
@@ -244,8 +244,8 @@  discard block
 block discarded – undo
244 244
      */
245 245
     function espresso_deactivate_plugin($plugin_basename = '')
246 246
     {
247
-        if (! function_exists('deactivate_plugins')) {
248
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
247
+        if ( ! function_exists('deactivate_plugins')) {
248
+            require_once ABSPATH.'wp-admin/includes/plugin.php';
249 249
         }
250 250
         unset($_GET['activate'], $_REQUEST['activate']);
251 251
         deactivate_plugins($plugin_basename);
Please login to merge, or discard this patch.
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -38,216 +38,216 @@
 block discarded – undo
38 38
  * @since       4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 
64 64
 } else {
65
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
66
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67
-        /**
68
-         * espresso_minimum_php_version_error
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
65
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
66
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67
+		/**
68
+		 * espresso_minimum_php_version_error
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
-        /**
98
-         * espresso_version
99
-         * Returns the plugin version
100
-         *
101
-         * @return string
102
-         */
103
-        function espresso_version()
104
-        {
105
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.54.rc.041');
106
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
+		/**
98
+		 * espresso_version
99
+		 * Returns the plugin version
100
+		 *
101
+		 * @return string
102
+		 */
103
+		function espresso_version()
104
+		{
105
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.54.rc.041');
106
+		}
107 107
 
108
-        /**
109
-         * espresso_plugin_activation
110
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
-         */
112
-        function espresso_plugin_activation()
113
-        {
114
-            update_option('ee_espresso_activation', true);
115
-        }
108
+		/**
109
+		 * espresso_plugin_activation
110
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
+		 */
112
+		function espresso_plugin_activation()
113
+		{
114
+			update_option('ee_espresso_activation', true);
115
+		}
116 116
 
117
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118
-        /**
119
-         *    espresso_load_error_handling
120
-         *    this function loads EE's class for handling exceptions and errors
121
-         */
122
-        function espresso_load_error_handling()
123
-        {
124
-            static $error_handling_loaded = false;
125
-            if ($error_handling_loaded) {
126
-                return;
127
-            }
128
-            // load debugging tools
129
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
130
-                require_once   EE_HELPERS . 'EEH_Debug_Tools.helper.php';
131
-                \EEH_Debug_Tools::instance();
132
-            }
133
-            // load error handling
134
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
135
-                require_once EE_CORE . 'EE_Error.core.php';
136
-            } else {
137
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
138
-            }
139
-            $error_handling_loaded = true;
140
-        }
117
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118
+		/**
119
+		 *    espresso_load_error_handling
120
+		 *    this function loads EE's class for handling exceptions and errors
121
+		 */
122
+		function espresso_load_error_handling()
123
+		{
124
+			static $error_handling_loaded = false;
125
+			if ($error_handling_loaded) {
126
+				return;
127
+			}
128
+			// load debugging tools
129
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
130
+				require_once   EE_HELPERS . 'EEH_Debug_Tools.helper.php';
131
+				\EEH_Debug_Tools::instance();
132
+			}
133
+			// load error handling
134
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
135
+				require_once EE_CORE . 'EE_Error.core.php';
136
+			} else {
137
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
138
+			}
139
+			$error_handling_loaded = true;
140
+		}
141 141
 
142
-        /**
143
-         *    espresso_load_required
144
-         *    given a class name and path, this function will load that file or throw an exception
145
-         *
146
-         * @param    string $classname
147
-         * @param    string $full_path_to_file
148
-         * @throws    EE_Error
149
-         */
150
-        function espresso_load_required($classname, $full_path_to_file)
151
-        {
152
-            if (is_readable($full_path_to_file)) {
153
-                require_once $full_path_to_file;
154
-            } else {
155
-                throw new \EE_Error (
156
-                    sprintf(
157
-                        esc_html__(
158
-                            'The %s class file could not be located or is not readable due to file permissions.',
159
-                            'event_espresso'
160
-                        ),
161
-                        $classname
162
-                    )
163
-                );
164
-            }
165
-        }
142
+		/**
143
+		 *    espresso_load_required
144
+		 *    given a class name and path, this function will load that file or throw an exception
145
+		 *
146
+		 * @param    string $classname
147
+		 * @param    string $full_path_to_file
148
+		 * @throws    EE_Error
149
+		 */
150
+		function espresso_load_required($classname, $full_path_to_file)
151
+		{
152
+			if (is_readable($full_path_to_file)) {
153
+				require_once $full_path_to_file;
154
+			} else {
155
+				throw new \EE_Error (
156
+					sprintf(
157
+						esc_html__(
158
+							'The %s class file could not be located or is not readable due to file permissions.',
159
+							'event_espresso'
160
+						),
161
+						$classname
162
+					)
163
+				);
164
+			}
165
+		}
166 166
 
167
-        /**
168
-         * @since 4.9.27
169
-         * @throws \EE_Error
170
-         * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
171
-         * @throws \EventEspresso\core\exceptions\InvalidEntityException
172
-         * @throws \EventEspresso\core\exceptions\InvalidIdentifierException
173
-         * @throws \EventEspresso\core\exceptions\InvalidClassException
174
-         * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
175
-         * @throws \EventEspresso\core\services\container\exceptions\ServiceExistsException
176
-         * @throws \EventEspresso\core\services\container\exceptions\ServiceNotFoundException
177
-         * @throws \OutOfBoundsException
178
-         */
179
-        function bootstrap_espresso()
180
-        {
181
-            require_once __DIR__ . '/core/espresso_definitions.php';
182
-            try {
183
-                espresso_load_error_handling();
184
-                espresso_load_required(
185
-                    'EEH_Base',
186
-                    EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php'
187
-                );
188
-                espresso_load_required(
189
-                    'EEH_File',
190
-                    EE_CORE . 'interfaces' . DS . 'EEHI_File.interface.php'
191
-                );
192
-                espresso_load_required(
193
-                    'EEH_File',
194
-                    EE_CORE . 'helpers' . DS . 'EEH_File.helper.php'
195
-                );
196
-                espresso_load_required(
197
-                    'EEH_Array',
198
-                    EE_CORE . 'helpers' . DS . 'EEH_Array.helper.php'
199
-                );
200
-                // instantiate and configure PSR4 autoloader
201
-                espresso_load_required(
202
-                    'Psr4Autoloader',
203
-                    EE_CORE . 'Psr4Autoloader.php'
204
-                );
205
-                espresso_load_required(
206
-                    'EE_Psr4AutoloaderInit',
207
-                    EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
208
-                );
209
-                $AutoloaderInit = new EE_Psr4AutoloaderInit();
210
-                $AutoloaderInit->initializeAutoloader();
211
-                espresso_load_required(
212
-                    'EE_Request',
213
-                    EE_CORE . 'request_stack' . DS . 'EE_Request.core.php'
214
-                );
215
-                espresso_load_required(
216
-                    'EE_Response',
217
-                    EE_CORE . 'request_stack' . DS . 'EE_Response.core.php'
218
-                );
219
-                espresso_load_required(
220
-                    'EE_Bootstrap',
221
-                    EE_CORE . 'EE_Bootstrap.core.php'
222
-                );
223
-                // bootstrap EE and the request stack
224
-                new EE_Bootstrap(
225
-                    new EE_Request($_GET, $_POST, $_COOKIE),
226
-                    new EE_Response()
227
-                );
228
-            } catch (Exception $e) {
229
-                require_once EE_CORE . 'exceptions' . DS . 'ExceptionStackTraceDisplay.php';
230
-                new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
231
-            }
232
-        }
233
-        bootstrap_espresso();
234
-    }
167
+		/**
168
+		 * @since 4.9.27
169
+		 * @throws \EE_Error
170
+		 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
171
+		 * @throws \EventEspresso\core\exceptions\InvalidEntityException
172
+		 * @throws \EventEspresso\core\exceptions\InvalidIdentifierException
173
+		 * @throws \EventEspresso\core\exceptions\InvalidClassException
174
+		 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
175
+		 * @throws \EventEspresso\core\services\container\exceptions\ServiceExistsException
176
+		 * @throws \EventEspresso\core\services\container\exceptions\ServiceNotFoundException
177
+		 * @throws \OutOfBoundsException
178
+		 */
179
+		function bootstrap_espresso()
180
+		{
181
+			require_once __DIR__ . '/core/espresso_definitions.php';
182
+			try {
183
+				espresso_load_error_handling();
184
+				espresso_load_required(
185
+					'EEH_Base',
186
+					EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php'
187
+				);
188
+				espresso_load_required(
189
+					'EEH_File',
190
+					EE_CORE . 'interfaces' . DS . 'EEHI_File.interface.php'
191
+				);
192
+				espresso_load_required(
193
+					'EEH_File',
194
+					EE_CORE . 'helpers' . DS . 'EEH_File.helper.php'
195
+				);
196
+				espresso_load_required(
197
+					'EEH_Array',
198
+					EE_CORE . 'helpers' . DS . 'EEH_Array.helper.php'
199
+				);
200
+				// instantiate and configure PSR4 autoloader
201
+				espresso_load_required(
202
+					'Psr4Autoloader',
203
+					EE_CORE . 'Psr4Autoloader.php'
204
+				);
205
+				espresso_load_required(
206
+					'EE_Psr4AutoloaderInit',
207
+					EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
208
+				);
209
+				$AutoloaderInit = new EE_Psr4AutoloaderInit();
210
+				$AutoloaderInit->initializeAutoloader();
211
+				espresso_load_required(
212
+					'EE_Request',
213
+					EE_CORE . 'request_stack' . DS . 'EE_Request.core.php'
214
+				);
215
+				espresso_load_required(
216
+					'EE_Response',
217
+					EE_CORE . 'request_stack' . DS . 'EE_Response.core.php'
218
+				);
219
+				espresso_load_required(
220
+					'EE_Bootstrap',
221
+					EE_CORE . 'EE_Bootstrap.core.php'
222
+				);
223
+				// bootstrap EE and the request stack
224
+				new EE_Bootstrap(
225
+					new EE_Request($_GET, $_POST, $_COOKIE),
226
+					new EE_Response()
227
+				);
228
+			} catch (Exception $e) {
229
+				require_once EE_CORE . 'exceptions' . DS . 'ExceptionStackTraceDisplay.php';
230
+				new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
231
+			}
232
+		}
233
+		bootstrap_espresso();
234
+	}
235 235
 }
236 236
 if (! function_exists('espresso_deactivate_plugin')) {
237
-    /**
238
-     *    deactivate_plugin
239
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
240
-     *
241
-     * @access public
242
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
243
-     * @return    void
244
-     */
245
-    function espresso_deactivate_plugin($plugin_basename = '')
246
-    {
247
-        if (! function_exists('deactivate_plugins')) {
248
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
249
-        }
250
-        unset($_GET['activate'], $_REQUEST['activate']);
251
-        deactivate_plugins($plugin_basename);
252
-    }
237
+	/**
238
+	 *    deactivate_plugin
239
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
240
+	 *
241
+	 * @access public
242
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
243
+	 * @return    void
244
+	 */
245
+	function espresso_deactivate_plugin($plugin_basename = '')
246
+	{
247
+		if (! function_exists('deactivate_plugins')) {
248
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
249
+		}
250
+		unset($_GET['activate'], $_REQUEST['activate']);
251
+		deactivate_plugins($plugin_basename);
252
+	}
253 253
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Line_Item.helper.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -874,7 +874,7 @@  discard block
 block discarded – undo
874 874
      * Deletes ALL children of the passed line item
875 875
      *
876 876
      * @param EE_Line_Item $parent_line_item
877
-     * @return bool
877
+     * @return integer
878 878
      * @throws \EE_Error
879 879
      */
880 880
     public static function delete_all_child_items(EE_Line_Item $parent_line_item)
@@ -1138,6 +1138,7 @@  discard block
 block discarded – undo
1138 1138
      * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1139 1139
      * @param string $line_item_type one of the EEM_Line_Item constants
1140 1140
      * @param string | NULL $obj_type object model class name (minus prefix) or NULL to ignore object type when searching
1141
+     * @param string $obj_type
1141 1142
      * @return EE_Line_Item[]
1142 1143
      */
1143 1144
     protected static function _get_descendants_by_type_and_object_type(
Please login to merge, or discard this patch.
Indentation   +1701 added lines, -1701 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (!defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -23,1706 +23,1706 @@  discard block
 block discarded – undo
23 23
 class EEH_Line_Item
24 24
 {
25 25
 
26
-    //other functions: cancel ticket purchase
27
-    //delete ticket purchase
28
-    //add promotion
29
-
30
-
31
-    /**
32
-     * Adds a simple item ( unrelated to any other model object) to the total line item
33
-     * in the correct spot in the line item tree (also verifying it doesn't add a duplicate based on the LIN_code)
34
-     * beneath the pre-tax-total (alongside event subtotals).
35
-     * Automatically re-calculates the line item totals and updates the related transaction. But
36
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
37
-     * should probably change because of this).
38
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
39
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
40
-     *
41
-     * @param EE_Line_Item $parent_line_item
42
-     * @param string $name
43
-     * @param float $unit_price
44
-     * @param string $description
45
-     * @param int $quantity
46
-     * @param boolean $taxable
47
-     * @param boolean $code if set to a value, ensures there is only one line item with that code
48
-     * @return boolean success
49
-     * @throws \EE_Error
50
-     */
51
-    public static function add_unrelated_item(EE_Line_Item $parent_line_item, $name, $unit_price, $description = '', $quantity = 1, $taxable = FALSE, $code = NULL)
52
-    {
53
-        $items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
54
-        $line_item = EE_Line_Item::new_instance(array(
55
-            'LIN_name' => $name,
56
-            'LIN_desc' => $description,
57
-            'LIN_unit_price' => $unit_price,
58
-            'LIN_quantity' => $quantity,
59
-            'LIN_percent' => null,
60
-            'LIN_is_taxable' => $taxable,
61
-            'LIN_order' => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
62
-            'LIN_total' => (float)$unit_price * (int)$quantity,
63
-            'LIN_type' => EEM_Line_Item::type_line_item,
64
-            'LIN_code' => $code,
65
-        ));
66
-        $line_item = apply_filters(
67
-            'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
68
-            $line_item,
69
-            $parent_line_item
70
-        );
71
-        return self::add_item($parent_line_item, $line_item);
72
-    }
73
-
74
-
75
-    /**
76
-     * Adds a simple item ( unrelated to any other model object) to the total line item,
77
-     * in the correct spot in the line item tree. Automatically
78
-     * re-calculates the line item totals and updates the related transaction. But
79
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
80
-     * should probably change because of this).
81
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
82
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
83
-     *
84
-     * @param EE_Line_Item $parent_line_item
85
-     * @param string $name
86
-     * @param float $percentage_amount
87
-     * @param string $description
88
-     * @param boolean $taxable
89
-     * @return boolean success
90
-     * @throws \EE_Error
91
-     */
92
-    public static function add_percentage_based_item(EE_Line_Item $parent_line_item, $name, $percentage_amount, $description = '', $taxable = FALSE)
93
-    {
94
-        $line_item = EE_Line_Item::new_instance(array(
95
-            'LIN_name' => $name,
96
-            'LIN_desc' => $description,
97
-            'LIN_unit_price' => 0,
98
-            'LIN_percent' => $percentage_amount,
99
-            'LIN_quantity' => NULL,
100
-            'LIN_is_taxable' => $taxable,
101
-            'LIN_total' => (float)($percentage_amount * ($parent_line_item->total() / 100)),
102
-            'LIN_type' => EEM_Line_Item::type_line_item,
103
-            'LIN_parent' => $parent_line_item->ID()
104
-        ));
105
-        $line_item = apply_filters(
106
-            'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
107
-            $line_item
108
-        );
109
-        return $parent_line_item->add_child_line_item($line_item, false);
110
-    }
111
-
112
-
113
-    /**
114
-     * Returns the new line item created by adding a purchase of the ticket
115
-     * ensures that ticket line item is saved, and that cart total has been recalculated.
116
-     * If this ticket has already been purchased, just increments its count.
117
-     * Automatically re-calculates the line item totals and updates the related transaction. But
118
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
119
-     * should probably change because of this).
120
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
121
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
122
-     *
123
-     * @param EE_Line_Item $total_line_item grand total line item of type EEM_Line_Item::type_total
124
-     * @param EE_Ticket $ticket
125
-     * @param int $qty
126
-     * @return \EE_Line_Item
127
-     * @throws \EE_Error
128
-     */
129
-    public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
130
-    {
131
-        if (!$total_line_item instanceof EE_Line_Item || !$total_line_item->is_total()) {
132
-            throw new EE_Error(sprintf(__('A valid line item total is required in order to add tickets. A line item of type "%s" was passed.', 'event_espresso'), $ticket->ID(), $total_line_item->ID()));
133
-        }
134
-        // either increment the qty for an existing ticket
135
-        $line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
136
-        // or add a new one
137
-        if (!$line_item instanceof EE_Line_Item) {
138
-            $line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
139
-        }
140
-        $total_line_item->recalculate_total_including_taxes();
141
-        return $line_item;
142
-    }
143
-
144
-
145
-    /**
146
-     * Returns the new line item created by adding a purchase of the ticket
147
-     * @param \EE_Line_Item $total_line_item
148
-     * @param EE_Ticket $ticket
149
-     * @param int $qty
150
-     * @return \EE_Line_Item
151
-     * @throws \EE_Error
152
-     */
153
-    public static function increment_ticket_qty_if_already_in_cart(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
154
-    {
155
-        $line_item = null;
156
-        if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
157
-            $ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
158
-            foreach ((array)$ticket_line_items as $ticket_line_item) {
159
-                if (
160
-                    $ticket_line_item instanceof EE_Line_Item
161
-                    && (int)$ticket_line_item->OBJ_ID() === (int)$ticket->ID()
162
-                ) {
163
-                    $line_item = $ticket_line_item;
164
-                    break;
165
-                }
166
-            }
167
-        }
168
-        if ($line_item instanceof EE_Line_Item) {
169
-            EEH_Line_Item::increment_quantity($line_item, $qty);
170
-            return $line_item;
171
-        }
172
-        return null;
173
-    }
174
-
175
-
176
-    /**
177
-     * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
178
-     * Does NOT save or recalculate other line items totals
179
-     *
180
-     * @param EE_Line_Item $line_item
181
-     * @param int $qty
182
-     * @return void
183
-     * @throws \EE_Error
184
-     */
185
-    public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
186
-    {
187
-        if (!$line_item->is_percent()) {
188
-            $qty += $line_item->quantity();
189
-            $line_item->set_quantity($qty);
190
-            $line_item->set_total($line_item->unit_price() * $qty);
191
-            $line_item->save();
192
-        }
193
-        foreach ($line_item->children() as $child) {
194
-            if ($child->is_sub_line_item()) {
195
-                EEH_Line_Item::update_quantity($child, $qty);
196
-            }
197
-        }
198
-    }
199
-
200
-
201
-    /**
202
-     * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
203
-     * Does NOT save or recalculate other line items totals
204
-     *
205
-     * @param EE_Line_Item $line_item
206
-     * @param int $qty
207
-     * @return void
208
-     * @throws \EE_Error
209
-     */
210
-    public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
211
-    {
212
-        if (!$line_item->is_percent()) {
213
-            $qty = $line_item->quantity() - $qty;
214
-            $qty = max($qty, 0);
215
-            $line_item->set_quantity($qty);
216
-            $line_item->set_total($line_item->unit_price() * $qty);
217
-            $line_item->save();
218
-        }
219
-        foreach ($line_item->children() as $child) {
220
-            if ($child->is_sub_line_item()) {
221
-                EEH_Line_Item::update_quantity($child, $qty);
222
-            }
223
-        }
224
-    }
225
-
226
-
227
-    /**
228
-     * Updates the line item and its children's quantities to the specified number.
229
-     * Does NOT save them or recalculate totals.
230
-     *
231
-     * @param EE_Line_Item $line_item
232
-     * @param int $new_quantity
233
-     * @throws \EE_Error
234
-     */
235
-    public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
236
-    {
237
-        if (!$line_item->is_percent()) {
238
-            $line_item->set_quantity($new_quantity);
239
-            $line_item->set_total($line_item->unit_price() * $new_quantity);
240
-            $line_item->save();
241
-        }
242
-        foreach ($line_item->children() as $child) {
243
-            if ($child->is_sub_line_item()) {
244
-                EEH_Line_Item::update_quantity($child, $new_quantity);
245
-            }
246
-        }
247
-    }
248
-
249
-
250
-    /**
251
-     * Returns the new line item created by adding a purchase of the ticket
252
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
253
-     * @param EE_Ticket $ticket
254
-     * @param int $qty
255
-     * @return \EE_Line_Item
256
-     * @throws \EE_Error
257
-     */
258
-    public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
259
-    {
260
-        $datetimes = $ticket->datetimes();
261
-        $first_datetime = reset($datetimes);
262
-        if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
263
-            $first_datetime_name = $first_datetime->event()->name();
264
-        } else {
265
-            $first_datetime_name = __('Event', 'event_espresso');
266
-        }
267
-        $event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
268
-        // get event subtotal line
269
-        $events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
270
-        // add $ticket to cart
271
-        $line_item = EE_Line_Item::new_instance(array(
272
-            'LIN_name' => $ticket->name(),
273
-            'LIN_desc' => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
274
-            'LIN_unit_price' => $ticket->price(),
275
-            'LIN_quantity' => $qty,
276
-            'LIN_is_taxable' => $ticket->taxable(),
277
-            'LIN_order' => count($events_sub_total->children()),
278
-            'LIN_total' => $ticket->price() * $qty,
279
-            'LIN_type' => EEM_Line_Item::type_line_item,
280
-            'OBJ_ID' => $ticket->ID(),
281
-            'OBJ_type' => 'Ticket'
282
-        ));
283
-        $line_item = apply_filters(
284
-            'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
285
-            $line_item
286
-        );
287
-        $events_sub_total->add_child_line_item($line_item);
288
-        //now add the sub-line items
289
-        $running_total_for_ticket = 0;
290
-        foreach ($ticket->prices(array('order_by' => array('PRC_order' => 'ASC'))) as $price) {
291
-            $sign = $price->is_discount() ? -1 : 1;
292
-            $price_total = $price->is_percent()
293
-                ? $running_total_for_ticket * $price->amount() / 100
294
-                : $price->amount() * $qty;
295
-            $sub_line_item = EE_Line_Item::new_instance(array(
296
-                'LIN_name' => $price->name(),
297
-                'LIN_desc' => $price->desc(),
298
-                'LIN_quantity' => $price->is_percent() ? null : $qty,
299
-                'LIN_is_taxable' => false,
300
-                'LIN_order' => $price->order(),
301
-                'LIN_total' => $sign * $price_total,
302
-                'LIN_type' => EEM_Line_Item::type_sub_line_item,
303
-                'OBJ_ID' => $price->ID(),
304
-                'OBJ_type' => 'Price'
305
-            ));
306
-            $sub_line_item = apply_filters(
307
-                'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
308
-                $sub_line_item
309
-            );
310
-            if ($price->is_percent()) {
311
-                $sub_line_item->set_percent($sign * $price->amount());
312
-            } else {
313
-                $sub_line_item->set_unit_price($sign * $price->amount());
314
-            }
315
-            $running_total_for_ticket += $price_total;
316
-            $line_item->add_child_line_item($sub_line_item);
317
-        }
318
-        return $line_item;
319
-    }
320
-
321
-
322
-    /**
323
-     * Adds the specified item under the pre-tax-sub-total line item. Automatically
324
-     * re-calculates the line item totals and updates the related transaction. But
325
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
326
-     * should probably change because of this).
327
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
328
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
329
-     *
330
-     * @param EE_Line_Item $total_line_item
331
-     * @param EE_Line_Item $item to be added
332
-     * @return boolean
333
-     * @throws \EE_Error
334
-     */
335
-    public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item)
336
-    {
337
-        $pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
338
-        if ($pre_tax_subtotal instanceof EE_Line_Item) {
339
-            $success = $pre_tax_subtotal->add_child_line_item($item);
340
-        } else {
341
-            return FALSE;
342
-        }
343
-        $total_line_item->recalculate_total_including_taxes();
344
-        return $success;
345
-    }
346
-
347
-
348
-    /**
349
-     * cancels an existing ticket line item,
350
-     * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
351
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
352
-     *
353
-     * @param EE_Line_Item $ticket_line_item
354
-     * @param int $qty
355
-     * @return bool success
356
-     * @throws \EE_Error
357
-     */
358
-    public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
359
-    {
360
-        // validate incoming line_item
361
-        if ($ticket_line_item->OBJ_type() !== 'Ticket') {
362
-            throw new EE_Error(
363
-                sprintf(
364
-                    __('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
365
-                    $ticket_line_item->type()
366
-                )
367
-            );
368
-        }
369
-        if ($ticket_line_item->quantity() < $qty) {
370
-            throw new EE_Error(
371
-                sprintf(
372
-                    __('Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.', 'event_espresso'),
373
-                    $qty,
374
-                    $ticket_line_item->quantity()
375
-                )
376
-            );
377
-        }
378
-        // decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
379
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
380
-        foreach ($ticket_line_item->children() as $child_line_item) {
381
-            if (
382
-                $child_line_item->is_sub_line_item()
383
-                && !$child_line_item->is_percent()
384
-                && !$child_line_item->is_cancellation()
385
-            ) {
386
-                $child_line_item->set_quantity($child_line_item->quantity() - $qty);
387
-            }
388
-        }
389
-        // get cancellation sub line item
390
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
391
-            $ticket_line_item,
392
-            EEM_Line_Item::type_cancellation
393
-        );
394
-        $cancellation_line_item = reset($cancellation_line_item);
395
-        // verify that this ticket was indeed previously cancelled
396
-        if ($cancellation_line_item instanceof EE_Line_Item) {
397
-            // increment cancelled quantity
398
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
399
-        } else {
400
-            // create cancellation sub line item
401
-            $cancellation_line_item = EE_Line_Item::new_instance(array(
402
-                'LIN_name' => __('Cancellation', 'event_espresso'),
403
-                'LIN_desc' => sprintf(
404
-                    _x('Cancelled %1$s : %2$s', 'Cancelled Ticket Name : 2015-01-01 11:11', 'event_espresso'),
405
-                    $ticket_line_item->name(),
406
-                    current_time(get_option('date_format') . ' ' . get_option('time_format'))
407
-                ),
408
-                'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
409
-                'LIN_quantity' => $qty,
410
-                'LIN_is_taxable' => $ticket_line_item->is_taxable(),
411
-                'LIN_order' => count($ticket_line_item->children()),
412
-                'LIN_total' => 0, // $ticket_line_item->unit_price()
413
-                'LIN_type' => EEM_Line_Item::type_cancellation,
414
-            ));
415
-            $ticket_line_item->add_child_line_item($cancellation_line_item);
416
-        }
417
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
418
-            // decrement parent line item quantity
419
-            $event_line_item = $ticket_line_item->parent();
420
-            if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
421
-                $event_line_item->set_quantity($event_line_item->quantity() - $qty);
422
-                $event_line_item->save();
423
-            }
424
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
425
-            return true;
426
-        }
427
-        return false;
428
-    }
429
-
430
-
431
-    /**
432
-     * reinstates (un-cancels?) a previously canceled ticket line item,
433
-     * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
434
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
435
-     *
436
-     * @param EE_Line_Item $ticket_line_item
437
-     * @param int $qty
438
-     * @return bool success
439
-     * @throws \EE_Error
440
-     */
441
-    public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
442
-    {
443
-        // validate incoming line_item
444
-        if ($ticket_line_item->OBJ_type() !== 'Ticket') {
445
-            throw new EE_Error(
446
-                sprintf(
447
-                    __('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
448
-                    $ticket_line_item->type()
449
-                )
450
-            );
451
-        }
452
-        // get cancellation sub line item
453
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
454
-            $ticket_line_item,
455
-            EEM_Line_Item::type_cancellation
456
-        );
457
-        $cancellation_line_item = reset($cancellation_line_item);
458
-        // verify that this ticket was indeed previously cancelled
459
-        if (!$cancellation_line_item instanceof EE_Line_Item) {
460
-            return false;
461
-        }
462
-        if ($cancellation_line_item->quantity() > $qty) {
463
-            // decrement cancelled quantity
464
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
465
-        } else if ($cancellation_line_item->quantity() == $qty) {
466
-            // decrement cancelled quantity in case anyone still has the object kicking around
467
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
468
-            // delete because quantity will end up as 0
469
-            $cancellation_line_item->delete();
470
-            // and attempt to destroy the object,
471
-            // even though PHP won't actually destroy it until it needs the memory
472
-            unset($cancellation_line_item);
473
-        } else {
474
-            // what ?!?! negative quantity ?!?!
475
-            throw new EE_Error(
476
-                sprintf(
477
-                    __('Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
478
-                        'event_espresso'),
479
-                    $qty,
480
-                    $cancellation_line_item->quantity()
481
-                )
482
-            );
483
-        }
484
-        // increment ticket quantity
485
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
486
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
487
-            // increment parent line item quantity
488
-            $event_line_item = $ticket_line_item->parent();
489
-            if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
490
-                $event_line_item->set_quantity($event_line_item->quantity() + $qty);
491
-            }
492
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
493
-            return true;
494
-        }
495
-        return false;
496
-    }
497
-
498
-
499
-    /**
500
-     * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
501
-     * then EE_Line_Item::recalculate_total_including_taxes() on the result
502
-     *
503
-     * @param EE_Line_Item $line_item
504
-     * @return \EE_Line_Item
505
-     */
506
-    public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
507
-    {
508
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
509
-        return $grand_total_line_item->recalculate_total_including_taxes();
510
-    }
511
-
512
-
513
-    /**
514
-     * Gets the line item which contains the subtotal of all the items
515
-     *
516
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
517
-     * @return \EE_Line_Item
518
-     * @throws \EE_Error
519
-     */
520
-    public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
521
-    {
522
-        $pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
523
-        return $pre_tax_subtotal instanceof EE_Line_Item
524
-            ? $pre_tax_subtotal
525
-            : self::create_pre_tax_subtotal($total_line_item);
526
-    }
527
-
528
-
529
-    /**
530
-     * Gets the line item for the taxes subtotal
531
-     *
532
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
533
-     * @return \EE_Line_Item
534
-     * @throws \EE_Error
535
-     */
536
-    public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
537
-    {
538
-        $taxes = $total_line_item->get_child_line_item('taxes');
539
-        return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
540
-    }
541
-
542
-
543
-    /**
544
-     * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
545
-     *
546
-     * @param EE_Line_Item $line_item
547
-     * @param EE_Transaction $transaction
548
-     * @return void
549
-     * @throws \EE_Error
550
-     */
551
-    public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = NULL)
552
-    {
553
-        if ($transaction) {
554
-            /** @type EEM_Transaction $EEM_Transaction */
555
-            $EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
556
-            $TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
557
-            $line_item->set_TXN_ID($TXN_ID);
558
-        }
559
-    }
560
-
561
-
562
-    /**
563
-     * Creates a new default total line item for the transaction,
564
-     * and its tickets subtotal and taxes subtotal line items (and adds the
565
-     * existing taxes as children of the taxes subtotal line item)
566
-     *
567
-     * @param EE_Transaction $transaction
568
-     * @return \EE_Line_Item of type total
569
-     * @throws \EE_Error
570
-     */
571
-    public static function create_total_line_item($transaction = NULL)
572
-    {
573
-        $total_line_item = EE_Line_Item::new_instance(array(
574
-            'LIN_code' => 'total',
575
-            'LIN_name' => __('Grand Total', 'event_espresso'),
576
-            'LIN_type' => EEM_Line_Item::type_total,
577
-            'OBJ_type' => 'Transaction'
578
-        ));
579
-        $total_line_item = apply_filters(
580
-            'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
581
-            $total_line_item
582
-        );
583
-        self::set_TXN_ID($total_line_item, $transaction);
584
-        self::create_pre_tax_subtotal($total_line_item, $transaction);
585
-        self::create_taxes_subtotal($total_line_item, $transaction);
586
-        return $total_line_item;
587
-    }
588
-
589
-
590
-    /**
591
-     * Creates a default items subtotal line item
592
-     *
593
-     * @param EE_Line_Item $total_line_item
594
-     * @param EE_Transaction $transaction
595
-     * @return EE_Line_Item
596
-     * @throws \EE_Error
597
-     */
598
-    protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
599
-    {
600
-        $pre_tax_line_item = EE_Line_Item::new_instance(array(
601
-            'LIN_code' => 'pre-tax-subtotal',
602
-            'LIN_name' => __('Pre-Tax Subtotal', 'event_espresso'),
603
-            'LIN_type' => EEM_Line_Item::type_sub_total
604
-        ));
605
-        $pre_tax_line_item = apply_filters(
606
-            'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
607
-            $pre_tax_line_item
608
-        );
609
-        self::set_TXN_ID($pre_tax_line_item, $transaction);
610
-        $total_line_item->add_child_line_item($pre_tax_line_item);
611
-        self::create_event_subtotal($pre_tax_line_item, $transaction);
612
-        return $pre_tax_line_item;
613
-    }
614
-
615
-
616
-    /**
617
-     * Creates a line item for the taxes subtotal and finds all the tax prices
618
-     * and applies taxes to it
619
-     *
620
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
621
-     * @param EE_Transaction $transaction
622
-     * @return EE_Line_Item
623
-     * @throws \EE_Error
624
-     */
625
-    protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
626
-    {
627
-        $tax_line_item = EE_Line_Item::new_instance(array(
628
-            'LIN_code' => 'taxes',
629
-            'LIN_name' => __('Taxes', 'event_espresso'),
630
-            'LIN_type' => EEM_Line_Item::type_tax_sub_total,
631
-            'LIN_order' => 1000,//this should always come last
632
-        ));
633
-        $tax_line_item = apply_filters(
634
-            'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
635
-            $tax_line_item
636
-        );
637
-        self::set_TXN_ID($tax_line_item, $transaction);
638
-        $total_line_item->add_child_line_item($tax_line_item);
639
-        //and lastly, add the actual taxes
640
-        self::apply_taxes($total_line_item);
641
-        return $tax_line_item;
642
-    }
643
-
644
-
645
-    /**
646
-     * Creates a default items subtotal line item
647
-     *
648
-     * @param EE_Line_Item $pre_tax_line_item
649
-     * @param EE_Transaction $transaction
650
-     * @param EE_Event $event
651
-     * @return EE_Line_Item
652
-     * @throws \EE_Error
653
-     */
654
-    public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = NULL, $event = NULL)
655
-    {
656
-        $event_line_item = EE_Line_Item::new_instance(array(
657
-            'LIN_code' => self::get_event_code($event),
658
-            'LIN_name' => self::get_event_name($event),
659
-            'LIN_desc' => self::get_event_desc($event),
660
-            'LIN_type' => EEM_Line_Item::type_sub_total,
661
-            'OBJ_type' => 'Event',
662
-            'OBJ_ID' => $event instanceof EE_Event ? $event->ID() : 0
663
-        ));
664
-        $event_line_item = apply_filters(
665
-            'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
666
-            $event_line_item
667
-        );
668
-        self::set_TXN_ID($event_line_item, $transaction);
669
-        $pre_tax_line_item->add_child_line_item($event_line_item);
670
-        return $event_line_item;
671
-    }
672
-
673
-
674
-    /**
675
-     * Gets what the event ticket's code SHOULD be
676
-     *
677
-     * @param EE_Event $event
678
-     * @return string
679
-     * @throws \EE_Error
680
-     */
681
-    public static function get_event_code($event)
682
-    {
683
-        return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
684
-    }
685
-
686
-    /**
687
-     * Gets the event name
688
-     * @param EE_Event $event
689
-     * @return string
690
-     */
691
-    public static function get_event_name($event)
692
-    {
693
-        return $event instanceof EE_Event ? $event->name() : __('Event', 'event_espresso');
694
-    }
695
-
696
-    /**
697
-     * Gets the event excerpt
698
-     * @param EE_Event $event
699
-     * @return string
700
-     */
701
-    public static function get_event_desc($event)
702
-    {
703
-        return $event instanceof EE_Event ? $event->short_description() : '';
704
-    }
705
-
706
-    /**
707
-     * Given the grand total line item and a ticket, finds the event sub-total
708
-     * line item the ticket's purchase should be added onto
709
-     *
710
-     * @access public
711
-     * @param EE_Line_Item $grand_total the grand total line item
712
-     * @param EE_Ticket $ticket
713
-     * @throws \EE_Error
714
-     * @return EE_Line_Item
715
-     */
716
-    public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
717
-    {
718
-        $first_datetime = $ticket->first_datetime();
719
-        if (!$first_datetime instanceof EE_Datetime) {
720
-            throw new EE_Error(
721
-                sprintf(__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'), $ticket->ID())
722
-            );
723
-        }
724
-        $event = $first_datetime->event();
725
-        if (!$event instanceof EE_Event) {
726
-            throw new EE_Error(
727
-                sprintf(
728
-                    __('The supplied ticket (ID %d) has no event data associated with it.', 'event_espresso'),
729
-                    $ticket->ID()
730
-                )
731
-            );
732
-        }
733
-        $events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
734
-        if (!$events_sub_total instanceof EE_Line_Item) {
735
-            throw new EE_Error(
736
-                sprintf(
737
-                    __('There is no events sub-total for ticket %s on total line item %d', 'event_espresso'),
738
-                    $ticket->ID(),
739
-                    $grand_total->ID()
740
-                )
741
-            );
742
-        }
743
-        return $events_sub_total;
744
-    }
745
-
746
-
747
-    /**
748
-     * Gets the event line item
749
-     *
750
-     * @param EE_Line_Item $grand_total
751
-     * @param EE_Event $event
752
-     * @return EE_Line_Item for the event subtotal which is a child of $grand_total
753
-     * @throws \EE_Error
754
-     */
755
-    public static function get_event_line_item(EE_Line_Item $grand_total, $event)
756
-    {
757
-        /** @type EE_Event $event */
758
-        $event = EEM_Event::instance()->ensure_is_obj($event, true);
759
-        $event_line_item = NULL;
760
-        $found = false;
761
-        foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
762
-            // default event subtotal, we should only ever find this the first time this method is called
763
-            if (!$event_line_item->OBJ_ID()) {
764
-                // let's use this! but first... set the event details
765
-                EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
766
-                $found = true;
767
-                break;
768
-            } else if ($event_line_item->OBJ_ID() === $event->ID()) {
769
-                // found existing line item for this event in the cart, so break out of loop and use this one
770
-                $found = true;
771
-                break;
772
-            }
773
-        }
774
-        if (!$found) {
775
-            //there is no event sub-total yet, so add it
776
-            $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
777
-            // create a new "event" subtotal below that
778
-            $event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
779
-            // and set the event details
780
-            EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
781
-        }
782
-        return $event_line_item;
783
-    }
784
-
785
-
786
-    /**
787
-     * Creates a default items subtotal line item
788
-     *
789
-     * @param EE_Line_Item $event_line_item
790
-     * @param EE_Event $event
791
-     * @param EE_Transaction $transaction
792
-     * @return EE_Line_Item
793
-     * @throws \EE_Error
794
-     */
795
-    public static function set_event_subtotal_details(
796
-        EE_Line_Item $event_line_item,
797
-        EE_Event $event,
798
-        $transaction = null
799
-    )
800
-    {
801
-        if ($event instanceof EE_Event) {
802
-            $event_line_item->set_code(self::get_event_code($event));
803
-            $event_line_item->set_name(self::get_event_name($event));
804
-            $event_line_item->set_desc(self::get_event_desc($event));
805
-            $event_line_item->set_OBJ_ID($event->ID());
806
-        }
807
-        self::set_TXN_ID($event_line_item, $transaction);
808
-    }
809
-
810
-
811
-    /**
812
-     * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
813
-     * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
814
-     * any old taxes are removed
815
-     *
816
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
817
-     * @throws \EE_Error
818
-     */
819
-    public static function apply_taxes(EE_Line_Item $total_line_item)
820
-    {
821
-        /** @type EEM_Price $EEM_Price */
822
-        $EEM_Price = EE_Registry::instance()->load_model('Price');
823
-        // get array of taxes via Price Model
824
-        $ordered_taxes = $EEM_Price->get_all_prices_that_are_taxes();
825
-        ksort($ordered_taxes);
826
-        $taxes_line_item = self::get_taxes_subtotal($total_line_item);
827
-        //just to be safe, remove its old tax line items
828
-        $taxes_line_item->delete_children_line_items();
829
-        //loop thru taxes
830
-        foreach ($ordered_taxes as $order => $taxes) {
831
-            foreach ($taxes as $tax) {
832
-                if ($tax instanceof EE_Price) {
833
-                    $tax_line_item = EE_Line_Item::new_instance(
834
-                        array(
835
-                            'LIN_name' => $tax->name(),
836
-                            'LIN_desc' => $tax->desc(),
837
-                            'LIN_percent' => $tax->amount(),
838
-                            'LIN_is_taxable' => false,
839
-                            'LIN_order' => $order,
840
-                            'LIN_total' => 0,
841
-                            'LIN_type' => EEM_Line_Item::type_tax,
842
-                            'OBJ_type' => 'Price',
843
-                            'OBJ_ID' => $tax->ID()
844
-                        )
845
-                    );
846
-                    $tax_line_item = apply_filters(
847
-                        'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
848
-                        $tax_line_item
849
-                    );
850
-                    $taxes_line_item->add_child_line_item($tax_line_item);
851
-                }
852
-            }
853
-        }
854
-        $total_line_item->recalculate_total_including_taxes();
855
-    }
856
-
857
-
858
-    /**
859
-     * Ensures that taxes have been applied to the order, if not applies them.
860
-     * Returns the total amount of tax
861
-     *
862
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
863
-     * @return float
864
-     * @throws \EE_Error
865
-     */
866
-    public static function ensure_taxes_applied($total_line_item)
867
-    {
868
-        $taxes_subtotal = self::get_taxes_subtotal($total_line_item);
869
-        if (!$taxes_subtotal->children()) {
870
-            self::apply_taxes($total_line_item);
871
-        }
872
-        return $taxes_subtotal->total();
873
-    }
874
-
875
-
876
-    /**
877
-     * Deletes ALL children of the passed line item
878
-     *
879
-     * @param EE_Line_Item $parent_line_item
880
-     * @return bool
881
-     * @throws \EE_Error
882
-     */
883
-    public static function delete_all_child_items(EE_Line_Item $parent_line_item)
884
-    {
885
-        $deleted = 0;
886
-        foreach ($parent_line_item->children() as $child_line_item) {
887
-            if ($child_line_item instanceof EE_Line_Item) {
888
-                $deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
889
-                if ($child_line_item->ID()) {
890
-                    $child_line_item->delete();
891
-                    unset($child_line_item);
892
-                } else {
893
-                    $parent_line_item->delete_child_line_item($child_line_item->code());
894
-                }
895
-                $deleted++;
896
-            }
897
-        }
898
-        return $deleted;
899
-    }
900
-
901
-
902
-    /**
903
-     * Deletes the line items as indicated by the line item code(s) provided,
904
-     * regardless of where they're found in the line item tree. Automatically
905
-     * re-calculates the line item totals and updates the related transaction. But
906
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
907
-     * should probably change because of this).
908
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
909
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
910
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
911
-     * @param array|bool|string $line_item_codes
912
-     * @return int number of items successfully removed
913
-     */
914
-    public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = FALSE)
915
-    {
916
-
917
-        if ($total_line_item->type() !== EEM_Line_Item::type_total) {
918
-            EE_Error::doing_it_wrong(
919
-                'EEH_Line_Item::delete_items',
920
-                __(
921
-                    'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
922
-                    'event_espresso'
923
-                ),
924
-                '4.6.18'
925
-            );
926
-        }
927
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
928
-
929
-        // check if only a single line_item_id was passed
930
-        if (!empty($line_item_codes) && !is_array($line_item_codes)) {
931
-            // place single line_item_id in an array to appear as multiple line_item_ids
932
-            $line_item_codes = array($line_item_codes);
933
-        }
934
-        $removals = 0;
935
-        // cycle thru line_item_ids
936
-        foreach ($line_item_codes as $line_item_id) {
937
-            $removals += $total_line_item->delete_child_line_item($line_item_id);
938
-        }
939
-
940
-        if ($removals > 0) {
941
-            $total_line_item->recalculate_taxes_and_tax_total();
942
-            return $removals;
943
-        } else {
944
-            return FALSE;
945
-        }
946
-    }
947
-
948
-
949
-    /**
950
-     * Overwrites the previous tax by clearing out the old taxes, and creates a new
951
-     * tax and updates the total line item accordingly
952
-     *
953
-     * @param EE_Line_Item $total_line_item
954
-     * @param float $amount
955
-     * @param string $name
956
-     * @param string $description
957
-     * @param string $code
958
-     * @param boolean $add_to_existing_line_item
959
-     *                          if true, and a duplicate line item with the same code is found,
960
-     *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
961
-     * @return EE_Line_Item the new tax line item created
962
-     * @throws \EE_Error
963
-     */
964
-    public static function set_total_tax_to(
965
-        EE_Line_Item $total_line_item,
966
-        $amount,
967
-        $name = null,
968
-        $description = null,
969
-        $code = null,
970
-        $add_to_existing_line_item = false
971
-    )
972
-    {
973
-        $tax_subtotal = self::get_taxes_subtotal($total_line_item);
974
-        $taxable_total = $total_line_item->taxable_total();
975
-
976
-        if ($add_to_existing_line_item) {
977
-            $new_tax = $tax_subtotal->get_child_line_item($code);
978
-            EEM_Line_Item::instance()->delete(
979
-                array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
980
-            );
981
-        } else {
982
-            $new_tax = null;
983
-            $tax_subtotal->delete_children_line_items();
984
-        }
985
-        if ($new_tax) {
986
-            $new_tax->set_total($new_tax->total() + $amount);
987
-            $new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
988
-        } else {
989
-            //no existing tax item. Create it
990
-            $new_tax = EE_Line_Item::new_instance(array(
991
-                'TXN_ID' => $total_line_item->TXN_ID(),
992
-                'LIN_name' => $name ? $name : __('Tax', 'event_espresso'),
993
-                'LIN_desc' => $description ? $description : '',
994
-                'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
995
-                'LIN_total' => $amount,
996
-                'LIN_parent' => $tax_subtotal->ID(),
997
-                'LIN_type' => EEM_Line_Item::type_tax,
998
-                'LIN_code' => $code
999
-            ));
1000
-        }
1001
-
1002
-        $new_tax = apply_filters(
1003
-            'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1004
-            $new_tax,
1005
-            $total_line_item
1006
-        );
1007
-        $new_tax->save();
1008
-        $tax_subtotal->set_total($new_tax->total());
1009
-        $tax_subtotal->save();
1010
-        $total_line_item->recalculate_total_including_taxes();
1011
-        return $new_tax;
1012
-    }
1013
-
1014
-
1015
-    /**
1016
-     * Makes all the line items which are children of $line_item taxable (or not).
1017
-     * Does NOT save the line items
1018
-     * @param EE_Line_Item $line_item
1019
-     * @param string $code_substring_for_whitelist if this string is part of the line item's code
1020
-     *  it will be whitelisted (ie, except from becoming taxable)
1021
-     * @param boolean $taxable
1022
-     */
1023
-    public static function set_line_items_taxable(
1024
-        EE_Line_Item $line_item,
1025
-        $taxable = true,
1026
-        $code_substring_for_whitelist = null
1027
-    )
1028
-    {
1029
-        $whitelisted = false;
1030
-        if ($code_substring_for_whitelist !== null) {
1031
-            $whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false ? true : false;
1032
-        }
1033
-        if (!$whitelisted && $line_item->is_line_item()) {
1034
-            $line_item->set_is_taxable($taxable);
1035
-        }
1036
-        foreach ($line_item->children() as $child_line_item) {
1037
-            EEH_Line_Item::set_line_items_taxable($child_line_item, $taxable, $code_substring_for_whitelist);
1038
-        }
1039
-    }
1040
-
1041
-
1042
-    /**
1043
-     * Gets all descendants that are event subtotals
1044
-     *
1045
-     * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1046
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1047
-     * @return EE_Line_Item[]
1048
-     */
1049
-    public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1050
-    {
1051
-        return self::get_subtotals_of_object_type($parent_line_item, 'Event');
1052
-    }
1053
-
1054
-
1055
-    /**
1056
-     * Gets all descendants subtotals that match the supplied object type
1057
-     *
1058
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1059
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1060
-     * @param string $obj_type
1061
-     * @return EE_Line_Item[]
1062
-     */
1063
-    public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1064
-    {
1065
-        return self::_get_descendants_by_type_and_object_type(
1066
-            $parent_line_item,
1067
-            EEM_Line_Item::type_sub_total,
1068
-            $obj_type
1069
-        );
1070
-    }
1071
-
1072
-
1073
-    /**
1074
-     * Gets all descendants that are tickets
1075
-     *
1076
-     * @uses  EEH_Line_Item::get_line_items_of_object_type()
1077
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1078
-     * @return EE_Line_Item[]
1079
-     */
1080
-    public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1081
-    {
1082
-        return self::get_line_items_of_object_type($parent_line_item, 'Ticket');
1083
-    }
1084
-
1085
-
1086
-    /**
1087
-     * Gets all descendants subtotals that match the supplied object type
1088
-     *
1089
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1090
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1091
-     * @param string $obj_type
1092
-     * @return EE_Line_Item[]
1093
-     */
1094
-    public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1095
-    {
1096
-        return self::_get_descendants_by_type_and_object_type($parent_line_item, EEM_Line_Item::type_line_item, $obj_type);
1097
-    }
1098
-
1099
-
1100
-    /**
1101
-     * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1102
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1103
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1104
-     * @return EE_Line_Item[]
1105
-     */
1106
-    public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1107
-    {
1108
-        return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_tax);
1109
-    }
1110
-
1111
-
1112
-    /**
1113
-     * Gets all the real items purchased which are children of this item
1114
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1115
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1116
-     * @return EE_Line_Item[]
1117
-     */
1118
-    public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1119
-    {
1120
-        return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_line_item);
1121
-    }
1122
-
1123
-
1124
-    /**
1125
-     * Gets all descendants of supplied line item that match the supplied line item type
1126
-     *
1127
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1128
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1129
-     * @param string $line_item_type one of the EEM_Line_Item constants
1130
-     * @return EE_Line_Item[]
1131
-     */
1132
-    public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1133
-    {
1134
-        return self::_get_descendants_by_type_and_object_type($parent_line_item, $line_item_type, NULL);
1135
-    }
1136
-
1137
-
1138
-    /**
1139
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1140
-     *
1141
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1142
-     * @param string $line_item_type one of the EEM_Line_Item constants
1143
-     * @param string | NULL $obj_type object model class name (minus prefix) or NULL to ignore object type when searching
1144
-     * @return EE_Line_Item[]
1145
-     */
1146
-    protected static function _get_descendants_by_type_and_object_type(
1147
-        EE_Line_Item $parent_line_item,
1148
-        $line_item_type,
1149
-        $obj_type = null
1150
-    )
1151
-    {
1152
-        $objects = array();
1153
-        foreach ($parent_line_item->children() as $child_line_item) {
1154
-            if ($child_line_item instanceof EE_Line_Item) {
1155
-                if (
1156
-                    $child_line_item->type() === $line_item_type
1157
-                    && (
1158
-                        $child_line_item->OBJ_type() === $obj_type || $obj_type === null
1159
-                    )
1160
-                ) {
1161
-                    $objects[] = $child_line_item;
1162
-                } else {
1163
-                    //go-through-all-its children looking for more matches
1164
-                    $objects = array_merge(
1165
-                        $objects,
1166
-                        self::_get_descendants_by_type_and_object_type(
1167
-                            $child_line_item,
1168
-                            $line_item_type,
1169
-                            $obj_type
1170
-                        )
1171
-                    );
1172
-                }
1173
-            }
1174
-        }
1175
-        return $objects;
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * Gets all descendants subtotals that match the supplied object type
1181
-     *
1182
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1183
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1184
-     * @param string $OBJ_type object type (like Event)
1185
-     * @param array $OBJ_IDs array of OBJ_IDs
1186
-     * @return EE_Line_Item[]
1187
-     */
1188
-    public static function get_line_items_by_object_type_and_IDs(
1189
-        EE_Line_Item $parent_line_item,
1190
-        $OBJ_type = '',
1191
-        $OBJ_IDs = array()
1192
-    )
1193
-    {
1194
-        return self::_get_descendants_by_object_type_and_object_ID($parent_line_item, $OBJ_type, $OBJ_IDs);
1195
-    }
1196
-
1197
-
1198
-    /**
1199
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1200
-     *
1201
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1202
-     * @param string $OBJ_type object type (like Event)
1203
-     * @param array $OBJ_IDs array of OBJ_IDs
1204
-     * @return EE_Line_Item[]
1205
-     */
1206
-    protected static function _get_descendants_by_object_type_and_object_ID(
1207
-        EE_Line_Item $parent_line_item,
1208
-        $OBJ_type,
1209
-        $OBJ_IDs
1210
-    )
1211
-    {
1212
-        $objects = array();
1213
-        foreach ($parent_line_item->children() as $child_line_item) {
1214
-            if ($child_line_item instanceof EE_Line_Item) {
1215
-                if (
1216
-                    $child_line_item->OBJ_type() === $OBJ_type
1217
-                    && is_array($OBJ_IDs)
1218
-                    && in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1219
-                ) {
1220
-                    $objects[] = $child_line_item;
1221
-                } else {
1222
-                    //go-through-all-its children looking for more matches
1223
-                    $objects = array_merge(
1224
-                        $objects,
1225
-                        self::_get_descendants_by_object_type_and_object_ID(
1226
-                            $child_line_item,
1227
-                            $OBJ_type,
1228
-                            $OBJ_IDs
1229
-                        )
1230
-                    );
1231
-                }
1232
-            }
1233
-        }
1234
-        return $objects;
1235
-    }
1236
-
1237
-
1238
-    /**
1239
-     * Uses a breadth-first-search in order to find the nearest descendant of
1240
-     * the specified type and returns it, else NULL
1241
-     *
1242
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1243
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1244
-     * @param string $type like one of the EEM_Line_Item::type_*
1245
-     * @return EE_Line_Item
1246
-     */
1247
-    public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1248
-    {
1249
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1250
-    }
1251
-
1252
-
1253
-    /**
1254
-     * Uses a breadth-first-search in order to find the nearest descendant
1255
-     * having the specified LIN_code and returns it, else NULL
1256
-     *
1257
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1258
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1259
-     * @param string $code any value used for LIN_code
1260
-     * @return EE_Line_Item
1261
-     */
1262
-    public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1263
-    {
1264
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1265
-    }
1266
-
1267
-
1268
-    /**
1269
-     * Uses a breadth-first-search in order to find the nearest descendant
1270
-     * having the specified LIN_code and returns it, else NULL
1271
-     *
1272
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1273
-     * @param string $search_field name of EE_Line_Item property
1274
-     * @param string $value any value stored in $search_field
1275
-     * @return EE_Line_Item
1276
-     */
1277
-    protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1278
-    {
1279
-        foreach ($parent_line_item->children() as $child) {
1280
-            if ($child->get($search_field) == $value) {
1281
-                return $child;
1282
-            }
1283
-        }
1284
-        foreach ($parent_line_item->children() as $child) {
1285
-            $descendant_found = self::_get_nearest_descendant($child, $search_field, $value);
1286
-            if ($descendant_found) {
1287
-                return $descendant_found;
1288
-            }
1289
-        }
1290
-        return NULL;
1291
-    }
1292
-
1293
-
1294
-    /**
1295
-     * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1296
-     * else recursively walks up the line item tree until a parent of type total is found,
1297
-     *
1298
-     * @param EE_Line_Item $line_item
1299
-     * @return \EE_Line_Item
1300
-     * @throws \EE_Error
1301
-     */
1302
-    public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item)
1303
-    {
1304
-        if ($line_item->TXN_ID()) {
1305
-            $total_line_item = $line_item->transaction()->total_line_item(false);
1306
-            if ($total_line_item instanceof EE_Line_Item) {
1307
-                return $total_line_item;
1308
-            }
1309
-        } else {
1310
-            $line_item_parent = $line_item->parent();
1311
-            if ($line_item_parent instanceof EE_Line_Item) {
1312
-                if ($line_item_parent->is_total()) {
1313
-                    return $line_item_parent;
1314
-                }
1315
-                return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1316
-            }
1317
-        }
1318
-        throw new EE_Error(
1319
-            sprintf(
1320
-                __('A valid grand total for line item %1$d was not found.', 'event_espresso'),
1321
-                $line_item->ID()
1322
-            )
1323
-        );
1324
-    }
1325
-
1326
-
1327
-    /**
1328
-     * Prints out a representation of the line item tree
1329
-     *
1330
-     * @param EE_Line_Item $line_item
1331
-     * @param int $indentation
1332
-     * @return void
1333
-     * @throws \EE_Error
1334
-     */
1335
-    public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1336
-    {
1337
-        echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1338
-        if (!$indentation) {
1339
-            echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1340
-        }
1341
-        for ($i = 0; $i < $indentation; $i++) {
1342
-            echo ". ";
1343
-        }
1344
-        $breakdown = '';
1345
-        if ($line_item->is_line_item()) {
1346
-            if ($line_item->is_percent()) {
1347
-                $breakdown = "{$line_item->percent()}%";
1348
-            } else {
1349
-                $breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1350
-            }
1351
-        }
1352
-        echo $line_item->name() . " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : " . '$' . "{$line_item->total()}";
1353
-        if ($breakdown) {
1354
-            echo " ( {$breakdown} )";
1355
-        }
1356
-        if ($line_item->is_taxable()) {
1357
-            echo "  * taxable";
1358
-        }
1359
-        if ($line_item->children()) {
1360
-            foreach ($line_item->children() as $child) {
1361
-                self::visualize($child, $indentation + 1);
1362
-            }
1363
-        }
1364
-    }
1365
-
1366
-
1367
-    /**
1368
-     * Calculates the registration's final price, taking into account that they
1369
-     * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1370
-     * and receive a portion of any transaction-wide discounts.
1371
-     * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1372
-     * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1373
-     * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1374
-     * and brent's final price should be $5.50.
1375
-     *
1376
-     * In order to do this, we basically need to traverse the line item tree calculating
1377
-     * the running totals (just as if we were recalculating the total), but when we identify
1378
-     * regular line items, we need to keep track of their share of the grand total.
1379
-     * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1380
-     * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1381
-     * when there are non-taxable items; otherwise they would be the same)
1382
-     *
1383
-     * @param EE_Line_Item $line_item
1384
-     * @param array $billable_ticket_quantities array of EE_Ticket IDs and their corresponding quantity that
1385
-     *                                                                            can be included in price calculations at this moment
1386
-     * @return array        keys are line items for tickets IDs and values are their share of the running total,
1387
-     *                                          plus the key 'total', and 'taxable' which also has keys of all the ticket IDs. Eg
1388
-     *                                          array(
1389
-     *                                          12 => 4.3
1390
-     *                                          23 => 8.0
1391
-     *                                          'total' => 16.6,
1392
-     *                                          'taxable' => array(
1393
-     *                                          12 => 10,
1394
-     *                                          23 => 4
1395
-     *                                          ).
1396
-     *                                          So to find which registrations have which final price, we need to find which line item
1397
-     *                                          is theirs, which can be done with
1398
-     *                                          `EEM_Line_Item::instance()->get_line_item_for_registration( $registration );`
1399
-     */
1400
-    public static function calculate_reg_final_prices_per_line_item(EE_Line_Item $line_item, $billable_ticket_quantities = array())
1401
-    {
1402
-        //init running grand total if not already
1403
-        if (!isset($running_totals['total'])) {
1404
-            $running_totals['total'] = 0;
1405
-        }
1406
-        if (!isset($running_totals['taxable'])) {
1407
-            $running_totals['taxable'] = array('total' => 0);
1408
-        }
1409
-        foreach ($line_item->children() as $child_line_item) {
1410
-            switch ($child_line_item->type()) {
1411
-
1412
-                case EEM_Line_Item::type_sub_total :
1413
-                    $running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item($child_line_item, $billable_ticket_quantities);
1414
-                    //combine arrays but preserve numeric keys
1415
-                    $running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1416
-                    $running_totals['total'] += $running_totals_from_subtotal['total'];
1417
-                    $running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1418
-                    break;
1419
-
1420
-                case EEM_Line_Item::type_tax_sub_total :
1421
-
1422
-                    //find how much the taxes percentage is
1423
-                    if ($child_line_item->percent() !== 0) {
1424
-                        $tax_percent_decimal = $child_line_item->percent() / 100;
1425
-                    } else {
1426
-                        $tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1427
-                    }
1428
-                    //and apply to all the taxable totals, and add to the pretax totals
1429
-                    foreach ($running_totals as $line_item_id => $this_running_total) {
1430
-                        //"total" and "taxable" array key is an exception
1431
-                        if ($line_item_id === 'taxable') {
1432
-                            continue;
1433
-                        }
1434
-                        $taxable_total = $running_totals['taxable'][$line_item_id];
1435
-                        $running_totals[$line_item_id] += ($taxable_total * $tax_percent_decimal);
1436
-                    }
1437
-                    break;
1438
-
1439
-                case EEM_Line_Item::type_line_item :
1440
-
1441
-                    // ticket line items or ????
1442
-                    if ($child_line_item->OBJ_type() === 'Ticket') {
1443
-                        // kk it's a ticket
1444
-                        if (isset($running_totals[$child_line_item->ID()])) {
1445
-                            //huh? that shouldn't happen.
1446
-                            $running_totals['total'] += $child_line_item->total();
1447
-                        } else {
1448
-                            //its not in our running totals yet. great.
1449
-                            if ($child_line_item->is_taxable()) {
1450
-                                $taxable_amount = $child_line_item->unit_price();
1451
-                            } else {
1452
-                                $taxable_amount = 0;
1453
-                            }
1454
-                            // are we only calculating totals for some tickets?
1455
-                            if (isset($billable_ticket_quantities[$child_line_item->OBJ_ID()])) {
1456
-                                $quantity = $billable_ticket_quantities[$child_line_item->OBJ_ID()];
1457
-                                $running_totals[$child_line_item->ID()] = $quantity
1458
-                                    ? $child_line_item->unit_price()
1459
-                                    : 0;
1460
-                                $running_totals['taxable'][$child_line_item->ID()] = $quantity
1461
-                                    ? $taxable_amount
1462
-                                    : 0;
1463
-                            } else {
1464
-                                $quantity = $child_line_item->quantity();
1465
-                                $running_totals[$child_line_item->ID()] = $child_line_item->unit_price();
1466
-                                $running_totals['taxable'][$child_line_item->ID()] = $taxable_amount;
1467
-                            }
1468
-                            $running_totals['taxable']['total'] += $taxable_amount * $quantity;
1469
-                            $running_totals['total'] += $child_line_item->unit_price() * $quantity;
1470
-                        }
1471
-                    } else {
1472
-                        // it's some other type of item added to the cart
1473
-                        // it should affect the running totals
1474
-                        // basically we want to convert it into a PERCENT modifier. Because
1475
-                        // more clearly affect all registration's final price equally
1476
-                        $line_items_percent_of_running_total = $running_totals['total'] > 0
1477
-                            ? ($child_line_item->total() / $running_totals['total']) + 1
1478
-                            : 1;
1479
-                        foreach ($running_totals as $line_item_id => $this_running_total) {
1480
-                            //the "taxable" array key is an exception
1481
-                            if ($line_item_id === 'taxable') {
1482
-                                continue;
1483
-                            }
1484
-                            // update the running totals
1485
-                            // yes this actually even works for the running grand total!
1486
-                            $running_totals[$line_item_id] =
1487
-                                $line_items_percent_of_running_total * $this_running_total;
1488
-
1489
-                            if ($child_line_item->is_taxable()) {
1490
-                                $running_totals['taxable'][$line_item_id] =
1491
-                                    $line_items_percent_of_running_total * $running_totals['taxable'][$line_item_id];
1492
-                            }
1493
-                        }
1494
-                    }
1495
-                    break;
1496
-            }
1497
-        }
1498
-        return $running_totals;
1499
-    }
1500
-
1501
-
1502
-    /**
1503
-     * @param \EE_Line_Item $total_line_item
1504
-     * @param \EE_Line_Item $ticket_line_item
1505
-     * @return float | null
1506
-     * @throws \OutOfRangeException
1507
-     */
1508
-    public static function calculate_final_price_for_ticket_line_item(\EE_Line_Item $total_line_item, \EE_Line_Item $ticket_line_item)
1509
-    {
1510
-        static $final_prices_per_ticket_line_item = array();
1511
-        if (empty($final_prices_per_ticket_line_item)) {
1512
-            $final_prices_per_ticket_line_item = \EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1513
-                $total_line_item
1514
-            );
1515
-        }
1516
-        //ok now find this new registration's final price
1517
-        if (isset($final_prices_per_ticket_line_item[$ticket_line_item->ID()])) {
1518
-            return $final_prices_per_ticket_line_item[$ticket_line_item->ID()];
1519
-        }
1520
-        $message = sprintf(
1521
-            __(
1522
-                'The final price for the ticket line item (ID:%1$d) could not be calculated.',
1523
-                'event_espresso'
1524
-            ),
1525
-            $ticket_line_item->ID()
1526
-        );
1527
-        if (WP_DEBUG) {
1528
-            $message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1529
-            throw new \OutOfRangeException($message);
1530
-        } else {
1531
-            EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1532
-        }
1533
-        return null;
1534
-    }
1535
-
1536
-
1537
-    /**
1538
-     * Creates a duplicate of the line item tree, except only includes billable items
1539
-     * and the portion of line items attributed to billable things
1540
-     *
1541
-     * @param EE_Line_Item $line_item
1542
-     * @param EE_Registration[] $registrations
1543
-     * @return \EE_Line_Item
1544
-     * @throws \EE_Error
1545
-     */
1546
-    public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1547
-    {
1548
-        $copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1549
-        foreach ($line_item->children() as $child_li) {
1550
-            $copy_li->add_child_line_item(EEH_Line_Item::billable_line_item_tree($child_li, $registrations));
1551
-        }
1552
-        //if this is the grand total line item, make sure the totals all add up
1553
-        //(we could have duplicated this logic AS we copied the line items, but
1554
-        //it seems DRYer this way)
1555
-        if ($copy_li->type() === EEM_Line_Item::type_total) {
1556
-            $copy_li->recalculate_total_including_taxes();
1557
-        }
1558
-        return $copy_li;
1559
-    }
1560
-
1561
-
1562
-    /**
1563
-     * Creates a new, unsaved line item from $line_item that factors in the
1564
-     * number of billable registrations on $registrations.
1565
-     *
1566
-     * @param EE_Line_Item $line_item
1567
-     * @return EE_Line_Item
1568
-     * @throws \EE_Error
1569
-     * @param EE_Registration[] $registrations
1570
-     */
1571
-    public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1572
-    {
1573
-        $new_li_fields = $line_item->model_field_array();
1574
-        if ($line_item->type() === EEM_Line_Item::type_line_item &&
1575
-            $line_item->OBJ_type() === 'Ticket'
1576
-        ) {
1577
-            $count = 0;
1578
-            foreach ($registrations as $registration) {
1579
-                if ($line_item->OBJ_ID() === $registration->ticket_ID() &&
1580
-                    in_array($registration->status_ID(), EEM_Registration::reg_statuses_that_allow_payment())
1581
-                ) {
1582
-                    $count++;
1583
-                }
1584
-            }
1585
-            $new_li_fields['LIN_quantity'] = $count;
1586
-        }
1587
-        //don't set the total. We'll leave that up to the code that calculates it
1588
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1589
-        return EE_Line_Item::new_instance($new_li_fields);
1590
-    }
1591
-
1592
-
1593
-    /**
1594
-     * Returns a modified line item tree where all the subtotals which have a total of 0
1595
-     * are removed, and line items with a quantity of 0
1596
-     *
1597
-     * @param EE_Line_Item $line_item |null
1598
-     * @return \EE_Line_Item|null
1599
-     * @throws \EE_Error
1600
-     */
1601
-    public static function non_empty_line_items(EE_Line_Item $line_item)
1602
-    {
1603
-        $copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1604
-        if ($copied_li === null) {
1605
-            return null;
1606
-        }
1607
-        //if this is an event subtotal, we want to only include it if it
1608
-        //has a non-zero total and at least one ticket line item child
1609
-        $ticket_children = 0;
1610
-        foreach ($line_item->children() as $child_li) {
1611
-            $child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1612
-            if ($child_li_copy !== null) {
1613
-                $copied_li->add_child_line_item($child_li_copy);
1614
-                if ($child_li_copy->type() === EEM_Line_Item::type_line_item &&
1615
-                    $child_li_copy->OBJ_type() === 'Ticket'
1616
-                ) {
1617
-                    $ticket_children++;
1618
-                }
1619
-            }
1620
-        }
1621
-        //if this is an event subtotal with NO ticket children
1622
-        //we basically want to ignore it
1623
-        if (
1624
-            $ticket_children === 0
1625
-            && $line_item->type() === EEM_Line_Item::type_sub_total
1626
-            && $line_item->OBJ_type() === 'Event'
1627
-            && $line_item->total() === 0
1628
-        ) {
1629
-            return null;
1630
-        }
1631
-        return $copied_li;
1632
-    }
1633
-
1634
-
1635
-    /**
1636
-     * Creates a new, unsaved line item, but if it's a ticket line item
1637
-     * with a total of 0, or a subtotal of 0, returns null instead
1638
-     *
1639
-     * @param EE_Line_Item $line_item
1640
-     * @return EE_Line_Item
1641
-     * @throws \EE_Error
1642
-     */
1643
-    public static function non_empty_line_item(EE_Line_Item $line_item)
1644
-    {
1645
-        if ($line_item->type() === EEM_Line_Item::type_line_item &&
1646
-            $line_item->OBJ_type() === 'Ticket' &&
1647
-            $line_item->quantity() === 0
1648
-        ) {
1649
-            return null;
1650
-        }
1651
-        $new_li_fields = $line_item->model_field_array();
1652
-        //don't set the total. We'll leave that up to the code that calculates it
1653
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1654
-        return EE_Line_Item::new_instance($new_li_fields);
1655
-    }
1656
-
1657
-
1658
-
1659
-    /**************************************** @DEPRECATED METHODS *************************************** */
1660
-    /**
1661
-     * @deprecated
1662
-     * @param EE_Line_Item $total_line_item
1663
-     * @return \EE_Line_Item
1664
-     * @throws \EE_Error
1665
-     */
1666
-    public static function get_items_subtotal(EE_Line_Item $total_line_item)
1667
-    {
1668
-        EE_Error::doing_it_wrong('EEH_Line_Item::get_items_subtotal()', __('Method replaced with EEH_Line_Item::get_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1669
-        return self::get_pre_tax_subtotal($total_line_item);
1670
-    }
1671
-
1672
-
1673
-    /**
1674
-     * @deprecated
1675
-     * @param EE_Transaction $transaction
1676
-     * @return \EE_Line_Item
1677
-     * @throws \EE_Error
1678
-     */
1679
-    public static function create_default_total_line_item($transaction = NULL)
1680
-    {
1681
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_total_line_item()', __('Method replaced with EEH_Line_Item::create_total_line_item()', 'event_espresso'), '4.6.0');
1682
-        return self::create_total_line_item($transaction);
1683
-    }
1684
-
1685
-
1686
-    /**
1687
-     * @deprecated
1688
-     * @param EE_Line_Item $total_line_item
1689
-     * @param EE_Transaction $transaction
1690
-     * @return \EE_Line_Item
1691
-     * @throws \EE_Error
1692
-     */
1693
-    public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1694
-    {
1695
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_tickets_subtotal()', __('Method replaced with EEH_Line_Item::create_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1696
-        return self::create_pre_tax_subtotal($total_line_item, $transaction);
1697
-    }
1698
-
1699
-
1700
-    /**
1701
-     * @deprecated
1702
-     * @param EE_Line_Item $total_line_item
1703
-     * @param EE_Transaction $transaction
1704
-     * @return \EE_Line_Item
1705
-     * @throws \EE_Error
1706
-     */
1707
-    public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1708
-    {
1709
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_taxes_subtotal()', __('Method replaced with EEH_Line_Item::create_taxes_subtotal()', 'event_espresso'), '4.6.0');
1710
-        return self::create_taxes_subtotal($total_line_item, $transaction);
1711
-    }
1712
-
1713
-
1714
-    /**
1715
-     * @deprecated
1716
-     * @param EE_Line_Item $total_line_item
1717
-     * @param EE_Transaction $transaction
1718
-     * @return \EE_Line_Item
1719
-     * @throws \EE_Error
1720
-     */
1721
-    public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1722
-    {
1723
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_event_subtotal()', __('Method replaced with EEH_Line_Item::create_event_subtotal()', 'event_espresso'), '4.6.0');
1724
-        return self::create_event_subtotal($total_line_item, $transaction);
1725
-    }
26
+	//other functions: cancel ticket purchase
27
+	//delete ticket purchase
28
+	//add promotion
29
+
30
+
31
+	/**
32
+	 * Adds a simple item ( unrelated to any other model object) to the total line item
33
+	 * in the correct spot in the line item tree (also verifying it doesn't add a duplicate based on the LIN_code)
34
+	 * beneath the pre-tax-total (alongside event subtotals).
35
+	 * Automatically re-calculates the line item totals and updates the related transaction. But
36
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
37
+	 * should probably change because of this).
38
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
39
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
40
+	 *
41
+	 * @param EE_Line_Item $parent_line_item
42
+	 * @param string $name
43
+	 * @param float $unit_price
44
+	 * @param string $description
45
+	 * @param int $quantity
46
+	 * @param boolean $taxable
47
+	 * @param boolean $code if set to a value, ensures there is only one line item with that code
48
+	 * @return boolean success
49
+	 * @throws \EE_Error
50
+	 */
51
+	public static function add_unrelated_item(EE_Line_Item $parent_line_item, $name, $unit_price, $description = '', $quantity = 1, $taxable = FALSE, $code = NULL)
52
+	{
53
+		$items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
54
+		$line_item = EE_Line_Item::new_instance(array(
55
+			'LIN_name' => $name,
56
+			'LIN_desc' => $description,
57
+			'LIN_unit_price' => $unit_price,
58
+			'LIN_quantity' => $quantity,
59
+			'LIN_percent' => null,
60
+			'LIN_is_taxable' => $taxable,
61
+			'LIN_order' => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
62
+			'LIN_total' => (float)$unit_price * (int)$quantity,
63
+			'LIN_type' => EEM_Line_Item::type_line_item,
64
+			'LIN_code' => $code,
65
+		));
66
+		$line_item = apply_filters(
67
+			'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
68
+			$line_item,
69
+			$parent_line_item
70
+		);
71
+		return self::add_item($parent_line_item, $line_item);
72
+	}
73
+
74
+
75
+	/**
76
+	 * Adds a simple item ( unrelated to any other model object) to the total line item,
77
+	 * in the correct spot in the line item tree. Automatically
78
+	 * re-calculates the line item totals and updates the related transaction. But
79
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
80
+	 * should probably change because of this).
81
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
82
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
83
+	 *
84
+	 * @param EE_Line_Item $parent_line_item
85
+	 * @param string $name
86
+	 * @param float $percentage_amount
87
+	 * @param string $description
88
+	 * @param boolean $taxable
89
+	 * @return boolean success
90
+	 * @throws \EE_Error
91
+	 */
92
+	public static function add_percentage_based_item(EE_Line_Item $parent_line_item, $name, $percentage_amount, $description = '', $taxable = FALSE)
93
+	{
94
+		$line_item = EE_Line_Item::new_instance(array(
95
+			'LIN_name' => $name,
96
+			'LIN_desc' => $description,
97
+			'LIN_unit_price' => 0,
98
+			'LIN_percent' => $percentage_amount,
99
+			'LIN_quantity' => NULL,
100
+			'LIN_is_taxable' => $taxable,
101
+			'LIN_total' => (float)($percentage_amount * ($parent_line_item->total() / 100)),
102
+			'LIN_type' => EEM_Line_Item::type_line_item,
103
+			'LIN_parent' => $parent_line_item->ID()
104
+		));
105
+		$line_item = apply_filters(
106
+			'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
107
+			$line_item
108
+		);
109
+		return $parent_line_item->add_child_line_item($line_item, false);
110
+	}
111
+
112
+
113
+	/**
114
+	 * Returns the new line item created by adding a purchase of the ticket
115
+	 * ensures that ticket line item is saved, and that cart total has been recalculated.
116
+	 * If this ticket has already been purchased, just increments its count.
117
+	 * Automatically re-calculates the line item totals and updates the related transaction. But
118
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
119
+	 * should probably change because of this).
120
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
121
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
122
+	 *
123
+	 * @param EE_Line_Item $total_line_item grand total line item of type EEM_Line_Item::type_total
124
+	 * @param EE_Ticket $ticket
125
+	 * @param int $qty
126
+	 * @return \EE_Line_Item
127
+	 * @throws \EE_Error
128
+	 */
129
+	public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
130
+	{
131
+		if (!$total_line_item instanceof EE_Line_Item || !$total_line_item->is_total()) {
132
+			throw new EE_Error(sprintf(__('A valid line item total is required in order to add tickets. A line item of type "%s" was passed.', 'event_espresso'), $ticket->ID(), $total_line_item->ID()));
133
+		}
134
+		// either increment the qty for an existing ticket
135
+		$line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
136
+		// or add a new one
137
+		if (!$line_item instanceof EE_Line_Item) {
138
+			$line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
139
+		}
140
+		$total_line_item->recalculate_total_including_taxes();
141
+		return $line_item;
142
+	}
143
+
144
+
145
+	/**
146
+	 * Returns the new line item created by adding a purchase of the ticket
147
+	 * @param \EE_Line_Item $total_line_item
148
+	 * @param EE_Ticket $ticket
149
+	 * @param int $qty
150
+	 * @return \EE_Line_Item
151
+	 * @throws \EE_Error
152
+	 */
153
+	public static function increment_ticket_qty_if_already_in_cart(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
154
+	{
155
+		$line_item = null;
156
+		if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
157
+			$ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
158
+			foreach ((array)$ticket_line_items as $ticket_line_item) {
159
+				if (
160
+					$ticket_line_item instanceof EE_Line_Item
161
+					&& (int)$ticket_line_item->OBJ_ID() === (int)$ticket->ID()
162
+				) {
163
+					$line_item = $ticket_line_item;
164
+					break;
165
+				}
166
+			}
167
+		}
168
+		if ($line_item instanceof EE_Line_Item) {
169
+			EEH_Line_Item::increment_quantity($line_item, $qty);
170
+			return $line_item;
171
+		}
172
+		return null;
173
+	}
174
+
175
+
176
+	/**
177
+	 * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
178
+	 * Does NOT save or recalculate other line items totals
179
+	 *
180
+	 * @param EE_Line_Item $line_item
181
+	 * @param int $qty
182
+	 * @return void
183
+	 * @throws \EE_Error
184
+	 */
185
+	public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
186
+	{
187
+		if (!$line_item->is_percent()) {
188
+			$qty += $line_item->quantity();
189
+			$line_item->set_quantity($qty);
190
+			$line_item->set_total($line_item->unit_price() * $qty);
191
+			$line_item->save();
192
+		}
193
+		foreach ($line_item->children() as $child) {
194
+			if ($child->is_sub_line_item()) {
195
+				EEH_Line_Item::update_quantity($child, $qty);
196
+			}
197
+		}
198
+	}
199
+
200
+
201
+	/**
202
+	 * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
203
+	 * Does NOT save or recalculate other line items totals
204
+	 *
205
+	 * @param EE_Line_Item $line_item
206
+	 * @param int $qty
207
+	 * @return void
208
+	 * @throws \EE_Error
209
+	 */
210
+	public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
211
+	{
212
+		if (!$line_item->is_percent()) {
213
+			$qty = $line_item->quantity() - $qty;
214
+			$qty = max($qty, 0);
215
+			$line_item->set_quantity($qty);
216
+			$line_item->set_total($line_item->unit_price() * $qty);
217
+			$line_item->save();
218
+		}
219
+		foreach ($line_item->children() as $child) {
220
+			if ($child->is_sub_line_item()) {
221
+				EEH_Line_Item::update_quantity($child, $qty);
222
+			}
223
+		}
224
+	}
225
+
226
+
227
+	/**
228
+	 * Updates the line item and its children's quantities to the specified number.
229
+	 * Does NOT save them or recalculate totals.
230
+	 *
231
+	 * @param EE_Line_Item $line_item
232
+	 * @param int $new_quantity
233
+	 * @throws \EE_Error
234
+	 */
235
+	public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
236
+	{
237
+		if (!$line_item->is_percent()) {
238
+			$line_item->set_quantity($new_quantity);
239
+			$line_item->set_total($line_item->unit_price() * $new_quantity);
240
+			$line_item->save();
241
+		}
242
+		foreach ($line_item->children() as $child) {
243
+			if ($child->is_sub_line_item()) {
244
+				EEH_Line_Item::update_quantity($child, $new_quantity);
245
+			}
246
+		}
247
+	}
248
+
249
+
250
+	/**
251
+	 * Returns the new line item created by adding a purchase of the ticket
252
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
253
+	 * @param EE_Ticket $ticket
254
+	 * @param int $qty
255
+	 * @return \EE_Line_Item
256
+	 * @throws \EE_Error
257
+	 */
258
+	public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
259
+	{
260
+		$datetimes = $ticket->datetimes();
261
+		$first_datetime = reset($datetimes);
262
+		if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
263
+			$first_datetime_name = $first_datetime->event()->name();
264
+		} else {
265
+			$first_datetime_name = __('Event', 'event_espresso');
266
+		}
267
+		$event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
268
+		// get event subtotal line
269
+		$events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
270
+		// add $ticket to cart
271
+		$line_item = EE_Line_Item::new_instance(array(
272
+			'LIN_name' => $ticket->name(),
273
+			'LIN_desc' => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
274
+			'LIN_unit_price' => $ticket->price(),
275
+			'LIN_quantity' => $qty,
276
+			'LIN_is_taxable' => $ticket->taxable(),
277
+			'LIN_order' => count($events_sub_total->children()),
278
+			'LIN_total' => $ticket->price() * $qty,
279
+			'LIN_type' => EEM_Line_Item::type_line_item,
280
+			'OBJ_ID' => $ticket->ID(),
281
+			'OBJ_type' => 'Ticket'
282
+		));
283
+		$line_item = apply_filters(
284
+			'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
285
+			$line_item
286
+		);
287
+		$events_sub_total->add_child_line_item($line_item);
288
+		//now add the sub-line items
289
+		$running_total_for_ticket = 0;
290
+		foreach ($ticket->prices(array('order_by' => array('PRC_order' => 'ASC'))) as $price) {
291
+			$sign = $price->is_discount() ? -1 : 1;
292
+			$price_total = $price->is_percent()
293
+				? $running_total_for_ticket * $price->amount() / 100
294
+				: $price->amount() * $qty;
295
+			$sub_line_item = EE_Line_Item::new_instance(array(
296
+				'LIN_name' => $price->name(),
297
+				'LIN_desc' => $price->desc(),
298
+				'LIN_quantity' => $price->is_percent() ? null : $qty,
299
+				'LIN_is_taxable' => false,
300
+				'LIN_order' => $price->order(),
301
+				'LIN_total' => $sign * $price_total,
302
+				'LIN_type' => EEM_Line_Item::type_sub_line_item,
303
+				'OBJ_ID' => $price->ID(),
304
+				'OBJ_type' => 'Price'
305
+			));
306
+			$sub_line_item = apply_filters(
307
+				'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
308
+				$sub_line_item
309
+			);
310
+			if ($price->is_percent()) {
311
+				$sub_line_item->set_percent($sign * $price->amount());
312
+			} else {
313
+				$sub_line_item->set_unit_price($sign * $price->amount());
314
+			}
315
+			$running_total_for_ticket += $price_total;
316
+			$line_item->add_child_line_item($sub_line_item);
317
+		}
318
+		return $line_item;
319
+	}
320
+
321
+
322
+	/**
323
+	 * Adds the specified item under the pre-tax-sub-total line item. Automatically
324
+	 * re-calculates the line item totals and updates the related transaction. But
325
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
326
+	 * should probably change because of this).
327
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
328
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
329
+	 *
330
+	 * @param EE_Line_Item $total_line_item
331
+	 * @param EE_Line_Item $item to be added
332
+	 * @return boolean
333
+	 * @throws \EE_Error
334
+	 */
335
+	public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item)
336
+	{
337
+		$pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
338
+		if ($pre_tax_subtotal instanceof EE_Line_Item) {
339
+			$success = $pre_tax_subtotal->add_child_line_item($item);
340
+		} else {
341
+			return FALSE;
342
+		}
343
+		$total_line_item->recalculate_total_including_taxes();
344
+		return $success;
345
+	}
346
+
347
+
348
+	/**
349
+	 * cancels an existing ticket line item,
350
+	 * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
351
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
352
+	 *
353
+	 * @param EE_Line_Item $ticket_line_item
354
+	 * @param int $qty
355
+	 * @return bool success
356
+	 * @throws \EE_Error
357
+	 */
358
+	public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
359
+	{
360
+		// validate incoming line_item
361
+		if ($ticket_line_item->OBJ_type() !== 'Ticket') {
362
+			throw new EE_Error(
363
+				sprintf(
364
+					__('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
365
+					$ticket_line_item->type()
366
+				)
367
+			);
368
+		}
369
+		if ($ticket_line_item->quantity() < $qty) {
370
+			throw new EE_Error(
371
+				sprintf(
372
+					__('Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.', 'event_espresso'),
373
+					$qty,
374
+					$ticket_line_item->quantity()
375
+				)
376
+			);
377
+		}
378
+		// decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
379
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
380
+		foreach ($ticket_line_item->children() as $child_line_item) {
381
+			if (
382
+				$child_line_item->is_sub_line_item()
383
+				&& !$child_line_item->is_percent()
384
+				&& !$child_line_item->is_cancellation()
385
+			) {
386
+				$child_line_item->set_quantity($child_line_item->quantity() - $qty);
387
+			}
388
+		}
389
+		// get cancellation sub line item
390
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
391
+			$ticket_line_item,
392
+			EEM_Line_Item::type_cancellation
393
+		);
394
+		$cancellation_line_item = reset($cancellation_line_item);
395
+		// verify that this ticket was indeed previously cancelled
396
+		if ($cancellation_line_item instanceof EE_Line_Item) {
397
+			// increment cancelled quantity
398
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
399
+		} else {
400
+			// create cancellation sub line item
401
+			$cancellation_line_item = EE_Line_Item::new_instance(array(
402
+				'LIN_name' => __('Cancellation', 'event_espresso'),
403
+				'LIN_desc' => sprintf(
404
+					_x('Cancelled %1$s : %2$s', 'Cancelled Ticket Name : 2015-01-01 11:11', 'event_espresso'),
405
+					$ticket_line_item->name(),
406
+					current_time(get_option('date_format') . ' ' . get_option('time_format'))
407
+				),
408
+				'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
409
+				'LIN_quantity' => $qty,
410
+				'LIN_is_taxable' => $ticket_line_item->is_taxable(),
411
+				'LIN_order' => count($ticket_line_item->children()),
412
+				'LIN_total' => 0, // $ticket_line_item->unit_price()
413
+				'LIN_type' => EEM_Line_Item::type_cancellation,
414
+			));
415
+			$ticket_line_item->add_child_line_item($cancellation_line_item);
416
+		}
417
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
418
+			// decrement parent line item quantity
419
+			$event_line_item = $ticket_line_item->parent();
420
+			if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
421
+				$event_line_item->set_quantity($event_line_item->quantity() - $qty);
422
+				$event_line_item->save();
423
+			}
424
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
425
+			return true;
426
+		}
427
+		return false;
428
+	}
429
+
430
+
431
+	/**
432
+	 * reinstates (un-cancels?) a previously canceled ticket line item,
433
+	 * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
434
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
435
+	 *
436
+	 * @param EE_Line_Item $ticket_line_item
437
+	 * @param int $qty
438
+	 * @return bool success
439
+	 * @throws \EE_Error
440
+	 */
441
+	public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
442
+	{
443
+		// validate incoming line_item
444
+		if ($ticket_line_item->OBJ_type() !== 'Ticket') {
445
+			throw new EE_Error(
446
+				sprintf(
447
+					__('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
448
+					$ticket_line_item->type()
449
+				)
450
+			);
451
+		}
452
+		// get cancellation sub line item
453
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
454
+			$ticket_line_item,
455
+			EEM_Line_Item::type_cancellation
456
+		);
457
+		$cancellation_line_item = reset($cancellation_line_item);
458
+		// verify that this ticket was indeed previously cancelled
459
+		if (!$cancellation_line_item instanceof EE_Line_Item) {
460
+			return false;
461
+		}
462
+		if ($cancellation_line_item->quantity() > $qty) {
463
+			// decrement cancelled quantity
464
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
465
+		} else if ($cancellation_line_item->quantity() == $qty) {
466
+			// decrement cancelled quantity in case anyone still has the object kicking around
467
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
468
+			// delete because quantity will end up as 0
469
+			$cancellation_line_item->delete();
470
+			// and attempt to destroy the object,
471
+			// even though PHP won't actually destroy it until it needs the memory
472
+			unset($cancellation_line_item);
473
+		} else {
474
+			// what ?!?! negative quantity ?!?!
475
+			throw new EE_Error(
476
+				sprintf(
477
+					__('Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
478
+						'event_espresso'),
479
+					$qty,
480
+					$cancellation_line_item->quantity()
481
+				)
482
+			);
483
+		}
484
+		// increment ticket quantity
485
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
486
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
487
+			// increment parent line item quantity
488
+			$event_line_item = $ticket_line_item->parent();
489
+			if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
490
+				$event_line_item->set_quantity($event_line_item->quantity() + $qty);
491
+			}
492
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
493
+			return true;
494
+		}
495
+		return false;
496
+	}
497
+
498
+
499
+	/**
500
+	 * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
501
+	 * then EE_Line_Item::recalculate_total_including_taxes() on the result
502
+	 *
503
+	 * @param EE_Line_Item $line_item
504
+	 * @return \EE_Line_Item
505
+	 */
506
+	public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
507
+	{
508
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
509
+		return $grand_total_line_item->recalculate_total_including_taxes();
510
+	}
511
+
512
+
513
+	/**
514
+	 * Gets the line item which contains the subtotal of all the items
515
+	 *
516
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
517
+	 * @return \EE_Line_Item
518
+	 * @throws \EE_Error
519
+	 */
520
+	public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
521
+	{
522
+		$pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
523
+		return $pre_tax_subtotal instanceof EE_Line_Item
524
+			? $pre_tax_subtotal
525
+			: self::create_pre_tax_subtotal($total_line_item);
526
+	}
527
+
528
+
529
+	/**
530
+	 * Gets the line item for the taxes subtotal
531
+	 *
532
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
533
+	 * @return \EE_Line_Item
534
+	 * @throws \EE_Error
535
+	 */
536
+	public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
537
+	{
538
+		$taxes = $total_line_item->get_child_line_item('taxes');
539
+		return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
540
+	}
541
+
542
+
543
+	/**
544
+	 * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
545
+	 *
546
+	 * @param EE_Line_Item $line_item
547
+	 * @param EE_Transaction $transaction
548
+	 * @return void
549
+	 * @throws \EE_Error
550
+	 */
551
+	public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = NULL)
552
+	{
553
+		if ($transaction) {
554
+			/** @type EEM_Transaction $EEM_Transaction */
555
+			$EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
556
+			$TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
557
+			$line_item->set_TXN_ID($TXN_ID);
558
+		}
559
+	}
560
+
561
+
562
+	/**
563
+	 * Creates a new default total line item for the transaction,
564
+	 * and its tickets subtotal and taxes subtotal line items (and adds the
565
+	 * existing taxes as children of the taxes subtotal line item)
566
+	 *
567
+	 * @param EE_Transaction $transaction
568
+	 * @return \EE_Line_Item of type total
569
+	 * @throws \EE_Error
570
+	 */
571
+	public static function create_total_line_item($transaction = NULL)
572
+	{
573
+		$total_line_item = EE_Line_Item::new_instance(array(
574
+			'LIN_code' => 'total',
575
+			'LIN_name' => __('Grand Total', 'event_espresso'),
576
+			'LIN_type' => EEM_Line_Item::type_total,
577
+			'OBJ_type' => 'Transaction'
578
+		));
579
+		$total_line_item = apply_filters(
580
+			'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
581
+			$total_line_item
582
+		);
583
+		self::set_TXN_ID($total_line_item, $transaction);
584
+		self::create_pre_tax_subtotal($total_line_item, $transaction);
585
+		self::create_taxes_subtotal($total_line_item, $transaction);
586
+		return $total_line_item;
587
+	}
588
+
589
+
590
+	/**
591
+	 * Creates a default items subtotal line item
592
+	 *
593
+	 * @param EE_Line_Item $total_line_item
594
+	 * @param EE_Transaction $transaction
595
+	 * @return EE_Line_Item
596
+	 * @throws \EE_Error
597
+	 */
598
+	protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
599
+	{
600
+		$pre_tax_line_item = EE_Line_Item::new_instance(array(
601
+			'LIN_code' => 'pre-tax-subtotal',
602
+			'LIN_name' => __('Pre-Tax Subtotal', 'event_espresso'),
603
+			'LIN_type' => EEM_Line_Item::type_sub_total
604
+		));
605
+		$pre_tax_line_item = apply_filters(
606
+			'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
607
+			$pre_tax_line_item
608
+		);
609
+		self::set_TXN_ID($pre_tax_line_item, $transaction);
610
+		$total_line_item->add_child_line_item($pre_tax_line_item);
611
+		self::create_event_subtotal($pre_tax_line_item, $transaction);
612
+		return $pre_tax_line_item;
613
+	}
614
+
615
+
616
+	/**
617
+	 * Creates a line item for the taxes subtotal and finds all the tax prices
618
+	 * and applies taxes to it
619
+	 *
620
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
621
+	 * @param EE_Transaction $transaction
622
+	 * @return EE_Line_Item
623
+	 * @throws \EE_Error
624
+	 */
625
+	protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
626
+	{
627
+		$tax_line_item = EE_Line_Item::new_instance(array(
628
+			'LIN_code' => 'taxes',
629
+			'LIN_name' => __('Taxes', 'event_espresso'),
630
+			'LIN_type' => EEM_Line_Item::type_tax_sub_total,
631
+			'LIN_order' => 1000,//this should always come last
632
+		));
633
+		$tax_line_item = apply_filters(
634
+			'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
635
+			$tax_line_item
636
+		);
637
+		self::set_TXN_ID($tax_line_item, $transaction);
638
+		$total_line_item->add_child_line_item($tax_line_item);
639
+		//and lastly, add the actual taxes
640
+		self::apply_taxes($total_line_item);
641
+		return $tax_line_item;
642
+	}
643
+
644
+
645
+	/**
646
+	 * Creates a default items subtotal line item
647
+	 *
648
+	 * @param EE_Line_Item $pre_tax_line_item
649
+	 * @param EE_Transaction $transaction
650
+	 * @param EE_Event $event
651
+	 * @return EE_Line_Item
652
+	 * @throws \EE_Error
653
+	 */
654
+	public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = NULL, $event = NULL)
655
+	{
656
+		$event_line_item = EE_Line_Item::new_instance(array(
657
+			'LIN_code' => self::get_event_code($event),
658
+			'LIN_name' => self::get_event_name($event),
659
+			'LIN_desc' => self::get_event_desc($event),
660
+			'LIN_type' => EEM_Line_Item::type_sub_total,
661
+			'OBJ_type' => 'Event',
662
+			'OBJ_ID' => $event instanceof EE_Event ? $event->ID() : 0
663
+		));
664
+		$event_line_item = apply_filters(
665
+			'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
666
+			$event_line_item
667
+		);
668
+		self::set_TXN_ID($event_line_item, $transaction);
669
+		$pre_tax_line_item->add_child_line_item($event_line_item);
670
+		return $event_line_item;
671
+	}
672
+
673
+
674
+	/**
675
+	 * Gets what the event ticket's code SHOULD be
676
+	 *
677
+	 * @param EE_Event $event
678
+	 * @return string
679
+	 * @throws \EE_Error
680
+	 */
681
+	public static function get_event_code($event)
682
+	{
683
+		return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
684
+	}
685
+
686
+	/**
687
+	 * Gets the event name
688
+	 * @param EE_Event $event
689
+	 * @return string
690
+	 */
691
+	public static function get_event_name($event)
692
+	{
693
+		return $event instanceof EE_Event ? $event->name() : __('Event', 'event_espresso');
694
+	}
695
+
696
+	/**
697
+	 * Gets the event excerpt
698
+	 * @param EE_Event $event
699
+	 * @return string
700
+	 */
701
+	public static function get_event_desc($event)
702
+	{
703
+		return $event instanceof EE_Event ? $event->short_description() : '';
704
+	}
705
+
706
+	/**
707
+	 * Given the grand total line item and a ticket, finds the event sub-total
708
+	 * line item the ticket's purchase should be added onto
709
+	 *
710
+	 * @access public
711
+	 * @param EE_Line_Item $grand_total the grand total line item
712
+	 * @param EE_Ticket $ticket
713
+	 * @throws \EE_Error
714
+	 * @return EE_Line_Item
715
+	 */
716
+	public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
717
+	{
718
+		$first_datetime = $ticket->first_datetime();
719
+		if (!$first_datetime instanceof EE_Datetime) {
720
+			throw new EE_Error(
721
+				sprintf(__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'), $ticket->ID())
722
+			);
723
+		}
724
+		$event = $first_datetime->event();
725
+		if (!$event instanceof EE_Event) {
726
+			throw new EE_Error(
727
+				sprintf(
728
+					__('The supplied ticket (ID %d) has no event data associated with it.', 'event_espresso'),
729
+					$ticket->ID()
730
+				)
731
+			);
732
+		}
733
+		$events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
734
+		if (!$events_sub_total instanceof EE_Line_Item) {
735
+			throw new EE_Error(
736
+				sprintf(
737
+					__('There is no events sub-total for ticket %s on total line item %d', 'event_espresso'),
738
+					$ticket->ID(),
739
+					$grand_total->ID()
740
+				)
741
+			);
742
+		}
743
+		return $events_sub_total;
744
+	}
745
+
746
+
747
+	/**
748
+	 * Gets the event line item
749
+	 *
750
+	 * @param EE_Line_Item $grand_total
751
+	 * @param EE_Event $event
752
+	 * @return EE_Line_Item for the event subtotal which is a child of $grand_total
753
+	 * @throws \EE_Error
754
+	 */
755
+	public static function get_event_line_item(EE_Line_Item $grand_total, $event)
756
+	{
757
+		/** @type EE_Event $event */
758
+		$event = EEM_Event::instance()->ensure_is_obj($event, true);
759
+		$event_line_item = NULL;
760
+		$found = false;
761
+		foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
762
+			// default event subtotal, we should only ever find this the first time this method is called
763
+			if (!$event_line_item->OBJ_ID()) {
764
+				// let's use this! but first... set the event details
765
+				EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
766
+				$found = true;
767
+				break;
768
+			} else if ($event_line_item->OBJ_ID() === $event->ID()) {
769
+				// found existing line item for this event in the cart, so break out of loop and use this one
770
+				$found = true;
771
+				break;
772
+			}
773
+		}
774
+		if (!$found) {
775
+			//there is no event sub-total yet, so add it
776
+			$pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
777
+			// create a new "event" subtotal below that
778
+			$event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
779
+			// and set the event details
780
+			EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
781
+		}
782
+		return $event_line_item;
783
+	}
784
+
785
+
786
+	/**
787
+	 * Creates a default items subtotal line item
788
+	 *
789
+	 * @param EE_Line_Item $event_line_item
790
+	 * @param EE_Event $event
791
+	 * @param EE_Transaction $transaction
792
+	 * @return EE_Line_Item
793
+	 * @throws \EE_Error
794
+	 */
795
+	public static function set_event_subtotal_details(
796
+		EE_Line_Item $event_line_item,
797
+		EE_Event $event,
798
+		$transaction = null
799
+	)
800
+	{
801
+		if ($event instanceof EE_Event) {
802
+			$event_line_item->set_code(self::get_event_code($event));
803
+			$event_line_item->set_name(self::get_event_name($event));
804
+			$event_line_item->set_desc(self::get_event_desc($event));
805
+			$event_line_item->set_OBJ_ID($event->ID());
806
+		}
807
+		self::set_TXN_ID($event_line_item, $transaction);
808
+	}
809
+
810
+
811
+	/**
812
+	 * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
813
+	 * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
814
+	 * any old taxes are removed
815
+	 *
816
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
817
+	 * @throws \EE_Error
818
+	 */
819
+	public static function apply_taxes(EE_Line_Item $total_line_item)
820
+	{
821
+		/** @type EEM_Price $EEM_Price */
822
+		$EEM_Price = EE_Registry::instance()->load_model('Price');
823
+		// get array of taxes via Price Model
824
+		$ordered_taxes = $EEM_Price->get_all_prices_that_are_taxes();
825
+		ksort($ordered_taxes);
826
+		$taxes_line_item = self::get_taxes_subtotal($total_line_item);
827
+		//just to be safe, remove its old tax line items
828
+		$taxes_line_item->delete_children_line_items();
829
+		//loop thru taxes
830
+		foreach ($ordered_taxes as $order => $taxes) {
831
+			foreach ($taxes as $tax) {
832
+				if ($tax instanceof EE_Price) {
833
+					$tax_line_item = EE_Line_Item::new_instance(
834
+						array(
835
+							'LIN_name' => $tax->name(),
836
+							'LIN_desc' => $tax->desc(),
837
+							'LIN_percent' => $tax->amount(),
838
+							'LIN_is_taxable' => false,
839
+							'LIN_order' => $order,
840
+							'LIN_total' => 0,
841
+							'LIN_type' => EEM_Line_Item::type_tax,
842
+							'OBJ_type' => 'Price',
843
+							'OBJ_ID' => $tax->ID()
844
+						)
845
+					);
846
+					$tax_line_item = apply_filters(
847
+						'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
848
+						$tax_line_item
849
+					);
850
+					$taxes_line_item->add_child_line_item($tax_line_item);
851
+				}
852
+			}
853
+		}
854
+		$total_line_item->recalculate_total_including_taxes();
855
+	}
856
+
857
+
858
+	/**
859
+	 * Ensures that taxes have been applied to the order, if not applies them.
860
+	 * Returns the total amount of tax
861
+	 *
862
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
863
+	 * @return float
864
+	 * @throws \EE_Error
865
+	 */
866
+	public static function ensure_taxes_applied($total_line_item)
867
+	{
868
+		$taxes_subtotal = self::get_taxes_subtotal($total_line_item);
869
+		if (!$taxes_subtotal->children()) {
870
+			self::apply_taxes($total_line_item);
871
+		}
872
+		return $taxes_subtotal->total();
873
+	}
874
+
875
+
876
+	/**
877
+	 * Deletes ALL children of the passed line item
878
+	 *
879
+	 * @param EE_Line_Item $parent_line_item
880
+	 * @return bool
881
+	 * @throws \EE_Error
882
+	 */
883
+	public static function delete_all_child_items(EE_Line_Item $parent_line_item)
884
+	{
885
+		$deleted = 0;
886
+		foreach ($parent_line_item->children() as $child_line_item) {
887
+			if ($child_line_item instanceof EE_Line_Item) {
888
+				$deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
889
+				if ($child_line_item->ID()) {
890
+					$child_line_item->delete();
891
+					unset($child_line_item);
892
+				} else {
893
+					$parent_line_item->delete_child_line_item($child_line_item->code());
894
+				}
895
+				$deleted++;
896
+			}
897
+		}
898
+		return $deleted;
899
+	}
900
+
901
+
902
+	/**
903
+	 * Deletes the line items as indicated by the line item code(s) provided,
904
+	 * regardless of where they're found in the line item tree. Automatically
905
+	 * re-calculates the line item totals and updates the related transaction. But
906
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
907
+	 * should probably change because of this).
908
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
909
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
910
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
911
+	 * @param array|bool|string $line_item_codes
912
+	 * @return int number of items successfully removed
913
+	 */
914
+	public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = FALSE)
915
+	{
916
+
917
+		if ($total_line_item->type() !== EEM_Line_Item::type_total) {
918
+			EE_Error::doing_it_wrong(
919
+				'EEH_Line_Item::delete_items',
920
+				__(
921
+					'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
922
+					'event_espresso'
923
+				),
924
+				'4.6.18'
925
+			);
926
+		}
927
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
928
+
929
+		// check if only a single line_item_id was passed
930
+		if (!empty($line_item_codes) && !is_array($line_item_codes)) {
931
+			// place single line_item_id in an array to appear as multiple line_item_ids
932
+			$line_item_codes = array($line_item_codes);
933
+		}
934
+		$removals = 0;
935
+		// cycle thru line_item_ids
936
+		foreach ($line_item_codes as $line_item_id) {
937
+			$removals += $total_line_item->delete_child_line_item($line_item_id);
938
+		}
939
+
940
+		if ($removals > 0) {
941
+			$total_line_item->recalculate_taxes_and_tax_total();
942
+			return $removals;
943
+		} else {
944
+			return FALSE;
945
+		}
946
+	}
947
+
948
+
949
+	/**
950
+	 * Overwrites the previous tax by clearing out the old taxes, and creates a new
951
+	 * tax and updates the total line item accordingly
952
+	 *
953
+	 * @param EE_Line_Item $total_line_item
954
+	 * @param float $amount
955
+	 * @param string $name
956
+	 * @param string $description
957
+	 * @param string $code
958
+	 * @param boolean $add_to_existing_line_item
959
+	 *                          if true, and a duplicate line item with the same code is found,
960
+	 *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
961
+	 * @return EE_Line_Item the new tax line item created
962
+	 * @throws \EE_Error
963
+	 */
964
+	public static function set_total_tax_to(
965
+		EE_Line_Item $total_line_item,
966
+		$amount,
967
+		$name = null,
968
+		$description = null,
969
+		$code = null,
970
+		$add_to_existing_line_item = false
971
+	)
972
+	{
973
+		$tax_subtotal = self::get_taxes_subtotal($total_line_item);
974
+		$taxable_total = $total_line_item->taxable_total();
975
+
976
+		if ($add_to_existing_line_item) {
977
+			$new_tax = $tax_subtotal->get_child_line_item($code);
978
+			EEM_Line_Item::instance()->delete(
979
+				array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
980
+			);
981
+		} else {
982
+			$new_tax = null;
983
+			$tax_subtotal->delete_children_line_items();
984
+		}
985
+		if ($new_tax) {
986
+			$new_tax->set_total($new_tax->total() + $amount);
987
+			$new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
988
+		} else {
989
+			//no existing tax item. Create it
990
+			$new_tax = EE_Line_Item::new_instance(array(
991
+				'TXN_ID' => $total_line_item->TXN_ID(),
992
+				'LIN_name' => $name ? $name : __('Tax', 'event_espresso'),
993
+				'LIN_desc' => $description ? $description : '',
994
+				'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
995
+				'LIN_total' => $amount,
996
+				'LIN_parent' => $tax_subtotal->ID(),
997
+				'LIN_type' => EEM_Line_Item::type_tax,
998
+				'LIN_code' => $code
999
+			));
1000
+		}
1001
+
1002
+		$new_tax = apply_filters(
1003
+			'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1004
+			$new_tax,
1005
+			$total_line_item
1006
+		);
1007
+		$new_tax->save();
1008
+		$tax_subtotal->set_total($new_tax->total());
1009
+		$tax_subtotal->save();
1010
+		$total_line_item->recalculate_total_including_taxes();
1011
+		return $new_tax;
1012
+	}
1013
+
1014
+
1015
+	/**
1016
+	 * Makes all the line items which are children of $line_item taxable (or not).
1017
+	 * Does NOT save the line items
1018
+	 * @param EE_Line_Item $line_item
1019
+	 * @param string $code_substring_for_whitelist if this string is part of the line item's code
1020
+	 *  it will be whitelisted (ie, except from becoming taxable)
1021
+	 * @param boolean $taxable
1022
+	 */
1023
+	public static function set_line_items_taxable(
1024
+		EE_Line_Item $line_item,
1025
+		$taxable = true,
1026
+		$code_substring_for_whitelist = null
1027
+	)
1028
+	{
1029
+		$whitelisted = false;
1030
+		if ($code_substring_for_whitelist !== null) {
1031
+			$whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false ? true : false;
1032
+		}
1033
+		if (!$whitelisted && $line_item->is_line_item()) {
1034
+			$line_item->set_is_taxable($taxable);
1035
+		}
1036
+		foreach ($line_item->children() as $child_line_item) {
1037
+			EEH_Line_Item::set_line_items_taxable($child_line_item, $taxable, $code_substring_for_whitelist);
1038
+		}
1039
+	}
1040
+
1041
+
1042
+	/**
1043
+	 * Gets all descendants that are event subtotals
1044
+	 *
1045
+	 * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1046
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1047
+	 * @return EE_Line_Item[]
1048
+	 */
1049
+	public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1050
+	{
1051
+		return self::get_subtotals_of_object_type($parent_line_item, 'Event');
1052
+	}
1053
+
1054
+
1055
+	/**
1056
+	 * Gets all descendants subtotals that match the supplied object type
1057
+	 *
1058
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1059
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1060
+	 * @param string $obj_type
1061
+	 * @return EE_Line_Item[]
1062
+	 */
1063
+	public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1064
+	{
1065
+		return self::_get_descendants_by_type_and_object_type(
1066
+			$parent_line_item,
1067
+			EEM_Line_Item::type_sub_total,
1068
+			$obj_type
1069
+		);
1070
+	}
1071
+
1072
+
1073
+	/**
1074
+	 * Gets all descendants that are tickets
1075
+	 *
1076
+	 * @uses  EEH_Line_Item::get_line_items_of_object_type()
1077
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1078
+	 * @return EE_Line_Item[]
1079
+	 */
1080
+	public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1081
+	{
1082
+		return self::get_line_items_of_object_type($parent_line_item, 'Ticket');
1083
+	}
1084
+
1085
+
1086
+	/**
1087
+	 * Gets all descendants subtotals that match the supplied object type
1088
+	 *
1089
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1090
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1091
+	 * @param string $obj_type
1092
+	 * @return EE_Line_Item[]
1093
+	 */
1094
+	public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1095
+	{
1096
+		return self::_get_descendants_by_type_and_object_type($parent_line_item, EEM_Line_Item::type_line_item, $obj_type);
1097
+	}
1098
+
1099
+
1100
+	/**
1101
+	 * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1102
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1103
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1104
+	 * @return EE_Line_Item[]
1105
+	 */
1106
+	public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1107
+	{
1108
+		return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_tax);
1109
+	}
1110
+
1111
+
1112
+	/**
1113
+	 * Gets all the real items purchased which are children of this item
1114
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1115
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1116
+	 * @return EE_Line_Item[]
1117
+	 */
1118
+	public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1119
+	{
1120
+		return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_line_item);
1121
+	}
1122
+
1123
+
1124
+	/**
1125
+	 * Gets all descendants of supplied line item that match the supplied line item type
1126
+	 *
1127
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1128
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1129
+	 * @param string $line_item_type one of the EEM_Line_Item constants
1130
+	 * @return EE_Line_Item[]
1131
+	 */
1132
+	public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1133
+	{
1134
+		return self::_get_descendants_by_type_and_object_type($parent_line_item, $line_item_type, NULL);
1135
+	}
1136
+
1137
+
1138
+	/**
1139
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1140
+	 *
1141
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1142
+	 * @param string $line_item_type one of the EEM_Line_Item constants
1143
+	 * @param string | NULL $obj_type object model class name (minus prefix) or NULL to ignore object type when searching
1144
+	 * @return EE_Line_Item[]
1145
+	 */
1146
+	protected static function _get_descendants_by_type_and_object_type(
1147
+		EE_Line_Item $parent_line_item,
1148
+		$line_item_type,
1149
+		$obj_type = null
1150
+	)
1151
+	{
1152
+		$objects = array();
1153
+		foreach ($parent_line_item->children() as $child_line_item) {
1154
+			if ($child_line_item instanceof EE_Line_Item) {
1155
+				if (
1156
+					$child_line_item->type() === $line_item_type
1157
+					&& (
1158
+						$child_line_item->OBJ_type() === $obj_type || $obj_type === null
1159
+					)
1160
+				) {
1161
+					$objects[] = $child_line_item;
1162
+				} else {
1163
+					//go-through-all-its children looking for more matches
1164
+					$objects = array_merge(
1165
+						$objects,
1166
+						self::_get_descendants_by_type_and_object_type(
1167
+							$child_line_item,
1168
+							$line_item_type,
1169
+							$obj_type
1170
+						)
1171
+					);
1172
+				}
1173
+			}
1174
+		}
1175
+		return $objects;
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * Gets all descendants subtotals that match the supplied object type
1181
+	 *
1182
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1183
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1184
+	 * @param string $OBJ_type object type (like Event)
1185
+	 * @param array $OBJ_IDs array of OBJ_IDs
1186
+	 * @return EE_Line_Item[]
1187
+	 */
1188
+	public static function get_line_items_by_object_type_and_IDs(
1189
+		EE_Line_Item $parent_line_item,
1190
+		$OBJ_type = '',
1191
+		$OBJ_IDs = array()
1192
+	)
1193
+	{
1194
+		return self::_get_descendants_by_object_type_and_object_ID($parent_line_item, $OBJ_type, $OBJ_IDs);
1195
+	}
1196
+
1197
+
1198
+	/**
1199
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1200
+	 *
1201
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1202
+	 * @param string $OBJ_type object type (like Event)
1203
+	 * @param array $OBJ_IDs array of OBJ_IDs
1204
+	 * @return EE_Line_Item[]
1205
+	 */
1206
+	protected static function _get_descendants_by_object_type_and_object_ID(
1207
+		EE_Line_Item $parent_line_item,
1208
+		$OBJ_type,
1209
+		$OBJ_IDs
1210
+	)
1211
+	{
1212
+		$objects = array();
1213
+		foreach ($parent_line_item->children() as $child_line_item) {
1214
+			if ($child_line_item instanceof EE_Line_Item) {
1215
+				if (
1216
+					$child_line_item->OBJ_type() === $OBJ_type
1217
+					&& is_array($OBJ_IDs)
1218
+					&& in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1219
+				) {
1220
+					$objects[] = $child_line_item;
1221
+				} else {
1222
+					//go-through-all-its children looking for more matches
1223
+					$objects = array_merge(
1224
+						$objects,
1225
+						self::_get_descendants_by_object_type_and_object_ID(
1226
+							$child_line_item,
1227
+							$OBJ_type,
1228
+							$OBJ_IDs
1229
+						)
1230
+					);
1231
+				}
1232
+			}
1233
+		}
1234
+		return $objects;
1235
+	}
1236
+
1237
+
1238
+	/**
1239
+	 * Uses a breadth-first-search in order to find the nearest descendant of
1240
+	 * the specified type and returns it, else NULL
1241
+	 *
1242
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1243
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1244
+	 * @param string $type like one of the EEM_Line_Item::type_*
1245
+	 * @return EE_Line_Item
1246
+	 */
1247
+	public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1248
+	{
1249
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1250
+	}
1251
+
1252
+
1253
+	/**
1254
+	 * Uses a breadth-first-search in order to find the nearest descendant
1255
+	 * having the specified LIN_code and returns it, else NULL
1256
+	 *
1257
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1258
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1259
+	 * @param string $code any value used for LIN_code
1260
+	 * @return EE_Line_Item
1261
+	 */
1262
+	public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1263
+	{
1264
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1265
+	}
1266
+
1267
+
1268
+	/**
1269
+	 * Uses a breadth-first-search in order to find the nearest descendant
1270
+	 * having the specified LIN_code and returns it, else NULL
1271
+	 *
1272
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1273
+	 * @param string $search_field name of EE_Line_Item property
1274
+	 * @param string $value any value stored in $search_field
1275
+	 * @return EE_Line_Item
1276
+	 */
1277
+	protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1278
+	{
1279
+		foreach ($parent_line_item->children() as $child) {
1280
+			if ($child->get($search_field) == $value) {
1281
+				return $child;
1282
+			}
1283
+		}
1284
+		foreach ($parent_line_item->children() as $child) {
1285
+			$descendant_found = self::_get_nearest_descendant($child, $search_field, $value);
1286
+			if ($descendant_found) {
1287
+				return $descendant_found;
1288
+			}
1289
+		}
1290
+		return NULL;
1291
+	}
1292
+
1293
+
1294
+	/**
1295
+	 * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1296
+	 * else recursively walks up the line item tree until a parent of type total is found,
1297
+	 *
1298
+	 * @param EE_Line_Item $line_item
1299
+	 * @return \EE_Line_Item
1300
+	 * @throws \EE_Error
1301
+	 */
1302
+	public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item)
1303
+	{
1304
+		if ($line_item->TXN_ID()) {
1305
+			$total_line_item = $line_item->transaction()->total_line_item(false);
1306
+			if ($total_line_item instanceof EE_Line_Item) {
1307
+				return $total_line_item;
1308
+			}
1309
+		} else {
1310
+			$line_item_parent = $line_item->parent();
1311
+			if ($line_item_parent instanceof EE_Line_Item) {
1312
+				if ($line_item_parent->is_total()) {
1313
+					return $line_item_parent;
1314
+				}
1315
+				return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1316
+			}
1317
+		}
1318
+		throw new EE_Error(
1319
+			sprintf(
1320
+				__('A valid grand total for line item %1$d was not found.', 'event_espresso'),
1321
+				$line_item->ID()
1322
+			)
1323
+		);
1324
+	}
1325
+
1326
+
1327
+	/**
1328
+	 * Prints out a representation of the line item tree
1329
+	 *
1330
+	 * @param EE_Line_Item $line_item
1331
+	 * @param int $indentation
1332
+	 * @return void
1333
+	 * @throws \EE_Error
1334
+	 */
1335
+	public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1336
+	{
1337
+		echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1338
+		if (!$indentation) {
1339
+			echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1340
+		}
1341
+		for ($i = 0; $i < $indentation; $i++) {
1342
+			echo ". ";
1343
+		}
1344
+		$breakdown = '';
1345
+		if ($line_item->is_line_item()) {
1346
+			if ($line_item->is_percent()) {
1347
+				$breakdown = "{$line_item->percent()}%";
1348
+			} else {
1349
+				$breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1350
+			}
1351
+		}
1352
+		echo $line_item->name() . " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : " . '$' . "{$line_item->total()}";
1353
+		if ($breakdown) {
1354
+			echo " ( {$breakdown} )";
1355
+		}
1356
+		if ($line_item->is_taxable()) {
1357
+			echo "  * taxable";
1358
+		}
1359
+		if ($line_item->children()) {
1360
+			foreach ($line_item->children() as $child) {
1361
+				self::visualize($child, $indentation + 1);
1362
+			}
1363
+		}
1364
+	}
1365
+
1366
+
1367
+	/**
1368
+	 * Calculates the registration's final price, taking into account that they
1369
+	 * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1370
+	 * and receive a portion of any transaction-wide discounts.
1371
+	 * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1372
+	 * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1373
+	 * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1374
+	 * and brent's final price should be $5.50.
1375
+	 *
1376
+	 * In order to do this, we basically need to traverse the line item tree calculating
1377
+	 * the running totals (just as if we were recalculating the total), but when we identify
1378
+	 * regular line items, we need to keep track of their share of the grand total.
1379
+	 * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1380
+	 * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1381
+	 * when there are non-taxable items; otherwise they would be the same)
1382
+	 *
1383
+	 * @param EE_Line_Item $line_item
1384
+	 * @param array $billable_ticket_quantities array of EE_Ticket IDs and their corresponding quantity that
1385
+	 *                                                                            can be included in price calculations at this moment
1386
+	 * @return array        keys are line items for tickets IDs and values are their share of the running total,
1387
+	 *                                          plus the key 'total', and 'taxable' which also has keys of all the ticket IDs. Eg
1388
+	 *                                          array(
1389
+	 *                                          12 => 4.3
1390
+	 *                                          23 => 8.0
1391
+	 *                                          'total' => 16.6,
1392
+	 *                                          'taxable' => array(
1393
+	 *                                          12 => 10,
1394
+	 *                                          23 => 4
1395
+	 *                                          ).
1396
+	 *                                          So to find which registrations have which final price, we need to find which line item
1397
+	 *                                          is theirs, which can be done with
1398
+	 *                                          `EEM_Line_Item::instance()->get_line_item_for_registration( $registration );`
1399
+	 */
1400
+	public static function calculate_reg_final_prices_per_line_item(EE_Line_Item $line_item, $billable_ticket_quantities = array())
1401
+	{
1402
+		//init running grand total if not already
1403
+		if (!isset($running_totals['total'])) {
1404
+			$running_totals['total'] = 0;
1405
+		}
1406
+		if (!isset($running_totals['taxable'])) {
1407
+			$running_totals['taxable'] = array('total' => 0);
1408
+		}
1409
+		foreach ($line_item->children() as $child_line_item) {
1410
+			switch ($child_line_item->type()) {
1411
+
1412
+				case EEM_Line_Item::type_sub_total :
1413
+					$running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item($child_line_item, $billable_ticket_quantities);
1414
+					//combine arrays but preserve numeric keys
1415
+					$running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1416
+					$running_totals['total'] += $running_totals_from_subtotal['total'];
1417
+					$running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1418
+					break;
1419
+
1420
+				case EEM_Line_Item::type_tax_sub_total :
1421
+
1422
+					//find how much the taxes percentage is
1423
+					if ($child_line_item->percent() !== 0) {
1424
+						$tax_percent_decimal = $child_line_item->percent() / 100;
1425
+					} else {
1426
+						$tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1427
+					}
1428
+					//and apply to all the taxable totals, and add to the pretax totals
1429
+					foreach ($running_totals as $line_item_id => $this_running_total) {
1430
+						//"total" and "taxable" array key is an exception
1431
+						if ($line_item_id === 'taxable') {
1432
+							continue;
1433
+						}
1434
+						$taxable_total = $running_totals['taxable'][$line_item_id];
1435
+						$running_totals[$line_item_id] += ($taxable_total * $tax_percent_decimal);
1436
+					}
1437
+					break;
1438
+
1439
+				case EEM_Line_Item::type_line_item :
1440
+
1441
+					// ticket line items or ????
1442
+					if ($child_line_item->OBJ_type() === 'Ticket') {
1443
+						// kk it's a ticket
1444
+						if (isset($running_totals[$child_line_item->ID()])) {
1445
+							//huh? that shouldn't happen.
1446
+							$running_totals['total'] += $child_line_item->total();
1447
+						} else {
1448
+							//its not in our running totals yet. great.
1449
+							if ($child_line_item->is_taxable()) {
1450
+								$taxable_amount = $child_line_item->unit_price();
1451
+							} else {
1452
+								$taxable_amount = 0;
1453
+							}
1454
+							// are we only calculating totals for some tickets?
1455
+							if (isset($billable_ticket_quantities[$child_line_item->OBJ_ID()])) {
1456
+								$quantity = $billable_ticket_quantities[$child_line_item->OBJ_ID()];
1457
+								$running_totals[$child_line_item->ID()] = $quantity
1458
+									? $child_line_item->unit_price()
1459
+									: 0;
1460
+								$running_totals['taxable'][$child_line_item->ID()] = $quantity
1461
+									? $taxable_amount
1462
+									: 0;
1463
+							} else {
1464
+								$quantity = $child_line_item->quantity();
1465
+								$running_totals[$child_line_item->ID()] = $child_line_item->unit_price();
1466
+								$running_totals['taxable'][$child_line_item->ID()] = $taxable_amount;
1467
+							}
1468
+							$running_totals['taxable']['total'] += $taxable_amount * $quantity;
1469
+							$running_totals['total'] += $child_line_item->unit_price() * $quantity;
1470
+						}
1471
+					} else {
1472
+						// it's some other type of item added to the cart
1473
+						// it should affect the running totals
1474
+						// basically we want to convert it into a PERCENT modifier. Because
1475
+						// more clearly affect all registration's final price equally
1476
+						$line_items_percent_of_running_total = $running_totals['total'] > 0
1477
+							? ($child_line_item->total() / $running_totals['total']) + 1
1478
+							: 1;
1479
+						foreach ($running_totals as $line_item_id => $this_running_total) {
1480
+							//the "taxable" array key is an exception
1481
+							if ($line_item_id === 'taxable') {
1482
+								continue;
1483
+							}
1484
+							// update the running totals
1485
+							// yes this actually even works for the running grand total!
1486
+							$running_totals[$line_item_id] =
1487
+								$line_items_percent_of_running_total * $this_running_total;
1488
+
1489
+							if ($child_line_item->is_taxable()) {
1490
+								$running_totals['taxable'][$line_item_id] =
1491
+									$line_items_percent_of_running_total * $running_totals['taxable'][$line_item_id];
1492
+							}
1493
+						}
1494
+					}
1495
+					break;
1496
+			}
1497
+		}
1498
+		return $running_totals;
1499
+	}
1500
+
1501
+
1502
+	/**
1503
+	 * @param \EE_Line_Item $total_line_item
1504
+	 * @param \EE_Line_Item $ticket_line_item
1505
+	 * @return float | null
1506
+	 * @throws \OutOfRangeException
1507
+	 */
1508
+	public static function calculate_final_price_for_ticket_line_item(\EE_Line_Item $total_line_item, \EE_Line_Item $ticket_line_item)
1509
+	{
1510
+		static $final_prices_per_ticket_line_item = array();
1511
+		if (empty($final_prices_per_ticket_line_item)) {
1512
+			$final_prices_per_ticket_line_item = \EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1513
+				$total_line_item
1514
+			);
1515
+		}
1516
+		//ok now find this new registration's final price
1517
+		if (isset($final_prices_per_ticket_line_item[$ticket_line_item->ID()])) {
1518
+			return $final_prices_per_ticket_line_item[$ticket_line_item->ID()];
1519
+		}
1520
+		$message = sprintf(
1521
+			__(
1522
+				'The final price for the ticket line item (ID:%1$d) could not be calculated.',
1523
+				'event_espresso'
1524
+			),
1525
+			$ticket_line_item->ID()
1526
+		);
1527
+		if (WP_DEBUG) {
1528
+			$message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1529
+			throw new \OutOfRangeException($message);
1530
+		} else {
1531
+			EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1532
+		}
1533
+		return null;
1534
+	}
1535
+
1536
+
1537
+	/**
1538
+	 * Creates a duplicate of the line item tree, except only includes billable items
1539
+	 * and the portion of line items attributed to billable things
1540
+	 *
1541
+	 * @param EE_Line_Item $line_item
1542
+	 * @param EE_Registration[] $registrations
1543
+	 * @return \EE_Line_Item
1544
+	 * @throws \EE_Error
1545
+	 */
1546
+	public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1547
+	{
1548
+		$copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1549
+		foreach ($line_item->children() as $child_li) {
1550
+			$copy_li->add_child_line_item(EEH_Line_Item::billable_line_item_tree($child_li, $registrations));
1551
+		}
1552
+		//if this is the grand total line item, make sure the totals all add up
1553
+		//(we could have duplicated this logic AS we copied the line items, but
1554
+		//it seems DRYer this way)
1555
+		if ($copy_li->type() === EEM_Line_Item::type_total) {
1556
+			$copy_li->recalculate_total_including_taxes();
1557
+		}
1558
+		return $copy_li;
1559
+	}
1560
+
1561
+
1562
+	/**
1563
+	 * Creates a new, unsaved line item from $line_item that factors in the
1564
+	 * number of billable registrations on $registrations.
1565
+	 *
1566
+	 * @param EE_Line_Item $line_item
1567
+	 * @return EE_Line_Item
1568
+	 * @throws \EE_Error
1569
+	 * @param EE_Registration[] $registrations
1570
+	 */
1571
+	public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1572
+	{
1573
+		$new_li_fields = $line_item->model_field_array();
1574
+		if ($line_item->type() === EEM_Line_Item::type_line_item &&
1575
+			$line_item->OBJ_type() === 'Ticket'
1576
+		) {
1577
+			$count = 0;
1578
+			foreach ($registrations as $registration) {
1579
+				if ($line_item->OBJ_ID() === $registration->ticket_ID() &&
1580
+					in_array($registration->status_ID(), EEM_Registration::reg_statuses_that_allow_payment())
1581
+				) {
1582
+					$count++;
1583
+				}
1584
+			}
1585
+			$new_li_fields['LIN_quantity'] = $count;
1586
+		}
1587
+		//don't set the total. We'll leave that up to the code that calculates it
1588
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1589
+		return EE_Line_Item::new_instance($new_li_fields);
1590
+	}
1591
+
1592
+
1593
+	/**
1594
+	 * Returns a modified line item tree where all the subtotals which have a total of 0
1595
+	 * are removed, and line items with a quantity of 0
1596
+	 *
1597
+	 * @param EE_Line_Item $line_item |null
1598
+	 * @return \EE_Line_Item|null
1599
+	 * @throws \EE_Error
1600
+	 */
1601
+	public static function non_empty_line_items(EE_Line_Item $line_item)
1602
+	{
1603
+		$copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1604
+		if ($copied_li === null) {
1605
+			return null;
1606
+		}
1607
+		//if this is an event subtotal, we want to only include it if it
1608
+		//has a non-zero total and at least one ticket line item child
1609
+		$ticket_children = 0;
1610
+		foreach ($line_item->children() as $child_li) {
1611
+			$child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1612
+			if ($child_li_copy !== null) {
1613
+				$copied_li->add_child_line_item($child_li_copy);
1614
+				if ($child_li_copy->type() === EEM_Line_Item::type_line_item &&
1615
+					$child_li_copy->OBJ_type() === 'Ticket'
1616
+				) {
1617
+					$ticket_children++;
1618
+				}
1619
+			}
1620
+		}
1621
+		//if this is an event subtotal with NO ticket children
1622
+		//we basically want to ignore it
1623
+		if (
1624
+			$ticket_children === 0
1625
+			&& $line_item->type() === EEM_Line_Item::type_sub_total
1626
+			&& $line_item->OBJ_type() === 'Event'
1627
+			&& $line_item->total() === 0
1628
+		) {
1629
+			return null;
1630
+		}
1631
+		return $copied_li;
1632
+	}
1633
+
1634
+
1635
+	/**
1636
+	 * Creates a new, unsaved line item, but if it's a ticket line item
1637
+	 * with a total of 0, or a subtotal of 0, returns null instead
1638
+	 *
1639
+	 * @param EE_Line_Item $line_item
1640
+	 * @return EE_Line_Item
1641
+	 * @throws \EE_Error
1642
+	 */
1643
+	public static function non_empty_line_item(EE_Line_Item $line_item)
1644
+	{
1645
+		if ($line_item->type() === EEM_Line_Item::type_line_item &&
1646
+			$line_item->OBJ_type() === 'Ticket' &&
1647
+			$line_item->quantity() === 0
1648
+		) {
1649
+			return null;
1650
+		}
1651
+		$new_li_fields = $line_item->model_field_array();
1652
+		//don't set the total. We'll leave that up to the code that calculates it
1653
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1654
+		return EE_Line_Item::new_instance($new_li_fields);
1655
+	}
1656
+
1657
+
1658
+
1659
+	/**************************************** @DEPRECATED METHODS *************************************** */
1660
+	/**
1661
+	 * @deprecated
1662
+	 * @param EE_Line_Item $total_line_item
1663
+	 * @return \EE_Line_Item
1664
+	 * @throws \EE_Error
1665
+	 */
1666
+	public static function get_items_subtotal(EE_Line_Item $total_line_item)
1667
+	{
1668
+		EE_Error::doing_it_wrong('EEH_Line_Item::get_items_subtotal()', __('Method replaced with EEH_Line_Item::get_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1669
+		return self::get_pre_tax_subtotal($total_line_item);
1670
+	}
1671
+
1672
+
1673
+	/**
1674
+	 * @deprecated
1675
+	 * @param EE_Transaction $transaction
1676
+	 * @return \EE_Line_Item
1677
+	 * @throws \EE_Error
1678
+	 */
1679
+	public static function create_default_total_line_item($transaction = NULL)
1680
+	{
1681
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_total_line_item()', __('Method replaced with EEH_Line_Item::create_total_line_item()', 'event_espresso'), '4.6.0');
1682
+		return self::create_total_line_item($transaction);
1683
+	}
1684
+
1685
+
1686
+	/**
1687
+	 * @deprecated
1688
+	 * @param EE_Line_Item $total_line_item
1689
+	 * @param EE_Transaction $transaction
1690
+	 * @return \EE_Line_Item
1691
+	 * @throws \EE_Error
1692
+	 */
1693
+	public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1694
+	{
1695
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_tickets_subtotal()', __('Method replaced with EEH_Line_Item::create_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1696
+		return self::create_pre_tax_subtotal($total_line_item, $transaction);
1697
+	}
1698
+
1699
+
1700
+	/**
1701
+	 * @deprecated
1702
+	 * @param EE_Line_Item $total_line_item
1703
+	 * @param EE_Transaction $transaction
1704
+	 * @return \EE_Line_Item
1705
+	 * @throws \EE_Error
1706
+	 */
1707
+	public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1708
+	{
1709
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_taxes_subtotal()', __('Method replaced with EEH_Line_Item::create_taxes_subtotal()', 'event_espresso'), '4.6.0');
1710
+		return self::create_taxes_subtotal($total_line_item, $transaction);
1711
+	}
1712
+
1713
+
1714
+	/**
1715
+	 * @deprecated
1716
+	 * @param EE_Line_Item $total_line_item
1717
+	 * @param EE_Transaction $transaction
1718
+	 * @return \EE_Line_Item
1719
+	 * @throws \EE_Error
1720
+	 */
1721
+	public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = NULL)
1722
+	{
1723
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_event_subtotal()', __('Method replaced with EEH_Line_Item::create_event_subtotal()', 'event_espresso'), '4.6.0');
1724
+		return self::create_event_subtotal($total_line_item, $transaction);
1725
+	}
1726 1726
 
1727 1727
 
1728 1728
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (!defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4 4
 
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
             'LIN_percent' => null,
60 60
             'LIN_is_taxable' => $taxable,
61 61
             'LIN_order' => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
62
-            'LIN_total' => (float)$unit_price * (int)$quantity,
62
+            'LIN_total' => (float) $unit_price * (int) $quantity,
63 63
             'LIN_type' => EEM_Line_Item::type_line_item,
64 64
             'LIN_code' => $code,
65 65
         ));
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
             'LIN_percent' => $percentage_amount,
99 99
             'LIN_quantity' => NULL,
100 100
             'LIN_is_taxable' => $taxable,
101
-            'LIN_total' => (float)($percentage_amount * ($parent_line_item->total() / 100)),
101
+            'LIN_total' => (float) ($percentage_amount * ($parent_line_item->total() / 100)),
102 102
             'LIN_type' => EEM_Line_Item::type_line_item,
103 103
             'LIN_parent' => $parent_line_item->ID()
104 104
         ));
@@ -128,13 +128,13 @@  discard block
 block discarded – undo
128 128
      */
129 129
     public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
130 130
     {
131
-        if (!$total_line_item instanceof EE_Line_Item || !$total_line_item->is_total()) {
131
+        if ( ! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
132 132
             throw new EE_Error(sprintf(__('A valid line item total is required in order to add tickets. A line item of type "%s" was passed.', 'event_espresso'), $ticket->ID(), $total_line_item->ID()));
133 133
         }
134 134
         // either increment the qty for an existing ticket
135 135
         $line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
136 136
         // or add a new one
137
-        if (!$line_item instanceof EE_Line_Item) {
137
+        if ( ! $line_item instanceof EE_Line_Item) {
138 138
             $line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
139 139
         }
140 140
         $total_line_item->recalculate_total_including_taxes();
@@ -155,10 +155,10 @@  discard block
 block discarded – undo
155 155
         $line_item = null;
156 156
         if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
157 157
             $ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
158
-            foreach ((array)$ticket_line_items as $ticket_line_item) {
158
+            foreach ((array) $ticket_line_items as $ticket_line_item) {
159 159
                 if (
160 160
                     $ticket_line_item instanceof EE_Line_Item
161
-                    && (int)$ticket_line_item->OBJ_ID() === (int)$ticket->ID()
161
+                    && (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
162 162
                 ) {
163 163
                     $line_item = $ticket_line_item;
164 164
                     break;
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
      */
185 185
     public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
186 186
     {
187
-        if (!$line_item->is_percent()) {
187
+        if ( ! $line_item->is_percent()) {
188 188
             $qty += $line_item->quantity();
189 189
             $line_item->set_quantity($qty);
190 190
             $line_item->set_total($line_item->unit_price() * $qty);
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
      */
210 210
     public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
211 211
     {
212
-        if (!$line_item->is_percent()) {
212
+        if ( ! $line_item->is_percent()) {
213 213
             $qty = $line_item->quantity() - $qty;
214 214
             $qty = max($qty, 0);
215 215
             $line_item->set_quantity($qty);
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
      */
235 235
     public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
236 236
     {
237
-        if (!$line_item->is_percent()) {
237
+        if ( ! $line_item->is_percent()) {
238 238
             $line_item->set_quantity($new_quantity);
239 239
             $line_item->set_total($line_item->unit_price() * $new_quantity);
240 240
             $line_item->save();
@@ -270,7 +270,7 @@  discard block
 block discarded – undo
270 270
         // add $ticket to cart
271 271
         $line_item = EE_Line_Item::new_instance(array(
272 272
             'LIN_name' => $ticket->name(),
273
-            'LIN_desc' => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
273
+            'LIN_desc' => $ticket->description() !== '' ? $ticket->description().' '.$event : $event,
274 274
             'LIN_unit_price' => $ticket->price(),
275 275
             'LIN_quantity' => $qty,
276 276
             'LIN_is_taxable' => $ticket->taxable(),
@@ -380,8 +380,8 @@  discard block
 block discarded – undo
380 380
         foreach ($ticket_line_item->children() as $child_line_item) {
381 381
             if (
382 382
                 $child_line_item->is_sub_line_item()
383
-                && !$child_line_item->is_percent()
384
-                && !$child_line_item->is_cancellation()
383
+                && ! $child_line_item->is_percent()
384
+                && ! $child_line_item->is_cancellation()
385 385
             ) {
386 386
                 $child_line_item->set_quantity($child_line_item->quantity() - $qty);
387 387
             }
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
                 'LIN_desc' => sprintf(
404 404
                     _x('Cancelled %1$s : %2$s', 'Cancelled Ticket Name : 2015-01-01 11:11', 'event_espresso'),
405 405
                     $ticket_line_item->name(),
406
-                    current_time(get_option('date_format') . ' ' . get_option('time_format'))
406
+                    current_time(get_option('date_format').' '.get_option('time_format'))
407 407
                 ),
408 408
                 'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
409 409
                 'LIN_quantity' => $qty,
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
         );
457 457
         $cancellation_line_item = reset($cancellation_line_item);
458 458
         // verify that this ticket was indeed previously cancelled
459
-        if (!$cancellation_line_item instanceof EE_Line_Item) {
459
+        if ( ! $cancellation_line_item instanceof EE_Line_Item) {
460 460
             return false;
461 461
         }
462 462
         if ($cancellation_line_item->quantity() > $qty) {
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
             'LIN_code' => 'taxes',
629 629
             'LIN_name' => __('Taxes', 'event_espresso'),
630 630
             'LIN_type' => EEM_Line_Item::type_tax_sub_total,
631
-            'LIN_order' => 1000,//this should always come last
631
+            'LIN_order' => 1000, //this should always come last
632 632
         ));
633 633
         $tax_line_item = apply_filters(
634 634
             'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
      */
681 681
     public static function get_event_code($event)
682 682
     {
683
-        return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
683
+        return 'event-'.($event instanceof EE_Event ? $event->ID() : '0');
684 684
     }
685 685
 
686 686
     /**
@@ -716,13 +716,13 @@  discard block
 block discarded – undo
716 716
     public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
717 717
     {
718 718
         $first_datetime = $ticket->first_datetime();
719
-        if (!$first_datetime instanceof EE_Datetime) {
719
+        if ( ! $first_datetime instanceof EE_Datetime) {
720 720
             throw new EE_Error(
721 721
                 sprintf(__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'), $ticket->ID())
722 722
             );
723 723
         }
724 724
         $event = $first_datetime->event();
725
-        if (!$event instanceof EE_Event) {
725
+        if ( ! $event instanceof EE_Event) {
726 726
             throw new EE_Error(
727 727
                 sprintf(
728 728
                     __('The supplied ticket (ID %d) has no event data associated with it.', 'event_espresso'),
@@ -731,7 +731,7 @@  discard block
 block discarded – undo
731 731
             );
732 732
         }
733 733
         $events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
734
-        if (!$events_sub_total instanceof EE_Line_Item) {
734
+        if ( ! $events_sub_total instanceof EE_Line_Item) {
735 735
             throw new EE_Error(
736 736
                 sprintf(
737 737
                     __('There is no events sub-total for ticket %s on total line item %d', 'event_espresso'),
@@ -760,7 +760,7 @@  discard block
 block discarded – undo
760 760
         $found = false;
761 761
         foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
762 762
             // default event subtotal, we should only ever find this the first time this method is called
763
-            if (!$event_line_item->OBJ_ID()) {
763
+            if ( ! $event_line_item->OBJ_ID()) {
764 764
                 // let's use this! but first... set the event details
765 765
                 EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
766 766
                 $found = true;
@@ -771,7 +771,7 @@  discard block
 block discarded – undo
771 771
                 break;
772 772
             }
773 773
         }
774
-        if (!$found) {
774
+        if ( ! $found) {
775 775
             //there is no event sub-total yet, so add it
776 776
             $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
777 777
             // create a new "event" subtotal below that
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
     public static function ensure_taxes_applied($total_line_item)
867 867
     {
868 868
         $taxes_subtotal = self::get_taxes_subtotal($total_line_item);
869
-        if (!$taxes_subtotal->children()) {
869
+        if ( ! $taxes_subtotal->children()) {
870 870
             self::apply_taxes($total_line_item);
871 871
         }
872 872
         return $taxes_subtotal->total();
@@ -927,7 +927,7 @@  discard block
 block discarded – undo
927 927
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
928 928
 
929 929
         // check if only a single line_item_id was passed
930
-        if (!empty($line_item_codes) && !is_array($line_item_codes)) {
930
+        if ( ! empty($line_item_codes) && ! is_array($line_item_codes)) {
931 931
             // place single line_item_id in an array to appear as multiple line_item_ids
932 932
             $line_item_codes = array($line_item_codes);
933 933
         }
@@ -1030,7 +1030,7 @@  discard block
 block discarded – undo
1030 1030
         if ($code_substring_for_whitelist !== null) {
1031 1031
             $whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false ? true : false;
1032 1032
         }
1033
-        if (!$whitelisted && $line_item->is_line_item()) {
1033
+        if ( ! $whitelisted && $line_item->is_line_item()) {
1034 1034
             $line_item->set_is_taxable($taxable);
1035 1035
         }
1036 1036
         foreach ($line_item->children() as $child_line_item) {
@@ -1335,7 +1335,7 @@  discard block
 block discarded – undo
1335 1335
     public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1336 1336
     {
1337 1337
         echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1338
-        if (!$indentation) {
1338
+        if ( ! $indentation) {
1339 1339
             echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1340 1340
         }
1341 1341
         for ($i = 0; $i < $indentation; $i++) {
@@ -1346,10 +1346,10 @@  discard block
 block discarded – undo
1346 1346
             if ($line_item->is_percent()) {
1347 1347
                 $breakdown = "{$line_item->percent()}%";
1348 1348
             } else {
1349
-                $breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1349
+                $breakdown = '$'."{$line_item->unit_price()} x {$line_item->quantity()}";
1350 1350
             }
1351 1351
         }
1352
-        echo $line_item->name() . " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : " . '$' . "{$line_item->total()}";
1352
+        echo $line_item->name()." [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ".'$'."{$line_item->total()}";
1353 1353
         if ($breakdown) {
1354 1354
             echo " ( {$breakdown} )";
1355 1355
         }
@@ -1400,10 +1400,10 @@  discard block
 block discarded – undo
1400 1400
     public static function calculate_reg_final_prices_per_line_item(EE_Line_Item $line_item, $billable_ticket_quantities = array())
1401 1401
     {
1402 1402
         //init running grand total if not already
1403
-        if (!isset($running_totals['total'])) {
1403
+        if ( ! isset($running_totals['total'])) {
1404 1404
             $running_totals['total'] = 0;
1405 1405
         }
1406
-        if (!isset($running_totals['taxable'])) {
1406
+        if ( ! isset($running_totals['taxable'])) {
1407 1407
             $running_totals['taxable'] = array('total' => 0);
1408 1408
         }
1409 1409
         foreach ($line_item->children() as $child_line_item) {
@@ -1525,7 +1525,7 @@  discard block
 block discarded – undo
1525 1525
             $ticket_line_item->ID()
1526 1526
         );
1527 1527
         if (WP_DEBUG) {
1528
-            $message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1528
+            $message .= '<br>'.print_r($final_prices_per_ticket_line_item, true);
1529 1529
             throw new \OutOfRangeException($message);
1530 1530
         } else {
1531 1531
             EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
Please login to merge, or discard this patch.