Completed
Branch dev (65a946)
by
unknown
35:11 queued 25:50
created
core/EE_Dependency_Map.core.php 1 patch
Indentation   +1032 added lines, -1032 removed lines patch added patch discarded remove patch
@@ -21,1036 +21,1036 @@
 block discarded – undo
21 21
 class EE_Dependency_Map
22 22
 {
23 23
 
24
-    /**
25
-     * This means that the requested class dependency is not present in the dependency map
26
-     */
27
-    const not_registered = 0;
28
-
29
-    /**
30
-     * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
31
-     */
32
-    const load_new_object = 1;
33
-
34
-    /**
35
-     * This instructs class loaders to return a previously instantiated and cached object for the requested class.
36
-     * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
37
-     */
38
-    const load_from_cache = 2;
39
-
40
-    /**
41
-     * When registering a dependency,
42
-     * this indicates to keep any existing dependencies that already exist,
43
-     * and simply discard any new dependencies declared in the incoming data
44
-     */
45
-    const KEEP_EXISTING_DEPENDENCIES = 0;
46
-
47
-    /**
48
-     * When registering a dependency,
49
-     * this indicates to overwrite any existing dependencies that already exist using the incoming data
50
-     */
51
-    const OVERWRITE_DEPENDENCIES = 1;
52
-
53
-    /**
54
-     * @type EE_Dependency_Map $_instance
55
-     */
56
-    protected static $_instance;
57
-
58
-    /**
59
-     * @var ClassInterfaceCache $class_cache
60
-     */
61
-    private $class_cache;
62
-
63
-    /**
64
-     * @type RequestInterface $request
65
-     */
66
-    protected $request;
67
-
68
-    /**
69
-     * @type LegacyRequestInterface $legacy_request
70
-     */
71
-    protected $legacy_request;
72
-
73
-    /**
74
-     * @type ResponseInterface $response
75
-     */
76
-    protected $response;
77
-
78
-    /**
79
-     * @type LoaderInterface $loader
80
-     */
81
-    protected $loader;
82
-
83
-    /**
84
-     * @type array $_dependency_map
85
-     */
86
-    protected $_dependency_map = [];
87
-
88
-    /**
89
-     * @type array $_class_loaders
90
-     */
91
-    protected $_class_loaders = [];
92
-
93
-
94
-    /**
95
-     * EE_Dependency_Map constructor.
96
-     *
97
-     * @param ClassInterfaceCache $class_cache
98
-     */
99
-    protected function __construct(ClassInterfaceCache $class_cache)
100
-    {
101
-        $this->class_cache = $class_cache;
102
-        do_action('EE_Dependency_Map____construct', $this);
103
-    }
104
-
105
-
106
-    /**
107
-     * @return void
108
-     * @throws InvalidAliasException
109
-     */
110
-    public function initialize()
111
-    {
112
-        $this->_register_core_dependencies();
113
-        $this->_register_core_class_loaders();
114
-        $this->_register_core_aliases();
115
-    }
116
-
117
-
118
-    /**
119
-     * @singleton method used to instantiate class object
120
-     * @param ClassInterfaceCache|null $class_cache
121
-     * @return EE_Dependency_Map
122
-     */
123
-    public static function instance(ClassInterfaceCache $class_cache = null)
124
-    {
125
-        // check if class object is instantiated, and instantiated properly
126
-        if (
127
-            ! EE_Dependency_Map::$_instance instanceof EE_Dependency_Map
128
-            && $class_cache instanceof ClassInterfaceCache
129
-        ) {
130
-            EE_Dependency_Map::$_instance = new EE_Dependency_Map($class_cache);
131
-        }
132
-        return EE_Dependency_Map::$_instance;
133
-    }
134
-
135
-
136
-    /**
137
-     * @param RequestInterface $request
138
-     */
139
-    public function setRequest(RequestInterface $request)
140
-    {
141
-        $this->request = $request;
142
-    }
143
-
144
-
145
-    /**
146
-     * @param LegacyRequestInterface $legacy_request
147
-     */
148
-    public function setLegacyRequest(LegacyRequestInterface $legacy_request)
149
-    {
150
-        $this->legacy_request = $legacy_request;
151
-    }
152
-
153
-
154
-    /**
155
-     * @param ResponseInterface $response
156
-     */
157
-    public function setResponse(ResponseInterface $response)
158
-    {
159
-        $this->response = $response;
160
-    }
161
-
162
-
163
-    /**
164
-     * @param LoaderInterface $loader
165
-     */
166
-    public function setLoader(LoaderInterface $loader)
167
-    {
168
-        $this->loader = $loader;
169
-    }
170
-
171
-
172
-    /**
173
-     * @param string $class
174
-     * @param array  $dependencies
175
-     * @param int    $overwrite
176
-     * @return bool
177
-     */
178
-    public static function register_dependencies(
179
-        $class,
180
-        array $dependencies,
181
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
182
-    ) {
183
-        return EE_Dependency_Map::$_instance->registerDependencies($class, $dependencies, $overwrite);
184
-    }
185
-
186
-
187
-    /**
188
-     * Assigns an array of class names and corresponding load sources (new or cached)
189
-     * to the class specified by the first parameter.
190
-     * IMPORTANT !!!
191
-     * The order of elements in the incoming $dependencies array MUST match
192
-     * the order of the constructor parameters for the class in question.
193
-     * This is especially important when overriding any existing dependencies that are registered.
194
-     * the third parameter controls whether any duplicate dependencies are overwritten or not.
195
-     *
196
-     * @param string $class
197
-     * @param array  $dependencies
198
-     * @param int    $overwrite
199
-     * @return bool
200
-     */
201
-    public function registerDependencies(
202
-        $class,
203
-        array $dependencies,
204
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
205
-    ) {
206
-        $class      = trim($class, '\\');
207
-        $registered = false;
208
-        if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
209
-            EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
210
-        }
211
-        // we need to make sure that any aliases used when registering a dependency
212
-        // get resolved to the correct class name
213
-        foreach ($dependencies as $dependency => $load_source) {
214
-            $alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
215
-            if (
216
-                $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
217
-                || ! isset(EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ])
218
-            ) {
219
-                unset($dependencies[ $dependency ]);
220
-                $dependencies[ $alias ] = $load_source;
221
-                $registered             = true;
222
-            }
223
-        }
224
-        // now add our two lists of dependencies together.
225
-        // using Union (+=) favours the arrays in precedence from left to right,
226
-        // so $dependencies is NOT overwritten because it is listed first
227
-        // ie: with A = B + C, entries in B take precedence over duplicate entries in C
228
-        // Union is way faster than array_merge() but should be used with caution...
229
-        // especially with numerically indexed arrays
230
-        $dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
231
-        // now we need to ensure that the resulting dependencies
232
-        // array only has the entries that are required for the class
233
-        // so first count how many dependencies were originally registered for the class
234
-        $dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
235
-        // if that count is non-zero (meaning dependencies were already registered)
236
-        EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
237
-            // then truncate the  final array to match that count
238
-            ? array_slice($dependencies, 0, $dependency_count)
239
-            // otherwise just take the incoming array because nothing previously existed
240
-            : $dependencies;
241
-        return $registered;
242
-    }
243
-
244
-
245
-    /**
246
-     * @param string $class_name
247
-     * @param string $loader
248
-     * @return bool
249
-     * @throws DomainException
250
-     */
251
-    public static function register_class_loader($class_name, $loader = 'load_core')
252
-    {
253
-        return EE_Dependency_Map::$_instance->registerClassLoader($class_name, $loader);
254
-    }
255
-
256
-
257
-    /**
258
-     * @param string $class_name
259
-     * @param string $loader
260
-     * @return bool
261
-     * @throws DomainException
262
-     */
263
-    public function registerClassLoader($class_name, $loader = 'load_core')
264
-    {
265
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
266
-            throw new DomainException(
267
-                esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
268
-            );
269
-        }
270
-        // check that loader is callable or method starts with "load_" and exists in EE_Registry
271
-        if (
272
-            ! is_callable($loader)
273
-            && (
274
-                strpos($loader, 'load_') !== 0
275
-                || ! method_exists('EE_Registry', $loader)
276
-            )
277
-        ) {
278
-            throw new DomainException(
279
-                sprintf(
280
-                    esc_html__(
281
-                        '"%1$s" is not a valid loader method on EE_Registry.',
282
-                        'event_espresso'
283
-                    ),
284
-                    $loader
285
-                )
286
-            );
287
-        }
288
-        $class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
289
-        if (! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
290
-            EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
291
-            return true;
292
-        }
293
-        return false;
294
-    }
295
-
296
-
297
-    /**
298
-     * @return array
299
-     */
300
-    public function dependency_map()
301
-    {
302
-        return $this->_dependency_map;
303
-    }
304
-
305
-
306
-    /**
307
-     * returns TRUE if dependency map contains a listing for the provided class name
308
-     *
309
-     * @param string $class_name
310
-     * @return boolean
311
-     */
312
-    public function has($class_name = '')
313
-    {
314
-        // all legacy models have the same dependencies
315
-        if (strpos($class_name, 'EEM_') === 0) {
316
-            $class_name = 'LEGACY_MODELS';
317
-        }
318
-        return isset($this->_dependency_map[ $class_name ]);
319
-    }
320
-
321
-
322
-    /**
323
-     * returns TRUE if dependency map contains a listing for the provided class name AND dependency
324
-     *
325
-     * @param string $class_name
326
-     * @param string $dependency
327
-     * @return bool
328
-     */
329
-    public function has_dependency_for_class($class_name = '', $dependency = '')
330
-    {
331
-        // all legacy models have the same dependencies
332
-        if (strpos($class_name, 'EEM_') === 0) {
333
-            $class_name = 'LEGACY_MODELS';
334
-        }
335
-        $dependency = $this->getFqnForAlias($dependency, $class_name);
336
-        return isset($this->_dependency_map[ $class_name ][ $dependency ]);
337
-    }
338
-
339
-
340
-    /**
341
-     * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
342
-     *
343
-     * @param string $class_name
344
-     * @param string $dependency
345
-     * @return int
346
-     */
347
-    public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
348
-    {
349
-        // all legacy models have the same dependencies
350
-        if (strpos($class_name, 'EEM_') === 0) {
351
-            $class_name = 'LEGACY_MODELS';
352
-        }
353
-        $dependency = $this->getFqnForAlias($dependency);
354
-        return $this->has_dependency_for_class($class_name, $dependency)
355
-            ? $this->_dependency_map[ $class_name ][ $dependency ]
356
-            : EE_Dependency_Map::not_registered;
357
-    }
358
-
359
-
360
-    /**
361
-     * @param string $class_name
362
-     * @return string | Closure
363
-     */
364
-    public function class_loader($class_name)
365
-    {
366
-        // all legacy models use load_model()
367
-        if (strpos($class_name, 'EEM_') === 0) {
368
-            return 'load_model';
369
-        }
370
-        // EE_CPT_*_Strategy classes like EE_CPT_Event_Strategy, EE_CPT_Venue_Strategy, etc
371
-        // perform strpos() first to avoid loading regex every time we load a class
372
-        if (
373
-            strpos($class_name, 'EE_CPT_') === 0
374
-            && preg_match('/^EE_CPT_([a-zA-Z]+)_Strategy$/', $class_name)
375
-        ) {
376
-            return 'load_core';
377
-        }
378
-        $class_name = $this->getFqnForAlias($class_name);
379
-        return isset($this->_class_loaders[ $class_name ]) ? $this->_class_loaders[ $class_name ] : '';
380
-    }
381
-
382
-
383
-    /**
384
-     * @return array
385
-     */
386
-    public function class_loaders()
387
-    {
388
-        return $this->_class_loaders;
389
-    }
390
-
391
-
392
-    /**
393
-     * adds an alias for a classname
394
-     *
395
-     * @param string $fqcn      the class name that should be used (concrete class to replace interface)
396
-     * @param string $alias     the class name that would be type hinted for (abstract parent or interface)
397
-     * @param string $for_class the class that has the dependency (is type hinting for the interface)
398
-     * @throws InvalidAliasException
399
-     */
400
-    public function add_alias($fqcn, $alias, $for_class = '')
401
-    {
402
-        $this->class_cache->addAlias($fqcn, $alias, $for_class);
403
-    }
404
-
405
-
406
-    /**
407
-     * Returns TRUE if the provided fully qualified name IS an alias
408
-     * WHY?
409
-     * Because if a class is type hinting for a concretion,
410
-     * then why would we need to find another class to supply it?
411
-     * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
412
-     * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
413
-     * Don't go looking for some substitute.
414
-     * Whereas if a class is type hinting for an interface...
415
-     * then we need to find an actual class to use.
416
-     * So the interface IS the alias for some other FQN,
417
-     * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
418
-     * represents some other class.
419
-     *
420
-     * @param string $fqn
421
-     * @param string $for_class
422
-     * @return bool
423
-     */
424
-    public function isAlias($fqn = '', $for_class = '')
425
-    {
426
-        return $this->class_cache->isAlias($fqn, $for_class);
427
-    }
428
-
429
-
430
-    /**
431
-     * Returns a FQN for provided alias if one exists, otherwise returns the original $alias
432
-     * functions recursively, so that multiple aliases can be used to drill down to a FQN
433
-     *  for example:
434
-     *      if the following two entries were added to the _aliases array:
435
-     *          array(
436
-     *              'interface_alias'           => 'some\namespace\interface'
437
-     *              'some\namespace\interface'  => 'some\namespace\classname'
438
-     *          )
439
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
440
-     *      to load an instance of 'some\namespace\classname'
441
-     *
442
-     * @param string $alias
443
-     * @param string $for_class
444
-     * @return string
445
-     */
446
-    public function getFqnForAlias($alias = '', $for_class = '')
447
-    {
448
-        return (string) $this->class_cache->getFqnForAlias($alias, $for_class);
449
-    }
450
-
451
-
452
-    /**
453
-     * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
454
-     * if one exists, or whether a new object should be generated every time the requested class is loaded.
455
-     * This is done by using the following class constants:
456
-     *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
457
-     *        EE_Dependency_Map::load_new_object - generates a new object every time
458
-     */
459
-    protected function _register_core_dependencies()
460
-    {
461
-        $this->_dependency_map = [
462
-            'EE_Request_Handler'                                                                                          => [
463
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
464
-            ],
465
-            'EE_System'                                                                                                   => [
466
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
467
-                'EE_Maintenance_Mode'                         => EE_Dependency_Map::load_from_cache,
468
-                'EE_Registry'                                 => EE_Dependency_Map::load_from_cache,
469
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
470
-                'EventEspresso\core\services\routing\Router'  => EE_Dependency_Map::load_from_cache,
471
-            ],
472
-            'EE_Admin'                                                                                                    => [
473
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
474
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
475
-            ],
476
-            'EE_Cart'                                                                                                     => [
477
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
478
-            ],
479
-            'EE_Messenger_Collection_Loader'                                                                              => [
480
-                'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
481
-            ],
482
-            'EE_Message_Type_Collection_Loader'                                                                           => [
483
-                'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
484
-            ],
485
-            'EE_Message_Resource_Manager'                                                                                 => [
486
-                'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
487
-                'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
488
-                'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
489
-            ],
490
-            'EE_Message_Factory'                                                                                          => [
491
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
492
-            ],
493
-            'EE_messages'                                                                                                 => [
494
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
495
-            ],
496
-            'EE_Messages_Generator'                                                                                       => [
497
-                'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
498
-                'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
499
-                'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
500
-                'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
501
-            ],
502
-            'EE_Messages_Processor'                                                                                       => [
503
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
504
-            ],
505
-            'EE_Messages_Queue'                                                                                           => [
506
-                'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
507
-            ],
508
-            'EE_Messages_Template_Defaults'                                                                               => [
509
-                'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
510
-                'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
511
-            ],
512
-            'EE_Message_To_Generate_From_Request'                                                                         => [
513
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
514
-                'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
515
-            ],
516
-            'EventEspresso\core\services\commands\CommandBus'                                                             => [
517
-                'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
518
-            ],
519
-            'EventEspresso\services\commands\CommandHandler'                                                              => [
520
-                'EE_Registry'         => EE_Dependency_Map::load_from_cache,
521
-                'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
522
-            ],
523
-            'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => [
524
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
525
-            ],
526
-            'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => [
527
-                'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
528
-                'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
529
-            ],
530
-            'EventEspresso\core\services\commands\CommandFactory'                                                         => [
531
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
532
-            ],
533
-            'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => [
534
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
535
-            ],
536
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => [
537
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
538
-            ],
539
-            'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => [
540
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
541
-            ],
542
-            'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => [
543
-                'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
544
-            ],
545
-            'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => [
546
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
547
-            ],
548
-            'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => [
549
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
550
-            ],
551
-            'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => [
552
-                'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
553
-            ],
554
-            'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => [
555
-                'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
556
-            ],
557
-            'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => [
558
-                'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
559
-            ],
560
-            'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => [
561
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
562
-            ],
563
-            'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => [
564
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
565
-            ],
566
-            'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => [
567
-                'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
568
-            ],
569
-            'EventEspresso\core\services\database\TableManager'                                                           => [
570
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
571
-            ],
572
-            'EE_Data_Migration_Class_Base'                                                                                => [
573
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
574
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
575
-            ],
576
-            'EE_DMS_Core_4_1_0'                                                                                           => [
577
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
578
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
579
-            ],
580
-            'EE_DMS_Core_4_2_0'                                                                                           => [
581
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
582
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
583
-            ],
584
-            'EE_DMS_Core_4_3_0'                                                                                           => [
585
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
586
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
587
-            ],
588
-            'EE_DMS_Core_4_4_0'                                                                                           => [
589
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
590
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
591
-            ],
592
-            'EE_DMS_Core_4_5_0'                                                                                           => [
593
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
594
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
595
-            ],
596
-            'EE_DMS_Core_4_6_0'                                                                                           => [
597
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
598
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
599
-            ],
600
-            'EE_DMS_Core_4_7_0'                                                                                           => [
601
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
602
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
603
-            ],
604
-            'EE_DMS_Core_4_8_0'                                                                                           => [
605
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
606
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
607
-            ],
608
-            'EE_DMS_Core_4_9_0'                                                                                           => [
609
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
610
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
611
-            ],
612
-            'EE_DMS_Core_4_10_0'                                                                                          => [
613
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
614
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
615
-                'EE_DMS_Core_4_9_0'                                  => EE_Dependency_Map::load_from_cache,
616
-            ],
617
-            'EE_DMS_Core_4_11_0'                                                                                          => [
618
-                'EE_DMS_Core_4_10_0'                                 => EE_Dependency_Map::load_from_cache,
619
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
620
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
621
-            ],
622
-            'EventEspresso\core\services\assets\Registry'                                                                 => [
623
-                'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_new_object,
624
-                'EventEspresso\core\services\assets\AssetManifest'   => EE_Dependency_Map::load_from_cache,
625
-            ],
626
-            'EventEspresso\core\services\cache\BasicCacheManager'                                                         => [
627
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
628
-            ],
629
-            'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => [
630
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
631
-            ],
632
-            'EventEspresso\core\domain\services\validation\email\EmailValidationService'                                  => [
633
-                'EE_Registration_Config'                     => EE_Dependency_Map::load_from_cache,
634
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
635
-            ],
636
-            'EventEspresso\core\domain\values\EmailAddress'                                                               => [
637
-                null,
638
-                'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
639
-            ],
640
-            'EventEspresso\core\services\orm\ModelFieldFactory'                                                           => [
641
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
642
-            ],
643
-            'LEGACY_MODELS'                                                                                               => [
644
-                null,
645
-                'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
646
-            ],
647
-            'EE_Module_Request_Router'                                                                                    => [
648
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
649
-            ],
650
-            'EE_Registration_Processor'                                                                                   => [
651
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
652
-            ],
653
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'                                      => [
654
-                null,
655
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
656
-                'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
657
-            ],
658
-            'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha'                                    => [
659
-                'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
660
-                'EE_Session'             => EE_Dependency_Map::load_from_cache,
661
-            ],
662
-            'EventEspresso\modules\ticket_selector\ProcessTicketSelector'                                                 => [
663
-                'EE_Core_Config'                                                          => EE_Dependency_Map::load_from_cache,
664
-                'EventEspresso\core\services\request\Request'                             => EE_Dependency_Map::load_from_cache,
665
-                'EE_Session'                                                              => EE_Dependency_Map::load_from_cache,
666
-                'EEM_Ticket'                                                              => EE_Dependency_Map::load_from_cache,
667
-                'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
668
-            ],
669
-            'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker'                                     => [
670
-                'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
671
-            ],
672
-            'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'                              => [
673
-                'EE_Core_Config'                             => EE_Dependency_Map::load_from_cache,
674
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
675
-            ],
676
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'                                => [
677
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
678
-            ],
679
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'                               => [
680
-                'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
681
-            ],
682
-            'EE_CPT_Strategy'                                                                                             => [
683
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
684
-                'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
685
-            ],
686
-            'EventEspresso\core\services\loaders\ObjectIdentifier'                                                        => [
687
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
688
-            ],
689
-            'EventEspresso\core\CPTs\CptQueryModifier'                                                                    => [
690
-                null,
691
-                null,
692
-                null,
693
-                'EE_Request_Handler'                          => EE_Dependency_Map::load_from_cache,
694
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
695
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
696
-            ],
697
-            'EventEspresso\core\services\dependencies\DependencyResolver'                                                 => [
698
-                'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
699
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
700
-                'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
701
-            ],
702
-            'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver'                               => [
703
-                'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
704
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
705
-                'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
706
-            ],
707
-            'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'                                          => [
708
-                'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver' => EE_Dependency_Map::load_from_cache,
709
-                'EventEspresso\core\services\loaders\Loader'                                    => EE_Dependency_Map::load_from_cache,
710
-            ],
711
-            'EventEspresso\core\services\routing\RouteMatchSpecificationManager'                                          => [
712
-                'EventEspresso\core\services\routing\RouteMatchSpecificationCollection' => EE_Dependency_Map::load_from_cache,
713
-                'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'    => EE_Dependency_Map::load_from_cache,
714
-            ],
715
-            'EE_URL_Validation_Strategy'                                                                                  => [
716
-                null,
717
-                null,
718
-                'EventEspresso\core\services\validators\URLValidator' => EE_Dependency_Map::load_from_cache,
719
-            ],
720
-            'EventEspresso\core\services\request\files\FilesDataHandler'                                                  => [
721
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
722
-            ],
723
-            'EventEspressoBatchRequest\BatchRequestProcessor'                                                             => [
724
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
725
-            ],
726
-            'EventEspresso\core\domain\services\converters\RestApiSpoofer'                                                => [
727
-                'WP_REST_Server'                                               => EE_Dependency_Map::load_from_cache,
728
-                'EED_Core_Rest_Api'                                            => EE_Dependency_Map::load_from_cache,
729
-                'EventEspresso\core\libraries\rest_api\controllers\model\Read' => EE_Dependency_Map::load_from_cache,
730
-                null,
731
-            ],
732
-            'EventEspresso\core\services\routing\RouteHandler'                                                            => [
733
-                'EventEspresso\core\services\json\JsonDataNodeHandler' => EE_Dependency_Map::load_from_cache,
734
-                'EventEspresso\core\services\loaders\Loader'           => EE_Dependency_Map::load_from_cache,
735
-                'EventEspresso\core\services\request\Request'          => EE_Dependency_Map::load_from_cache,
736
-                'EventEspresso\core\services\routing\RouteCollection'  => EE_Dependency_Map::load_from_cache,
737
-            ],
738
-            'EventEspresso\core\services\json\JsonDataNodeHandler'                                                        => [
739
-                'EventEspresso\core\services\json\JsonDataNodeValidator' => EE_Dependency_Map::load_from_cache,
740
-            ],
741
-            'EventEspresso\core\services\routing\Router'                                                                  => [
742
-                'EE_Dependency_Map'                                => EE_Dependency_Map::load_from_cache,
743
-                'EventEspresso\core\services\loaders\Loader'       => EE_Dependency_Map::load_from_cache,
744
-                'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
745
-            ],
746
-            'EventEspresso\core\services\assets\AssetManifest'                                                            => [
747
-                'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
748
-            ],
749
-            'EventEspresso\core\services\assets\AssetManifestFactory'                                                     => [
750
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
751
-            ],
752
-            'EventEspresso\core\services\assets\BaristaFactory'                                                           => [
753
-                'EventEspresso\core\services\assets\AssetManifestFactory' => EE_Dependency_Map::load_from_cache,
754
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
755
-            ],
756
-            'EventEspresso\core\domain\services\capabilities\FeatureFlags'                                                => [
757
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
758
-            ],
759
-            'EventEspresso\core\services\addon\AddonManager' => [
760
-                'EventEspresso\core\services\addon\AddonCollection'              => EE_Dependency_Map::load_from_cache,
761
-                'EventEspresso\core\Psr4Autoloader'                              => EE_Dependency_Map::load_from_cache,
762
-                'EventEspresso\core\services\addon\api\v1\RegisterAddon'         => EE_Dependency_Map::load_from_cache,
763
-                'EventEspresso\core\services\addon\api\IncompatibleAddonHandler' => EE_Dependency_Map::load_from_cache,
764
-                'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'  => EE_Dependency_Map::load_from_cache,
765
-            ],
766
-            'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler' => [
767
-                'EventEspresso\core\services\request\Request'  => EE_Dependency_Map::load_from_cache,
768
-            ],
769
-            'EventEspressoBatchRequest\JobHandlers\ExecuteBatchDeletion' => [
770
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
771
-            ],
772
-            'EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion' => [
773
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
774
-            ],
775
-            'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion' => [
776
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
777
-                'EEM_Event' => EE_Dependency_Map::load_from_cache,
778
-                'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
779
-                'EEM_Registration' => EE_Dependency_Map::load_from_cache
780
-            ],
781
-            'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion' => [
782
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
783
-            ]
784
-        ];
785
-    }
786
-
787
-
788
-    /**
789
-     * Registers how core classes are loaded.
790
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
791
-     *        'EE_Request_Handler' => 'load_core'
792
-     *        'EE_Messages_Queue'  => 'load_lib'
793
-     *        'EEH_Debug_Tools'    => 'load_helper'
794
-     * or, if greater control is required, by providing a custom closure. For example:
795
-     *        'Some_Class' => function () {
796
-     *            return new Some_Class();
797
-     *        },
798
-     * This is required for instantiating dependencies
799
-     * where an interface has been type hinted in a class constructor. For example:
800
-     *        'Required_Interface' => function () {
801
-     *            return new A_Class_That_Implements_Required_Interface();
802
-     *        },
803
-     */
804
-    protected function _register_core_class_loaders()
805
-    {
806
-        $this->_class_loaders = [
807
-            // load_core
808
-            'EE_Dependency_Map'                            => function () {
809
-                return $this;
810
-            },
811
-            'EE_Capabilities'                              => 'load_core',
812
-            'EE_Encryption'                                => 'load_core',
813
-            'EE_Front_Controller'                          => 'load_core',
814
-            'EE_Module_Request_Router'                     => 'load_core',
815
-            'EE_Registry'                                  => 'load_core',
816
-            'EE_Request'                                   => function () {
817
-                return $this->legacy_request;
818
-            },
819
-            'EventEspresso\core\services\request\Request'  => function () {
820
-                return $this->request;
821
-            },
822
-            'EventEspresso\core\services\request\Response' => function () {
823
-                return $this->response;
824
-            },
825
-            'EE_Base'                                      => 'load_core',
826
-            'EE_Request_Handler'                           => 'load_core',
827
-            'EE_Session'                                   => 'load_core',
828
-            'EE_Cron_Tasks'                                => 'load_core',
829
-            'EE_System'                                    => 'load_core',
830
-            'EE_Maintenance_Mode'                          => 'load_core',
831
-            'EE_Register_CPTs'                             => 'load_core',
832
-            'EE_Admin'                                     => 'load_core',
833
-            'EE_CPT_Strategy'                              => 'load_core',
834
-            // load_class
835
-            'EE_Registration_Processor'                    => 'load_class',
836
-            // load_lib
837
-            'EE_Message_Resource_Manager'                  => 'load_lib',
838
-            'EE_Message_Type_Collection'                   => 'load_lib',
839
-            'EE_Message_Type_Collection_Loader'            => 'load_lib',
840
-            'EE_Messenger_Collection'                      => 'load_lib',
841
-            'EE_Messenger_Collection_Loader'               => 'load_lib',
842
-            'EE_Messages_Processor'                        => 'load_lib',
843
-            'EE_Message_Repository'                        => 'load_lib',
844
-            'EE_Messages_Queue'                            => 'load_lib',
845
-            'EE_Messages_Data_Handler_Collection'          => 'load_lib',
846
-            'EE_Message_Template_Group_Collection'         => 'load_lib',
847
-            'EE_Payment_Method_Manager'                    => 'load_lib',
848
-            'EE_DMS_Core_4_1_0'                            => 'load_dms',
849
-            'EE_DMS_Core_4_2_0'                            => 'load_dms',
850
-            'EE_DMS_Core_4_3_0'                            => 'load_dms',
851
-            'EE_DMS_Core_4_5_0'                            => 'load_dms',
852
-            'EE_DMS_Core_4_6_0'                            => 'load_dms',
853
-            'EE_DMS_Core_4_7_0'                            => 'load_dms',
854
-            'EE_DMS_Core_4_8_0'                            => 'load_dms',
855
-            'EE_DMS_Core_4_9_0'                            => 'load_dms',
856
-            'EE_DMS_Core_4_10_0'                           => 'load_dms',
857
-            'EE_DMS_Core_4_11_0'                           => 'load_dms',
858
-            'EE_Messages_Generator'                        => static function () {
859
-                return EE_Registry::instance()->load_lib(
860
-                    'Messages_Generator',
861
-                    [],
862
-                    false,
863
-                    false
864
-                );
865
-            },
866
-            'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
867
-                return EE_Registry::instance()->load_lib(
868
-                    'Messages_Template_Defaults',
869
-                    $arguments,
870
-                    false,
871
-                    false
872
-                );
873
-            },
874
-            // load_helper
875
-            'EEH_Parse_Shortcodes'                         => static function () {
876
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
877
-                    return new EEH_Parse_Shortcodes();
878
-                }
879
-                return null;
880
-            },
881
-            'EE_Template_Config'                           => static function () {
882
-                return EE_Config::instance()->template_settings;
883
-            },
884
-            'EE_Currency_Config'                           => static function () {
885
-                return EE_Config::instance()->currency;
886
-            },
887
-            'EE_Registration_Config'                       => static function () {
888
-                return EE_Config::instance()->registration;
889
-            },
890
-            'EE_Core_Config'                               => static function () {
891
-                return EE_Config::instance()->core;
892
-            },
893
-            'EventEspresso\core\services\loaders\Loader'   => static function () {
894
-                return LoaderFactory::getLoader();
895
-            },
896
-            'EE_Network_Config'                            => static function () {
897
-                return EE_Network_Config::instance();
898
-            },
899
-            'EE_Config'                                    => static function () {
900
-                return EE_Config::instance();
901
-            },
902
-            'EventEspresso\core\domain\Domain'             => static function () {
903
-                return DomainFactory::getEventEspressoCoreDomain();
904
-            },
905
-            'EE_Admin_Config'                              => static function () {
906
-                return EE_Config::instance()->admin;
907
-            },
908
-            'EE_Organization_Config'                       => static function () {
909
-                return EE_Config::instance()->organization;
910
-            },
911
-            'EE_Network_Core_Config'                       => static function () {
912
-                return EE_Network_Config::instance()->core;
913
-            },
914
-            'EE_Environment_Config'                        => static function () {
915
-                return EE_Config::instance()->environment;
916
-            },
917
-            'EED_Core_Rest_Api'                            => static function () {
918
-                return EED_Core_Rest_Api::instance();
919
-            },
920
-            'WP_REST_Server'                               => static function () {
921
-                return rest_get_server();
922
-            },
923
-            'EventEspresso\core\Psr4Autoloader'            => static function () {
924
-                return EE_Psr4AutoloaderInit::psr4_loader();
925
-            },
926
-        ];
927
-    }
928
-
929
-
930
-    /**
931
-     * can be used for supplying alternate names for classes,
932
-     * or for connecting interface names to instantiable classes
933
-     *
934
-     * @throws InvalidAliasException
935
-     */
936
-    protected function _register_core_aliases()
937
-    {
938
-        $aliases = [
939
-            'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
940
-            'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
941
-            'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
942
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
943
-            'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
944
-            'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
945
-            'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
946
-            'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
947
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
948
-            'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
949
-            'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
950
-            'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
951
-            'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
952
-            'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
953
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
954
-            'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
955
-            'CreateTransactionCommandHandler'                                              => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
956
-            'CreateAttendeeCommandHandler'                                                 => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
957
-            'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
958
-            'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
959
-            'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
960
-            'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
961
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
962
-            'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
963
-            'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
964
-            'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
965
-            'CommandFactoryInterface'                                                      => 'EventEspresso\core\services\commands\CommandFactoryInterface',
966
-            'EventEspresso\core\services\commands\CommandFactoryInterface'                 => 'EventEspresso\core\services\commands\CommandFactory',
967
-            'EmailValidatorInterface'                                                      => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
968
-            'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface'  => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
969
-            'NoticeConverterInterface'                                                     => 'EventEspresso\core\services\notices\NoticeConverterInterface',
970
-            'EventEspresso\core\services\notices\NoticeConverterInterface'                 => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
971
-            'NoticesContainerInterface'                                                    => 'EventEspresso\core\services\notices\NoticesContainerInterface',
972
-            'EventEspresso\core\services\notices\NoticesContainerInterface'                => 'EventEspresso\core\services\notices\NoticesContainer',
973
-            'EventEspresso\core\services\request\RequestInterface'                         => 'EventEspresso\core\services\request\Request',
974
-            'EventEspresso\core\services\request\ResponseInterface'                        => 'EventEspresso\core\services\request\Response',
975
-            'EventEspresso\core\domain\DomainInterface'                                    => 'EventEspresso\core\domain\Domain',
976
-            'Registration_Processor'                                                       => 'EE_Registration_Processor',
977
-            'EventEspresso\core\services\assets\AssetManifestInterface'                    => 'EventEspresso\core\services\assets\AssetManifest',
978
-        ];
979
-        foreach ($aliases as $alias => $fqn) {
980
-            if (is_array($fqn)) {
981
-                foreach ($fqn as $class => $for_class) {
982
-                    $this->class_cache->addAlias($class, $alias, $for_class);
983
-                }
984
-                continue;
985
-            }
986
-            $this->class_cache->addAlias($fqn, $alias);
987
-        }
988
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
989
-            $this->class_cache->addAlias(
990
-                'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
991
-                'EventEspresso\core\services\notices\NoticeConverterInterface'
992
-            );
993
-        }
994
-    }
995
-
996
-
997
-    /**
998
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
999
-     * request Primarily used by unit tests.
1000
-     */
1001
-    public function reset()
1002
-    {
1003
-        $this->_register_core_class_loaders();
1004
-        $this->_register_core_dependencies();
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * PLZ NOTE: a better name for this method would be is_alias()
1010
-     * because it returns TRUE if the provided fully qualified name IS an alias
1011
-     * WHY?
1012
-     * Because if a class is type hinting for a concretion,
1013
-     * then why would we need to find another class to supply it?
1014
-     * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
1015
-     * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
1016
-     * Don't go looking for some substitute.
1017
-     * Whereas if a class is type hinting for an interface...
1018
-     * then we need to find an actual class to use.
1019
-     * So the interface IS the alias for some other FQN,
1020
-     * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
1021
-     * represents some other class.
1022
-     *
1023
-     * @param string $fqn
1024
-     * @param string $for_class
1025
-     * @return bool
1026
-     * @deprecated 4.9.62.p
1027
-     */
1028
-    public function has_alias($fqn = '', $for_class = '')
1029
-    {
1030
-        return $this->isAlias($fqn, $for_class);
1031
-    }
1032
-
1033
-
1034
-    /**
1035
-     * PLZ NOTE: a better name for this method would be get_fqn_for_alias()
1036
-     * because it returns a FQN for provided alias if one exists, otherwise returns the original $alias
1037
-     * functions recursively, so that multiple aliases can be used to drill down to a FQN
1038
-     *  for example:
1039
-     *      if the following two entries were added to the _aliases array:
1040
-     *          array(
1041
-     *              'interface_alias'           => 'some\namespace\interface'
1042
-     *              'some\namespace\interface'  => 'some\namespace\classname'
1043
-     *          )
1044
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
1045
-     *      to load an instance of 'some\namespace\classname'
1046
-     *
1047
-     * @param string $alias
1048
-     * @param string $for_class
1049
-     * @return string
1050
-     * @deprecated 4.9.62.p
1051
-     */
1052
-    public function get_alias($alias = '', $for_class = '')
1053
-    {
1054
-        return $this->getFqnForAlias($alias, $for_class);
1055
-    }
24
+	/**
25
+	 * This means that the requested class dependency is not present in the dependency map
26
+	 */
27
+	const not_registered = 0;
28
+
29
+	/**
30
+	 * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
31
+	 */
32
+	const load_new_object = 1;
33
+
34
+	/**
35
+	 * This instructs class loaders to return a previously instantiated and cached object for the requested class.
36
+	 * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
37
+	 */
38
+	const load_from_cache = 2;
39
+
40
+	/**
41
+	 * When registering a dependency,
42
+	 * this indicates to keep any existing dependencies that already exist,
43
+	 * and simply discard any new dependencies declared in the incoming data
44
+	 */
45
+	const KEEP_EXISTING_DEPENDENCIES = 0;
46
+
47
+	/**
48
+	 * When registering a dependency,
49
+	 * this indicates to overwrite any existing dependencies that already exist using the incoming data
50
+	 */
51
+	const OVERWRITE_DEPENDENCIES = 1;
52
+
53
+	/**
54
+	 * @type EE_Dependency_Map $_instance
55
+	 */
56
+	protected static $_instance;
57
+
58
+	/**
59
+	 * @var ClassInterfaceCache $class_cache
60
+	 */
61
+	private $class_cache;
62
+
63
+	/**
64
+	 * @type RequestInterface $request
65
+	 */
66
+	protected $request;
67
+
68
+	/**
69
+	 * @type LegacyRequestInterface $legacy_request
70
+	 */
71
+	protected $legacy_request;
72
+
73
+	/**
74
+	 * @type ResponseInterface $response
75
+	 */
76
+	protected $response;
77
+
78
+	/**
79
+	 * @type LoaderInterface $loader
80
+	 */
81
+	protected $loader;
82
+
83
+	/**
84
+	 * @type array $_dependency_map
85
+	 */
86
+	protected $_dependency_map = [];
87
+
88
+	/**
89
+	 * @type array $_class_loaders
90
+	 */
91
+	protected $_class_loaders = [];
92
+
93
+
94
+	/**
95
+	 * EE_Dependency_Map constructor.
96
+	 *
97
+	 * @param ClassInterfaceCache $class_cache
98
+	 */
99
+	protected function __construct(ClassInterfaceCache $class_cache)
100
+	{
101
+		$this->class_cache = $class_cache;
102
+		do_action('EE_Dependency_Map____construct', $this);
103
+	}
104
+
105
+
106
+	/**
107
+	 * @return void
108
+	 * @throws InvalidAliasException
109
+	 */
110
+	public function initialize()
111
+	{
112
+		$this->_register_core_dependencies();
113
+		$this->_register_core_class_loaders();
114
+		$this->_register_core_aliases();
115
+	}
116
+
117
+
118
+	/**
119
+	 * @singleton method used to instantiate class object
120
+	 * @param ClassInterfaceCache|null $class_cache
121
+	 * @return EE_Dependency_Map
122
+	 */
123
+	public static function instance(ClassInterfaceCache $class_cache = null)
124
+	{
125
+		// check if class object is instantiated, and instantiated properly
126
+		if (
127
+			! EE_Dependency_Map::$_instance instanceof EE_Dependency_Map
128
+			&& $class_cache instanceof ClassInterfaceCache
129
+		) {
130
+			EE_Dependency_Map::$_instance = new EE_Dependency_Map($class_cache);
131
+		}
132
+		return EE_Dependency_Map::$_instance;
133
+	}
134
+
135
+
136
+	/**
137
+	 * @param RequestInterface $request
138
+	 */
139
+	public function setRequest(RequestInterface $request)
140
+	{
141
+		$this->request = $request;
142
+	}
143
+
144
+
145
+	/**
146
+	 * @param LegacyRequestInterface $legacy_request
147
+	 */
148
+	public function setLegacyRequest(LegacyRequestInterface $legacy_request)
149
+	{
150
+		$this->legacy_request = $legacy_request;
151
+	}
152
+
153
+
154
+	/**
155
+	 * @param ResponseInterface $response
156
+	 */
157
+	public function setResponse(ResponseInterface $response)
158
+	{
159
+		$this->response = $response;
160
+	}
161
+
162
+
163
+	/**
164
+	 * @param LoaderInterface $loader
165
+	 */
166
+	public function setLoader(LoaderInterface $loader)
167
+	{
168
+		$this->loader = $loader;
169
+	}
170
+
171
+
172
+	/**
173
+	 * @param string $class
174
+	 * @param array  $dependencies
175
+	 * @param int    $overwrite
176
+	 * @return bool
177
+	 */
178
+	public static function register_dependencies(
179
+		$class,
180
+		array $dependencies,
181
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
182
+	) {
183
+		return EE_Dependency_Map::$_instance->registerDependencies($class, $dependencies, $overwrite);
184
+	}
185
+
186
+
187
+	/**
188
+	 * Assigns an array of class names and corresponding load sources (new or cached)
189
+	 * to the class specified by the first parameter.
190
+	 * IMPORTANT !!!
191
+	 * The order of elements in the incoming $dependencies array MUST match
192
+	 * the order of the constructor parameters for the class in question.
193
+	 * This is especially important when overriding any existing dependencies that are registered.
194
+	 * the third parameter controls whether any duplicate dependencies are overwritten or not.
195
+	 *
196
+	 * @param string $class
197
+	 * @param array  $dependencies
198
+	 * @param int    $overwrite
199
+	 * @return bool
200
+	 */
201
+	public function registerDependencies(
202
+		$class,
203
+		array $dependencies,
204
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
205
+	) {
206
+		$class      = trim($class, '\\');
207
+		$registered = false;
208
+		if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
209
+			EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
210
+		}
211
+		// we need to make sure that any aliases used when registering a dependency
212
+		// get resolved to the correct class name
213
+		foreach ($dependencies as $dependency => $load_source) {
214
+			$alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
215
+			if (
216
+				$overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
217
+				|| ! isset(EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ])
218
+			) {
219
+				unset($dependencies[ $dependency ]);
220
+				$dependencies[ $alias ] = $load_source;
221
+				$registered             = true;
222
+			}
223
+		}
224
+		// now add our two lists of dependencies together.
225
+		// using Union (+=) favours the arrays in precedence from left to right,
226
+		// so $dependencies is NOT overwritten because it is listed first
227
+		// ie: with A = B + C, entries in B take precedence over duplicate entries in C
228
+		// Union is way faster than array_merge() but should be used with caution...
229
+		// especially with numerically indexed arrays
230
+		$dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
231
+		// now we need to ensure that the resulting dependencies
232
+		// array only has the entries that are required for the class
233
+		// so first count how many dependencies were originally registered for the class
234
+		$dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
235
+		// if that count is non-zero (meaning dependencies were already registered)
236
+		EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
237
+			// then truncate the  final array to match that count
238
+			? array_slice($dependencies, 0, $dependency_count)
239
+			// otherwise just take the incoming array because nothing previously existed
240
+			: $dependencies;
241
+		return $registered;
242
+	}
243
+
244
+
245
+	/**
246
+	 * @param string $class_name
247
+	 * @param string $loader
248
+	 * @return bool
249
+	 * @throws DomainException
250
+	 */
251
+	public static function register_class_loader($class_name, $loader = 'load_core')
252
+	{
253
+		return EE_Dependency_Map::$_instance->registerClassLoader($class_name, $loader);
254
+	}
255
+
256
+
257
+	/**
258
+	 * @param string $class_name
259
+	 * @param string $loader
260
+	 * @return bool
261
+	 * @throws DomainException
262
+	 */
263
+	public function registerClassLoader($class_name, $loader = 'load_core')
264
+	{
265
+		if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
266
+			throw new DomainException(
267
+				esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
268
+			);
269
+		}
270
+		// check that loader is callable or method starts with "load_" and exists in EE_Registry
271
+		if (
272
+			! is_callable($loader)
273
+			&& (
274
+				strpos($loader, 'load_') !== 0
275
+				|| ! method_exists('EE_Registry', $loader)
276
+			)
277
+		) {
278
+			throw new DomainException(
279
+				sprintf(
280
+					esc_html__(
281
+						'"%1$s" is not a valid loader method on EE_Registry.',
282
+						'event_espresso'
283
+					),
284
+					$loader
285
+				)
286
+			);
287
+		}
288
+		$class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
289
+		if (! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
290
+			EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
291
+			return true;
292
+		}
293
+		return false;
294
+	}
295
+
296
+
297
+	/**
298
+	 * @return array
299
+	 */
300
+	public function dependency_map()
301
+	{
302
+		return $this->_dependency_map;
303
+	}
304
+
305
+
306
+	/**
307
+	 * returns TRUE if dependency map contains a listing for the provided class name
308
+	 *
309
+	 * @param string $class_name
310
+	 * @return boolean
311
+	 */
312
+	public function has($class_name = '')
313
+	{
314
+		// all legacy models have the same dependencies
315
+		if (strpos($class_name, 'EEM_') === 0) {
316
+			$class_name = 'LEGACY_MODELS';
317
+		}
318
+		return isset($this->_dependency_map[ $class_name ]);
319
+	}
320
+
321
+
322
+	/**
323
+	 * returns TRUE if dependency map contains a listing for the provided class name AND dependency
324
+	 *
325
+	 * @param string $class_name
326
+	 * @param string $dependency
327
+	 * @return bool
328
+	 */
329
+	public function has_dependency_for_class($class_name = '', $dependency = '')
330
+	{
331
+		// all legacy models have the same dependencies
332
+		if (strpos($class_name, 'EEM_') === 0) {
333
+			$class_name = 'LEGACY_MODELS';
334
+		}
335
+		$dependency = $this->getFqnForAlias($dependency, $class_name);
336
+		return isset($this->_dependency_map[ $class_name ][ $dependency ]);
337
+	}
338
+
339
+
340
+	/**
341
+	 * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
342
+	 *
343
+	 * @param string $class_name
344
+	 * @param string $dependency
345
+	 * @return int
346
+	 */
347
+	public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
348
+	{
349
+		// all legacy models have the same dependencies
350
+		if (strpos($class_name, 'EEM_') === 0) {
351
+			$class_name = 'LEGACY_MODELS';
352
+		}
353
+		$dependency = $this->getFqnForAlias($dependency);
354
+		return $this->has_dependency_for_class($class_name, $dependency)
355
+			? $this->_dependency_map[ $class_name ][ $dependency ]
356
+			: EE_Dependency_Map::not_registered;
357
+	}
358
+
359
+
360
+	/**
361
+	 * @param string $class_name
362
+	 * @return string | Closure
363
+	 */
364
+	public function class_loader($class_name)
365
+	{
366
+		// all legacy models use load_model()
367
+		if (strpos($class_name, 'EEM_') === 0) {
368
+			return 'load_model';
369
+		}
370
+		// EE_CPT_*_Strategy classes like EE_CPT_Event_Strategy, EE_CPT_Venue_Strategy, etc
371
+		// perform strpos() first to avoid loading regex every time we load a class
372
+		if (
373
+			strpos($class_name, 'EE_CPT_') === 0
374
+			&& preg_match('/^EE_CPT_([a-zA-Z]+)_Strategy$/', $class_name)
375
+		) {
376
+			return 'load_core';
377
+		}
378
+		$class_name = $this->getFqnForAlias($class_name);
379
+		return isset($this->_class_loaders[ $class_name ]) ? $this->_class_loaders[ $class_name ] : '';
380
+	}
381
+
382
+
383
+	/**
384
+	 * @return array
385
+	 */
386
+	public function class_loaders()
387
+	{
388
+		return $this->_class_loaders;
389
+	}
390
+
391
+
392
+	/**
393
+	 * adds an alias for a classname
394
+	 *
395
+	 * @param string $fqcn      the class name that should be used (concrete class to replace interface)
396
+	 * @param string $alias     the class name that would be type hinted for (abstract parent or interface)
397
+	 * @param string $for_class the class that has the dependency (is type hinting for the interface)
398
+	 * @throws InvalidAliasException
399
+	 */
400
+	public function add_alias($fqcn, $alias, $for_class = '')
401
+	{
402
+		$this->class_cache->addAlias($fqcn, $alias, $for_class);
403
+	}
404
+
405
+
406
+	/**
407
+	 * Returns TRUE if the provided fully qualified name IS an alias
408
+	 * WHY?
409
+	 * Because if a class is type hinting for a concretion,
410
+	 * then why would we need to find another class to supply it?
411
+	 * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
412
+	 * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
413
+	 * Don't go looking for some substitute.
414
+	 * Whereas if a class is type hinting for an interface...
415
+	 * then we need to find an actual class to use.
416
+	 * So the interface IS the alias for some other FQN,
417
+	 * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
418
+	 * represents some other class.
419
+	 *
420
+	 * @param string $fqn
421
+	 * @param string $for_class
422
+	 * @return bool
423
+	 */
424
+	public function isAlias($fqn = '', $for_class = '')
425
+	{
426
+		return $this->class_cache->isAlias($fqn, $for_class);
427
+	}
428
+
429
+
430
+	/**
431
+	 * Returns a FQN for provided alias if one exists, otherwise returns the original $alias
432
+	 * functions recursively, so that multiple aliases can be used to drill down to a FQN
433
+	 *  for example:
434
+	 *      if the following two entries were added to the _aliases array:
435
+	 *          array(
436
+	 *              'interface_alias'           => 'some\namespace\interface'
437
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
438
+	 *          )
439
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
440
+	 *      to load an instance of 'some\namespace\classname'
441
+	 *
442
+	 * @param string $alias
443
+	 * @param string $for_class
444
+	 * @return string
445
+	 */
446
+	public function getFqnForAlias($alias = '', $for_class = '')
447
+	{
448
+		return (string) $this->class_cache->getFqnForAlias($alias, $for_class);
449
+	}
450
+
451
+
452
+	/**
453
+	 * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
454
+	 * if one exists, or whether a new object should be generated every time the requested class is loaded.
455
+	 * This is done by using the following class constants:
456
+	 *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
457
+	 *        EE_Dependency_Map::load_new_object - generates a new object every time
458
+	 */
459
+	protected function _register_core_dependencies()
460
+	{
461
+		$this->_dependency_map = [
462
+			'EE_Request_Handler'                                                                                          => [
463
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
464
+			],
465
+			'EE_System'                                                                                                   => [
466
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
467
+				'EE_Maintenance_Mode'                         => EE_Dependency_Map::load_from_cache,
468
+				'EE_Registry'                                 => EE_Dependency_Map::load_from_cache,
469
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
470
+				'EventEspresso\core\services\routing\Router'  => EE_Dependency_Map::load_from_cache,
471
+			],
472
+			'EE_Admin'                                                                                                    => [
473
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
474
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
475
+			],
476
+			'EE_Cart'                                                                                                     => [
477
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
478
+			],
479
+			'EE_Messenger_Collection_Loader'                                                                              => [
480
+				'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
481
+			],
482
+			'EE_Message_Type_Collection_Loader'                                                                           => [
483
+				'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
484
+			],
485
+			'EE_Message_Resource_Manager'                                                                                 => [
486
+				'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
487
+				'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
488
+				'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
489
+			],
490
+			'EE_Message_Factory'                                                                                          => [
491
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
492
+			],
493
+			'EE_messages'                                                                                                 => [
494
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
495
+			],
496
+			'EE_Messages_Generator'                                                                                       => [
497
+				'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
498
+				'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
499
+				'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
500
+				'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
501
+			],
502
+			'EE_Messages_Processor'                                                                                       => [
503
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
504
+			],
505
+			'EE_Messages_Queue'                                                                                           => [
506
+				'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
507
+			],
508
+			'EE_Messages_Template_Defaults'                                                                               => [
509
+				'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
510
+				'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
511
+			],
512
+			'EE_Message_To_Generate_From_Request'                                                                         => [
513
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
514
+				'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
515
+			],
516
+			'EventEspresso\core\services\commands\CommandBus'                                                             => [
517
+				'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
518
+			],
519
+			'EventEspresso\services\commands\CommandHandler'                                                              => [
520
+				'EE_Registry'         => EE_Dependency_Map::load_from_cache,
521
+				'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
522
+			],
523
+			'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => [
524
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
525
+			],
526
+			'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => [
527
+				'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
528
+				'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
529
+			],
530
+			'EventEspresso\core\services\commands\CommandFactory'                                                         => [
531
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
532
+			],
533
+			'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => [
534
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
535
+			],
536
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => [
537
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
538
+			],
539
+			'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => [
540
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
541
+			],
542
+			'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => [
543
+				'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
544
+			],
545
+			'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => [
546
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
547
+			],
548
+			'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => [
549
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
550
+			],
551
+			'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => [
552
+				'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
553
+			],
554
+			'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => [
555
+				'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
556
+			],
557
+			'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => [
558
+				'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
559
+			],
560
+			'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => [
561
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
562
+			],
563
+			'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => [
564
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
565
+			],
566
+			'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => [
567
+				'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
568
+			],
569
+			'EventEspresso\core\services\database\TableManager'                                                           => [
570
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
571
+			],
572
+			'EE_Data_Migration_Class_Base'                                                                                => [
573
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
574
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
575
+			],
576
+			'EE_DMS_Core_4_1_0'                                                                                           => [
577
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
578
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
579
+			],
580
+			'EE_DMS_Core_4_2_0'                                                                                           => [
581
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
582
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
583
+			],
584
+			'EE_DMS_Core_4_3_0'                                                                                           => [
585
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
586
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
587
+			],
588
+			'EE_DMS_Core_4_4_0'                                                                                           => [
589
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
590
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
591
+			],
592
+			'EE_DMS_Core_4_5_0'                                                                                           => [
593
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
594
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
595
+			],
596
+			'EE_DMS_Core_4_6_0'                                                                                           => [
597
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
598
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
599
+			],
600
+			'EE_DMS_Core_4_7_0'                                                                                           => [
601
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
602
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
603
+			],
604
+			'EE_DMS_Core_4_8_0'                                                                                           => [
605
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
606
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
607
+			],
608
+			'EE_DMS_Core_4_9_0'                                                                                           => [
609
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
610
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
611
+			],
612
+			'EE_DMS_Core_4_10_0'                                                                                          => [
613
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
614
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
615
+				'EE_DMS_Core_4_9_0'                                  => EE_Dependency_Map::load_from_cache,
616
+			],
617
+			'EE_DMS_Core_4_11_0'                                                                                          => [
618
+				'EE_DMS_Core_4_10_0'                                 => EE_Dependency_Map::load_from_cache,
619
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
620
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
621
+			],
622
+			'EventEspresso\core\services\assets\Registry'                                                                 => [
623
+				'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_new_object,
624
+				'EventEspresso\core\services\assets\AssetManifest'   => EE_Dependency_Map::load_from_cache,
625
+			],
626
+			'EventEspresso\core\services\cache\BasicCacheManager'                                                         => [
627
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
628
+			],
629
+			'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => [
630
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
631
+			],
632
+			'EventEspresso\core\domain\services\validation\email\EmailValidationService'                                  => [
633
+				'EE_Registration_Config'                     => EE_Dependency_Map::load_from_cache,
634
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
635
+			],
636
+			'EventEspresso\core\domain\values\EmailAddress'                                                               => [
637
+				null,
638
+				'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
639
+			],
640
+			'EventEspresso\core\services\orm\ModelFieldFactory'                                                           => [
641
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
642
+			],
643
+			'LEGACY_MODELS'                                                                                               => [
644
+				null,
645
+				'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
646
+			],
647
+			'EE_Module_Request_Router'                                                                                    => [
648
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
649
+			],
650
+			'EE_Registration_Processor'                                                                                   => [
651
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
652
+			],
653
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'                                      => [
654
+				null,
655
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
656
+				'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
657
+			],
658
+			'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha'                                    => [
659
+				'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
660
+				'EE_Session'             => EE_Dependency_Map::load_from_cache,
661
+			],
662
+			'EventEspresso\modules\ticket_selector\ProcessTicketSelector'                                                 => [
663
+				'EE_Core_Config'                                                          => EE_Dependency_Map::load_from_cache,
664
+				'EventEspresso\core\services\request\Request'                             => EE_Dependency_Map::load_from_cache,
665
+				'EE_Session'                                                              => EE_Dependency_Map::load_from_cache,
666
+				'EEM_Ticket'                                                              => EE_Dependency_Map::load_from_cache,
667
+				'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
668
+			],
669
+			'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker'                                     => [
670
+				'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
671
+			],
672
+			'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'                              => [
673
+				'EE_Core_Config'                             => EE_Dependency_Map::load_from_cache,
674
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
675
+			],
676
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'                                => [
677
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
678
+			],
679
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'                               => [
680
+				'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
681
+			],
682
+			'EE_CPT_Strategy'                                                                                             => [
683
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
684
+				'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
685
+			],
686
+			'EventEspresso\core\services\loaders\ObjectIdentifier'                                                        => [
687
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
688
+			],
689
+			'EventEspresso\core\CPTs\CptQueryModifier'                                                                    => [
690
+				null,
691
+				null,
692
+				null,
693
+				'EE_Request_Handler'                          => EE_Dependency_Map::load_from_cache,
694
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
695
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
696
+			],
697
+			'EventEspresso\core\services\dependencies\DependencyResolver'                                                 => [
698
+				'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
699
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
700
+				'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
701
+			],
702
+			'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver'                               => [
703
+				'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
704
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
705
+				'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
706
+			],
707
+			'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'                                          => [
708
+				'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver' => EE_Dependency_Map::load_from_cache,
709
+				'EventEspresso\core\services\loaders\Loader'                                    => EE_Dependency_Map::load_from_cache,
710
+			],
711
+			'EventEspresso\core\services\routing\RouteMatchSpecificationManager'                                          => [
712
+				'EventEspresso\core\services\routing\RouteMatchSpecificationCollection' => EE_Dependency_Map::load_from_cache,
713
+				'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'    => EE_Dependency_Map::load_from_cache,
714
+			],
715
+			'EE_URL_Validation_Strategy'                                                                                  => [
716
+				null,
717
+				null,
718
+				'EventEspresso\core\services\validators\URLValidator' => EE_Dependency_Map::load_from_cache,
719
+			],
720
+			'EventEspresso\core\services\request\files\FilesDataHandler'                                                  => [
721
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
722
+			],
723
+			'EventEspressoBatchRequest\BatchRequestProcessor'                                                             => [
724
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
725
+			],
726
+			'EventEspresso\core\domain\services\converters\RestApiSpoofer'                                                => [
727
+				'WP_REST_Server'                                               => EE_Dependency_Map::load_from_cache,
728
+				'EED_Core_Rest_Api'                                            => EE_Dependency_Map::load_from_cache,
729
+				'EventEspresso\core\libraries\rest_api\controllers\model\Read' => EE_Dependency_Map::load_from_cache,
730
+				null,
731
+			],
732
+			'EventEspresso\core\services\routing\RouteHandler'                                                            => [
733
+				'EventEspresso\core\services\json\JsonDataNodeHandler' => EE_Dependency_Map::load_from_cache,
734
+				'EventEspresso\core\services\loaders\Loader'           => EE_Dependency_Map::load_from_cache,
735
+				'EventEspresso\core\services\request\Request'          => EE_Dependency_Map::load_from_cache,
736
+				'EventEspresso\core\services\routing\RouteCollection'  => EE_Dependency_Map::load_from_cache,
737
+			],
738
+			'EventEspresso\core\services\json\JsonDataNodeHandler'                                                        => [
739
+				'EventEspresso\core\services\json\JsonDataNodeValidator' => EE_Dependency_Map::load_from_cache,
740
+			],
741
+			'EventEspresso\core\services\routing\Router'                                                                  => [
742
+				'EE_Dependency_Map'                                => EE_Dependency_Map::load_from_cache,
743
+				'EventEspresso\core\services\loaders\Loader'       => EE_Dependency_Map::load_from_cache,
744
+				'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
745
+			],
746
+			'EventEspresso\core\services\assets\AssetManifest'                                                            => [
747
+				'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
748
+			],
749
+			'EventEspresso\core\services\assets\AssetManifestFactory'                                                     => [
750
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
751
+			],
752
+			'EventEspresso\core\services\assets\BaristaFactory'                                                           => [
753
+				'EventEspresso\core\services\assets\AssetManifestFactory' => EE_Dependency_Map::load_from_cache,
754
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
755
+			],
756
+			'EventEspresso\core\domain\services\capabilities\FeatureFlags'                                                => [
757
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
758
+			],
759
+			'EventEspresso\core\services\addon\AddonManager' => [
760
+				'EventEspresso\core\services\addon\AddonCollection'              => EE_Dependency_Map::load_from_cache,
761
+				'EventEspresso\core\Psr4Autoloader'                              => EE_Dependency_Map::load_from_cache,
762
+				'EventEspresso\core\services\addon\api\v1\RegisterAddon'         => EE_Dependency_Map::load_from_cache,
763
+				'EventEspresso\core\services\addon\api\IncompatibleAddonHandler' => EE_Dependency_Map::load_from_cache,
764
+				'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'  => EE_Dependency_Map::load_from_cache,
765
+			],
766
+			'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler' => [
767
+				'EventEspresso\core\services\request\Request'  => EE_Dependency_Map::load_from_cache,
768
+			],
769
+			'EventEspressoBatchRequest\JobHandlers\ExecuteBatchDeletion' => [
770
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
771
+			],
772
+			'EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion' => [
773
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
774
+			],
775
+			'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion' => [
776
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
777
+				'EEM_Event' => EE_Dependency_Map::load_from_cache,
778
+				'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
779
+				'EEM_Registration' => EE_Dependency_Map::load_from_cache
780
+			],
781
+			'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion' => [
782
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
783
+			]
784
+		];
785
+	}
786
+
787
+
788
+	/**
789
+	 * Registers how core classes are loaded.
790
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
791
+	 *        'EE_Request_Handler' => 'load_core'
792
+	 *        'EE_Messages_Queue'  => 'load_lib'
793
+	 *        'EEH_Debug_Tools'    => 'load_helper'
794
+	 * or, if greater control is required, by providing a custom closure. For example:
795
+	 *        'Some_Class' => function () {
796
+	 *            return new Some_Class();
797
+	 *        },
798
+	 * This is required for instantiating dependencies
799
+	 * where an interface has been type hinted in a class constructor. For example:
800
+	 *        'Required_Interface' => function () {
801
+	 *            return new A_Class_That_Implements_Required_Interface();
802
+	 *        },
803
+	 */
804
+	protected function _register_core_class_loaders()
805
+	{
806
+		$this->_class_loaders = [
807
+			// load_core
808
+			'EE_Dependency_Map'                            => function () {
809
+				return $this;
810
+			},
811
+			'EE_Capabilities'                              => 'load_core',
812
+			'EE_Encryption'                                => 'load_core',
813
+			'EE_Front_Controller'                          => 'load_core',
814
+			'EE_Module_Request_Router'                     => 'load_core',
815
+			'EE_Registry'                                  => 'load_core',
816
+			'EE_Request'                                   => function () {
817
+				return $this->legacy_request;
818
+			},
819
+			'EventEspresso\core\services\request\Request'  => function () {
820
+				return $this->request;
821
+			},
822
+			'EventEspresso\core\services\request\Response' => function () {
823
+				return $this->response;
824
+			},
825
+			'EE_Base'                                      => 'load_core',
826
+			'EE_Request_Handler'                           => 'load_core',
827
+			'EE_Session'                                   => 'load_core',
828
+			'EE_Cron_Tasks'                                => 'load_core',
829
+			'EE_System'                                    => 'load_core',
830
+			'EE_Maintenance_Mode'                          => 'load_core',
831
+			'EE_Register_CPTs'                             => 'load_core',
832
+			'EE_Admin'                                     => 'load_core',
833
+			'EE_CPT_Strategy'                              => 'load_core',
834
+			// load_class
835
+			'EE_Registration_Processor'                    => 'load_class',
836
+			// load_lib
837
+			'EE_Message_Resource_Manager'                  => 'load_lib',
838
+			'EE_Message_Type_Collection'                   => 'load_lib',
839
+			'EE_Message_Type_Collection_Loader'            => 'load_lib',
840
+			'EE_Messenger_Collection'                      => 'load_lib',
841
+			'EE_Messenger_Collection_Loader'               => 'load_lib',
842
+			'EE_Messages_Processor'                        => 'load_lib',
843
+			'EE_Message_Repository'                        => 'load_lib',
844
+			'EE_Messages_Queue'                            => 'load_lib',
845
+			'EE_Messages_Data_Handler_Collection'          => 'load_lib',
846
+			'EE_Message_Template_Group_Collection'         => 'load_lib',
847
+			'EE_Payment_Method_Manager'                    => 'load_lib',
848
+			'EE_DMS_Core_4_1_0'                            => 'load_dms',
849
+			'EE_DMS_Core_4_2_0'                            => 'load_dms',
850
+			'EE_DMS_Core_4_3_0'                            => 'load_dms',
851
+			'EE_DMS_Core_4_5_0'                            => 'load_dms',
852
+			'EE_DMS_Core_4_6_0'                            => 'load_dms',
853
+			'EE_DMS_Core_4_7_0'                            => 'load_dms',
854
+			'EE_DMS_Core_4_8_0'                            => 'load_dms',
855
+			'EE_DMS_Core_4_9_0'                            => 'load_dms',
856
+			'EE_DMS_Core_4_10_0'                           => 'load_dms',
857
+			'EE_DMS_Core_4_11_0'                           => 'load_dms',
858
+			'EE_Messages_Generator'                        => static function () {
859
+				return EE_Registry::instance()->load_lib(
860
+					'Messages_Generator',
861
+					[],
862
+					false,
863
+					false
864
+				);
865
+			},
866
+			'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
867
+				return EE_Registry::instance()->load_lib(
868
+					'Messages_Template_Defaults',
869
+					$arguments,
870
+					false,
871
+					false
872
+				);
873
+			},
874
+			// load_helper
875
+			'EEH_Parse_Shortcodes'                         => static function () {
876
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
877
+					return new EEH_Parse_Shortcodes();
878
+				}
879
+				return null;
880
+			},
881
+			'EE_Template_Config'                           => static function () {
882
+				return EE_Config::instance()->template_settings;
883
+			},
884
+			'EE_Currency_Config'                           => static function () {
885
+				return EE_Config::instance()->currency;
886
+			},
887
+			'EE_Registration_Config'                       => static function () {
888
+				return EE_Config::instance()->registration;
889
+			},
890
+			'EE_Core_Config'                               => static function () {
891
+				return EE_Config::instance()->core;
892
+			},
893
+			'EventEspresso\core\services\loaders\Loader'   => static function () {
894
+				return LoaderFactory::getLoader();
895
+			},
896
+			'EE_Network_Config'                            => static function () {
897
+				return EE_Network_Config::instance();
898
+			},
899
+			'EE_Config'                                    => static function () {
900
+				return EE_Config::instance();
901
+			},
902
+			'EventEspresso\core\domain\Domain'             => static function () {
903
+				return DomainFactory::getEventEspressoCoreDomain();
904
+			},
905
+			'EE_Admin_Config'                              => static function () {
906
+				return EE_Config::instance()->admin;
907
+			},
908
+			'EE_Organization_Config'                       => static function () {
909
+				return EE_Config::instance()->organization;
910
+			},
911
+			'EE_Network_Core_Config'                       => static function () {
912
+				return EE_Network_Config::instance()->core;
913
+			},
914
+			'EE_Environment_Config'                        => static function () {
915
+				return EE_Config::instance()->environment;
916
+			},
917
+			'EED_Core_Rest_Api'                            => static function () {
918
+				return EED_Core_Rest_Api::instance();
919
+			},
920
+			'WP_REST_Server'                               => static function () {
921
+				return rest_get_server();
922
+			},
923
+			'EventEspresso\core\Psr4Autoloader'            => static function () {
924
+				return EE_Psr4AutoloaderInit::psr4_loader();
925
+			},
926
+		];
927
+	}
928
+
929
+
930
+	/**
931
+	 * can be used for supplying alternate names for classes,
932
+	 * or for connecting interface names to instantiable classes
933
+	 *
934
+	 * @throws InvalidAliasException
935
+	 */
936
+	protected function _register_core_aliases()
937
+	{
938
+		$aliases = [
939
+			'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
940
+			'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
941
+			'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
942
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
943
+			'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
944
+			'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
945
+			'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
946
+			'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
947
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
948
+			'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
949
+			'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
950
+			'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
951
+			'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
952
+			'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
953
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
954
+			'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
955
+			'CreateTransactionCommandHandler'                                              => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
956
+			'CreateAttendeeCommandHandler'                                                 => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
957
+			'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
958
+			'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
959
+			'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
960
+			'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
961
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
962
+			'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
963
+			'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
964
+			'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
965
+			'CommandFactoryInterface'                                                      => 'EventEspresso\core\services\commands\CommandFactoryInterface',
966
+			'EventEspresso\core\services\commands\CommandFactoryInterface'                 => 'EventEspresso\core\services\commands\CommandFactory',
967
+			'EmailValidatorInterface'                                                      => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
968
+			'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface'  => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
969
+			'NoticeConverterInterface'                                                     => 'EventEspresso\core\services\notices\NoticeConverterInterface',
970
+			'EventEspresso\core\services\notices\NoticeConverterInterface'                 => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
971
+			'NoticesContainerInterface'                                                    => 'EventEspresso\core\services\notices\NoticesContainerInterface',
972
+			'EventEspresso\core\services\notices\NoticesContainerInterface'                => 'EventEspresso\core\services\notices\NoticesContainer',
973
+			'EventEspresso\core\services\request\RequestInterface'                         => 'EventEspresso\core\services\request\Request',
974
+			'EventEspresso\core\services\request\ResponseInterface'                        => 'EventEspresso\core\services\request\Response',
975
+			'EventEspresso\core\domain\DomainInterface'                                    => 'EventEspresso\core\domain\Domain',
976
+			'Registration_Processor'                                                       => 'EE_Registration_Processor',
977
+			'EventEspresso\core\services\assets\AssetManifestInterface'                    => 'EventEspresso\core\services\assets\AssetManifest',
978
+		];
979
+		foreach ($aliases as $alias => $fqn) {
980
+			if (is_array($fqn)) {
981
+				foreach ($fqn as $class => $for_class) {
982
+					$this->class_cache->addAlias($class, $alias, $for_class);
983
+				}
984
+				continue;
985
+			}
986
+			$this->class_cache->addAlias($fqn, $alias);
987
+		}
988
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
989
+			$this->class_cache->addAlias(
990
+				'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
991
+				'EventEspresso\core\services\notices\NoticeConverterInterface'
992
+			);
993
+		}
994
+	}
995
+
996
+
997
+	/**
998
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
999
+	 * request Primarily used by unit tests.
1000
+	 */
1001
+	public function reset()
1002
+	{
1003
+		$this->_register_core_class_loaders();
1004
+		$this->_register_core_dependencies();
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * PLZ NOTE: a better name for this method would be is_alias()
1010
+	 * because it returns TRUE if the provided fully qualified name IS an alias
1011
+	 * WHY?
1012
+	 * Because if a class is type hinting for a concretion,
1013
+	 * then why would we need to find another class to supply it?
1014
+	 * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
1015
+	 * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
1016
+	 * Don't go looking for some substitute.
1017
+	 * Whereas if a class is type hinting for an interface...
1018
+	 * then we need to find an actual class to use.
1019
+	 * So the interface IS the alias for some other FQN,
1020
+	 * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
1021
+	 * represents some other class.
1022
+	 *
1023
+	 * @param string $fqn
1024
+	 * @param string $for_class
1025
+	 * @return bool
1026
+	 * @deprecated 4.9.62.p
1027
+	 */
1028
+	public function has_alias($fqn = '', $for_class = '')
1029
+	{
1030
+		return $this->isAlias($fqn, $for_class);
1031
+	}
1032
+
1033
+
1034
+	/**
1035
+	 * PLZ NOTE: a better name for this method would be get_fqn_for_alias()
1036
+	 * because it returns a FQN for provided alias if one exists, otherwise returns the original $alias
1037
+	 * functions recursively, so that multiple aliases can be used to drill down to a FQN
1038
+	 *  for example:
1039
+	 *      if the following two entries were added to the _aliases array:
1040
+	 *          array(
1041
+	 *              'interface_alias'           => 'some\namespace\interface'
1042
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
1043
+	 *          )
1044
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
1045
+	 *      to load an instance of 'some\namespace\classname'
1046
+	 *
1047
+	 * @param string $alias
1048
+	 * @param string $for_class
1049
+	 * @return string
1050
+	 * @deprecated 4.9.62.p
1051
+	 */
1052
+	public function get_alias($alias = '', $for_class = '')
1053
+	{
1054
+		return $this->getFqnForAlias($alias, $for_class);
1055
+	}
1056 1056
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6482 added lines, -6482 removed lines patch added patch discarded remove patch
@@ -35,6488 +35,6488 @@
 block discarded – undo
35 35
 abstract class EEM_Base extends EE_Base implements ResettableInterface
36 36
 {
37 37
 
38
-    /**
39
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
-     * They almost always WILL NOT, but it's not necessarily a requirement.
42
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
-     *
44
-     * @var boolean
45
-     */
46
-    private $_values_already_prepared_by_model_object = 0;
47
-
48
-    /**
49
-     * when $_values_already_prepared_by_model_object equals this, we assume
50
-     * the data is just like form input that needs to have the model fields'
51
-     * prepare_for_set and prepare_for_use_in_db called on it
52
-     */
53
-    const not_prepared_by_model_object = 0;
54
-
55
-    /**
56
-     * when $_values_already_prepared_by_model_object equals this, we
57
-     * assume this value is coming from a model object and doesn't need to have
58
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
59
-     */
60
-    const prepared_by_model_object = 1;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the values are already to be used in the database (ie no processing is done
65
-     * on them by the model's fields)
66
-     */
67
-    const prepared_for_use_in_db = 2;
68
-
69
-
70
-    protected $singular_item = 'Item';
71
-
72
-    protected $plural_item   = 'Items';
73
-
74
-    /**
75
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
-     */
77
-    protected $_tables;
78
-
79
-    /**
80
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
-     *
84
-     * @var \EE_Model_Field_Base[][] $_fields
85
-     */
86
-    protected $_fields;
87
-
88
-    /**
89
-     * array of different kinds of relations
90
-     *
91
-     * @var \EE_Model_Relation_Base[] $_model_relations
92
-     */
93
-    protected $_model_relations;
94
-
95
-    /**
96
-     * @var \EE_Index[] $_indexes
97
-     */
98
-    protected $_indexes = array();
99
-
100
-    /**
101
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
102
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
-     * by setting the same columns as used in these queries in the query yourself.
104
-     *
105
-     * @var EE_Default_Where_Conditions
106
-     */
107
-    protected $_default_where_conditions_strategy;
108
-
109
-    /**
110
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
-     * This is particularly useful when you want something between 'none' and 'default'
112
-     *
113
-     * @var EE_Default_Where_Conditions
114
-     */
115
-    protected $_minimum_where_conditions_strategy;
116
-
117
-    /**
118
-     * String describing how to find the "owner" of this model's objects.
119
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
-     * But when there isn't, this indicates which related model, or transiently-related model,
121
-     * has the foreign key to the wp_users table.
122
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
-     * related to events, and events have a foreign key to wp_users.
124
-     * On EEM_Transaction, this would be 'Transaction.Event'
125
-     *
126
-     * @var string
127
-     */
128
-    protected $_model_chain_to_wp_user = '';
129
-
130
-    /**
131
-     * String describing how to find the model with a password controlling access to this model. This property has the
132
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
-     * This value is the path of models to follow to arrive at the model with the password field.
134
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
-     * model with a password that should affect reading this on the front-end.
136
-     * Eg this is an empty string for the Event model because it has a password.
137
-     * This is null for the Registration model, because its event's password has no bearing on whether
138
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
-     * should hide tickets for datetimes for events that have a password set.
141
-     * @var string |null
142
-     */
143
-    protected $model_chain_to_password = null;
144
-
145
-    /**
146
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
-     * don't need it (particularly CPT models)
148
-     *
149
-     * @var bool
150
-     */
151
-    protected $_ignore_where_strategy = false;
152
-
153
-    /**
154
-     * String used in caps relating to this model. Eg, if the caps relating to this
155
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
-     *
157
-     * @var string. If null it hasn't been initialized yet. If false then we
158
-     * have indicated capabilities don't apply to this
159
-     */
160
-    protected $_caps_slug = null;
161
-
162
-    /**
163
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
-     * and next-level keys are capability names, and each's value is a
165
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
-     * they specify which context to use (ie, frontend, backend, edit or delete)
167
-     * and then each capability in the corresponding sub-array that they're missing
168
-     * adds the where conditions onto the query.
169
-     *
170
-     * @var array
171
-     */
172
-    protected $_cap_restrictions = array(
173
-        self::caps_read       => array(),
174
-        self::caps_read_admin => array(),
175
-        self::caps_edit       => array(),
176
-        self::caps_delete     => array(),
177
-    );
178
-
179
-    /**
180
-     * Array defining which cap restriction generators to use to create default
181
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
182
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
-     * automatically set this to false (not just null).
185
-     *
186
-     * @var EE_Restriction_Generator_Base[]
187
-     */
188
-    protected $_cap_restriction_generators = array();
189
-
190
-    /**
191
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
-     */
193
-    const caps_read       = 'read';
194
-
195
-    const caps_read_admin = 'read_admin';
196
-
197
-    const caps_edit       = 'edit';
198
-
199
-    const caps_delete     = 'delete';
200
-
201
-    /**
202
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
-     * maps to 'read' because when looking for relevant permissions we're going to use
205
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
206
-     *
207
-     * @var array
208
-     */
209
-    protected $_cap_contexts_to_cap_action_map = array(
210
-        self::caps_read       => 'read',
211
-        self::caps_read_admin => 'read',
212
-        self::caps_edit       => 'edit',
213
-        self::caps_delete     => 'delete',
214
-    );
215
-
216
-    /**
217
-     * Timezone
218
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
-     * EE_Datetime_Field data type will have access to it.
222
-     *
223
-     * @var string
224
-     */
225
-    protected $_timezone;
226
-
227
-
228
-    /**
229
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
-     * multisite.
231
-     *
232
-     * @var int
233
-     */
234
-    protected static $_model_query_blog_id;
235
-
236
-    /**
237
-     * A copy of _fields, except the array keys are the model names pointed to by
238
-     * the field
239
-     *
240
-     * @var EE_Model_Field_Base[]
241
-     */
242
-    private $_cache_foreign_key_to_fields = array();
243
-
244
-    /**
245
-     * Cached list of all the fields on the model, indexed by their name
246
-     *
247
-     * @var EE_Model_Field_Base[]
248
-     */
249
-    private $_cached_fields = null;
250
-
251
-    /**
252
-     * Cached list of all the fields on the model, except those that are
253
-     * marked as only pertinent to the database
254
-     *
255
-     * @var EE_Model_Field_Base[]
256
-     */
257
-    private $_cached_fields_non_db_only = null;
258
-
259
-    /**
260
-     * A cached reference to the primary key for quick lookup
261
-     *
262
-     * @var EE_Model_Field_Base
263
-     */
264
-    private $_primary_key_field = null;
265
-
266
-    /**
267
-     * Flag indicating whether this model has a primary key or not
268
-     *
269
-     * @var boolean
270
-     */
271
-    protected $_has_primary_key_field = null;
272
-
273
-    /**
274
-     * array in the format:  [ FK alias => full PK ]
275
-     * where keys are local column name aliases for foreign keys
276
-     * and values are the fully qualified column name for the primary key they represent
277
-     *  ex:
278
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
-     *
280
-     * @var array $foreign_key_aliases
281
-     */
282
-    protected $foreign_key_aliases = [];
283
-
284
-    /**
285
-     * Whether or not this model is based off a table in WP core only (CPTs should set
286
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
-     * This should be true for models that deal with data that should exist independent of EE.
288
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
290
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
292
-     * @var boolean
293
-     */
294
-    protected $_wp_core_model = false;
295
-
296
-    /**
297
-     * @var bool stores whether this model has a password field or not.
298
-     * null until initialized by hasPasswordField()
299
-     */
300
-    protected $has_password_field;
301
-
302
-    /**
303
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
-     */
305
-    protected $password_field;
306
-
307
-    /**
308
-     *    List of valid operators that can be used for querying.
309
-     * The keys are all operators we'll accept, the values are the real SQL
310
-     * operators used
311
-     *
312
-     * @var array
313
-     */
314
-    protected $_valid_operators = array(
315
-        '='           => '=',
316
-        '<='          => '<=',
317
-        '<'           => '<',
318
-        '>='          => '>=',
319
-        '>'           => '>',
320
-        '!='          => '!=',
321
-        'LIKE'        => 'LIKE',
322
-        'like'        => 'LIKE',
323
-        'NOT_LIKE'    => 'NOT LIKE',
324
-        'not_like'    => 'NOT LIKE',
325
-        'NOT LIKE'    => 'NOT LIKE',
326
-        'not like'    => 'NOT LIKE',
327
-        'IN'          => 'IN',
328
-        'in'          => 'IN',
329
-        'NOT_IN'      => 'NOT IN',
330
-        'not_in'      => 'NOT IN',
331
-        'NOT IN'      => 'NOT IN',
332
-        'not in'      => 'NOT IN',
333
-        'between'     => 'BETWEEN',
334
-        'BETWEEN'     => 'BETWEEN',
335
-        'IS_NOT_NULL' => 'IS NOT NULL',
336
-        'is_not_null' => 'IS NOT NULL',
337
-        'IS NOT NULL' => 'IS NOT NULL',
338
-        'is not null' => 'IS NOT NULL',
339
-        'IS_NULL'     => 'IS NULL',
340
-        'is_null'     => 'IS NULL',
341
-        'IS NULL'     => 'IS NULL',
342
-        'is null'     => 'IS NULL',
343
-        'REGEXP'      => 'REGEXP',
344
-        'regexp'      => 'REGEXP',
345
-        'NOT_REGEXP'  => 'NOT REGEXP',
346
-        'not_regexp'  => 'NOT REGEXP',
347
-        'NOT REGEXP'  => 'NOT REGEXP',
348
-        'not regexp'  => 'NOT REGEXP',
349
-    );
350
-
351
-    /**
352
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
-     *
354
-     * @var array
355
-     */
356
-    protected $_in_style_operators = array('IN', 'NOT IN');
357
-
358
-    /**
359
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
-     * '12-31-2012'"
361
-     *
362
-     * @var array
363
-     */
364
-    protected $_between_style_operators = array('BETWEEN');
365
-
366
-    /**
367
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
-     * @var array
369
-     */
370
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
-    /**
372
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
-     * on a join table.
374
-     *
375
-     * @var array
376
-     */
377
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
-
379
-    /**
380
-     * Allowed values for $query_params['order'] for ordering in queries
381
-     *
382
-     * @var array
383
-     */
384
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
-
386
-    /**
387
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
389
-     *
390
-     * @var array
391
-     */
392
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
-
394
-    /**
395
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
397
-     *
398
-     * @var array
399
-     */
400
-    private $_allowed_query_params = array(
401
-        0,
402
-        'limit',
403
-        'order_by',
404
-        'group_by',
405
-        'having',
406
-        'force_join',
407
-        'order',
408
-        'on_join_limit',
409
-        'default_where_conditions',
410
-        'caps',
411
-        'extra_selects',
412
-        'exclude_protected',
413
-    );
414
-
415
-    /**
416
-     * All the data types that can be used in $wpdb->prepare statements.
417
-     *
418
-     * @var array
419
-     */
420
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
-
422
-    /**
423
-     * @var EE_Registry $EE
424
-     */
425
-    protected $EE = null;
426
-
427
-
428
-    /**
429
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
-     *
431
-     * @var int
432
-     */
433
-    protected $_show_next_x_db_queries = 0;
434
-
435
-    /**
436
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
-     * WHERE, GROUP_BY, etc.
439
-     *
440
-     * @var CustomSelects
441
-     */
442
-    protected $_custom_selections = array();
443
-
444
-    /**
445
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
-     * caches every model object we've fetched from the DB on this request
447
-     *
448
-     * @var array
449
-     */
450
-    protected $_entity_map;
451
-
452
-    /**
453
-     * @var LoaderInterface $loader
454
-     */
455
-    private static $loader;
456
-
457
-
458
-    /**
459
-     * constant used to show EEM_Base has not yet verified the db on this http request
460
-     */
461
-    const db_verified_none = 0;
462
-
463
-    /**
464
-     * constant used to show EEM_Base has verified the EE core db on this http request,
465
-     * but not the addons' dbs
466
-     */
467
-    const db_verified_core = 1;
468
-
469
-    /**
470
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
-     * the EE core db too)
472
-     */
473
-    const db_verified_addons = 2;
474
-
475
-    /**
476
-     * indicates whether an EEM_Base child has already re-verified the DB
477
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
478
-     * looking like EEM_Base::db_verified_*
479
-     *
480
-     * @var int - 0 = none, 1 = core, 2 = addons
481
-     */
482
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
483
-
484
-    /**
485
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
-     *        registrations for non-trashed tickets for non-trashed datetimes)
488
-     */
489
-    const default_where_conditions_all = 'all';
490
-
491
-    /**
492
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
-     *        models which share tables with other models, this can return data for the wrong model.
497
-     */
498
-    const default_where_conditions_this_only = 'this_model_only';
499
-
500
-    /**
501
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
-     */
505
-    const default_where_conditions_others_only = 'other_models_only';
506
-
507
-    /**
508
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
511
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
-     *        (regardless of whether those events and venues are trashed)
513
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
-     *        events.
515
-     */
516
-    const default_where_conditions_minimum_all = 'minimum';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
-     *        not)
523
-     */
524
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
-
526
-    /**
527
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
-     *        it's possible it will return table entries for other models. You should use
530
-     *        EEM_Base::default_where_conditions_minimum_all instead.
531
-     */
532
-    const default_where_conditions_none = 'none';
533
-
534
-
535
-
536
-    /**
537
-     * About all child constructors:
538
-     * they should define the _tables, _fields and _model_relations arrays.
539
-     * Should ALWAYS be called after child constructor.
540
-     * In order to make the child constructors to be as simple as possible, this parent constructor
541
-     * finalizes constructing all the object's attributes.
542
-     * Generally, rather than requiring a child to code
543
-     * $this->_tables = array(
544
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
-     *        ...);
546
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
-     * each EE_Table has a function to set the table's alias after the constructor, using
548
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
-     * do something similar.
550
-     *
551
-     * @param null $timezone
552
-     * @throws EE_Error
553
-     */
554
-    protected function __construct($timezone = null)
555
-    {
556
-        // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
-            throw new EE_Error(
559
-                sprintf(
560
-                    __(
561
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
562
-                        'event_espresso'
563
-                    ),
564
-                    get_class($this)
565
-                )
566
-            );
567
-        }
568
-        /**
569
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
-         */
571
-        if (empty(EEM_Base::$_model_query_blog_id)) {
572
-            EEM_Base::set_model_query_blog_id();
573
-        }
574
-        /**
575
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
-         * just use EE_Register_Model_Extension
577
-         *
578
-         * @var EE_Table_Base[] $_tables
579
-         */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
-        foreach ($this->_tables as $table_alias => $table_obj) {
582
-            /** @var $table_obj EE_Table_Base */
583
-            $table_obj->_construct_finalize_with_alias($table_alias);
584
-            if ($table_obj instanceof EE_Secondary_Table) {
585
-                /** @var $table_obj EE_Secondary_Table */
586
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
-            }
588
-        }
589
-        /**
590
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
-         * EE_Register_Model_Extension
592
-         *
593
-         * @param EE_Model_Field_Base[] $_fields
594
-         */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
-        $this->_invalidate_field_caches();
597
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
599
-                throw new EE_Error(sprintf(__(
600
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
-                    'event_espresso'
602
-                ), $table_alias, implode(",", $this->_fields)));
603
-            }
604
-            foreach ($fields_for_table as $field_name => $field_obj) {
605
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
-                // primary key field base has a slightly different _construct_finalize
607
-                /** @var $field_obj EE_Model_Field_Base */
608
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
-            }
610
-        }
611
-        // everything is related to Extra_Meta
612
-        if (get_class($this) !== 'EEM_Extra_Meta') {
613
-            // make extra meta related to everything, but don't block deleting things just
614
-            // because they have related extra meta info. For now just orphan those extra meta
615
-            // in the future we should automatically delete them
616
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
-        }
618
-        // and change logs
619
-        if (get_class($this) !== 'EEM_Change_Log') {
620
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
-        }
622
-        /**
623
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
-         * EE_Register_Model_Extension
625
-         *
626
-         * @param EE_Model_Relation_Base[] $_model_relations
627
-         */
628
-        $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
630
-            $this->_model_relations
631
-        );
632
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
633
-            /** @var $relation_obj EE_Model_Relation_Base */
634
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
-        }
636
-        foreach ($this->_indexes as $index_name => $index_obj) {
637
-            /** @var $index_obj EE_Index */
638
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
-        }
640
-        $this->set_timezone($timezone);
641
-        // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
643
-            // nothing was set during child constructor, so set default
644
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
-        }
646
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
648
-            // nothing was set during child constructor, so set default
649
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
-        }
651
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
653
-        // to indicate to NOT set it, set it to the logical default
654
-        if ($this->_caps_slug === null) {
655
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
-        }
657
-        // initialize the standard cap restriction generators if none were specified by the child constructor
658
-        if ($this->_cap_restriction_generators !== false) {
659
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
-                        new EE_Restriction_Generator_Protected(),
664
-                        $cap_context,
665
-                        $this
666
-                    );
667
-                }
668
-            }
669
-        }
670
-        // if there are cap restriction generators, use them to make the default cap restrictions
671
-        if ($this->_cap_restriction_generators !== false) {
672
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
674
-                    continue;
675
-                }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
-                    throw new EE_Error(
678
-                        sprintf(
679
-                            __(
680
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
681
-                                'event_espresso'
682
-                            ),
683
-                            $context,
684
-                            $this->get_this_model_name()
685
-                        )
686
-                    );
687
-                }
688
-                $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
690
-                    $generator_object->_construct_finalize($this, $action);
691
-                }
692
-            }
693
-        }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     * Used to set the $_model_query_blog_id static property.
701
-     *
702
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
-     *                      value for get_current_blog_id() will be used.
704
-     */
705
-    public static function set_model_query_blog_id($blog_id = 0)
706
-    {
707
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
-    }
709
-
710
-
711
-
712
-    /**
713
-     * Returns whatever is set as the internal $model_query_blog_id.
714
-     *
715
-     * @return int
716
-     */
717
-    public static function get_model_query_blog_id()
718
-    {
719
-        return EEM_Base::$_model_query_blog_id;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * This function is a singleton method used to instantiate the Espresso_model object
726
-     *
727
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
-     *                                (and any incoming timezone data that gets saved).
729
-     *                                Note this just sends the timezone info to the date time model field objects.
730
-     *                                Default is NULL
731
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
-     * @return static (as in the concrete child class)
733
-     * @throws EE_Error
734
-     * @throws InvalidArgumentException
735
-     * @throws InvalidDataTypeException
736
-     * @throws InvalidInterfaceException
737
-     */
738
-    public static function instance($timezone = null)
739
-    {
740
-        // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
742
-            // instantiate Espresso_model
743
-            static::$_instance = new static(
744
-                $timezone,
745
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
-            );
747
-        }
748
-        // we might have a timezone set, let set_timezone decide what to do with it
749
-        static::$_instance->set_timezone($timezone);
750
-        // Espresso_model object
751
-        return static::$_instance;
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * resets the model and returns it
758
-     *
759
-     * @param null | string $timezone
760
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
-     * all its properties reset; if it wasn't instantiated, returns null)
762
-     * @throws EE_Error
763
-     * @throws ReflectionException
764
-     * @throws InvalidArgumentException
765
-     * @throws InvalidDataTypeException
766
-     * @throws InvalidInterfaceException
767
-     */
768
-    public static function reset($timezone = null)
769
-    {
770
-        if (static::$_instance instanceof EEM_Base) {
771
-            // let's try to NOT swap out the current instance for a new one
772
-            // because if someone has a reference to it, we can't remove their reference
773
-            // so it's best to keep using the same reference, but change the original object
774
-            // reset all its properties to their original values as defined in the class
775
-            $r = new ReflectionClass(get_class(static::$_instance));
776
-            $static_properties = $r->getStaticProperties();
777
-            foreach ($r->getDefaultProperties() as $property => $value) {
778
-                // don't set instance to null like it was originally,
779
-                // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
781
-                    static::$_instance->{$property} = $value;
782
-                }
783
-            }
784
-            // and then directly call its constructor again, like we would if we were creating a new one
785
-            static::$_instance->__construct(
786
-                $timezone,
787
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
-            );
789
-            return self::instance();
790
-        }
791
-        return null;
792
-    }
793
-
794
-
795
-
796
-    /**
797
-     * @return LoaderInterface
798
-     * @throws InvalidArgumentException
799
-     * @throws InvalidDataTypeException
800
-     * @throws InvalidInterfaceException
801
-     */
802
-    private static function getLoader()
803
-    {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
805
-            EEM_Base::$loader = LoaderFactory::getLoader();
806
-        }
807
-        return EEM_Base::$loader;
808
-    }
809
-
810
-
811
-
812
-    /**
813
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
-     *
815
-     * @param  boolean $translated return localized strings or JUST the array.
816
-     * @return array
817
-     * @throws EE_Error
818
-     * @throws InvalidArgumentException
819
-     * @throws InvalidDataTypeException
820
-     * @throws InvalidInterfaceException
821
-     */
822
-    public function status_array($translated = false)
823
-    {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
825
-            return array();
826
-        }
827
-        $model_name = $this->get_this_model_name();
828
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
-        $status_array = array();
831
-        foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
833
-        }
834
-        return $translated
835
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
-            : $status_array;
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
-     *
844
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
-     *                             or if you have the development copy of EE you can view this at the path:
846
-     *                             /docs/G--Model-System/model-query-params.md
847
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
-     *                                        array( array(
852
-     *                                        'OR'=>array(
853
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
-     *                                        )
856
-     *                                        ),
857
-     *                                        'limit'=>10,
858
-     *                                        'group_by'=>'TXN_ID'
859
-     *                                        ));
860
-     *                                        get all the answers to the question titled "shirt size" for event with id
861
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
-     *                                        'Question.QST_display_text'=>'shirt size',
863
-     *                                        'Registration.Event.EVT_ID'=>12
864
-     *                                        ),
865
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
866
-     *                                        ));
867
-     * @throws EE_Error
868
-     */
869
-    public function get_all($query_params = array())
870
-    {
871
-        if (
872
-            isset($query_params['limit'])
873
-            && ! isset($query_params['group_by'])
874
-        ) {
875
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
876
-        }
877
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
878
-    }
879
-
880
-
881
-
882
-    /**
883
-     * Modifies the query parameters so we only get back model objects
884
-     * that "belong" to the current user
885
-     *
886
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
-     */
889
-    public function alter_query_params_to_only_include_mine($query_params = array())
890
-    {
891
-        $wp_user_field_name = $this->wp_user_field_name();
892
-        if ($wp_user_field_name) {
893
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
894
-        }
895
-        return $query_params;
896
-    }
897
-
898
-
899
-
900
-    /**
901
-     * Returns the name of the field's name that points to the WP_User table
902
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
903
-     * foreign key to the WP_User table)
904
-     *
905
-     * @return string|boolean string on success, boolean false when there is no
906
-     * foreign key to the WP_User table
907
-     */
908
-    public function wp_user_field_name()
909
-    {
910
-        try {
911
-            if (! empty($this->_model_chain_to_wp_user)) {
912
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
913
-                $last_model_name = end($models_to_follow_to_wp_users);
914
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
915
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
916
-            } else {
917
-                $model_with_fk_to_wp_users = $this;
918
-                $model_chain_to_wp_user = '';
919
-            }
920
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
921
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
922
-        } catch (EE_Error $e) {
923
-            return false;
924
-        }
925
-    }
926
-
927
-
928
-
929
-    /**
930
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
931
-     * (or transiently-related model) has a foreign key to the wp_users table;
932
-     * useful for finding if model objects of this type are 'owned' by the current user.
933
-     * This is an empty string when the foreign key is on this model and when it isn't,
934
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
935
-     * (or transiently-related model)
936
-     *
937
-     * @return string
938
-     */
939
-    public function model_chain_to_wp_user()
940
-    {
941
-        return $this->_model_chain_to_wp_user;
942
-    }
943
-
944
-
945
-
946
-    /**
947
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
948
-     * like how registrations don't have a foreign key to wp_users, but the
949
-     * events they are for are), or is unrelated to wp users.
950
-     * generally available
951
-     *
952
-     * @return boolean
953
-     */
954
-    public function is_owned()
955
-    {
956
-        if ($this->model_chain_to_wp_user()) {
957
-            return true;
958
-        }
959
-        try {
960
-            $this->get_foreign_key_to('WP_User');
961
-            return true;
962
-        } catch (EE_Error $e) {
963
-            return false;
964
-        }
965
-    }
966
-
967
-
968
-    /**
969
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
970
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
971
-     * the model)
972
-     *
973
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
974
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
975
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
976
-     *                                  fields on the model, and the models we joined to in the query. However, you can
977
-     *                                  override this and set the select to "*", or a specific column name, like
978
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
979
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
980
-     *                                  the aliases used to refer to this selection, and values are to be
981
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
982
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
983
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
984
-     * @throws EE_Error
985
-     * @throws InvalidArgumentException
986
-     */
987
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
988
-    {
989
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
990
-        ;
991
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
992
-        $select_expressions = $columns_to_select === null
993
-            ? $this->_construct_default_select_sql($model_query_info)
994
-            : '';
995
-        if ($this->_custom_selections instanceof CustomSelects) {
996
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
997
-            $select_expressions .= $select_expressions
998
-                ? ', ' . $custom_expressions
999
-                : $custom_expressions;
1000
-        }
1001
-
1002
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1003
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1004
-    }
1005
-
1006
-
1007
-    /**
1008
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1009
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1010
-     * method of including extra select information.
1011
-     *
1012
-     * @param array             $query_params
1013
-     * @param null|array|string $columns_to_select
1014
-     * @return null|CustomSelects
1015
-     * @throws InvalidArgumentException
1016
-     */
1017
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1018
-    {
1019
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020
-            return null;
1021
-        }
1022
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1023
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1024
-        return new CustomSelects($selects);
1025
-    }
1026
-
1027
-
1028
-
1029
-    /**
1030
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1031
-     * but you can use the model query params to more easily
1032
-     * take care of joins, field preparation etc.
1033
-     *
1034
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1038
-     *                                  override this and set the select to "*", or a specific column name, like
1039
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
-     *                                  the aliases used to refer to this selection, and values are to be
1042
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
-     * @throws EE_Error
1046
-     */
1047
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
-    {
1049
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1050
-    }
1051
-
1052
-
1053
-
1054
-    /**
1055
-     * For creating a custom select statement
1056
-     *
1057
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1058
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1059
-     *                                 SQL, and 1=>is the datatype
1060
-     * @throws EE_Error
1061
-     * @return string
1062
-     */
1063
-    private function _construct_select_from_input($columns_to_select)
1064
-    {
1065
-        if (is_array($columns_to_select)) {
1066
-            $select_sql_array = array();
1067
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1068
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
-                    throw new EE_Error(
1070
-                        sprintf(
1071
-                            __(
1072
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1073
-                                'event_espresso'
1074
-                            ),
1075
-                            $selection_and_datatype,
1076
-                            $alias
1077
-                        )
1078
-                    );
1079
-                }
1080
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081
-                    throw new EE_Error(
1082
-                        sprintf(
1083
-                            esc_html__(
1084
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1085
-                                'event_espresso'
1086
-                            ),
1087
-                            $selection_and_datatype[1],
1088
-                            $selection_and_datatype[0],
1089
-                            $alias,
1090
-                            implode(', ', $this->_valid_wpdb_data_types)
1091
-                        )
1092
-                    );
1093
-                }
1094
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1095
-            }
1096
-            $columns_to_select_string = implode(', ', $select_sql_array);
1097
-        } else {
1098
-            $columns_to_select_string = $columns_to_select;
1099
-        }
1100
-        return $columns_to_select_string;
1101
-    }
1102
-
1103
-
1104
-
1105
-    /**
1106
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1107
-     *
1108
-     * @return string
1109
-     * @throws EE_Error
1110
-     */
1111
-    public function primary_key_name()
1112
-    {
1113
-        return $this->get_primary_key_field()->get_name();
1114
-    }
1115
-
1116
-
1117
-    /**
1118
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1119
-     * If there is no primary key on this model, $id is treated as primary key string
1120
-     *
1121
-     * @param mixed $id int or string, depending on the type of the model's primary key
1122
-     * @return EE_Base_Class
1123
-     * @throws EE_Error
1124
-     */
1125
-    public function get_one_by_ID($id)
1126
-    {
1127
-        if ($this->get_from_entity_map($id)) {
1128
-            return $this->get_from_entity_map($id);
1129
-        }
1130
-        $model_object = $this->get_one(
1131
-            $this->alter_query_params_to_restrict_by_ID(
1132
-                $id,
1133
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1134
-            )
1135
-        );
1136
-        $className = $this->_get_class_name();
1137
-        if ($model_object instanceof $className) {
1138
-            // make sure valid objects get added to the entity map
1139
-            // so that the next call to this method doesn't trigger another trip to the db
1140
-            $this->add_to_entity_map($model_object);
1141
-        }
1142
-        return $model_object;
1143
-    }
1144
-
1145
-
1146
-
1147
-    /**
1148
-     * Alters query parameters to only get items with this ID are returned.
1149
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1150
-     * or could just be a simple primary key ID
1151
-     *
1152
-     * @param int   $id
1153
-     * @param array $query_params
1154
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1155
-     * @throws EE_Error
1156
-     */
1157
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1158
-    {
1159
-        if (! isset($query_params[0])) {
1160
-            $query_params[0] = array();
1161
-        }
1162
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1163
-        if ($conditions_from_id === null) {
1164
-            $query_params[0][ $this->primary_key_name() ] = $id;
1165
-        } else {
1166
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1167
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1168
-        }
1169
-        return $query_params;
1170
-    }
1171
-
1172
-
1173
-
1174
-    /**
1175
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1176
-     * array. If no item is found, null is returned.
1177
-     *
1178
-     * @param array $query_params like EEM_Base's $query_params variable.
1179
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1180
-     * @throws EE_Error
1181
-     */
1182
-    public function get_one($query_params = array())
1183
-    {
1184
-        if (! is_array($query_params)) {
1185
-            EE_Error::doing_it_wrong(
1186
-                'EEM_Base::get_one',
1187
-                sprintf(
1188
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1189
-                    gettype($query_params)
1190
-                ),
1191
-                '4.6.0'
1192
-            );
1193
-            $query_params = array();
1194
-        }
1195
-        $query_params['limit'] = 1;
1196
-        $items = $this->get_all($query_params);
1197
-        if (empty($items)) {
1198
-            return null;
1199
-        }
1200
-        return array_shift($items);
1201
-    }
1202
-
1203
-
1204
-
1205
-    /**
1206
-     * Returns the next x number of items in sequence from the given value as
1207
-     * found in the database matching the given query conditions.
1208
-     *
1209
-     * @param mixed $current_field_value    Value used for the reference point.
1210
-     * @param null  $field_to_order_by      What field is used for the
1211
-     *                                      reference point.
1212
-     * @param int   $limit                  How many to return.
1213
-     * @param array $query_params           Extra conditions on the query.
1214
-     * @param null  $columns_to_select      If left null, then an array of
1215
-     *                                      EE_Base_Class objects is returned,
1216
-     *                                      otherwise you can indicate just the
1217
-     *                                      columns you want returned.
1218
-     * @return EE_Base_Class[]|array
1219
-     * @throws EE_Error
1220
-     */
1221
-    public function next_x(
1222
-        $current_field_value,
1223
-        $field_to_order_by = null,
1224
-        $limit = 1,
1225
-        $query_params = array(),
1226
-        $columns_to_select = null
1227
-    ) {
1228
-        return $this->_get_consecutive(
1229
-            $current_field_value,
1230
-            '>',
1231
-            $field_to_order_by,
1232
-            $limit,
1233
-            $query_params,
1234
-            $columns_to_select
1235
-        );
1236
-    }
1237
-
1238
-
1239
-
1240
-    /**
1241
-     * Returns the previous x number of items in sequence from the given value
1242
-     * as found in the database matching the given query conditions.
1243
-     *
1244
-     * @param mixed $current_field_value    Value used for the reference point.
1245
-     * @param null  $field_to_order_by      What field is used for the
1246
-     *                                      reference point.
1247
-     * @param int   $limit                  How many to return.
1248
-     * @param array $query_params           Extra conditions on the query.
1249
-     * @param null  $columns_to_select      If left null, then an array of
1250
-     *                                      EE_Base_Class objects is returned,
1251
-     *                                      otherwise you can indicate just the
1252
-     *                                      columns you want returned.
1253
-     * @return EE_Base_Class[]|array
1254
-     * @throws EE_Error
1255
-     */
1256
-    public function previous_x(
1257
-        $current_field_value,
1258
-        $field_to_order_by = null,
1259
-        $limit = 1,
1260
-        $query_params = array(),
1261
-        $columns_to_select = null
1262
-    ) {
1263
-        return $this->_get_consecutive(
1264
-            $current_field_value,
1265
-            '<',
1266
-            $field_to_order_by,
1267
-            $limit,
1268
-            $query_params,
1269
-            $columns_to_select
1270
-        );
1271
-    }
1272
-
1273
-
1274
-
1275
-    /**
1276
-     * Returns the next item in sequence from the given value as found in the
1277
-     * database matching the given query conditions.
1278
-     *
1279
-     * @param mixed $current_field_value    Value used for the reference point.
1280
-     * @param null  $field_to_order_by      What field is used for the
1281
-     *                                      reference point.
1282
-     * @param array $query_params           Extra conditions on the query.
1283
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1284
-     *                                      object is returned, otherwise you
1285
-     *                                      can indicate just the columns you
1286
-     *                                      want and a single array indexed by
1287
-     *                                      the columns will be returned.
1288
-     * @return EE_Base_Class|null|array()
1289
-     * @throws EE_Error
1290
-     */
1291
-    public function next(
1292
-        $current_field_value,
1293
-        $field_to_order_by = null,
1294
-        $query_params = array(),
1295
-        $columns_to_select = null
1296
-    ) {
1297
-        $results = $this->_get_consecutive(
1298
-            $current_field_value,
1299
-            '>',
1300
-            $field_to_order_by,
1301
-            1,
1302
-            $query_params,
1303
-            $columns_to_select
1304
-        );
1305
-        return empty($results) ? null : reset($results);
1306
-    }
1307
-
1308
-
1309
-
1310
-    /**
1311
-     * Returns the previous item in sequence from the given value as found in
1312
-     * the database matching the given query conditions.
1313
-     *
1314
-     * @param mixed $current_field_value    Value used for the reference point.
1315
-     * @param null  $field_to_order_by      What field is used for the
1316
-     *                                      reference point.
1317
-     * @param array $query_params           Extra conditions on the query.
1318
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1319
-     *                                      object is returned, otherwise you
1320
-     *                                      can indicate just the columns you
1321
-     *                                      want and a single array indexed by
1322
-     *                                      the columns will be returned.
1323
-     * @return EE_Base_Class|null|array()
1324
-     * @throws EE_Error
1325
-     */
1326
-    public function previous(
1327
-        $current_field_value,
1328
-        $field_to_order_by = null,
1329
-        $query_params = array(),
1330
-        $columns_to_select = null
1331
-    ) {
1332
-        $results = $this->_get_consecutive(
1333
-            $current_field_value,
1334
-            '<',
1335
-            $field_to_order_by,
1336
-            1,
1337
-            $query_params,
1338
-            $columns_to_select
1339
-        );
1340
-        return empty($results) ? null : reset($results);
1341
-    }
1342
-
1343
-
1344
-
1345
-    /**
1346
-     * Returns the a consecutive number of items in sequence from the given
1347
-     * value as found in the database matching the given query conditions.
1348
-     *
1349
-     * @param mixed  $current_field_value   Value used for the reference point.
1350
-     * @param string $operand               What operand is used for the sequence.
1351
-     * @param string $field_to_order_by     What field is used for the reference point.
1352
-     * @param int    $limit                 How many to return.
1353
-     * @param array  $query_params          Extra conditions on the query.
1354
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1355
-     *                                      otherwise you can indicate just the columns you want returned.
1356
-     * @return EE_Base_Class[]|array
1357
-     * @throws EE_Error
1358
-     */
1359
-    protected function _get_consecutive(
1360
-        $current_field_value,
1361
-        $operand = '>',
1362
-        $field_to_order_by = null,
1363
-        $limit = 1,
1364
-        $query_params = array(),
1365
-        $columns_to_select = null
1366
-    ) {
1367
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1368
-        if (empty($field_to_order_by)) {
1369
-            if ($this->has_primary_key_field()) {
1370
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1371
-            } else {
1372
-                if (WP_DEBUG) {
1373
-                    throw new EE_Error(__(
1374
-                        'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1375
-                        'event_espresso'
1376
-                    ));
1377
-                }
1378
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1379
-                return array();
1380
-            }
1381
-        }
1382
-        if (! is_array($query_params)) {
1383
-            EE_Error::doing_it_wrong(
1384
-                'EEM_Base::_get_consecutive',
1385
-                sprintf(
1386
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1387
-                    gettype($query_params)
1388
-                ),
1389
-                '4.6.0'
1390
-            );
1391
-            $query_params = array();
1392
-        }
1393
-        // let's add the where query param for consecutive look up.
1394
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1395
-        $query_params['limit'] = $limit;
1396
-        // set direction
1397
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1398
-        $query_params['order_by'] = $operand === '>'
1399
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1400
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1401
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1402
-        if (empty($columns_to_select)) {
1403
-            return $this->get_all($query_params);
1404
-        }
1405
-        // getting just the fields
1406
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1407
-    }
1408
-
1409
-
1410
-
1411
-    /**
1412
-     * This sets the _timezone property after model object has been instantiated.
1413
-     *
1414
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1415
-     */
1416
-    public function set_timezone($timezone)
1417
-    {
1418
-        if ($timezone !== null) {
1419
-            $this->_timezone = $timezone;
1420
-        }
1421
-        // note we need to loop through relations and set the timezone on those objects as well.
1422
-        foreach ($this->_model_relations as $relation) {
1423
-            $relation->set_timezone($timezone);
1424
-        }
1425
-        // and finally we do the same for any datetime fields
1426
-        foreach ($this->_fields as $field) {
1427
-            if ($field instanceof EE_Datetime_Field) {
1428
-                $field->set_timezone($timezone);
1429
-            }
1430
-        }
1431
-    }
1432
-
1433
-
1434
-
1435
-    /**
1436
-     * This just returns whatever is set for the current timezone.
1437
-     *
1438
-     * @access public
1439
-     * @return string
1440
-     */
1441
-    public function get_timezone()
1442
-    {
1443
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1444
-        if (empty($this->_timezone)) {
1445
-            foreach ($this->_fields as $field) {
1446
-                if ($field instanceof EE_Datetime_Field) {
1447
-                    $this->set_timezone($field->get_timezone());
1448
-                    break;
1449
-                }
1450
-            }
1451
-        }
1452
-        // if timezone STILL empty then return the default timezone for the site.
1453
-        if (empty($this->_timezone)) {
1454
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1455
-        }
1456
-        return $this->_timezone;
1457
-    }
1458
-
1459
-
1460
-
1461
-    /**
1462
-     * This returns the date formats set for the given field name and also ensures that
1463
-     * $this->_timezone property is set correctly.
1464
-     *
1465
-     * @since 4.6.x
1466
-     * @param string $field_name The name of the field the formats are being retrieved for.
1467
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1468
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1469
-     * @return array formats in an array with the date format first, and the time format last.
1470
-     */
1471
-    public function get_formats_for($field_name, $pretty = false)
1472
-    {
1473
-        $field_settings = $this->field_settings_for($field_name);
1474
-        // if not a valid EE_Datetime_Field then throw error
1475
-        if (! $field_settings instanceof EE_Datetime_Field) {
1476
-            throw new EE_Error(sprintf(__(
1477
-                'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1478
-                'event_espresso'
1479
-            ), $field_name));
1480
-        }
1481
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1482
-        // the field.
1483
-        $this->_timezone = $field_settings->get_timezone();
1484
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1485
-    }
1486
-
1487
-
1488
-
1489
-    /**
1490
-     * This returns the current time in a format setup for a query on this model.
1491
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1492
-     * it will return:
1493
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1494
-     *  NOW
1495
-     *  - or a unix timestamp (equivalent to time())
1496
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1497
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1498
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1499
-     * @since 4.6.x
1500
-     * @param string $field_name       The field the current time is needed for.
1501
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1502
-     *                                 formatted string matching the set format for the field in the set timezone will
1503
-     *                                 be returned.
1504
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1505
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1506
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1507
-     *                                 exception is triggered.
1508
-     */
1509
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1510
-    {
1511
-        $formats = $this->get_formats_for($field_name);
1512
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1513
-        if ($timestamp) {
1514
-            return $DateTime->format('U');
1515
-        }
1516
-        // not returning timestamp, so return formatted string in timezone.
1517
-        switch ($what) {
1518
-            case 'time':
1519
-                return $DateTime->format($formats[1]);
1520
-                break;
1521
-            case 'date':
1522
-                return $DateTime->format($formats[0]);
1523
-                break;
1524
-            default:
1525
-                return $DateTime->format(implode(' ', $formats));
1526
-                break;
1527
-        }
1528
-    }
1529
-
1530
-
1531
-
1532
-    /**
1533
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1534
-     * for the model are.  Returns a DateTime object.
1535
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1536
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1537
-     * ignored.
1538
-     *
1539
-     * @param string $field_name      The field being setup.
1540
-     * @param string $timestring      The date time string being used.
1541
-     * @param string $incoming_format The format for the time string.
1542
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1543
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1544
-     *                                format is
1545
-     *                                'U', this is ignored.
1546
-     * @return DateTime
1547
-     * @throws EE_Error
1548
-     */
1549
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1550
-    {
1551
-        // just using this to ensure the timezone is set correctly internally
1552
-        $this->get_formats_for($field_name);
1553
-        // load EEH_DTT_Helper
1554
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1555
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1556
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1557
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1558
-    }
1559
-
1560
-
1561
-
1562
-    /**
1563
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1564
-     *
1565
-     * @return EE_Table_Base[]
1566
-     */
1567
-    public function get_tables()
1568
-    {
1569
-        return $this->_tables;
1570
-    }
1571
-
1572
-
1573
-
1574
-    /**
1575
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1576
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1577
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1578
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1579
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1580
-     * model object with EVT_ID = 1
1581
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1582
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1583
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1584
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1585
-     * are not specified)
1586
-     *
1587
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1588
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1589
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1590
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1591
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1592
-     *                                         ID=34, we'd use this method as follows:
1593
-     *                                         EEM_Transaction::instance()->update(
1594
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1595
-     *                                         array(array('TXN_ID'=>34)));
1596
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1597
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1598
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1599
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1600
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1601
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1602
-     *                                         TRUE, it is assumed that you've already called
1603
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1604
-     *                                         malicious javascript. However, if
1605
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1606
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1607
-     *                                         and every other field, before insertion. We provide this parameter
1608
-     *                                         because model objects perform their prepare_for_set function on all
1609
-     *                                         their values, and so don't need to be called again (and in many cases,
1610
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1611
-     *                                         prepare_for_set method...)
1612
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1613
-     *                                         in this model's entity map according to $fields_n_values that match
1614
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1615
-     *                                         by setting this to FALSE, but be aware that model objects being used
1616
-     *                                         could get out-of-sync with the database
1617
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1618
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1619
-     *                                         bad)
1620
-     * @throws EE_Error
1621
-     */
1622
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1623
-    {
1624
-        if (! is_array($query_params)) {
1625
-            EE_Error::doing_it_wrong(
1626
-                'EEM_Base::update',
1627
-                sprintf(
1628
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1629
-                    gettype($query_params)
1630
-                ),
1631
-                '4.6.0'
1632
-            );
1633
-            $query_params = array();
1634
-        }
1635
-        /**
1636
-         * Action called before a model update call has been made.
1637
-         *
1638
-         * @param EEM_Base $model
1639
-         * @param array    $fields_n_values the updated fields and their new values
1640
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1641
-         */
1642
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1643
-        /**
1644
-         * Filters the fields about to be updated given the query parameters. You can provide the
1645
-         * $query_params to $this->get_all() to find exactly which records will be updated
1646
-         *
1647
-         * @param array    $fields_n_values fields and their new values
1648
-         * @param EEM_Base $model           the model being queried
1649
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1650
-         */
1651
-        $fields_n_values = (array) apply_filters(
1652
-            'FHEE__EEM_Base__update__fields_n_values',
1653
-            $fields_n_values,
1654
-            $this,
1655
-            $query_params
1656
-        );
1657
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1658
-        // to do that, for each table, verify that it's PK isn't null.
1659
-        $tables = $this->get_tables();
1660
-        // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1661
-        // NOTE: we should make this code more efficient by NOT querying twice
1662
-        // before the real update, but that needs to first go through ALPHA testing
1663
-        // as it's dangerous. says Mike August 8 2014
1664
-        // we want to make sure the default_where strategy is ignored
1665
-        $this->_ignore_where_strategy = true;
1666
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1667
-        foreach ($wpdb_select_results as $wpdb_result) {
1668
-            // type cast stdClass as array
1669
-            $wpdb_result = (array) $wpdb_result;
1670
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1671
-            if ($this->has_primary_key_field()) {
1672
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1673
-            } else {
1674
-                // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1675
-                $main_table_pk_value = null;
1676
-            }
1677
-            // if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1678
-            // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1679
-            if (count($tables) > 1) {
1680
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1681
-                // in that table, and so we'll want to insert one
1682
-                foreach ($tables as $table_obj) {
1683
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1684
-                    // if there is no private key for this table on the results, it means there's no entry
1685
-                    // in this table, right? so insert a row in the current table, using any fields available
1686
-                    if (
1687
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1688
-                           && $wpdb_result[ $this_table_pk_column ])
1689
-                    ) {
1690
-                        $success = $this->_insert_into_specific_table(
1691
-                            $table_obj,
1692
-                            $fields_n_values,
1693
-                            $main_table_pk_value
1694
-                        );
1695
-                        // if we died here, report the error
1696
-                        if (! $success) {
1697
-                            return false;
1698
-                        }
1699
-                    }
1700
-                }
1701
-            }
1702
-            //              //and now check that if we have cached any models by that ID on the model, that
1703
-            //              //they also get updated properly
1704
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1705
-            //              if( $model_object ){
1706
-            //                  foreach( $fields_n_values as $field => $value ){
1707
-            //                      $model_object->set($field, $value);
1708
-            // let's make sure default_where strategy is followed now
1709
-            $this->_ignore_where_strategy = false;
1710
-        }
1711
-        // if we want to keep model objects in sync, AND
1712
-        // if this wasn't called from a model object (to update itself)
1713
-        // then we want to make sure we keep all the existing
1714
-        // model objects in sync with the db
1715
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1716
-            if ($this->has_primary_key_field()) {
1717
-                $model_objs_affected_ids = $this->get_col($query_params);
1718
-            } else {
1719
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1720
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1721
-                $model_objs_affected_ids = array();
1722
-                foreach ($models_affected_key_columns as $row) {
1723
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1724
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1725
-                }
1726
-            }
1727
-            if (! $model_objs_affected_ids) {
1728
-                // wait wait wait- if nothing was affected let's stop here
1729
-                return 0;
1730
-            }
1731
-            foreach ($model_objs_affected_ids as $id) {
1732
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1733
-                if ($model_obj_in_entity_map) {
1734
-                    foreach ($fields_n_values as $field => $new_value) {
1735
-                        $model_obj_in_entity_map->set($field, $new_value);
1736
-                    }
1737
-                }
1738
-            }
1739
-            // if there is a primary key on this model, we can now do a slight optimization
1740
-            if ($this->has_primary_key_field()) {
1741
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1742
-                $query_params = array(
1743
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1744
-                    'limit'                    => count($model_objs_affected_ids),
1745
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1746
-                );
1747
-            }
1748
-        }
1749
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1750
-        $SQL = "UPDATE "
1751
-               . $model_query_info->get_full_join_sql()
1752
-               . " SET "
1753
-               . $this->_construct_update_sql($fields_n_values)
1754
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1755
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1756
-        /**
1757
-         * Action called after a model update call has been made.
1758
-         *
1759
-         * @param EEM_Base $model
1760
-         * @param array    $fields_n_values the updated fields and their new values
1761
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1762
-         * @param int      $rows_affected
1763
-         */
1764
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1765
-        return $rows_affected;// how many supposedly got updated
1766
-    }
1767
-
1768
-
1769
-
1770
-    /**
1771
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1772
-     * are teh values of the field specified (or by default the primary key field)
1773
-     * that matched the query params. Note that you should pass the name of the
1774
-     * model FIELD, not the database table's column name.
1775
-     *
1776
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1777
-     * @param string $field_to_select
1778
-     * @return array just like $wpdb->get_col()
1779
-     * @throws EE_Error
1780
-     */
1781
-    public function get_col($query_params = array(), $field_to_select = null)
1782
-    {
1783
-        if ($field_to_select) {
1784
-            $field = $this->field_settings_for($field_to_select);
1785
-        } elseif ($this->has_primary_key_field()) {
1786
-            $field = $this->get_primary_key_field();
1787
-        } else {
1788
-            // no primary key, just grab the first column
1789
-            $field = reset($this->field_settings());
1790
-        }
1791
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1792
-        $select_expressions = $field->get_qualified_column();
1793
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1794
-        return $this->_do_wpdb_query('get_col', array($SQL));
1795
-    }
1796
-
1797
-
1798
-
1799
-    /**
1800
-     * Returns a single column value for a single row from the database
1801
-     *
1802
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1803
-     * @param string $field_to_select @see EEM_Base::get_col()
1804
-     * @return string
1805
-     * @throws EE_Error
1806
-     */
1807
-    public function get_var($query_params = array(), $field_to_select = null)
1808
-    {
1809
-        $query_params['limit'] = 1;
1810
-        $col = $this->get_col($query_params, $field_to_select);
1811
-        if (! empty($col)) {
1812
-            return reset($col);
1813
-        }
1814
-        return null;
1815
-    }
1816
-
1817
-
1818
-
1819
-    /**
1820
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1821
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1822
-     * injection, but currently no further filtering is done
1823
-     *
1824
-     * @global      $wpdb
1825
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1826
-     *                               be updated to in the DB
1827
-     * @return string of SQL
1828
-     * @throws EE_Error
1829
-     */
1830
-    public function _construct_update_sql($fields_n_values)
1831
-    {
1832
-        /** @type WPDB $wpdb */
1833
-        global $wpdb;
1834
-        $cols_n_values = array();
1835
-        foreach ($fields_n_values as $field_name => $value) {
1836
-            $field_obj = $this->field_settings_for($field_name);
1837
-            // if the value is NULL, we want to assign the value to that.
1838
-            // wpdb->prepare doesn't really handle that properly
1839
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1840
-            $value_sql = $prepared_value === null ? 'NULL'
1841
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1842
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1843
-        }
1844
-        return implode(",", $cols_n_values);
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
-     * Performs a HARD delete, meaning the database row should always be removed,
1852
-     * not just have a flag field on it switched
1853
-     * Wrapper for EEM_Base::delete_permanently()
1854
-     *
1855
-     * @param mixed $id
1856
-     * @param boolean $allow_blocking
1857
-     * @return int the number of rows deleted
1858
-     * @throws EE_Error
1859
-     */
1860
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1861
-    {
1862
-        return $this->delete_permanently(
1863
-            array(
1864
-                array($this->get_primary_key_field()->get_name() => $id),
1865
-                'limit' => 1,
1866
-            ),
1867
-            $allow_blocking
1868
-        );
1869
-    }
1870
-
1871
-
1872
-
1873
-    /**
1874
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1875
-     * Wrapper for EEM_Base::delete()
1876
-     *
1877
-     * @param mixed $id
1878
-     * @param boolean $allow_blocking
1879
-     * @return int the number of rows deleted
1880
-     * @throws EE_Error
1881
-     */
1882
-    public function delete_by_ID($id, $allow_blocking = true)
1883
-    {
1884
-        return $this->delete(
1885
-            array(
1886
-                array($this->get_primary_key_field()->get_name() => $id),
1887
-                'limit' => 1,
1888
-            ),
1889
-            $allow_blocking
1890
-        );
1891
-    }
1892
-
1893
-
1894
-
1895
-    /**
1896
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1897
-     * meaning if the model has a field that indicates its been "trashed" or
1898
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1899
-     *
1900
-     * @see EEM_Base::delete_permanently
1901
-     * @param array   $query_params
1902
-     * @param boolean $allow_blocking
1903
-     * @return int how many rows got deleted
1904
-     * @throws EE_Error
1905
-     */
1906
-    public function delete($query_params, $allow_blocking = true)
1907
-    {
1908
-        return $this->delete_permanently($query_params, $allow_blocking);
1909
-    }
1910
-
1911
-
1912
-
1913
-    /**
1914
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1915
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1916
-     * as archived, not actually deleted
1917
-     *
1918
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1919
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1920
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1921
-     *                                deletes regardless of other objects which may depend on it. Its generally
1922
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1923
-     *                                DB
1924
-     * @return int how many rows got deleted
1925
-     * @throws EE_Error
1926
-     */
1927
-    public function delete_permanently($query_params, $allow_blocking = true)
1928
-    {
1929
-        /**
1930
-         * Action called just before performing a real deletion query. You can use the
1931
-         * model and its $query_params to find exactly which items will be deleted
1932
-         *
1933
-         * @param EEM_Base $model
1934
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1935
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1936
-         *                                 to block (prevent) this deletion
1937
-         */
1938
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1939
-        // some MySQL databases may be running safe mode, which may restrict
1940
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1941
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1942
-        // to delete them
1943
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1944
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1945
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1946
-            $columns_and_ids_for_deleting
1947
-        );
1948
-        /**
1949
-         * Allows client code to act on the items being deleted before the query is actually executed.
1950
-         *
1951
-         * @param EEM_Base $this  The model instance being acted on.
1952
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1953
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1954
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1955
-         *                                                  derived from the incoming query parameters.
1956
-         *                                                  @see details on the structure of this array in the phpdocs
1957
-         *                                                  for the `_get_ids_for_delete_method`
1958
-         *
1959
-         */
1960
-        do_action(
1961
-            'AHEE__EEM_Base__delete__before_query',
1962
-            $this,
1963
-            $query_params,
1964
-            $allow_blocking,
1965
-            $columns_and_ids_for_deleting
1966
-        );
1967
-        if ($deletion_where_query_part) {
1968
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1969
-            $table_aliases = array_keys($this->_tables);
1970
-            $SQL = "DELETE "
1971
-                   . implode(", ", $table_aliases)
1972
-                   . " FROM "
1973
-                   . $model_query_info->get_full_join_sql()
1974
-                   . " WHERE "
1975
-                   . $deletion_where_query_part;
1976
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1977
-        } else {
1978
-            $rows_deleted = 0;
1979
-        }
1980
-
1981
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1982
-        // there was no error with the delete query.
1983
-        if (
1984
-            $this->has_primary_key_field()
1985
-            && $rows_deleted !== false
1986
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1987
-        ) {
1988
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1989
-            foreach ($ids_for_removal as $id) {
1990
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1991
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1992
-                }
1993
-            }
1994
-
1995
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1996
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1997
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1998
-            // (although it is possible).
1999
-            // Note this can be skipped by using the provided filter and returning false.
2000
-            if (
2001
-                apply_filters(
2002
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2003
-                    ! $this instanceof EEM_Extra_Meta,
2004
-                    $this
2005
-                )
2006
-            ) {
2007
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2008
-                    0 => array(
2009
-                        'EXM_type' => $this->get_this_model_name(),
2010
-                        'OBJ_ID'   => array(
2011
-                            'IN',
2012
-                            $ids_for_removal
2013
-                        )
2014
-                    )
2015
-                ));
2016
-            }
2017
-        }
2018
-
2019
-        /**
2020
-         * Action called just after performing a real deletion query. Although at this point the
2021
-         * items should have been deleted
2022
-         *
2023
-         * @param EEM_Base $model
2024
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2025
-         * @param int      $rows_deleted
2026
-         */
2027
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2028
-        return $rows_deleted;// how many supposedly got deleted
2029
-    }
2030
-
2031
-
2032
-
2033
-    /**
2034
-     * Checks all the relations that throw error messages when there are blocking related objects
2035
-     * for related model objects. If there are any related model objects on those relations,
2036
-     * adds an EE_Error, and return true
2037
-     *
2038
-     * @param EE_Base_Class|int $this_model_obj_or_id
2039
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2040
-     *                                                 should be ignored when determining whether there are related
2041
-     *                                                 model objects which block this model object's deletion. Useful
2042
-     *                                                 if you know A is related to B and are considering deleting A,
2043
-     *                                                 but want to see if A has any other objects blocking its deletion
2044
-     *                                                 before removing the relation between A and B
2045
-     * @return boolean
2046
-     * @throws EE_Error
2047
-     */
2048
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2049
-    {
2050
-        // first, if $ignore_this_model_obj was supplied, get its model
2051
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2052
-            $ignored_model = $ignore_this_model_obj->get_model();
2053
-        } else {
2054
-            $ignored_model = null;
2055
-        }
2056
-        // now check all the relations of $this_model_obj_or_id and see if there
2057
-        // are any related model objects blocking it?
2058
-        $is_blocked = false;
2059
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2060
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2061
-                // if $ignore_this_model_obj was supplied, then for the query
2062
-                // on that model needs to be told to ignore $ignore_this_model_obj
2063
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2064
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2065
-                        array(
2066
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2067
-                                '!=',
2068
-                                $ignore_this_model_obj->ID(),
2069
-                            ),
2070
-                        ),
2071
-                    ));
2072
-                } else {
2073
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2074
-                }
2075
-                if ($related_model_objects) {
2076
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2077
-                    $is_blocked = true;
2078
-                }
2079
-            }
2080
-        }
2081
-        return $is_blocked;
2082
-    }
2083
-
2084
-
2085
-    /**
2086
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2087
-     * @param array $row_results_for_deleting
2088
-     * @param bool  $allow_blocking
2089
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2090
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2091
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2092
-     *                 deleted. Example:
2093
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2094
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2095
-     *                 where each element is a group of columns and values that get deleted. Example:
2096
-     *                      array(
2097
-     *                          0 => array(
2098
-     *                              'Term_Relationship.object_id' => 1
2099
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2100
-     *                          ),
2101
-     *                          1 => array(
2102
-     *                              'Term_Relationship.object_id' => 1
2103
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2104
-     *                          )
2105
-     *                      )
2106
-     * @throws EE_Error
2107
-     */
2108
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2109
-    {
2110
-        $ids_to_delete_indexed_by_column = array();
2111
-        if ($this->has_primary_key_field()) {
2112
-            $primary_table = $this->_get_main_table();
2113
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2114
-            $other_tables = $this->_get_other_tables();
2115
-            $ids_to_delete_indexed_by_column = $query = array();
2116
-            foreach ($row_results_for_deleting as $item_to_delete) {
2117
-                // before we mark this item for deletion,
2118
-                // make sure there's no related entities blocking its deletion (if we're checking)
2119
-                if (
2120
-                    $allow_blocking
2121
-                    && $this->delete_is_blocked_by_related_models(
2122
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2123
-                    )
2124
-                ) {
2125
-                    continue;
2126
-                }
2127
-                // primary table deletes
2128
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2129
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2130
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2131
-                }
2132
-            }
2133
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2134
-            $fields = $this->get_combined_primary_key_fields();
2135
-            foreach ($row_results_for_deleting as $item_to_delete) {
2136
-                $ids_to_delete_indexed_by_column_for_row = array();
2137
-                foreach ($fields as $cpk_field) {
2138
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2139
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2140
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2141
-                    }
2142
-                }
2143
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2144
-            }
2145
-        } else {
2146
-            // so there's no primary key and no combined key...
2147
-            // sorry, can't help you
2148
-            throw new EE_Error(
2149
-                sprintf(
2150
-                    __(
2151
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2152
-                        "event_espresso"
2153
-                    ),
2154
-                    get_class($this)
2155
-                )
2156
-            );
2157
-        }
2158
-        return $ids_to_delete_indexed_by_column;
2159
-    }
2160
-
2161
-
2162
-    /**
2163
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2164
-     * the corresponding query_part for the query performing the delete.
2165
-     *
2166
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2167
-     * @return string
2168
-     * @throws EE_Error
2169
-     */
2170
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2171
-    {
2172
-        $query_part = '';
2173
-        if (empty($ids_to_delete_indexed_by_column)) {
2174
-            return $query_part;
2175
-        } elseif ($this->has_primary_key_field()) {
2176
-            $query = array();
2177
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2178
-                // make sure we have unique $ids
2179
-                $ids = array_unique($ids);
2180
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2181
-            }
2182
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2183
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2184
-            $ways_to_identify_a_row = array();
2185
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2186
-                $values_for_each_combined_primary_key_for_a_row = array();
2187
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2188
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2189
-                }
2190
-                $ways_to_identify_a_row[] = '('
2191
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2192
-                                            . ')';
2193
-            }
2194
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2195
-        }
2196
-        return $query_part;
2197
-    }
2198
-
2199
-
2200
-
2201
-    /**
2202
-     * Gets the model field by the fully qualified name
2203
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2204
-     * @return EE_Model_Field_Base
2205
-     */
2206
-    public function get_field_by_column($qualified_column_name)
2207
-    {
2208
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2209
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2210
-                return $field_obj;
2211
-            }
2212
-        }
2213
-        throw new EE_Error(
2214
-            sprintf(
2215
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2216
-                $this->get_this_model_name(),
2217
-                $qualified_column_name
2218
-            )
2219
-        );
2220
-    }
2221
-
2222
-
2223
-
2224
-    /**
2225
-     * Count all the rows that match criteria the model query params.
2226
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2227
-     * column
2228
-     *
2229
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2230
-     * @param string $field_to_count field on model to count by (not column name)
2231
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2232
-     *                               that by the setting $distinct to TRUE;
2233
-     * @return int
2234
-     * @throws EE_Error
2235
-     */
2236
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2237
-    {
2238
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2239
-        if ($field_to_count) {
2240
-            $field_obj = $this->field_settings_for($field_to_count);
2241
-            $column_to_count = $field_obj->get_qualified_column();
2242
-        } elseif ($this->has_primary_key_field()) {
2243
-            $pk_field_obj = $this->get_primary_key_field();
2244
-            $column_to_count = $pk_field_obj->get_qualified_column();
2245
-        } else {
2246
-            // there's no primary key
2247
-            // if we're counting distinct items, and there's no primary key,
2248
-            // we need to list out the columns for distinction;
2249
-            // otherwise we can just use star
2250
-            if ($distinct) {
2251
-                $columns_to_use = array();
2252
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2253
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2254
-                }
2255
-                $column_to_count = implode(',', $columns_to_use);
2256
-            } else {
2257
-                $column_to_count = '*';
2258
-            }
2259
-        }
2260
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2261
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2262
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2263
-    }
2264
-
2265
-
2266
-
2267
-    /**
2268
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2269
-     *
2270
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2271
-     * @param string $field_to_sum name of field (array key in $_fields array)
2272
-     * @return float
2273
-     * @throws EE_Error
2274
-     */
2275
-    public function sum($query_params, $field_to_sum = null)
2276
-    {
2277
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2278
-        if ($field_to_sum) {
2279
-            $field_obj = $this->field_settings_for($field_to_sum);
2280
-        } else {
2281
-            $field_obj = $this->get_primary_key_field();
2282
-        }
2283
-        $column_to_count = $field_obj->get_qualified_column();
2284
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2285
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2286
-        $data_type = $field_obj->get_wpdb_data_type();
2287
-        if ($data_type === '%d' || $data_type === '%s') {
2288
-            return (float) $return_value;
2289
-        }
2290
-        // must be %f
2291
-        return (float) $return_value;
2292
-    }
2293
-
2294
-
2295
-
2296
-    /**
2297
-     * Just calls the specified method on $wpdb with the given arguments
2298
-     * Consolidates a little extra error handling code
2299
-     *
2300
-     * @param string $wpdb_method
2301
-     * @param array  $arguments_to_provide
2302
-     * @throws EE_Error
2303
-     * @global wpdb  $wpdb
2304
-     * @return mixed
2305
-     */
2306
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2307
-    {
2308
-        // if we're in maintenance mode level 2, DON'T run any queries
2309
-        // because level 2 indicates the database needs updating and
2310
-        // is probably out of sync with the code
2311
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2312
-            throw new EE_Error(sprintf(__(
2313
-                "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2314
-                "event_espresso"
2315
-            )));
2316
-        }
2317
-        /** @type WPDB $wpdb */
2318
-        global $wpdb;
2319
-        if (! method_exists($wpdb, $wpdb_method)) {
2320
-            throw new EE_Error(sprintf(__(
2321
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2322
-                'event_espresso'
2323
-            ), $wpdb_method));
2324
-        }
2325
-        if (WP_DEBUG) {
2326
-            $old_show_errors_value = $wpdb->show_errors;
2327
-            $wpdb->show_errors(false);
2328
-        }
2329
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2330
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2331
-        if (WP_DEBUG) {
2332
-            $wpdb->show_errors($old_show_errors_value);
2333
-            if (! empty($wpdb->last_error)) {
2334
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2335
-            }
2336
-            if ($result === false) {
2337
-                throw new EE_Error(sprintf(__(
2338
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2339
-                    'event_espresso'
2340
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2341
-            }
2342
-        } elseif ($result === false) {
2343
-            EE_Error::add_error(
2344
-                sprintf(
2345
-                    __(
2346
-                        'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2347
-                        'event_espresso'
2348
-                    ),
2349
-                    $wpdb_method,
2350
-                    var_export($arguments_to_provide, true),
2351
-                    $wpdb->last_error
2352
-                ),
2353
-                __FILE__,
2354
-                __FUNCTION__,
2355
-                __LINE__
2356
-            );
2357
-        }
2358
-        return $result;
2359
-    }
2360
-
2361
-
2362
-
2363
-    /**
2364
-     * Attempts to run the indicated WPDB method with the provided arguments,
2365
-     * and if there's an error tries to verify the DB is correct. Uses
2366
-     * the static property EEM_Base::$_db_verification_level to determine whether
2367
-     * we should try to fix the EE core db, the addons, or just give up
2368
-     *
2369
-     * @param string $wpdb_method
2370
-     * @param array  $arguments_to_provide
2371
-     * @return mixed
2372
-     */
2373
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2374
-    {
2375
-        /** @type WPDB $wpdb */
2376
-        global $wpdb;
2377
-        $wpdb->last_error = null;
2378
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2379
-        // was there an error running the query? but we don't care on new activations
2380
-        // (we're going to setup the DB anyway on new activations)
2381
-        if (
2382
-            ($result === false || ! empty($wpdb->last_error))
2383
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2384
-        ) {
2385
-            switch (EEM_Base::$_db_verification_level) {
2386
-                case EEM_Base::db_verified_none:
2387
-                    // let's double-check core's DB
2388
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2389
-                    break;
2390
-                case EEM_Base::db_verified_core:
2391
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2392
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2393
-                    break;
2394
-                case EEM_Base::db_verified_addons:
2395
-                    // ummmm... you in trouble
2396
-                    return $result;
2397
-                    break;
2398
-            }
2399
-            if (! empty($error_message)) {
2400
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2401
-                trigger_error($error_message);
2402
-            }
2403
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2404
-        }
2405
-        return $result;
2406
-    }
2407
-
2408
-
2409
-
2410
-    /**
2411
-     * Verifies the EE core database is up-to-date and records that we've done it on
2412
-     * EEM_Base::$_db_verification_level
2413
-     *
2414
-     * @param string $wpdb_method
2415
-     * @param array  $arguments_to_provide
2416
-     * @return string
2417
-     */
2418
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2419
-    {
2420
-        /** @type WPDB $wpdb */
2421
-        global $wpdb;
2422
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2423
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2424
-        $error_message = sprintf(
2425
-            __(
2426
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2427
-                'event_espresso'
2428
-            ),
2429
-            $wpdb->last_error,
2430
-            $wpdb_method,
2431
-            wp_json_encode($arguments_to_provide)
2432
-        );
2433
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2434
-        return $error_message;
2435
-    }
2436
-
2437
-
2438
-
2439
-    /**
2440
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2441
-     * EEM_Base::$_db_verification_level
2442
-     *
2443
-     * @param $wpdb_method
2444
-     * @param $arguments_to_provide
2445
-     * @return string
2446
-     */
2447
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2448
-    {
2449
-        /** @type WPDB $wpdb */
2450
-        global $wpdb;
2451
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2452
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2453
-        $error_message = sprintf(
2454
-            __(
2455
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2456
-                'event_espresso'
2457
-            ),
2458
-            $wpdb->last_error,
2459
-            $wpdb_method,
2460
-            wp_json_encode($arguments_to_provide)
2461
-        );
2462
-        EE_System::instance()->initialize_addons();
2463
-        return $error_message;
2464
-    }
2465
-
2466
-
2467
-
2468
-    /**
2469
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2470
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2471
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2472
-     * ..."
2473
-     *
2474
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2475
-     * @return string
2476
-     */
2477
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2478
-    {
2479
-        return " FROM " . $model_query_info->get_full_join_sql() .
2480
-               $model_query_info->get_where_sql() .
2481
-               $model_query_info->get_group_by_sql() .
2482
-               $model_query_info->get_having_sql() .
2483
-               $model_query_info->get_order_by_sql() .
2484
-               $model_query_info->get_limit_sql();
2485
-    }
2486
-
2487
-
2488
-
2489
-    /**
2490
-     * Set to easily debug the next X queries ran from this model.
2491
-     *
2492
-     * @param int $count
2493
-     */
2494
-    public function show_next_x_db_queries($count = 1)
2495
-    {
2496
-        $this->_show_next_x_db_queries = $count;
2497
-    }
2498
-
2499
-
2500
-
2501
-    /**
2502
-     * @param $sql_query
2503
-     */
2504
-    public function show_db_query_if_previously_requested($sql_query)
2505
-    {
2506
-        if ($this->_show_next_x_db_queries > 0) {
2507
-            echo $sql_query;
2508
-            $this->_show_next_x_db_queries--;
2509
-        }
2510
-    }
2511
-
2512
-
2513
-
2514
-    /**
2515
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2516
-     * There are the 3 cases:
2517
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2518
-     * $otherModelObject has no ID, it is first saved.
2519
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2520
-     * has no ID, it is first saved.
2521
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2522
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2523
-     * join table
2524
-     *
2525
-     * @param        EE_Base_Class                     /int $thisModelObject
2526
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2527
-     * @param string $relationName                     , key in EEM_Base::_relations
2528
-     *                                                 an attendee to a group, you also want to specify which role they
2529
-     *                                                 will have in that group. So you would use this parameter to
2530
-     *                                                 specify array('role-column-name'=>'role-id')
2531
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2532
-     *                                                 to for relation to methods that allow you to further specify
2533
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2534
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2535
-     *                                                 because these will be inserted in any new rows created as well.
2536
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2537
-     * @throws EE_Error
2538
-     */
2539
-    public function add_relationship_to(
2540
-        $id_or_obj,
2541
-        $other_model_id_or_obj,
2542
-        $relationName,
2543
-        $extra_join_model_fields_n_values = array()
2544
-    ) {
2545
-        $relation_obj = $this->related_settings_for($relationName);
2546
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2547
-    }
2548
-
2549
-
2550
-
2551
-    /**
2552
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2553
-     * There are the 3 cases:
2554
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2555
-     * error
2556
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2557
-     * an error
2558
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2559
-     *
2560
-     * @param        EE_Base_Class /int $id_or_obj
2561
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2562
-     * @param string $relationName key in EEM_Base::_relations
2563
-     * @return boolean of success
2564
-     * @throws EE_Error
2565
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2566
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2567
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2568
-     *                             because these will be inserted in any new rows created as well.
2569
-     */
2570
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2571
-    {
2572
-        $relation_obj = $this->related_settings_for($relationName);
2573
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2574
-    }
2575
-
2576
-
2577
-
2578
-    /**
2579
-     * @param mixed           $id_or_obj
2580
-     * @param string          $relationName
2581
-     * @param array           $where_query_params
2582
-     * @param EE_Base_Class[] objects to which relations were removed
2583
-     * @return \EE_Base_Class[]
2584
-     * @throws EE_Error
2585
-     */
2586
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2587
-    {
2588
-        $relation_obj = $this->related_settings_for($relationName);
2589
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2590
-    }
2591
-
2592
-
2593
-
2594
-    /**
2595
-     * Gets all the related items of the specified $model_name, using $query_params.
2596
-     * Note: by default, we remove the "default query params"
2597
-     * because we want to get even deleted items etc.
2598
-     *
2599
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2600
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2601
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2602
-     * @return EE_Base_Class[]
2603
-     * @throws EE_Error
2604
-     */
2605
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2606
-    {
2607
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2608
-        $relation_settings = $this->related_settings_for($model_name);
2609
-        return $relation_settings->get_all_related($model_obj, $query_params);
2610
-    }
2611
-
2612
-
2613
-
2614
-    /**
2615
-     * Deletes all the model objects across the relation indicated by $model_name
2616
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2617
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2618
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2619
-     *
2620
-     * @param EE_Base_Class|int|string $id_or_obj
2621
-     * @param string                   $model_name
2622
-     * @param array                    $query_params
2623
-     * @return int how many deleted
2624
-     * @throws EE_Error
2625
-     */
2626
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2627
-    {
2628
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2629
-        $relation_settings = $this->related_settings_for($model_name);
2630
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2631
-    }
2632
-
2633
-
2634
-
2635
-    /**
2636
-     * Hard deletes all the model objects across the relation indicated by $model_name
2637
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2638
-     * the model objects can't be hard deleted because of blocking related model objects,
2639
-     * just does a soft-delete on them instead.
2640
-     *
2641
-     * @param EE_Base_Class|int|string $id_or_obj
2642
-     * @param string                   $model_name
2643
-     * @param array                    $query_params
2644
-     * @return int how many deleted
2645
-     * @throws EE_Error
2646
-     */
2647
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2648
-    {
2649
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2650
-        $relation_settings = $this->related_settings_for($model_name);
2651
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2652
-    }
2653
-
2654
-
2655
-
2656
-    /**
2657
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2658
-     * unless otherwise specified in the $query_params
2659
-     *
2660
-     * @param        int             /EE_Base_Class $id_or_obj
2661
-     * @param string $model_name     like 'Event', or 'Registration'
2662
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2663
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2664
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2665
-     *                               that by the setting $distinct to TRUE;
2666
-     * @return int
2667
-     * @throws EE_Error
2668
-     */
2669
-    public function count_related(
2670
-        $id_or_obj,
2671
-        $model_name,
2672
-        $query_params = array(),
2673
-        $field_to_count = null,
2674
-        $distinct = false
2675
-    ) {
2676
-        $related_model = $this->get_related_model_obj($model_name);
2677
-        // we're just going to use the query params on the related model's normal get_all query,
2678
-        // except add a condition to say to match the current mod
2679
-        if (! isset($query_params['default_where_conditions'])) {
2680
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2681
-        }
2682
-        $this_model_name = $this->get_this_model_name();
2683
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2684
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2685
-        return $related_model->count($query_params, $field_to_count, $distinct);
2686
-    }
2687
-
2688
-
2689
-
2690
-    /**
2691
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2692
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2693
-     *
2694
-     * @param        int           /EE_Base_Class $id_or_obj
2695
-     * @param string $model_name   like 'Event', or 'Registration'
2696
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2697
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2698
-     * @return float
2699
-     * @throws EE_Error
2700
-     */
2701
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2702
-    {
2703
-        $related_model = $this->get_related_model_obj($model_name);
2704
-        if (! is_array($query_params)) {
2705
-            EE_Error::doing_it_wrong(
2706
-                'EEM_Base::sum_related',
2707
-                sprintf(
2708
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2709
-                    gettype($query_params)
2710
-                ),
2711
-                '4.6.0'
2712
-            );
2713
-            $query_params = array();
2714
-        }
2715
-        // we're just going to use the query params on the related model's normal get_all query,
2716
-        // except add a condition to say to match the current mod
2717
-        if (! isset($query_params['default_where_conditions'])) {
2718
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2719
-        }
2720
-        $this_model_name = $this->get_this_model_name();
2721
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2722
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2723
-        return $related_model->sum($query_params, $field_to_sum);
2724
-    }
2725
-
2726
-
2727
-
2728
-    /**
2729
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2730
-     * $modelObject
2731
-     *
2732
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2733
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2734
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2735
-     * @return EE_Base_Class
2736
-     * @throws EE_Error
2737
-     */
2738
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2739
-    {
2740
-        $query_params['limit'] = 1;
2741
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2742
-        if ($results) {
2743
-            return array_shift($results);
2744
-        }
2745
-        return null;
2746
-    }
2747
-
2748
-
2749
-
2750
-    /**
2751
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2752
-     *
2753
-     * @return string
2754
-     */
2755
-    public function get_this_model_name()
2756
-    {
2757
-        return str_replace("EEM_", "", get_class($this));
2758
-    }
2759
-
2760
-
2761
-
2762
-    /**
2763
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2764
-     *
2765
-     * @return EE_Any_Foreign_Model_Name_Field
2766
-     * @throws EE_Error
2767
-     */
2768
-    public function get_field_containing_related_model_name()
2769
-    {
2770
-        foreach ($this->field_settings(true) as $field) {
2771
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2772
-                $field_with_model_name = $field;
2773
-            }
2774
-        }
2775
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2776
-            throw new EE_Error(sprintf(
2777
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2778
-                $this->get_this_model_name()
2779
-            ));
2780
-        }
2781
-        return $field_with_model_name;
2782
-    }
2783
-
2784
-
2785
-
2786
-    /**
2787
-     * Inserts a new entry into the database, for each table.
2788
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2789
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2790
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2791
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2792
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2793
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2794
-     *
2795
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2796
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2797
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2798
-     *                              of EEM_Base)
2799
-     * @return int|string new primary key on main table that got inserted
2800
-     * @throws EE_Error
2801
-     */
2802
-    public function insert($field_n_values)
2803
-    {
2804
-        /**
2805
-         * Filters the fields and their values before inserting an item using the models
2806
-         *
2807
-         * @param array    $fields_n_values keys are the fields and values are their new values
2808
-         * @param EEM_Base $model           the model used
2809
-         */
2810
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2811
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2812
-            $main_table = $this->_get_main_table();
2813
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2814
-            if ($new_id !== false) {
2815
-                foreach ($this->_get_other_tables() as $other_table) {
2816
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2817
-                }
2818
-            }
2819
-            /**
2820
-             * Done just after attempting to insert a new model object
2821
-             *
2822
-             * @param EEM_Base   $model           used
2823
-             * @param array      $fields_n_values fields and their values
2824
-             * @param int|string the              ID of the newly-inserted model object
2825
-             */
2826
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2827
-            return $new_id;
2828
-        }
2829
-        return false;
2830
-    }
2831
-
2832
-
2833
-
2834
-    /**
2835
-     * Checks that the result would satisfy the unique indexes on this model
2836
-     *
2837
-     * @param array  $field_n_values
2838
-     * @param string $action
2839
-     * @return boolean
2840
-     * @throws EE_Error
2841
-     */
2842
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2843
-    {
2844
-        foreach ($this->unique_indexes() as $index_name => $index) {
2845
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2846
-            if ($this->exists(array($uniqueness_where_params))) {
2847
-                EE_Error::add_error(
2848
-                    sprintf(
2849
-                        __(
2850
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2851
-                            "event_espresso"
2852
-                        ),
2853
-                        $action,
2854
-                        $this->_get_class_name(),
2855
-                        $index_name,
2856
-                        implode(",", $index->field_names()),
2857
-                        http_build_query($uniqueness_where_params)
2858
-                    ),
2859
-                    __FILE__,
2860
-                    __FUNCTION__,
2861
-                    __LINE__
2862
-                );
2863
-                return false;
2864
-            }
2865
-        }
2866
-        return true;
2867
-    }
2868
-
2869
-
2870
-
2871
-    /**
2872
-     * Checks the database for an item that conflicts (ie, if this item were
2873
-     * saved to the DB would break some uniqueness requirement, like a primary key
2874
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2875
-     * can be either an EE_Base_Class or an array of fields n values
2876
-     *
2877
-     * @param EE_Base_Class|array $obj_or_fields_array
2878
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2879
-     *                                                 when looking for conflicts
2880
-     *                                                 (ie, if false, we ignore the model object's primary key
2881
-     *                                                 when finding "conflicts". If true, it's also considered).
2882
-     *                                                 Only works for INT primary key,
2883
-     *                                                 STRING primary keys cannot be ignored
2884
-     * @throws EE_Error
2885
-     * @return EE_Base_Class|array
2886
-     */
2887
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2888
-    {
2889
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2890
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2891
-        } elseif (is_array($obj_or_fields_array)) {
2892
-            $fields_n_values = $obj_or_fields_array;
2893
-        } else {
2894
-            throw new EE_Error(
2895
-                sprintf(
2896
-                    __(
2897
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2898
-                        "event_espresso"
2899
-                    ),
2900
-                    get_class($this),
2901
-                    $obj_or_fields_array
2902
-                )
2903
-            );
2904
-        }
2905
-        $query_params = array();
2906
-        if (
2907
-            $this->has_primary_key_field()
2908
-            && ($include_primary_key
2909
-                || $this->get_primary_key_field()
2910
-                   instanceof
2911
-                   EE_Primary_Key_String_Field)
2912
-            && isset($fields_n_values[ $this->primary_key_name() ])
2913
-        ) {
2914
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2915
-        }
2916
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2917
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2918
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2919
-        }
2920
-        // if there is nothing to base this search on, then we shouldn't find anything
2921
-        if (empty($query_params)) {
2922
-            return array();
2923
-        }
2924
-        return $this->get_one($query_params);
2925
-    }
2926
-
2927
-
2928
-
2929
-    /**
2930
-     * Like count, but is optimized and returns a boolean instead of an int
2931
-     *
2932
-     * @param array $query_params
2933
-     * @return boolean
2934
-     * @throws EE_Error
2935
-     */
2936
-    public function exists($query_params)
2937
-    {
2938
-        $query_params['limit'] = 1;
2939
-        return $this->count($query_params) > 0;
2940
-    }
2941
-
2942
-
2943
-
2944
-    /**
2945
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2946
-     *
2947
-     * @param int|string $id
2948
-     * @return boolean
2949
-     * @throws EE_Error
2950
-     */
2951
-    public function exists_by_ID($id)
2952
-    {
2953
-        return $this->exists(
2954
-            array(
2955
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2956
-                array(
2957
-                    $this->primary_key_name() => $id,
2958
-                ),
2959
-            )
2960
-        );
2961
-    }
2962
-
2963
-
2964
-
2965
-    /**
2966
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2967
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2968
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2969
-     * on the main table)
2970
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2971
-     * cases where we want to call it directly rather than via insert().
2972
-     *
2973
-     * @access   protected
2974
-     * @param EE_Table_Base $table
2975
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2976
-     *                                       float
2977
-     * @param int           $new_id          for now we assume only int keys
2978
-     * @throws EE_Error
2979
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2980
-     * @return int ID of new row inserted, or FALSE on failure
2981
-     */
2982
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2983
-    {
2984
-        global $wpdb;
2985
-        $insertion_col_n_values = array();
2986
-        $format_for_insertion = array();
2987
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2988
-        foreach ($fields_on_table as $field_name => $field_obj) {
2989
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2990
-            if ($field_obj->is_auto_increment()) {
2991
-                continue;
2992
-            }
2993
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2994
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2995
-            if ($prepared_value !== null) {
2996
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2997
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2998
-            }
2999
-        }
3000
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3001
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3002
-            // so add the fk to the main table as a column
3003
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3004
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3005
-        }
3006
-        // insert the new entry
3007
-        $result = $this->_do_wpdb_query(
3008
-            'insert',
3009
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3010
-        );
3011
-        if ($result === false) {
3012
-            return false;
3013
-        }
3014
-        // ok, now what do we return for the ID of the newly-inserted thing?
3015
-        if ($this->has_primary_key_field()) {
3016
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3017
-                return $wpdb->insert_id;
3018
-            }
3019
-            // it's not an auto-increment primary key, so
3020
-            // it must have been supplied
3021
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3022
-        }
3023
-        // we can't return a  primary key because there is none. instead return
3024
-        // a unique string indicating this model
3025
-        return $this->get_index_primary_key_string($fields_n_values);
3026
-    }
3027
-
3028
-
3029
-
3030
-    /**
3031
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3032
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3033
-     * and there is no default, we pass it along. WPDB will take care of it)
3034
-     *
3035
-     * @param EE_Model_Field_Base $field_obj
3036
-     * @param array               $fields_n_values
3037
-     * @return mixed string|int|float depending on what the table column will be expecting
3038
-     * @throws EE_Error
3039
-     */
3040
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3041
-    {
3042
-        // if this field doesn't allow nullable, don't allow it
3043
-        if (
3044
-            ! $field_obj->is_nullable()
3045
-            && (
3046
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3047
-                || $fields_n_values[ $field_obj->get_name() ] === null
3048
-            )
3049
-        ) {
3050
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3051
-        }
3052
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3053
-            ? $fields_n_values[ $field_obj->get_name() ]
3054
-            : null;
3055
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3056
-    }
3057
-
3058
-
3059
-
3060
-    /**
3061
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3062
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3063
-     * the field's prepare_for_set() method.
3064
-     *
3065
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3066
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3067
-     *                                   top of file)
3068
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3069
-     *                                   $value is a custom selection
3070
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3071
-     */
3072
-    private function _prepare_value_for_use_in_db($value, $field)
3073
-    {
3074
-        if ($field && $field instanceof EE_Model_Field_Base) {
3075
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3076
-            switch ($this->_values_already_prepared_by_model_object) {
3077
-                /** @noinspection PhpMissingBreakStatementInspection */
3078
-                case self::not_prepared_by_model_object:
3079
-                    $value = $field->prepare_for_set($value);
3080
-                // purposefully left out "return"
3081
-                case self::prepared_by_model_object:
3082
-                    /** @noinspection SuspiciousAssignmentsInspection */
3083
-                    $value = $field->prepare_for_use_in_db($value);
3084
-                case self::prepared_for_use_in_db:
3085
-                    // leave the value alone
3086
-            }
3087
-            return $value;
3088
-            // phpcs:enable
3089
-        }
3090
-        return $value;
3091
-    }
3092
-
3093
-
3094
-
3095
-    /**
3096
-     * Returns the main table on this model
3097
-     *
3098
-     * @return EE_Primary_Table
3099
-     * @throws EE_Error
3100
-     */
3101
-    protected function _get_main_table()
3102
-    {
3103
-        foreach ($this->_tables as $table) {
3104
-            if ($table instanceof EE_Primary_Table) {
3105
-                return $table;
3106
-            }
3107
-        }
3108
-        throw new EE_Error(sprintf(__(
3109
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3110
-            'event_espresso'
3111
-        ), get_class($this)));
3112
-    }
3113
-
3114
-
3115
-
3116
-    /**
3117
-     * table
3118
-     * returns EE_Primary_Table table name
3119
-     *
3120
-     * @return string
3121
-     * @throws EE_Error
3122
-     */
3123
-    public function table()
3124
-    {
3125
-        return $this->_get_main_table()->get_table_name();
3126
-    }
3127
-
3128
-
3129
-
3130
-    /**
3131
-     * table
3132
-     * returns first EE_Secondary_Table table name
3133
-     *
3134
-     * @return string
3135
-     */
3136
-    public function second_table()
3137
-    {
3138
-        // grab second table from tables array
3139
-        $second_table = end($this->_tables);
3140
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3141
-    }
3142
-
3143
-
3144
-
3145
-    /**
3146
-     * get_table_obj_by_alias
3147
-     * returns table name given it's alias
3148
-     *
3149
-     * @param string $table_alias
3150
-     * @return EE_Primary_Table | EE_Secondary_Table
3151
-     */
3152
-    public function get_table_obj_by_alias($table_alias = '')
3153
-    {
3154
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3155
-    }
3156
-
3157
-
3158
-
3159
-    /**
3160
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3161
-     *
3162
-     * @return EE_Secondary_Table[]
3163
-     */
3164
-    protected function _get_other_tables()
3165
-    {
3166
-        $other_tables = array();
3167
-        foreach ($this->_tables as $table_alias => $table) {
3168
-            if ($table instanceof EE_Secondary_Table) {
3169
-                $other_tables[ $table_alias ] = $table;
3170
-            }
3171
-        }
3172
-        return $other_tables;
3173
-    }
3174
-
3175
-
3176
-
3177
-    /**
3178
-     * Finds all the fields that correspond to the given table
3179
-     *
3180
-     * @param string $table_alias , array key in EEM_Base::_tables
3181
-     * @return EE_Model_Field_Base[]
3182
-     */
3183
-    public function _get_fields_for_table($table_alias)
3184
-    {
3185
-        return $this->_fields[ $table_alias ];
3186
-    }
3187
-
3188
-
3189
-
3190
-    /**
3191
-     * Recurses through all the where parameters, and finds all the related models we'll need
3192
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3193
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3194
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3195
-     * related Registration, Transaction, and Payment models.
3196
-     *
3197
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3198
-     * @return EE_Model_Query_Info_Carrier
3199
-     * @throws EE_Error
3200
-     */
3201
-    public function _extract_related_models_from_query($query_params)
3202
-    {
3203
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3204
-        if (array_key_exists(0, $query_params)) {
3205
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3206
-        }
3207
-        if (array_key_exists('group_by', $query_params)) {
3208
-            if (is_array($query_params['group_by'])) {
3209
-                $this->_extract_related_models_from_sub_params_array_values(
3210
-                    $query_params['group_by'],
3211
-                    $query_info_carrier,
3212
-                    'group_by'
3213
-                );
3214
-            } elseif (! empty($query_params['group_by'])) {
3215
-                $this->_extract_related_model_info_from_query_param(
3216
-                    $query_params['group_by'],
3217
-                    $query_info_carrier,
3218
-                    'group_by'
3219
-                );
3220
-            }
3221
-        }
3222
-        if (array_key_exists('having', $query_params)) {
3223
-            $this->_extract_related_models_from_sub_params_array_keys(
3224
-                $query_params[0],
3225
-                $query_info_carrier,
3226
-                'having'
3227
-            );
3228
-        }
3229
-        if (array_key_exists('order_by', $query_params)) {
3230
-            if (is_array($query_params['order_by'])) {
3231
-                $this->_extract_related_models_from_sub_params_array_keys(
3232
-                    $query_params['order_by'],
3233
-                    $query_info_carrier,
3234
-                    'order_by'
3235
-                );
3236
-            } elseif (! empty($query_params['order_by'])) {
3237
-                $this->_extract_related_model_info_from_query_param(
3238
-                    $query_params['order_by'],
3239
-                    $query_info_carrier,
3240
-                    'order_by'
3241
-                );
3242
-            }
3243
-        }
3244
-        if (array_key_exists('force_join', $query_params)) {
3245
-            $this->_extract_related_models_from_sub_params_array_values(
3246
-                $query_params['force_join'],
3247
-                $query_info_carrier,
3248
-                'force_join'
3249
-            );
3250
-        }
3251
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3252
-        return $query_info_carrier;
3253
-    }
3254
-
3255
-
3256
-
3257
-    /**
3258
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3259
-     *
3260
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3261
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3262
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3263
-     * @throws EE_Error
3264
-     * @return \EE_Model_Query_Info_Carrier
3265
-     */
3266
-    private function _extract_related_models_from_sub_params_array_keys(
3267
-        $sub_query_params,
3268
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3269
-        $query_param_type
3270
-    ) {
3271
-        if (! empty($sub_query_params)) {
3272
-            $sub_query_params = (array) $sub_query_params;
3273
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3274
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3275
-                $this->_extract_related_model_info_from_query_param(
3276
-                    $param,
3277
-                    $model_query_info_carrier,
3278
-                    $query_param_type
3279
-                );
3280
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3281
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3282
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3283
-                // of array('Registration.TXN_ID'=>23)
3284
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3285
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3286
-                    if (! is_array($possibly_array_of_params)) {
3287
-                        throw new EE_Error(sprintf(
3288
-                            __(
3289
-                                "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3290
-                                "event_espresso"
3291
-                            ),
3292
-                            $param,
3293
-                            $possibly_array_of_params
3294
-                        ));
3295
-                    }
3296
-                    $this->_extract_related_models_from_sub_params_array_keys(
3297
-                        $possibly_array_of_params,
3298
-                        $model_query_info_carrier,
3299
-                        $query_param_type
3300
-                    );
3301
-                } elseif (
3302
-                    $query_param_type === 0 // ie WHERE
3303
-                          && is_array($possibly_array_of_params)
3304
-                          && isset($possibly_array_of_params[2])
3305
-                          && $possibly_array_of_params[2] == true
3306
-                ) {
3307
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3308
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3309
-                    // from which we should extract query parameters!
3310
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3311
-                        throw new EE_Error(sprintf(__(
3312
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3313
-                            "event_espresso"
3314
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3315
-                    }
3316
-                    $this->_extract_related_model_info_from_query_param(
3317
-                        $possibly_array_of_params[1],
3318
-                        $model_query_info_carrier,
3319
-                        $query_param_type
3320
-                    );
3321
-                }
3322
-            }
3323
-        }
3324
-        return $model_query_info_carrier;
3325
-    }
3326
-
3327
-
3328
-
3329
-    /**
3330
-     * For extracting related models from forced_joins, where the array values contain the info about what
3331
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3332
-     *
3333
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3334
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3335
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3336
-     * @throws EE_Error
3337
-     * @return \EE_Model_Query_Info_Carrier
3338
-     */
3339
-    private function _extract_related_models_from_sub_params_array_values(
3340
-        $sub_query_params,
3341
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3342
-        $query_param_type
3343
-    ) {
3344
-        if (! empty($sub_query_params)) {
3345
-            if (! is_array($sub_query_params)) {
3346
-                throw new EE_Error(sprintf(
3347
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3348
-                    $sub_query_params
3349
-                ));
3350
-            }
3351
-            foreach ($sub_query_params as $param) {
3352
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3353
-                $this->_extract_related_model_info_from_query_param(
3354
-                    $param,
3355
-                    $model_query_info_carrier,
3356
-                    $query_param_type
3357
-                );
3358
-            }
3359
-        }
3360
-        return $model_query_info_carrier;
3361
-    }
3362
-
3363
-
3364
-    /**
3365
-     * Extract all the query parts from  model query params
3366
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3367
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3368
-     * but use them in a different order. Eg, we need to know what models we are querying
3369
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3370
-     * other models before we can finalize the where clause SQL.
3371
-     *
3372
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3373
-     * @throws EE_Error
3374
-     * @return EE_Model_Query_Info_Carrier
3375
-     * @throws ModelConfigurationException
3376
-     */
3377
-    public function _create_model_query_info_carrier($query_params)
3378
-    {
3379
-        if (! is_array($query_params)) {
3380
-            EE_Error::doing_it_wrong(
3381
-                'EEM_Base::_create_model_query_info_carrier',
3382
-                sprintf(
3383
-                    __(
3384
-                        '$query_params should be an array, you passed a variable of type %s',
3385
-                        'event_espresso'
3386
-                    ),
3387
-                    gettype($query_params)
3388
-                ),
3389
-                '4.6.0'
3390
-            );
3391
-            $query_params = array();
3392
-        }
3393
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3394
-        // first check if we should alter the query to account for caps or not
3395
-        // because the caps might require us to do extra joins
3396
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3397
-            $query_params[0] = array_replace_recursive(
3398
-                $query_params[0],
3399
-                $this->caps_where_conditions(
3400
-                    $query_params['caps']
3401
-                )
3402
-            );
3403
-        }
3404
-
3405
-        // check if we should alter the query to remove data related to protected
3406
-        // custom post types
3407
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3408
-            $where_param_key_for_password = $this->modelChainAndPassword();
3409
-            // only include if related to a cpt where no password has been set
3410
-            $query_params[0]['OR*nopassword'] = array(
3411
-                $where_param_key_for_password => '',
3412
-                $where_param_key_for_password . '*' => array('IS_NULL')
3413
-            );
3414
-        }
3415
-        $query_object = $this->_extract_related_models_from_query($query_params);
3416
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3417
-        foreach ($query_params[0] as $key => $value) {
3418
-            if (is_int($key)) {
3419
-                throw new EE_Error(
3420
-                    sprintf(
3421
-                        __(
3422
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3423
-                            "event_espresso"
3424
-                        ),
3425
-                        $key,
3426
-                        var_export($value, true),
3427
-                        var_export($query_params, true),
3428
-                        get_class($this)
3429
-                    )
3430
-                );
3431
-            }
3432
-        }
3433
-        if (
3434
-            array_key_exists('default_where_conditions', $query_params)
3435
-            && ! empty($query_params['default_where_conditions'])
3436
-        ) {
3437
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3438
-        } else {
3439
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3440
-        }
3441
-        $query_params[0] = array_merge(
3442
-            $this->_get_default_where_conditions_for_models_in_query(
3443
-                $query_object,
3444
-                $use_default_where_conditions,
3445
-                $query_params[0]
3446
-            ),
3447
-            $query_params[0]
3448
-        );
3449
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3450
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3451
-        // So we need to setup a subquery and use that for the main join.
3452
-        // Note for now this only works on the primary table for the model.
3453
-        // So for instance, you could set the limit array like this:
3454
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3455
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3456
-            $query_object->set_main_model_join_sql(
3457
-                $this->_construct_limit_join_select(
3458
-                    $query_params['on_join_limit'][0],
3459
-                    $query_params['on_join_limit'][1]
3460
-                )
3461
-            );
3462
-        }
3463
-        // set limit
3464
-        if (array_key_exists('limit', $query_params)) {
3465
-            if (is_array($query_params['limit'])) {
3466
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3467
-                    $e = sprintf(
3468
-                        __(
3469
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3470
-                            "event_espresso"
3471
-                        ),
3472
-                        http_build_query($query_params['limit'])
3473
-                    );
3474
-                    throw new EE_Error($e . "|" . $e);
3475
-                }
3476
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3477
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3478
-            } elseif (! empty($query_params['limit'])) {
3479
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3480
-            }
3481
-        }
3482
-        // set order by
3483
-        if (array_key_exists('order_by', $query_params)) {
3484
-            if (is_array($query_params['order_by'])) {
3485
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3486
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3487
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3488
-                if (array_key_exists('order', $query_params)) {
3489
-                    throw new EE_Error(
3490
-                        sprintf(
3491
-                            __(
3492
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3493
-                                "event_espresso"
3494
-                            ),
3495
-                            get_class($this),
3496
-                            implode(", ", array_keys($query_params['order_by'])),
3497
-                            implode(", ", $query_params['order_by']),
3498
-                            $query_params['order']
3499
-                        )
3500
-                    );
3501
-                }
3502
-                $this->_extract_related_models_from_sub_params_array_keys(
3503
-                    $query_params['order_by'],
3504
-                    $query_object,
3505
-                    'order_by'
3506
-                );
3507
-                // assume it's an array of fields to order by
3508
-                $order_array = array();
3509
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3510
-                    $order = $this->_extract_order($order);
3511
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3512
-                }
3513
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3514
-            } elseif (! empty($query_params['order_by'])) {
3515
-                $this->_extract_related_model_info_from_query_param(
3516
-                    $query_params['order_by'],
3517
-                    $query_object,
3518
-                    'order',
3519
-                    $query_params['order_by']
3520
-                );
3521
-                $order = isset($query_params['order'])
3522
-                    ? $this->_extract_order($query_params['order'])
3523
-                    : 'DESC';
3524
-                $query_object->set_order_by_sql(
3525
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3526
-                );
3527
-            }
3528
-        }
3529
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3530
-        if (
3531
-            ! array_key_exists('order_by', $query_params)
3532
-            && array_key_exists('order', $query_params)
3533
-            && ! empty($query_params['order'])
3534
-        ) {
3535
-            $pk_field = $this->get_primary_key_field();
3536
-            $order = $this->_extract_order($query_params['order']);
3537
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3538
-        }
3539
-        // set group by
3540
-        if (array_key_exists('group_by', $query_params)) {
3541
-            if (is_array($query_params['group_by'])) {
3542
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3543
-                $group_by_array = array();
3544
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3545
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3546
-                }
3547
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3548
-            } elseif (! empty($query_params['group_by'])) {
3549
-                $query_object->set_group_by_sql(
3550
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3551
-                );
3552
-            }
3553
-        }
3554
-        // set having
3555
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3556
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3557
-        }
3558
-        // now, just verify they didn't pass anything wack
3559
-        foreach ($query_params as $query_key => $query_value) {
3560
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3561
-                throw new EE_Error(
3562
-                    sprintf(
3563
-                        __(
3564
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3565
-                            'event_espresso'
3566
-                        ),
3567
-                        $query_key,
3568
-                        get_class($this),
3569
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3570
-                        implode(',', $this->_allowed_query_params)
3571
-                    )
3572
-                );
3573
-            }
3574
-        }
3575
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3576
-        if (empty($main_model_join_sql)) {
3577
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3578
-        }
3579
-        return $query_object;
3580
-    }
3581
-
3582
-
3583
-
3584
-    /**
3585
-     * Gets the where conditions that should be imposed on the query based on the
3586
-     * context (eg reading frontend, backend, edit or delete).
3587
-     *
3588
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3589
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3590
-     * @throws EE_Error
3591
-     */
3592
-    public function caps_where_conditions($context = self::caps_read)
3593
-    {
3594
-        EEM_Base::verify_is_valid_cap_context($context);
3595
-        $cap_where_conditions = array();
3596
-        $cap_restrictions = $this->caps_missing($context);
3597
-        /**
3598
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3599
-         */
3600
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3601
-            $cap_where_conditions = array_replace_recursive(
3602
-                $cap_where_conditions,
3603
-                $restriction_if_no_cap->get_default_where_conditions()
3604
-            );
3605
-        }
3606
-        return apply_filters(
3607
-            'FHEE__EEM_Base__caps_where_conditions__return',
3608
-            $cap_where_conditions,
3609
-            $this,
3610
-            $context,
3611
-            $cap_restrictions
3612
-        );
3613
-    }
3614
-
3615
-
3616
-
3617
-    /**
3618
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3619
-     * otherwise throws an exception
3620
-     *
3621
-     * @param string $should_be_order_string
3622
-     * @return string either ASC, asc, DESC or desc
3623
-     * @throws EE_Error
3624
-     */
3625
-    private function _extract_order($should_be_order_string)
3626
-    {
3627
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3628
-            return $should_be_order_string;
3629
-        }
3630
-        throw new EE_Error(
3631
-            sprintf(
3632
-                __(
3633
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3634
-                    "event_espresso"
3635
-                ),
3636
-                get_class($this),
3637
-                $should_be_order_string
3638
-            )
3639
-        );
3640
-    }
3641
-
3642
-
3643
-
3644
-    /**
3645
-     * Looks at all the models which are included in this query, and asks each
3646
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3647
-     * so they can be merged
3648
-     *
3649
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3650
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3651
-     *                                                                  'none' means NO default where conditions will
3652
-     *                                                                  be used AT ALL during this query.
3653
-     *                                                                  'other_models_only' means default where
3654
-     *                                                                  conditions from other models will be used, but
3655
-     *                                                                  not for this primary model. 'all', the default,
3656
-     *                                                                  means default where conditions will apply as
3657
-     *                                                                  normal
3658
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3659
-     * @throws EE_Error
3660
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3661
-     */
3662
-    private function _get_default_where_conditions_for_models_in_query(
3663
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3664
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3665
-        $where_query_params = array()
3666
-    ) {
3667
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3668
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3669
-            throw new EE_Error(sprintf(
3670
-                __(
3671
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3672
-                    "event_espresso"
3673
-                ),
3674
-                $use_default_where_conditions,
3675
-                implode(", ", $allowed_used_default_where_conditions_values)
3676
-            ));
3677
-        }
3678
-        $universal_query_params = array();
3679
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3680
-            $universal_query_params = $this->_get_default_where_conditions();
3681
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3682
-            $universal_query_params = $this->_get_minimum_where_conditions();
3683
-        }
3684
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3685
-            $related_model = $this->get_related_model_obj($model_name);
3686
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3687
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3688
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3689
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3690
-            } else {
3691
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3692
-                continue;
3693
-            }
3694
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3695
-                $related_model_universal_where_params,
3696
-                $where_query_params,
3697
-                $related_model,
3698
-                $model_relation_path
3699
-            );
3700
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3701
-                $universal_query_params,
3702
-                $overrides
3703
-            );
3704
-        }
3705
-        return $universal_query_params;
3706
-    }
3707
-
3708
-
3709
-
3710
-    /**
3711
-     * Determines whether or not we should use default where conditions for the model in question
3712
-     * (this model, or other related models).
3713
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3714
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3715
-     * We should use default where conditions on related models when they requested to use default where conditions
3716
-     * on all models, or specifically just on other related models
3717
-     * @param      $default_where_conditions_value
3718
-     * @param bool $for_this_model false means this is for OTHER related models
3719
-     * @return bool
3720
-     */
3721
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3722
-    {
3723
-        return (
3724
-                   $for_this_model
3725
-                   && in_array(
3726
-                       $default_where_conditions_value,
3727
-                       array(
3728
-                           EEM_Base::default_where_conditions_all,
3729
-                           EEM_Base::default_where_conditions_this_only,
3730
-                           EEM_Base::default_where_conditions_minimum_others,
3731
-                       ),
3732
-                       true
3733
-                   )
3734
-               )
3735
-               || (
3736
-                   ! $for_this_model
3737
-                   && in_array(
3738
-                       $default_where_conditions_value,
3739
-                       array(
3740
-                           EEM_Base::default_where_conditions_all,
3741
-                           EEM_Base::default_where_conditions_others_only,
3742
-                       ),
3743
-                       true
3744
-                   )
3745
-               );
3746
-    }
3747
-
3748
-    /**
3749
-     * Determines whether or not we should use default minimum conditions for the model in question
3750
-     * (this model, or other related models).
3751
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3752
-     * where conditions.
3753
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3754
-     * on this model or others
3755
-     * @param      $default_where_conditions_value
3756
-     * @param bool $for_this_model false means this is for OTHER related models
3757
-     * @return bool
3758
-     */
3759
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3760
-    {
3761
-        return (
3762
-                   $for_this_model
3763
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3764
-               )
3765
-               || (
3766
-                   ! $for_this_model
3767
-                   && in_array(
3768
-                       $default_where_conditions_value,
3769
-                       array(
3770
-                           EEM_Base::default_where_conditions_minimum_others,
3771
-                           EEM_Base::default_where_conditions_minimum_all,
3772
-                       ),
3773
-                       true
3774
-                   )
3775
-               );
3776
-    }
3777
-
3778
-
3779
-    /**
3780
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3781
-     * then we also add a special where condition which allows for that model's primary key
3782
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3783
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3784
-     *
3785
-     * @param array    $default_where_conditions
3786
-     * @param array    $provided_where_conditions
3787
-     * @param EEM_Base $model
3788
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3789
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3790
-     * @throws EE_Error
3791
-     */
3792
-    private function _override_defaults_or_make_null_friendly(
3793
-        $default_where_conditions,
3794
-        $provided_where_conditions,
3795
-        $model,
3796
-        $model_relation_path
3797
-    ) {
3798
-        $null_friendly_where_conditions = array();
3799
-        $none_overridden = true;
3800
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3801
-        foreach ($default_where_conditions as $key => $val) {
3802
-            if (isset($provided_where_conditions[ $key ])) {
3803
-                $none_overridden = false;
3804
-            } else {
3805
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3806
-            }
3807
-        }
3808
-        if ($none_overridden && $default_where_conditions) {
3809
-            if ($model->has_primary_key_field()) {
3810
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3811
-                                                                                . "."
3812
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3813
-            }/*else{
38
+	/**
39
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
42
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	private $_values_already_prepared_by_model_object = 0;
47
+
48
+	/**
49
+	 * when $_values_already_prepared_by_model_object equals this, we assume
50
+	 * the data is just like form input that needs to have the model fields'
51
+	 * prepare_for_set and prepare_for_use_in_db called on it
52
+	 */
53
+	const not_prepared_by_model_object = 0;
54
+
55
+	/**
56
+	 * when $_values_already_prepared_by_model_object equals this, we
57
+	 * assume this value is coming from a model object and doesn't need to have
58
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
59
+	 */
60
+	const prepared_by_model_object = 1;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the values are already to be used in the database (ie no processing is done
65
+	 * on them by the model's fields)
66
+	 */
67
+	const prepared_for_use_in_db = 2;
68
+
69
+
70
+	protected $singular_item = 'Item';
71
+
72
+	protected $plural_item   = 'Items';
73
+
74
+	/**
75
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
+	 */
77
+	protected $_tables;
78
+
79
+	/**
80
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
+	 *
84
+	 * @var \EE_Model_Field_Base[][] $_fields
85
+	 */
86
+	protected $_fields;
87
+
88
+	/**
89
+	 * array of different kinds of relations
90
+	 *
91
+	 * @var \EE_Model_Relation_Base[] $_model_relations
92
+	 */
93
+	protected $_model_relations;
94
+
95
+	/**
96
+	 * @var \EE_Index[] $_indexes
97
+	 */
98
+	protected $_indexes = array();
99
+
100
+	/**
101
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
102
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
+	 * by setting the same columns as used in these queries in the query yourself.
104
+	 *
105
+	 * @var EE_Default_Where_Conditions
106
+	 */
107
+	protected $_default_where_conditions_strategy;
108
+
109
+	/**
110
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
+	 * This is particularly useful when you want something between 'none' and 'default'
112
+	 *
113
+	 * @var EE_Default_Where_Conditions
114
+	 */
115
+	protected $_minimum_where_conditions_strategy;
116
+
117
+	/**
118
+	 * String describing how to find the "owner" of this model's objects.
119
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
+	 * But when there isn't, this indicates which related model, or transiently-related model,
121
+	 * has the foreign key to the wp_users table.
122
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
+	 * related to events, and events have a foreign key to wp_users.
124
+	 * On EEM_Transaction, this would be 'Transaction.Event'
125
+	 *
126
+	 * @var string
127
+	 */
128
+	protected $_model_chain_to_wp_user = '';
129
+
130
+	/**
131
+	 * String describing how to find the model with a password controlling access to this model. This property has the
132
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
+	 * This value is the path of models to follow to arrive at the model with the password field.
134
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
+	 * model with a password that should affect reading this on the front-end.
136
+	 * Eg this is an empty string for the Event model because it has a password.
137
+	 * This is null for the Registration model, because its event's password has no bearing on whether
138
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
+	 * should hide tickets for datetimes for events that have a password set.
141
+	 * @var string |null
142
+	 */
143
+	protected $model_chain_to_password = null;
144
+
145
+	/**
146
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
+	 * don't need it (particularly CPT models)
148
+	 *
149
+	 * @var bool
150
+	 */
151
+	protected $_ignore_where_strategy = false;
152
+
153
+	/**
154
+	 * String used in caps relating to this model. Eg, if the caps relating to this
155
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
+	 *
157
+	 * @var string. If null it hasn't been initialized yet. If false then we
158
+	 * have indicated capabilities don't apply to this
159
+	 */
160
+	protected $_caps_slug = null;
161
+
162
+	/**
163
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
+	 * and next-level keys are capability names, and each's value is a
165
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
167
+	 * and then each capability in the corresponding sub-array that they're missing
168
+	 * adds the where conditions onto the query.
169
+	 *
170
+	 * @var array
171
+	 */
172
+	protected $_cap_restrictions = array(
173
+		self::caps_read       => array(),
174
+		self::caps_read_admin => array(),
175
+		self::caps_edit       => array(),
176
+		self::caps_delete     => array(),
177
+	);
178
+
179
+	/**
180
+	 * Array defining which cap restriction generators to use to create default
181
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
182
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
+	 * automatically set this to false (not just null).
185
+	 *
186
+	 * @var EE_Restriction_Generator_Base[]
187
+	 */
188
+	protected $_cap_restriction_generators = array();
189
+
190
+	/**
191
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
+	 */
193
+	const caps_read       = 'read';
194
+
195
+	const caps_read_admin = 'read_admin';
196
+
197
+	const caps_edit       = 'edit';
198
+
199
+	const caps_delete     = 'delete';
200
+
201
+	/**
202
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
+	 * maps to 'read' because when looking for relevant permissions we're going to use
205
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
206
+	 *
207
+	 * @var array
208
+	 */
209
+	protected $_cap_contexts_to_cap_action_map = array(
210
+		self::caps_read       => 'read',
211
+		self::caps_read_admin => 'read',
212
+		self::caps_edit       => 'edit',
213
+		self::caps_delete     => 'delete',
214
+	);
215
+
216
+	/**
217
+	 * Timezone
218
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
+	 * EE_Datetime_Field data type will have access to it.
222
+	 *
223
+	 * @var string
224
+	 */
225
+	protected $_timezone;
226
+
227
+
228
+	/**
229
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
+	 * multisite.
231
+	 *
232
+	 * @var int
233
+	 */
234
+	protected static $_model_query_blog_id;
235
+
236
+	/**
237
+	 * A copy of _fields, except the array keys are the model names pointed to by
238
+	 * the field
239
+	 *
240
+	 * @var EE_Model_Field_Base[]
241
+	 */
242
+	private $_cache_foreign_key_to_fields = array();
243
+
244
+	/**
245
+	 * Cached list of all the fields on the model, indexed by their name
246
+	 *
247
+	 * @var EE_Model_Field_Base[]
248
+	 */
249
+	private $_cached_fields = null;
250
+
251
+	/**
252
+	 * Cached list of all the fields on the model, except those that are
253
+	 * marked as only pertinent to the database
254
+	 *
255
+	 * @var EE_Model_Field_Base[]
256
+	 */
257
+	private $_cached_fields_non_db_only = null;
258
+
259
+	/**
260
+	 * A cached reference to the primary key for quick lookup
261
+	 *
262
+	 * @var EE_Model_Field_Base
263
+	 */
264
+	private $_primary_key_field = null;
265
+
266
+	/**
267
+	 * Flag indicating whether this model has a primary key or not
268
+	 *
269
+	 * @var boolean
270
+	 */
271
+	protected $_has_primary_key_field = null;
272
+
273
+	/**
274
+	 * array in the format:  [ FK alias => full PK ]
275
+	 * where keys are local column name aliases for foreign keys
276
+	 * and values are the fully qualified column name for the primary key they represent
277
+	 *  ex:
278
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
+	 *
280
+	 * @var array $foreign_key_aliases
281
+	 */
282
+	protected $foreign_key_aliases = [];
283
+
284
+	/**
285
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
286
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
+	 * This should be true for models that deal with data that should exist independent of EE.
288
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
290
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
292
+	 * @var boolean
293
+	 */
294
+	protected $_wp_core_model = false;
295
+
296
+	/**
297
+	 * @var bool stores whether this model has a password field or not.
298
+	 * null until initialized by hasPasswordField()
299
+	 */
300
+	protected $has_password_field;
301
+
302
+	/**
303
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
+	 */
305
+	protected $password_field;
306
+
307
+	/**
308
+	 *    List of valid operators that can be used for querying.
309
+	 * The keys are all operators we'll accept, the values are the real SQL
310
+	 * operators used
311
+	 *
312
+	 * @var array
313
+	 */
314
+	protected $_valid_operators = array(
315
+		'='           => '=',
316
+		'<='          => '<=',
317
+		'<'           => '<',
318
+		'>='          => '>=',
319
+		'>'           => '>',
320
+		'!='          => '!=',
321
+		'LIKE'        => 'LIKE',
322
+		'like'        => 'LIKE',
323
+		'NOT_LIKE'    => 'NOT LIKE',
324
+		'not_like'    => 'NOT LIKE',
325
+		'NOT LIKE'    => 'NOT LIKE',
326
+		'not like'    => 'NOT LIKE',
327
+		'IN'          => 'IN',
328
+		'in'          => 'IN',
329
+		'NOT_IN'      => 'NOT IN',
330
+		'not_in'      => 'NOT IN',
331
+		'NOT IN'      => 'NOT IN',
332
+		'not in'      => 'NOT IN',
333
+		'between'     => 'BETWEEN',
334
+		'BETWEEN'     => 'BETWEEN',
335
+		'IS_NOT_NULL' => 'IS NOT NULL',
336
+		'is_not_null' => 'IS NOT NULL',
337
+		'IS NOT NULL' => 'IS NOT NULL',
338
+		'is not null' => 'IS NOT NULL',
339
+		'IS_NULL'     => 'IS NULL',
340
+		'is_null'     => 'IS NULL',
341
+		'IS NULL'     => 'IS NULL',
342
+		'is null'     => 'IS NULL',
343
+		'REGEXP'      => 'REGEXP',
344
+		'regexp'      => 'REGEXP',
345
+		'NOT_REGEXP'  => 'NOT REGEXP',
346
+		'not_regexp'  => 'NOT REGEXP',
347
+		'NOT REGEXP'  => 'NOT REGEXP',
348
+		'not regexp'  => 'NOT REGEXP',
349
+	);
350
+
351
+	/**
352
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
+	 *
354
+	 * @var array
355
+	 */
356
+	protected $_in_style_operators = array('IN', 'NOT IN');
357
+
358
+	/**
359
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
+	 * '12-31-2012'"
361
+	 *
362
+	 * @var array
363
+	 */
364
+	protected $_between_style_operators = array('BETWEEN');
365
+
366
+	/**
367
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
+	 * @var array
369
+	 */
370
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
+	/**
372
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
+	 * on a join table.
374
+	 *
375
+	 * @var array
376
+	 */
377
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
+
379
+	/**
380
+	 * Allowed values for $query_params['order'] for ordering in queries
381
+	 *
382
+	 * @var array
383
+	 */
384
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
+
386
+	/**
387
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
389
+	 *
390
+	 * @var array
391
+	 */
392
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
+
394
+	/**
395
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
397
+	 *
398
+	 * @var array
399
+	 */
400
+	private $_allowed_query_params = array(
401
+		0,
402
+		'limit',
403
+		'order_by',
404
+		'group_by',
405
+		'having',
406
+		'force_join',
407
+		'order',
408
+		'on_join_limit',
409
+		'default_where_conditions',
410
+		'caps',
411
+		'extra_selects',
412
+		'exclude_protected',
413
+	);
414
+
415
+	/**
416
+	 * All the data types that can be used in $wpdb->prepare statements.
417
+	 *
418
+	 * @var array
419
+	 */
420
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
+
422
+	/**
423
+	 * @var EE_Registry $EE
424
+	 */
425
+	protected $EE = null;
426
+
427
+
428
+	/**
429
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
+	 *
431
+	 * @var int
432
+	 */
433
+	protected $_show_next_x_db_queries = 0;
434
+
435
+	/**
436
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
+	 * WHERE, GROUP_BY, etc.
439
+	 *
440
+	 * @var CustomSelects
441
+	 */
442
+	protected $_custom_selections = array();
443
+
444
+	/**
445
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
+	 * caches every model object we've fetched from the DB on this request
447
+	 *
448
+	 * @var array
449
+	 */
450
+	protected $_entity_map;
451
+
452
+	/**
453
+	 * @var LoaderInterface $loader
454
+	 */
455
+	private static $loader;
456
+
457
+
458
+	/**
459
+	 * constant used to show EEM_Base has not yet verified the db on this http request
460
+	 */
461
+	const db_verified_none = 0;
462
+
463
+	/**
464
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
465
+	 * but not the addons' dbs
466
+	 */
467
+	const db_verified_core = 1;
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
+	 * the EE core db too)
472
+	 */
473
+	const db_verified_addons = 2;
474
+
475
+	/**
476
+	 * indicates whether an EEM_Base child has already re-verified the DB
477
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
478
+	 * looking like EEM_Base::db_verified_*
479
+	 *
480
+	 * @var int - 0 = none, 1 = core, 2 = addons
481
+	 */
482
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
483
+
484
+	/**
485
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
488
+	 */
489
+	const default_where_conditions_all = 'all';
490
+
491
+	/**
492
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
+	 *        models which share tables with other models, this can return data for the wrong model.
497
+	 */
498
+	const default_where_conditions_this_only = 'this_model_only';
499
+
500
+	/**
501
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
+	 */
505
+	const default_where_conditions_others_only = 'other_models_only';
506
+
507
+	/**
508
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
511
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
+	 *        (regardless of whether those events and venues are trashed)
513
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
+	 *        events.
515
+	 */
516
+	const default_where_conditions_minimum_all = 'minimum';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
+	 *        not)
523
+	 */
524
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
+
526
+	/**
527
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
+	 *        it's possible it will return table entries for other models. You should use
530
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
531
+	 */
532
+	const default_where_conditions_none = 'none';
533
+
534
+
535
+
536
+	/**
537
+	 * About all child constructors:
538
+	 * they should define the _tables, _fields and _model_relations arrays.
539
+	 * Should ALWAYS be called after child constructor.
540
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
541
+	 * finalizes constructing all the object's attributes.
542
+	 * Generally, rather than requiring a child to code
543
+	 * $this->_tables = array(
544
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
+	 *        ...);
546
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
+	 * each EE_Table has a function to set the table's alias after the constructor, using
548
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
+	 * do something similar.
550
+	 *
551
+	 * @param null $timezone
552
+	 * @throws EE_Error
553
+	 */
554
+	protected function __construct($timezone = null)
555
+	{
556
+		// check that the model has not been loaded too soon
557
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
+			throw new EE_Error(
559
+				sprintf(
560
+					__(
561
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
562
+						'event_espresso'
563
+					),
564
+					get_class($this)
565
+				)
566
+			);
567
+		}
568
+		/**
569
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
+		 */
571
+		if (empty(EEM_Base::$_model_query_blog_id)) {
572
+			EEM_Base::set_model_query_blog_id();
573
+		}
574
+		/**
575
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
+		 * just use EE_Register_Model_Extension
577
+		 *
578
+		 * @var EE_Table_Base[] $_tables
579
+		 */
580
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
+		foreach ($this->_tables as $table_alias => $table_obj) {
582
+			/** @var $table_obj EE_Table_Base */
583
+			$table_obj->_construct_finalize_with_alias($table_alias);
584
+			if ($table_obj instanceof EE_Secondary_Table) {
585
+				/** @var $table_obj EE_Secondary_Table */
586
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
+			}
588
+		}
589
+		/**
590
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
+		 * EE_Register_Model_Extension
592
+		 *
593
+		 * @param EE_Model_Field_Base[] $_fields
594
+		 */
595
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
+		$this->_invalidate_field_caches();
597
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
598
+			if (! array_key_exists($table_alias, $this->_tables)) {
599
+				throw new EE_Error(sprintf(__(
600
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
+					'event_espresso'
602
+				), $table_alias, implode(",", $this->_fields)));
603
+			}
604
+			foreach ($fields_for_table as $field_name => $field_obj) {
605
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
+				// primary key field base has a slightly different _construct_finalize
607
+				/** @var $field_obj EE_Model_Field_Base */
608
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
+			}
610
+		}
611
+		// everything is related to Extra_Meta
612
+		if (get_class($this) !== 'EEM_Extra_Meta') {
613
+			// make extra meta related to everything, but don't block deleting things just
614
+			// because they have related extra meta info. For now just orphan those extra meta
615
+			// in the future we should automatically delete them
616
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
+		}
618
+		// and change logs
619
+		if (get_class($this) !== 'EEM_Change_Log') {
620
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
+		}
622
+		/**
623
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
+		 * EE_Register_Model_Extension
625
+		 *
626
+		 * @param EE_Model_Relation_Base[] $_model_relations
627
+		 */
628
+		$this->_model_relations = (array) apply_filters(
629
+			'FHEE__' . get_class($this) . '__construct__model_relations',
630
+			$this->_model_relations
631
+		);
632
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
633
+			/** @var $relation_obj EE_Model_Relation_Base */
634
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
+		}
636
+		foreach ($this->_indexes as $index_name => $index_obj) {
637
+			/** @var $index_obj EE_Index */
638
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
+		}
640
+		$this->set_timezone($timezone);
641
+		// finalize default where condition strategy, or set default
642
+		if (! $this->_default_where_conditions_strategy) {
643
+			// nothing was set during child constructor, so set default
644
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
+		}
646
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
647
+		if (! $this->_minimum_where_conditions_strategy) {
648
+			// nothing was set during child constructor, so set default
649
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
+		}
651
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
653
+		// to indicate to NOT set it, set it to the logical default
654
+		if ($this->_caps_slug === null) {
655
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
+		}
657
+		// initialize the standard cap restriction generators if none were specified by the child constructor
658
+		if ($this->_cap_restriction_generators !== false) {
659
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
+						new EE_Restriction_Generator_Protected(),
664
+						$cap_context,
665
+						$this
666
+					);
667
+				}
668
+			}
669
+		}
670
+		// if there are cap restriction generators, use them to make the default cap restrictions
671
+		if ($this->_cap_restriction_generators !== false) {
672
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
+				if (! $generator_object) {
674
+					continue;
675
+				}
676
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
+					throw new EE_Error(
678
+						sprintf(
679
+							__(
680
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
681
+								'event_espresso'
682
+							),
683
+							$context,
684
+							$this->get_this_model_name()
685
+						)
686
+					);
687
+				}
688
+				$action = $this->cap_action_for_context($context);
689
+				if (! $generator_object->construction_finalized()) {
690
+					$generator_object->_construct_finalize($this, $action);
691
+				}
692
+			}
693
+		}
694
+		do_action('AHEE__' . get_class($this) . '__construct__end');
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 * Used to set the $_model_query_blog_id static property.
701
+	 *
702
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
+	 *                      value for get_current_blog_id() will be used.
704
+	 */
705
+	public static function set_model_query_blog_id($blog_id = 0)
706
+	{
707
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
+	}
709
+
710
+
711
+
712
+	/**
713
+	 * Returns whatever is set as the internal $model_query_blog_id.
714
+	 *
715
+	 * @return int
716
+	 */
717
+	public static function get_model_query_blog_id()
718
+	{
719
+		return EEM_Base::$_model_query_blog_id;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * This function is a singleton method used to instantiate the Espresso_model object
726
+	 *
727
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
+	 *                                (and any incoming timezone data that gets saved).
729
+	 *                                Note this just sends the timezone info to the date time model field objects.
730
+	 *                                Default is NULL
731
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
+	 * @return static (as in the concrete child class)
733
+	 * @throws EE_Error
734
+	 * @throws InvalidArgumentException
735
+	 * @throws InvalidDataTypeException
736
+	 * @throws InvalidInterfaceException
737
+	 */
738
+	public static function instance($timezone = null)
739
+	{
740
+		// check if instance of Espresso_model already exists
741
+		if (! static::$_instance instanceof static) {
742
+			// instantiate Espresso_model
743
+			static::$_instance = new static(
744
+				$timezone,
745
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
+			);
747
+		}
748
+		// we might have a timezone set, let set_timezone decide what to do with it
749
+		static::$_instance->set_timezone($timezone);
750
+		// Espresso_model object
751
+		return static::$_instance;
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * resets the model and returns it
758
+	 *
759
+	 * @param null | string $timezone
760
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
+	 * all its properties reset; if it wasn't instantiated, returns null)
762
+	 * @throws EE_Error
763
+	 * @throws ReflectionException
764
+	 * @throws InvalidArgumentException
765
+	 * @throws InvalidDataTypeException
766
+	 * @throws InvalidInterfaceException
767
+	 */
768
+	public static function reset($timezone = null)
769
+	{
770
+		if (static::$_instance instanceof EEM_Base) {
771
+			// let's try to NOT swap out the current instance for a new one
772
+			// because if someone has a reference to it, we can't remove their reference
773
+			// so it's best to keep using the same reference, but change the original object
774
+			// reset all its properties to their original values as defined in the class
775
+			$r = new ReflectionClass(get_class(static::$_instance));
776
+			$static_properties = $r->getStaticProperties();
777
+			foreach ($r->getDefaultProperties() as $property => $value) {
778
+				// don't set instance to null like it was originally,
779
+				// but it's static anyways, and we're ignoring static properties (for now at least)
780
+				if (! isset($static_properties[ $property ])) {
781
+					static::$_instance->{$property} = $value;
782
+				}
783
+			}
784
+			// and then directly call its constructor again, like we would if we were creating a new one
785
+			static::$_instance->__construct(
786
+				$timezone,
787
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
+			);
789
+			return self::instance();
790
+		}
791
+		return null;
792
+	}
793
+
794
+
795
+
796
+	/**
797
+	 * @return LoaderInterface
798
+	 * @throws InvalidArgumentException
799
+	 * @throws InvalidDataTypeException
800
+	 * @throws InvalidInterfaceException
801
+	 */
802
+	private static function getLoader()
803
+	{
804
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
805
+			EEM_Base::$loader = LoaderFactory::getLoader();
806
+		}
807
+		return EEM_Base::$loader;
808
+	}
809
+
810
+
811
+
812
+	/**
813
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
+	 *
815
+	 * @param  boolean $translated return localized strings or JUST the array.
816
+	 * @return array
817
+	 * @throws EE_Error
818
+	 * @throws InvalidArgumentException
819
+	 * @throws InvalidDataTypeException
820
+	 * @throws InvalidInterfaceException
821
+	 */
822
+	public function status_array($translated = false)
823
+	{
824
+		if (! array_key_exists('Status', $this->_model_relations)) {
825
+			return array();
826
+		}
827
+		$model_name = $this->get_this_model_name();
828
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
+		$status_array = array();
831
+		foreach ($stati as $status) {
832
+			$status_array[ $status->ID() ] = $status->get('STS_code');
833
+		}
834
+		return $translated
835
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
+			: $status_array;
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
+	 *
844
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
+	 *                             or if you have the development copy of EE you can view this at the path:
846
+	 *                             /docs/G--Model-System/model-query-params.md
847
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
+	 *                                        array( array(
852
+	 *                                        'OR'=>array(
853
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
+	 *                                        )
856
+	 *                                        ),
857
+	 *                                        'limit'=>10,
858
+	 *                                        'group_by'=>'TXN_ID'
859
+	 *                                        ));
860
+	 *                                        get all the answers to the question titled "shirt size" for event with id
861
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
+	 *                                        'Question.QST_display_text'=>'shirt size',
863
+	 *                                        'Registration.Event.EVT_ID'=>12
864
+	 *                                        ),
865
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
866
+	 *                                        ));
867
+	 * @throws EE_Error
868
+	 */
869
+	public function get_all($query_params = array())
870
+	{
871
+		if (
872
+			isset($query_params['limit'])
873
+			&& ! isset($query_params['group_by'])
874
+		) {
875
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
876
+		}
877
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
878
+	}
879
+
880
+
881
+
882
+	/**
883
+	 * Modifies the query parameters so we only get back model objects
884
+	 * that "belong" to the current user
885
+	 *
886
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
+	 */
889
+	public function alter_query_params_to_only_include_mine($query_params = array())
890
+	{
891
+		$wp_user_field_name = $this->wp_user_field_name();
892
+		if ($wp_user_field_name) {
893
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
894
+		}
895
+		return $query_params;
896
+	}
897
+
898
+
899
+
900
+	/**
901
+	 * Returns the name of the field's name that points to the WP_User table
902
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
903
+	 * foreign key to the WP_User table)
904
+	 *
905
+	 * @return string|boolean string on success, boolean false when there is no
906
+	 * foreign key to the WP_User table
907
+	 */
908
+	public function wp_user_field_name()
909
+	{
910
+		try {
911
+			if (! empty($this->_model_chain_to_wp_user)) {
912
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
913
+				$last_model_name = end($models_to_follow_to_wp_users);
914
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
915
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
916
+			} else {
917
+				$model_with_fk_to_wp_users = $this;
918
+				$model_chain_to_wp_user = '';
919
+			}
920
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
921
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
922
+		} catch (EE_Error $e) {
923
+			return false;
924
+		}
925
+	}
926
+
927
+
928
+
929
+	/**
930
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
931
+	 * (or transiently-related model) has a foreign key to the wp_users table;
932
+	 * useful for finding if model objects of this type are 'owned' by the current user.
933
+	 * This is an empty string when the foreign key is on this model and when it isn't,
934
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
935
+	 * (or transiently-related model)
936
+	 *
937
+	 * @return string
938
+	 */
939
+	public function model_chain_to_wp_user()
940
+	{
941
+		return $this->_model_chain_to_wp_user;
942
+	}
943
+
944
+
945
+
946
+	/**
947
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
948
+	 * like how registrations don't have a foreign key to wp_users, but the
949
+	 * events they are for are), or is unrelated to wp users.
950
+	 * generally available
951
+	 *
952
+	 * @return boolean
953
+	 */
954
+	public function is_owned()
955
+	{
956
+		if ($this->model_chain_to_wp_user()) {
957
+			return true;
958
+		}
959
+		try {
960
+			$this->get_foreign_key_to('WP_User');
961
+			return true;
962
+		} catch (EE_Error $e) {
963
+			return false;
964
+		}
965
+	}
966
+
967
+
968
+	/**
969
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
970
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
971
+	 * the model)
972
+	 *
973
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
974
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
975
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
976
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
977
+	 *                                  override this and set the select to "*", or a specific column name, like
978
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
979
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
980
+	 *                                  the aliases used to refer to this selection, and values are to be
981
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
982
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
983
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
984
+	 * @throws EE_Error
985
+	 * @throws InvalidArgumentException
986
+	 */
987
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
988
+	{
989
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
990
+		;
991
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
992
+		$select_expressions = $columns_to_select === null
993
+			? $this->_construct_default_select_sql($model_query_info)
994
+			: '';
995
+		if ($this->_custom_selections instanceof CustomSelects) {
996
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
997
+			$select_expressions .= $select_expressions
998
+				? ', ' . $custom_expressions
999
+				: $custom_expressions;
1000
+		}
1001
+
1002
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1003
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1004
+	}
1005
+
1006
+
1007
+	/**
1008
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1009
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1010
+	 * method of including extra select information.
1011
+	 *
1012
+	 * @param array             $query_params
1013
+	 * @param null|array|string $columns_to_select
1014
+	 * @return null|CustomSelects
1015
+	 * @throws InvalidArgumentException
1016
+	 */
1017
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1018
+	{
1019
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020
+			return null;
1021
+		}
1022
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1023
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1024
+		return new CustomSelects($selects);
1025
+	}
1026
+
1027
+
1028
+
1029
+	/**
1030
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1031
+	 * but you can use the model query params to more easily
1032
+	 * take care of joins, field preparation etc.
1033
+	 *
1034
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1038
+	 *                                  override this and set the select to "*", or a specific column name, like
1039
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
+	 *                                  the aliases used to refer to this selection, and values are to be
1042
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
+	 * @throws EE_Error
1046
+	 */
1047
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
+	{
1049
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1050
+	}
1051
+
1052
+
1053
+
1054
+	/**
1055
+	 * For creating a custom select statement
1056
+	 *
1057
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1058
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1059
+	 *                                 SQL, and 1=>is the datatype
1060
+	 * @throws EE_Error
1061
+	 * @return string
1062
+	 */
1063
+	private function _construct_select_from_input($columns_to_select)
1064
+	{
1065
+		if (is_array($columns_to_select)) {
1066
+			$select_sql_array = array();
1067
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1068
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
+					throw new EE_Error(
1070
+						sprintf(
1071
+							__(
1072
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1073
+								'event_espresso'
1074
+							),
1075
+							$selection_and_datatype,
1076
+							$alias
1077
+						)
1078
+					);
1079
+				}
1080
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081
+					throw new EE_Error(
1082
+						sprintf(
1083
+							esc_html__(
1084
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1085
+								'event_espresso'
1086
+							),
1087
+							$selection_and_datatype[1],
1088
+							$selection_and_datatype[0],
1089
+							$alias,
1090
+							implode(', ', $this->_valid_wpdb_data_types)
1091
+						)
1092
+					);
1093
+				}
1094
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1095
+			}
1096
+			$columns_to_select_string = implode(', ', $select_sql_array);
1097
+		} else {
1098
+			$columns_to_select_string = $columns_to_select;
1099
+		}
1100
+		return $columns_to_select_string;
1101
+	}
1102
+
1103
+
1104
+
1105
+	/**
1106
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1107
+	 *
1108
+	 * @return string
1109
+	 * @throws EE_Error
1110
+	 */
1111
+	public function primary_key_name()
1112
+	{
1113
+		return $this->get_primary_key_field()->get_name();
1114
+	}
1115
+
1116
+
1117
+	/**
1118
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1119
+	 * If there is no primary key on this model, $id is treated as primary key string
1120
+	 *
1121
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1122
+	 * @return EE_Base_Class
1123
+	 * @throws EE_Error
1124
+	 */
1125
+	public function get_one_by_ID($id)
1126
+	{
1127
+		if ($this->get_from_entity_map($id)) {
1128
+			return $this->get_from_entity_map($id);
1129
+		}
1130
+		$model_object = $this->get_one(
1131
+			$this->alter_query_params_to_restrict_by_ID(
1132
+				$id,
1133
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1134
+			)
1135
+		);
1136
+		$className = $this->_get_class_name();
1137
+		if ($model_object instanceof $className) {
1138
+			// make sure valid objects get added to the entity map
1139
+			// so that the next call to this method doesn't trigger another trip to the db
1140
+			$this->add_to_entity_map($model_object);
1141
+		}
1142
+		return $model_object;
1143
+	}
1144
+
1145
+
1146
+
1147
+	/**
1148
+	 * Alters query parameters to only get items with this ID are returned.
1149
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1150
+	 * or could just be a simple primary key ID
1151
+	 *
1152
+	 * @param int   $id
1153
+	 * @param array $query_params
1154
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1155
+	 * @throws EE_Error
1156
+	 */
1157
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1158
+	{
1159
+		if (! isset($query_params[0])) {
1160
+			$query_params[0] = array();
1161
+		}
1162
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1163
+		if ($conditions_from_id === null) {
1164
+			$query_params[0][ $this->primary_key_name() ] = $id;
1165
+		} else {
1166
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1167
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1168
+		}
1169
+		return $query_params;
1170
+	}
1171
+
1172
+
1173
+
1174
+	/**
1175
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1176
+	 * array. If no item is found, null is returned.
1177
+	 *
1178
+	 * @param array $query_params like EEM_Base's $query_params variable.
1179
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1180
+	 * @throws EE_Error
1181
+	 */
1182
+	public function get_one($query_params = array())
1183
+	{
1184
+		if (! is_array($query_params)) {
1185
+			EE_Error::doing_it_wrong(
1186
+				'EEM_Base::get_one',
1187
+				sprintf(
1188
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1189
+					gettype($query_params)
1190
+				),
1191
+				'4.6.0'
1192
+			);
1193
+			$query_params = array();
1194
+		}
1195
+		$query_params['limit'] = 1;
1196
+		$items = $this->get_all($query_params);
1197
+		if (empty($items)) {
1198
+			return null;
1199
+		}
1200
+		return array_shift($items);
1201
+	}
1202
+
1203
+
1204
+
1205
+	/**
1206
+	 * Returns the next x number of items in sequence from the given value as
1207
+	 * found in the database matching the given query conditions.
1208
+	 *
1209
+	 * @param mixed $current_field_value    Value used for the reference point.
1210
+	 * @param null  $field_to_order_by      What field is used for the
1211
+	 *                                      reference point.
1212
+	 * @param int   $limit                  How many to return.
1213
+	 * @param array $query_params           Extra conditions on the query.
1214
+	 * @param null  $columns_to_select      If left null, then an array of
1215
+	 *                                      EE_Base_Class objects is returned,
1216
+	 *                                      otherwise you can indicate just the
1217
+	 *                                      columns you want returned.
1218
+	 * @return EE_Base_Class[]|array
1219
+	 * @throws EE_Error
1220
+	 */
1221
+	public function next_x(
1222
+		$current_field_value,
1223
+		$field_to_order_by = null,
1224
+		$limit = 1,
1225
+		$query_params = array(),
1226
+		$columns_to_select = null
1227
+	) {
1228
+		return $this->_get_consecutive(
1229
+			$current_field_value,
1230
+			'>',
1231
+			$field_to_order_by,
1232
+			$limit,
1233
+			$query_params,
1234
+			$columns_to_select
1235
+		);
1236
+	}
1237
+
1238
+
1239
+
1240
+	/**
1241
+	 * Returns the previous x number of items in sequence from the given value
1242
+	 * as found in the database matching the given query conditions.
1243
+	 *
1244
+	 * @param mixed $current_field_value    Value used for the reference point.
1245
+	 * @param null  $field_to_order_by      What field is used for the
1246
+	 *                                      reference point.
1247
+	 * @param int   $limit                  How many to return.
1248
+	 * @param array $query_params           Extra conditions on the query.
1249
+	 * @param null  $columns_to_select      If left null, then an array of
1250
+	 *                                      EE_Base_Class objects is returned,
1251
+	 *                                      otherwise you can indicate just the
1252
+	 *                                      columns you want returned.
1253
+	 * @return EE_Base_Class[]|array
1254
+	 * @throws EE_Error
1255
+	 */
1256
+	public function previous_x(
1257
+		$current_field_value,
1258
+		$field_to_order_by = null,
1259
+		$limit = 1,
1260
+		$query_params = array(),
1261
+		$columns_to_select = null
1262
+	) {
1263
+		return $this->_get_consecutive(
1264
+			$current_field_value,
1265
+			'<',
1266
+			$field_to_order_by,
1267
+			$limit,
1268
+			$query_params,
1269
+			$columns_to_select
1270
+		);
1271
+	}
1272
+
1273
+
1274
+
1275
+	/**
1276
+	 * Returns the next item in sequence from the given value as found in the
1277
+	 * database matching the given query conditions.
1278
+	 *
1279
+	 * @param mixed $current_field_value    Value used for the reference point.
1280
+	 * @param null  $field_to_order_by      What field is used for the
1281
+	 *                                      reference point.
1282
+	 * @param array $query_params           Extra conditions on the query.
1283
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1284
+	 *                                      object is returned, otherwise you
1285
+	 *                                      can indicate just the columns you
1286
+	 *                                      want and a single array indexed by
1287
+	 *                                      the columns will be returned.
1288
+	 * @return EE_Base_Class|null|array()
1289
+	 * @throws EE_Error
1290
+	 */
1291
+	public function next(
1292
+		$current_field_value,
1293
+		$field_to_order_by = null,
1294
+		$query_params = array(),
1295
+		$columns_to_select = null
1296
+	) {
1297
+		$results = $this->_get_consecutive(
1298
+			$current_field_value,
1299
+			'>',
1300
+			$field_to_order_by,
1301
+			1,
1302
+			$query_params,
1303
+			$columns_to_select
1304
+		);
1305
+		return empty($results) ? null : reset($results);
1306
+	}
1307
+
1308
+
1309
+
1310
+	/**
1311
+	 * Returns the previous item in sequence from the given value as found in
1312
+	 * the database matching the given query conditions.
1313
+	 *
1314
+	 * @param mixed $current_field_value    Value used for the reference point.
1315
+	 * @param null  $field_to_order_by      What field is used for the
1316
+	 *                                      reference point.
1317
+	 * @param array $query_params           Extra conditions on the query.
1318
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1319
+	 *                                      object is returned, otherwise you
1320
+	 *                                      can indicate just the columns you
1321
+	 *                                      want and a single array indexed by
1322
+	 *                                      the columns will be returned.
1323
+	 * @return EE_Base_Class|null|array()
1324
+	 * @throws EE_Error
1325
+	 */
1326
+	public function previous(
1327
+		$current_field_value,
1328
+		$field_to_order_by = null,
1329
+		$query_params = array(),
1330
+		$columns_to_select = null
1331
+	) {
1332
+		$results = $this->_get_consecutive(
1333
+			$current_field_value,
1334
+			'<',
1335
+			$field_to_order_by,
1336
+			1,
1337
+			$query_params,
1338
+			$columns_to_select
1339
+		);
1340
+		return empty($results) ? null : reset($results);
1341
+	}
1342
+
1343
+
1344
+
1345
+	/**
1346
+	 * Returns the a consecutive number of items in sequence from the given
1347
+	 * value as found in the database matching the given query conditions.
1348
+	 *
1349
+	 * @param mixed  $current_field_value   Value used for the reference point.
1350
+	 * @param string $operand               What operand is used for the sequence.
1351
+	 * @param string $field_to_order_by     What field is used for the reference point.
1352
+	 * @param int    $limit                 How many to return.
1353
+	 * @param array  $query_params          Extra conditions on the query.
1354
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1355
+	 *                                      otherwise you can indicate just the columns you want returned.
1356
+	 * @return EE_Base_Class[]|array
1357
+	 * @throws EE_Error
1358
+	 */
1359
+	protected function _get_consecutive(
1360
+		$current_field_value,
1361
+		$operand = '>',
1362
+		$field_to_order_by = null,
1363
+		$limit = 1,
1364
+		$query_params = array(),
1365
+		$columns_to_select = null
1366
+	) {
1367
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1368
+		if (empty($field_to_order_by)) {
1369
+			if ($this->has_primary_key_field()) {
1370
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1371
+			} else {
1372
+				if (WP_DEBUG) {
1373
+					throw new EE_Error(__(
1374
+						'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1375
+						'event_espresso'
1376
+					));
1377
+				}
1378
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1379
+				return array();
1380
+			}
1381
+		}
1382
+		if (! is_array($query_params)) {
1383
+			EE_Error::doing_it_wrong(
1384
+				'EEM_Base::_get_consecutive',
1385
+				sprintf(
1386
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1387
+					gettype($query_params)
1388
+				),
1389
+				'4.6.0'
1390
+			);
1391
+			$query_params = array();
1392
+		}
1393
+		// let's add the where query param for consecutive look up.
1394
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1395
+		$query_params['limit'] = $limit;
1396
+		// set direction
1397
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1398
+		$query_params['order_by'] = $operand === '>'
1399
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1400
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1401
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1402
+		if (empty($columns_to_select)) {
1403
+			return $this->get_all($query_params);
1404
+		}
1405
+		// getting just the fields
1406
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1407
+	}
1408
+
1409
+
1410
+
1411
+	/**
1412
+	 * This sets the _timezone property after model object has been instantiated.
1413
+	 *
1414
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1415
+	 */
1416
+	public function set_timezone($timezone)
1417
+	{
1418
+		if ($timezone !== null) {
1419
+			$this->_timezone = $timezone;
1420
+		}
1421
+		// note we need to loop through relations and set the timezone on those objects as well.
1422
+		foreach ($this->_model_relations as $relation) {
1423
+			$relation->set_timezone($timezone);
1424
+		}
1425
+		// and finally we do the same for any datetime fields
1426
+		foreach ($this->_fields as $field) {
1427
+			if ($field instanceof EE_Datetime_Field) {
1428
+				$field->set_timezone($timezone);
1429
+			}
1430
+		}
1431
+	}
1432
+
1433
+
1434
+
1435
+	/**
1436
+	 * This just returns whatever is set for the current timezone.
1437
+	 *
1438
+	 * @access public
1439
+	 * @return string
1440
+	 */
1441
+	public function get_timezone()
1442
+	{
1443
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1444
+		if (empty($this->_timezone)) {
1445
+			foreach ($this->_fields as $field) {
1446
+				if ($field instanceof EE_Datetime_Field) {
1447
+					$this->set_timezone($field->get_timezone());
1448
+					break;
1449
+				}
1450
+			}
1451
+		}
1452
+		// if timezone STILL empty then return the default timezone for the site.
1453
+		if (empty($this->_timezone)) {
1454
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1455
+		}
1456
+		return $this->_timezone;
1457
+	}
1458
+
1459
+
1460
+
1461
+	/**
1462
+	 * This returns the date formats set for the given field name and also ensures that
1463
+	 * $this->_timezone property is set correctly.
1464
+	 *
1465
+	 * @since 4.6.x
1466
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1467
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1468
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1469
+	 * @return array formats in an array with the date format first, and the time format last.
1470
+	 */
1471
+	public function get_formats_for($field_name, $pretty = false)
1472
+	{
1473
+		$field_settings = $this->field_settings_for($field_name);
1474
+		// if not a valid EE_Datetime_Field then throw error
1475
+		if (! $field_settings instanceof EE_Datetime_Field) {
1476
+			throw new EE_Error(sprintf(__(
1477
+				'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1478
+				'event_espresso'
1479
+			), $field_name));
1480
+		}
1481
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1482
+		// the field.
1483
+		$this->_timezone = $field_settings->get_timezone();
1484
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1485
+	}
1486
+
1487
+
1488
+
1489
+	/**
1490
+	 * This returns the current time in a format setup for a query on this model.
1491
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1492
+	 * it will return:
1493
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1494
+	 *  NOW
1495
+	 *  - or a unix timestamp (equivalent to time())
1496
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1497
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1498
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1499
+	 * @since 4.6.x
1500
+	 * @param string $field_name       The field the current time is needed for.
1501
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1502
+	 *                                 formatted string matching the set format for the field in the set timezone will
1503
+	 *                                 be returned.
1504
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1505
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1506
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1507
+	 *                                 exception is triggered.
1508
+	 */
1509
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1510
+	{
1511
+		$formats = $this->get_formats_for($field_name);
1512
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1513
+		if ($timestamp) {
1514
+			return $DateTime->format('U');
1515
+		}
1516
+		// not returning timestamp, so return formatted string in timezone.
1517
+		switch ($what) {
1518
+			case 'time':
1519
+				return $DateTime->format($formats[1]);
1520
+				break;
1521
+			case 'date':
1522
+				return $DateTime->format($formats[0]);
1523
+				break;
1524
+			default:
1525
+				return $DateTime->format(implode(' ', $formats));
1526
+				break;
1527
+		}
1528
+	}
1529
+
1530
+
1531
+
1532
+	/**
1533
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1534
+	 * for the model are.  Returns a DateTime object.
1535
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1536
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1537
+	 * ignored.
1538
+	 *
1539
+	 * @param string $field_name      The field being setup.
1540
+	 * @param string $timestring      The date time string being used.
1541
+	 * @param string $incoming_format The format for the time string.
1542
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1543
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1544
+	 *                                format is
1545
+	 *                                'U', this is ignored.
1546
+	 * @return DateTime
1547
+	 * @throws EE_Error
1548
+	 */
1549
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1550
+	{
1551
+		// just using this to ensure the timezone is set correctly internally
1552
+		$this->get_formats_for($field_name);
1553
+		// load EEH_DTT_Helper
1554
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1555
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1556
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1557
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1558
+	}
1559
+
1560
+
1561
+
1562
+	/**
1563
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1564
+	 *
1565
+	 * @return EE_Table_Base[]
1566
+	 */
1567
+	public function get_tables()
1568
+	{
1569
+		return $this->_tables;
1570
+	}
1571
+
1572
+
1573
+
1574
+	/**
1575
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1576
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1577
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1578
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1579
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1580
+	 * model object with EVT_ID = 1
1581
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1582
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1583
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1584
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1585
+	 * are not specified)
1586
+	 *
1587
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1588
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1589
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1590
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1591
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1592
+	 *                                         ID=34, we'd use this method as follows:
1593
+	 *                                         EEM_Transaction::instance()->update(
1594
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1595
+	 *                                         array(array('TXN_ID'=>34)));
1596
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1597
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1598
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1599
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1600
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1601
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1602
+	 *                                         TRUE, it is assumed that you've already called
1603
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1604
+	 *                                         malicious javascript. However, if
1605
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1606
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1607
+	 *                                         and every other field, before insertion. We provide this parameter
1608
+	 *                                         because model objects perform their prepare_for_set function on all
1609
+	 *                                         their values, and so don't need to be called again (and in many cases,
1610
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1611
+	 *                                         prepare_for_set method...)
1612
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1613
+	 *                                         in this model's entity map according to $fields_n_values that match
1614
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1615
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1616
+	 *                                         could get out-of-sync with the database
1617
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1618
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1619
+	 *                                         bad)
1620
+	 * @throws EE_Error
1621
+	 */
1622
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1623
+	{
1624
+		if (! is_array($query_params)) {
1625
+			EE_Error::doing_it_wrong(
1626
+				'EEM_Base::update',
1627
+				sprintf(
1628
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1629
+					gettype($query_params)
1630
+				),
1631
+				'4.6.0'
1632
+			);
1633
+			$query_params = array();
1634
+		}
1635
+		/**
1636
+		 * Action called before a model update call has been made.
1637
+		 *
1638
+		 * @param EEM_Base $model
1639
+		 * @param array    $fields_n_values the updated fields and their new values
1640
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1641
+		 */
1642
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1643
+		/**
1644
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1645
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1646
+		 *
1647
+		 * @param array    $fields_n_values fields and their new values
1648
+		 * @param EEM_Base $model           the model being queried
1649
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1650
+		 */
1651
+		$fields_n_values = (array) apply_filters(
1652
+			'FHEE__EEM_Base__update__fields_n_values',
1653
+			$fields_n_values,
1654
+			$this,
1655
+			$query_params
1656
+		);
1657
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1658
+		// to do that, for each table, verify that it's PK isn't null.
1659
+		$tables = $this->get_tables();
1660
+		// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1661
+		// NOTE: we should make this code more efficient by NOT querying twice
1662
+		// before the real update, but that needs to first go through ALPHA testing
1663
+		// as it's dangerous. says Mike August 8 2014
1664
+		// we want to make sure the default_where strategy is ignored
1665
+		$this->_ignore_where_strategy = true;
1666
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1667
+		foreach ($wpdb_select_results as $wpdb_result) {
1668
+			// type cast stdClass as array
1669
+			$wpdb_result = (array) $wpdb_result;
1670
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1671
+			if ($this->has_primary_key_field()) {
1672
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1673
+			} else {
1674
+				// if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1675
+				$main_table_pk_value = null;
1676
+			}
1677
+			// if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1678
+			// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1679
+			if (count($tables) > 1) {
1680
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1681
+				// in that table, and so we'll want to insert one
1682
+				foreach ($tables as $table_obj) {
1683
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1684
+					// if there is no private key for this table on the results, it means there's no entry
1685
+					// in this table, right? so insert a row in the current table, using any fields available
1686
+					if (
1687
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1688
+						   && $wpdb_result[ $this_table_pk_column ])
1689
+					) {
1690
+						$success = $this->_insert_into_specific_table(
1691
+							$table_obj,
1692
+							$fields_n_values,
1693
+							$main_table_pk_value
1694
+						);
1695
+						// if we died here, report the error
1696
+						if (! $success) {
1697
+							return false;
1698
+						}
1699
+					}
1700
+				}
1701
+			}
1702
+			//              //and now check that if we have cached any models by that ID on the model, that
1703
+			//              //they also get updated properly
1704
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1705
+			//              if( $model_object ){
1706
+			//                  foreach( $fields_n_values as $field => $value ){
1707
+			//                      $model_object->set($field, $value);
1708
+			// let's make sure default_where strategy is followed now
1709
+			$this->_ignore_where_strategy = false;
1710
+		}
1711
+		// if we want to keep model objects in sync, AND
1712
+		// if this wasn't called from a model object (to update itself)
1713
+		// then we want to make sure we keep all the existing
1714
+		// model objects in sync with the db
1715
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1716
+			if ($this->has_primary_key_field()) {
1717
+				$model_objs_affected_ids = $this->get_col($query_params);
1718
+			} else {
1719
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1720
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1721
+				$model_objs_affected_ids = array();
1722
+				foreach ($models_affected_key_columns as $row) {
1723
+					$combined_index_key = $this->get_index_primary_key_string($row);
1724
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1725
+				}
1726
+			}
1727
+			if (! $model_objs_affected_ids) {
1728
+				// wait wait wait- if nothing was affected let's stop here
1729
+				return 0;
1730
+			}
1731
+			foreach ($model_objs_affected_ids as $id) {
1732
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1733
+				if ($model_obj_in_entity_map) {
1734
+					foreach ($fields_n_values as $field => $new_value) {
1735
+						$model_obj_in_entity_map->set($field, $new_value);
1736
+					}
1737
+				}
1738
+			}
1739
+			// if there is a primary key on this model, we can now do a slight optimization
1740
+			if ($this->has_primary_key_field()) {
1741
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1742
+				$query_params = array(
1743
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1744
+					'limit'                    => count($model_objs_affected_ids),
1745
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1746
+				);
1747
+			}
1748
+		}
1749
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1750
+		$SQL = "UPDATE "
1751
+			   . $model_query_info->get_full_join_sql()
1752
+			   . " SET "
1753
+			   . $this->_construct_update_sql($fields_n_values)
1754
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1755
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1756
+		/**
1757
+		 * Action called after a model update call has been made.
1758
+		 *
1759
+		 * @param EEM_Base $model
1760
+		 * @param array    $fields_n_values the updated fields and their new values
1761
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1762
+		 * @param int      $rows_affected
1763
+		 */
1764
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1765
+		return $rows_affected;// how many supposedly got updated
1766
+	}
1767
+
1768
+
1769
+
1770
+	/**
1771
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1772
+	 * are teh values of the field specified (or by default the primary key field)
1773
+	 * that matched the query params. Note that you should pass the name of the
1774
+	 * model FIELD, not the database table's column name.
1775
+	 *
1776
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1777
+	 * @param string $field_to_select
1778
+	 * @return array just like $wpdb->get_col()
1779
+	 * @throws EE_Error
1780
+	 */
1781
+	public function get_col($query_params = array(), $field_to_select = null)
1782
+	{
1783
+		if ($field_to_select) {
1784
+			$field = $this->field_settings_for($field_to_select);
1785
+		} elseif ($this->has_primary_key_field()) {
1786
+			$field = $this->get_primary_key_field();
1787
+		} else {
1788
+			// no primary key, just grab the first column
1789
+			$field = reset($this->field_settings());
1790
+		}
1791
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1792
+		$select_expressions = $field->get_qualified_column();
1793
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1794
+		return $this->_do_wpdb_query('get_col', array($SQL));
1795
+	}
1796
+
1797
+
1798
+
1799
+	/**
1800
+	 * Returns a single column value for a single row from the database
1801
+	 *
1802
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1803
+	 * @param string $field_to_select @see EEM_Base::get_col()
1804
+	 * @return string
1805
+	 * @throws EE_Error
1806
+	 */
1807
+	public function get_var($query_params = array(), $field_to_select = null)
1808
+	{
1809
+		$query_params['limit'] = 1;
1810
+		$col = $this->get_col($query_params, $field_to_select);
1811
+		if (! empty($col)) {
1812
+			return reset($col);
1813
+		}
1814
+		return null;
1815
+	}
1816
+
1817
+
1818
+
1819
+	/**
1820
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1821
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1822
+	 * injection, but currently no further filtering is done
1823
+	 *
1824
+	 * @global      $wpdb
1825
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1826
+	 *                               be updated to in the DB
1827
+	 * @return string of SQL
1828
+	 * @throws EE_Error
1829
+	 */
1830
+	public function _construct_update_sql($fields_n_values)
1831
+	{
1832
+		/** @type WPDB $wpdb */
1833
+		global $wpdb;
1834
+		$cols_n_values = array();
1835
+		foreach ($fields_n_values as $field_name => $value) {
1836
+			$field_obj = $this->field_settings_for($field_name);
1837
+			// if the value is NULL, we want to assign the value to that.
1838
+			// wpdb->prepare doesn't really handle that properly
1839
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1840
+			$value_sql = $prepared_value === null ? 'NULL'
1841
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1842
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1843
+		}
1844
+		return implode(",", $cols_n_values);
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
+	 * Performs a HARD delete, meaning the database row should always be removed,
1852
+	 * not just have a flag field on it switched
1853
+	 * Wrapper for EEM_Base::delete_permanently()
1854
+	 *
1855
+	 * @param mixed $id
1856
+	 * @param boolean $allow_blocking
1857
+	 * @return int the number of rows deleted
1858
+	 * @throws EE_Error
1859
+	 */
1860
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1861
+	{
1862
+		return $this->delete_permanently(
1863
+			array(
1864
+				array($this->get_primary_key_field()->get_name() => $id),
1865
+				'limit' => 1,
1866
+			),
1867
+			$allow_blocking
1868
+		);
1869
+	}
1870
+
1871
+
1872
+
1873
+	/**
1874
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1875
+	 * Wrapper for EEM_Base::delete()
1876
+	 *
1877
+	 * @param mixed $id
1878
+	 * @param boolean $allow_blocking
1879
+	 * @return int the number of rows deleted
1880
+	 * @throws EE_Error
1881
+	 */
1882
+	public function delete_by_ID($id, $allow_blocking = true)
1883
+	{
1884
+		return $this->delete(
1885
+			array(
1886
+				array($this->get_primary_key_field()->get_name() => $id),
1887
+				'limit' => 1,
1888
+			),
1889
+			$allow_blocking
1890
+		);
1891
+	}
1892
+
1893
+
1894
+
1895
+	/**
1896
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1897
+	 * meaning if the model has a field that indicates its been "trashed" or
1898
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1899
+	 *
1900
+	 * @see EEM_Base::delete_permanently
1901
+	 * @param array   $query_params
1902
+	 * @param boolean $allow_blocking
1903
+	 * @return int how many rows got deleted
1904
+	 * @throws EE_Error
1905
+	 */
1906
+	public function delete($query_params, $allow_blocking = true)
1907
+	{
1908
+		return $this->delete_permanently($query_params, $allow_blocking);
1909
+	}
1910
+
1911
+
1912
+
1913
+	/**
1914
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1915
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1916
+	 * as archived, not actually deleted
1917
+	 *
1918
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1919
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1920
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1921
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1922
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1923
+	 *                                DB
1924
+	 * @return int how many rows got deleted
1925
+	 * @throws EE_Error
1926
+	 */
1927
+	public function delete_permanently($query_params, $allow_blocking = true)
1928
+	{
1929
+		/**
1930
+		 * Action called just before performing a real deletion query. You can use the
1931
+		 * model and its $query_params to find exactly which items will be deleted
1932
+		 *
1933
+		 * @param EEM_Base $model
1934
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1935
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1936
+		 *                                 to block (prevent) this deletion
1937
+		 */
1938
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1939
+		// some MySQL databases may be running safe mode, which may restrict
1940
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1941
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1942
+		// to delete them
1943
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1944
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1945
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1946
+			$columns_and_ids_for_deleting
1947
+		);
1948
+		/**
1949
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1950
+		 *
1951
+		 * @param EEM_Base $this  The model instance being acted on.
1952
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1953
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1954
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1955
+		 *                                                  derived from the incoming query parameters.
1956
+		 *                                                  @see details on the structure of this array in the phpdocs
1957
+		 *                                                  for the `_get_ids_for_delete_method`
1958
+		 *
1959
+		 */
1960
+		do_action(
1961
+			'AHEE__EEM_Base__delete__before_query',
1962
+			$this,
1963
+			$query_params,
1964
+			$allow_blocking,
1965
+			$columns_and_ids_for_deleting
1966
+		);
1967
+		if ($deletion_where_query_part) {
1968
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1969
+			$table_aliases = array_keys($this->_tables);
1970
+			$SQL = "DELETE "
1971
+				   . implode(", ", $table_aliases)
1972
+				   . " FROM "
1973
+				   . $model_query_info->get_full_join_sql()
1974
+				   . " WHERE "
1975
+				   . $deletion_where_query_part;
1976
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1977
+		} else {
1978
+			$rows_deleted = 0;
1979
+		}
1980
+
1981
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1982
+		// there was no error with the delete query.
1983
+		if (
1984
+			$this->has_primary_key_field()
1985
+			&& $rows_deleted !== false
1986
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1987
+		) {
1988
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1989
+			foreach ($ids_for_removal as $id) {
1990
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1991
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1992
+				}
1993
+			}
1994
+
1995
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1996
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1997
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1998
+			// (although it is possible).
1999
+			// Note this can be skipped by using the provided filter and returning false.
2000
+			if (
2001
+				apply_filters(
2002
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2003
+					! $this instanceof EEM_Extra_Meta,
2004
+					$this
2005
+				)
2006
+			) {
2007
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2008
+					0 => array(
2009
+						'EXM_type' => $this->get_this_model_name(),
2010
+						'OBJ_ID'   => array(
2011
+							'IN',
2012
+							$ids_for_removal
2013
+						)
2014
+					)
2015
+				));
2016
+			}
2017
+		}
2018
+
2019
+		/**
2020
+		 * Action called just after performing a real deletion query. Although at this point the
2021
+		 * items should have been deleted
2022
+		 *
2023
+		 * @param EEM_Base $model
2024
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2025
+		 * @param int      $rows_deleted
2026
+		 */
2027
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2028
+		return $rows_deleted;// how many supposedly got deleted
2029
+	}
2030
+
2031
+
2032
+
2033
+	/**
2034
+	 * Checks all the relations that throw error messages when there are blocking related objects
2035
+	 * for related model objects. If there are any related model objects on those relations,
2036
+	 * adds an EE_Error, and return true
2037
+	 *
2038
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2039
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2040
+	 *                                                 should be ignored when determining whether there are related
2041
+	 *                                                 model objects which block this model object's deletion. Useful
2042
+	 *                                                 if you know A is related to B and are considering deleting A,
2043
+	 *                                                 but want to see if A has any other objects blocking its deletion
2044
+	 *                                                 before removing the relation between A and B
2045
+	 * @return boolean
2046
+	 * @throws EE_Error
2047
+	 */
2048
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2049
+	{
2050
+		// first, if $ignore_this_model_obj was supplied, get its model
2051
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2052
+			$ignored_model = $ignore_this_model_obj->get_model();
2053
+		} else {
2054
+			$ignored_model = null;
2055
+		}
2056
+		// now check all the relations of $this_model_obj_or_id and see if there
2057
+		// are any related model objects blocking it?
2058
+		$is_blocked = false;
2059
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2060
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2061
+				// if $ignore_this_model_obj was supplied, then for the query
2062
+				// on that model needs to be told to ignore $ignore_this_model_obj
2063
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2064
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2065
+						array(
2066
+							$ignored_model->get_primary_key_field()->get_name() => array(
2067
+								'!=',
2068
+								$ignore_this_model_obj->ID(),
2069
+							),
2070
+						),
2071
+					));
2072
+				} else {
2073
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2074
+				}
2075
+				if ($related_model_objects) {
2076
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2077
+					$is_blocked = true;
2078
+				}
2079
+			}
2080
+		}
2081
+		return $is_blocked;
2082
+	}
2083
+
2084
+
2085
+	/**
2086
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2087
+	 * @param array $row_results_for_deleting
2088
+	 * @param bool  $allow_blocking
2089
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2090
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2091
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2092
+	 *                 deleted. Example:
2093
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2094
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2095
+	 *                 where each element is a group of columns and values that get deleted. Example:
2096
+	 *                      array(
2097
+	 *                          0 => array(
2098
+	 *                              'Term_Relationship.object_id' => 1
2099
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2100
+	 *                          ),
2101
+	 *                          1 => array(
2102
+	 *                              'Term_Relationship.object_id' => 1
2103
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2104
+	 *                          )
2105
+	 *                      )
2106
+	 * @throws EE_Error
2107
+	 */
2108
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2109
+	{
2110
+		$ids_to_delete_indexed_by_column = array();
2111
+		if ($this->has_primary_key_field()) {
2112
+			$primary_table = $this->_get_main_table();
2113
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2114
+			$other_tables = $this->_get_other_tables();
2115
+			$ids_to_delete_indexed_by_column = $query = array();
2116
+			foreach ($row_results_for_deleting as $item_to_delete) {
2117
+				// before we mark this item for deletion,
2118
+				// make sure there's no related entities blocking its deletion (if we're checking)
2119
+				if (
2120
+					$allow_blocking
2121
+					&& $this->delete_is_blocked_by_related_models(
2122
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2123
+					)
2124
+				) {
2125
+					continue;
2126
+				}
2127
+				// primary table deletes
2128
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2129
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2130
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2131
+				}
2132
+			}
2133
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2134
+			$fields = $this->get_combined_primary_key_fields();
2135
+			foreach ($row_results_for_deleting as $item_to_delete) {
2136
+				$ids_to_delete_indexed_by_column_for_row = array();
2137
+				foreach ($fields as $cpk_field) {
2138
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2139
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2140
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2141
+					}
2142
+				}
2143
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2144
+			}
2145
+		} else {
2146
+			// so there's no primary key and no combined key...
2147
+			// sorry, can't help you
2148
+			throw new EE_Error(
2149
+				sprintf(
2150
+					__(
2151
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2152
+						"event_espresso"
2153
+					),
2154
+					get_class($this)
2155
+				)
2156
+			);
2157
+		}
2158
+		return $ids_to_delete_indexed_by_column;
2159
+	}
2160
+
2161
+
2162
+	/**
2163
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2164
+	 * the corresponding query_part for the query performing the delete.
2165
+	 *
2166
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2167
+	 * @return string
2168
+	 * @throws EE_Error
2169
+	 */
2170
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2171
+	{
2172
+		$query_part = '';
2173
+		if (empty($ids_to_delete_indexed_by_column)) {
2174
+			return $query_part;
2175
+		} elseif ($this->has_primary_key_field()) {
2176
+			$query = array();
2177
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2178
+				// make sure we have unique $ids
2179
+				$ids = array_unique($ids);
2180
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2181
+			}
2182
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2183
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2184
+			$ways_to_identify_a_row = array();
2185
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2186
+				$values_for_each_combined_primary_key_for_a_row = array();
2187
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2188
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2189
+				}
2190
+				$ways_to_identify_a_row[] = '('
2191
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2192
+											. ')';
2193
+			}
2194
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2195
+		}
2196
+		return $query_part;
2197
+	}
2198
+
2199
+
2200
+
2201
+	/**
2202
+	 * Gets the model field by the fully qualified name
2203
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2204
+	 * @return EE_Model_Field_Base
2205
+	 */
2206
+	public function get_field_by_column($qualified_column_name)
2207
+	{
2208
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2209
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2210
+				return $field_obj;
2211
+			}
2212
+		}
2213
+		throw new EE_Error(
2214
+			sprintf(
2215
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2216
+				$this->get_this_model_name(),
2217
+				$qualified_column_name
2218
+			)
2219
+		);
2220
+	}
2221
+
2222
+
2223
+
2224
+	/**
2225
+	 * Count all the rows that match criteria the model query params.
2226
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2227
+	 * column
2228
+	 *
2229
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2230
+	 * @param string $field_to_count field on model to count by (not column name)
2231
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2232
+	 *                               that by the setting $distinct to TRUE;
2233
+	 * @return int
2234
+	 * @throws EE_Error
2235
+	 */
2236
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2237
+	{
2238
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2239
+		if ($field_to_count) {
2240
+			$field_obj = $this->field_settings_for($field_to_count);
2241
+			$column_to_count = $field_obj->get_qualified_column();
2242
+		} elseif ($this->has_primary_key_field()) {
2243
+			$pk_field_obj = $this->get_primary_key_field();
2244
+			$column_to_count = $pk_field_obj->get_qualified_column();
2245
+		} else {
2246
+			// there's no primary key
2247
+			// if we're counting distinct items, and there's no primary key,
2248
+			// we need to list out the columns for distinction;
2249
+			// otherwise we can just use star
2250
+			if ($distinct) {
2251
+				$columns_to_use = array();
2252
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2253
+					$columns_to_use[] = $field_obj->get_qualified_column();
2254
+				}
2255
+				$column_to_count = implode(',', $columns_to_use);
2256
+			} else {
2257
+				$column_to_count = '*';
2258
+			}
2259
+		}
2260
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2261
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2262
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2263
+	}
2264
+
2265
+
2266
+
2267
+	/**
2268
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2269
+	 *
2270
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2271
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2272
+	 * @return float
2273
+	 * @throws EE_Error
2274
+	 */
2275
+	public function sum($query_params, $field_to_sum = null)
2276
+	{
2277
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2278
+		if ($field_to_sum) {
2279
+			$field_obj = $this->field_settings_for($field_to_sum);
2280
+		} else {
2281
+			$field_obj = $this->get_primary_key_field();
2282
+		}
2283
+		$column_to_count = $field_obj->get_qualified_column();
2284
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2285
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2286
+		$data_type = $field_obj->get_wpdb_data_type();
2287
+		if ($data_type === '%d' || $data_type === '%s') {
2288
+			return (float) $return_value;
2289
+		}
2290
+		// must be %f
2291
+		return (float) $return_value;
2292
+	}
2293
+
2294
+
2295
+
2296
+	/**
2297
+	 * Just calls the specified method on $wpdb with the given arguments
2298
+	 * Consolidates a little extra error handling code
2299
+	 *
2300
+	 * @param string $wpdb_method
2301
+	 * @param array  $arguments_to_provide
2302
+	 * @throws EE_Error
2303
+	 * @global wpdb  $wpdb
2304
+	 * @return mixed
2305
+	 */
2306
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2307
+	{
2308
+		// if we're in maintenance mode level 2, DON'T run any queries
2309
+		// because level 2 indicates the database needs updating and
2310
+		// is probably out of sync with the code
2311
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2312
+			throw new EE_Error(sprintf(__(
2313
+				"Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2314
+				"event_espresso"
2315
+			)));
2316
+		}
2317
+		/** @type WPDB $wpdb */
2318
+		global $wpdb;
2319
+		if (! method_exists($wpdb, $wpdb_method)) {
2320
+			throw new EE_Error(sprintf(__(
2321
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2322
+				'event_espresso'
2323
+			), $wpdb_method));
2324
+		}
2325
+		if (WP_DEBUG) {
2326
+			$old_show_errors_value = $wpdb->show_errors;
2327
+			$wpdb->show_errors(false);
2328
+		}
2329
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2330
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2331
+		if (WP_DEBUG) {
2332
+			$wpdb->show_errors($old_show_errors_value);
2333
+			if (! empty($wpdb->last_error)) {
2334
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2335
+			}
2336
+			if ($result === false) {
2337
+				throw new EE_Error(sprintf(__(
2338
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2339
+					'event_espresso'
2340
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2341
+			}
2342
+		} elseif ($result === false) {
2343
+			EE_Error::add_error(
2344
+				sprintf(
2345
+					__(
2346
+						'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2347
+						'event_espresso'
2348
+					),
2349
+					$wpdb_method,
2350
+					var_export($arguments_to_provide, true),
2351
+					$wpdb->last_error
2352
+				),
2353
+				__FILE__,
2354
+				__FUNCTION__,
2355
+				__LINE__
2356
+			);
2357
+		}
2358
+		return $result;
2359
+	}
2360
+
2361
+
2362
+
2363
+	/**
2364
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2365
+	 * and if there's an error tries to verify the DB is correct. Uses
2366
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2367
+	 * we should try to fix the EE core db, the addons, or just give up
2368
+	 *
2369
+	 * @param string $wpdb_method
2370
+	 * @param array  $arguments_to_provide
2371
+	 * @return mixed
2372
+	 */
2373
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2374
+	{
2375
+		/** @type WPDB $wpdb */
2376
+		global $wpdb;
2377
+		$wpdb->last_error = null;
2378
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2379
+		// was there an error running the query? but we don't care on new activations
2380
+		// (we're going to setup the DB anyway on new activations)
2381
+		if (
2382
+			($result === false || ! empty($wpdb->last_error))
2383
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2384
+		) {
2385
+			switch (EEM_Base::$_db_verification_level) {
2386
+				case EEM_Base::db_verified_none:
2387
+					// let's double-check core's DB
2388
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2389
+					break;
2390
+				case EEM_Base::db_verified_core:
2391
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2392
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2393
+					break;
2394
+				case EEM_Base::db_verified_addons:
2395
+					// ummmm... you in trouble
2396
+					return $result;
2397
+					break;
2398
+			}
2399
+			if (! empty($error_message)) {
2400
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2401
+				trigger_error($error_message);
2402
+			}
2403
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2404
+		}
2405
+		return $result;
2406
+	}
2407
+
2408
+
2409
+
2410
+	/**
2411
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2412
+	 * EEM_Base::$_db_verification_level
2413
+	 *
2414
+	 * @param string $wpdb_method
2415
+	 * @param array  $arguments_to_provide
2416
+	 * @return string
2417
+	 */
2418
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2419
+	{
2420
+		/** @type WPDB $wpdb */
2421
+		global $wpdb;
2422
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2423
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2424
+		$error_message = sprintf(
2425
+			__(
2426
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2427
+				'event_espresso'
2428
+			),
2429
+			$wpdb->last_error,
2430
+			$wpdb_method,
2431
+			wp_json_encode($arguments_to_provide)
2432
+		);
2433
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2434
+		return $error_message;
2435
+	}
2436
+
2437
+
2438
+
2439
+	/**
2440
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2441
+	 * EEM_Base::$_db_verification_level
2442
+	 *
2443
+	 * @param $wpdb_method
2444
+	 * @param $arguments_to_provide
2445
+	 * @return string
2446
+	 */
2447
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2448
+	{
2449
+		/** @type WPDB $wpdb */
2450
+		global $wpdb;
2451
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2452
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2453
+		$error_message = sprintf(
2454
+			__(
2455
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2456
+				'event_espresso'
2457
+			),
2458
+			$wpdb->last_error,
2459
+			$wpdb_method,
2460
+			wp_json_encode($arguments_to_provide)
2461
+		);
2462
+		EE_System::instance()->initialize_addons();
2463
+		return $error_message;
2464
+	}
2465
+
2466
+
2467
+
2468
+	/**
2469
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2470
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2471
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2472
+	 * ..."
2473
+	 *
2474
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2475
+	 * @return string
2476
+	 */
2477
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2478
+	{
2479
+		return " FROM " . $model_query_info->get_full_join_sql() .
2480
+			   $model_query_info->get_where_sql() .
2481
+			   $model_query_info->get_group_by_sql() .
2482
+			   $model_query_info->get_having_sql() .
2483
+			   $model_query_info->get_order_by_sql() .
2484
+			   $model_query_info->get_limit_sql();
2485
+	}
2486
+
2487
+
2488
+
2489
+	/**
2490
+	 * Set to easily debug the next X queries ran from this model.
2491
+	 *
2492
+	 * @param int $count
2493
+	 */
2494
+	public function show_next_x_db_queries($count = 1)
2495
+	{
2496
+		$this->_show_next_x_db_queries = $count;
2497
+	}
2498
+
2499
+
2500
+
2501
+	/**
2502
+	 * @param $sql_query
2503
+	 */
2504
+	public function show_db_query_if_previously_requested($sql_query)
2505
+	{
2506
+		if ($this->_show_next_x_db_queries > 0) {
2507
+			echo $sql_query;
2508
+			$this->_show_next_x_db_queries--;
2509
+		}
2510
+	}
2511
+
2512
+
2513
+
2514
+	/**
2515
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2516
+	 * There are the 3 cases:
2517
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2518
+	 * $otherModelObject has no ID, it is first saved.
2519
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2520
+	 * has no ID, it is first saved.
2521
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2522
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2523
+	 * join table
2524
+	 *
2525
+	 * @param        EE_Base_Class                     /int $thisModelObject
2526
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2527
+	 * @param string $relationName                     , key in EEM_Base::_relations
2528
+	 *                                                 an attendee to a group, you also want to specify which role they
2529
+	 *                                                 will have in that group. So you would use this parameter to
2530
+	 *                                                 specify array('role-column-name'=>'role-id')
2531
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2532
+	 *                                                 to for relation to methods that allow you to further specify
2533
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2534
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2535
+	 *                                                 because these will be inserted in any new rows created as well.
2536
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2537
+	 * @throws EE_Error
2538
+	 */
2539
+	public function add_relationship_to(
2540
+		$id_or_obj,
2541
+		$other_model_id_or_obj,
2542
+		$relationName,
2543
+		$extra_join_model_fields_n_values = array()
2544
+	) {
2545
+		$relation_obj = $this->related_settings_for($relationName);
2546
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2547
+	}
2548
+
2549
+
2550
+
2551
+	/**
2552
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2553
+	 * There are the 3 cases:
2554
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2555
+	 * error
2556
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2557
+	 * an error
2558
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2559
+	 *
2560
+	 * @param        EE_Base_Class /int $id_or_obj
2561
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2562
+	 * @param string $relationName key in EEM_Base::_relations
2563
+	 * @return boolean of success
2564
+	 * @throws EE_Error
2565
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2566
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2567
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2568
+	 *                             because these will be inserted in any new rows created as well.
2569
+	 */
2570
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2571
+	{
2572
+		$relation_obj = $this->related_settings_for($relationName);
2573
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2574
+	}
2575
+
2576
+
2577
+
2578
+	/**
2579
+	 * @param mixed           $id_or_obj
2580
+	 * @param string          $relationName
2581
+	 * @param array           $where_query_params
2582
+	 * @param EE_Base_Class[] objects to which relations were removed
2583
+	 * @return \EE_Base_Class[]
2584
+	 * @throws EE_Error
2585
+	 */
2586
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2587
+	{
2588
+		$relation_obj = $this->related_settings_for($relationName);
2589
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2590
+	}
2591
+
2592
+
2593
+
2594
+	/**
2595
+	 * Gets all the related items of the specified $model_name, using $query_params.
2596
+	 * Note: by default, we remove the "default query params"
2597
+	 * because we want to get even deleted items etc.
2598
+	 *
2599
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2600
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2601
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2602
+	 * @return EE_Base_Class[]
2603
+	 * @throws EE_Error
2604
+	 */
2605
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2606
+	{
2607
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2608
+		$relation_settings = $this->related_settings_for($model_name);
2609
+		return $relation_settings->get_all_related($model_obj, $query_params);
2610
+	}
2611
+
2612
+
2613
+
2614
+	/**
2615
+	 * Deletes all the model objects across the relation indicated by $model_name
2616
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2617
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2618
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2619
+	 *
2620
+	 * @param EE_Base_Class|int|string $id_or_obj
2621
+	 * @param string                   $model_name
2622
+	 * @param array                    $query_params
2623
+	 * @return int how many deleted
2624
+	 * @throws EE_Error
2625
+	 */
2626
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2627
+	{
2628
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2629
+		$relation_settings = $this->related_settings_for($model_name);
2630
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2631
+	}
2632
+
2633
+
2634
+
2635
+	/**
2636
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2637
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2638
+	 * the model objects can't be hard deleted because of blocking related model objects,
2639
+	 * just does a soft-delete on them instead.
2640
+	 *
2641
+	 * @param EE_Base_Class|int|string $id_or_obj
2642
+	 * @param string                   $model_name
2643
+	 * @param array                    $query_params
2644
+	 * @return int how many deleted
2645
+	 * @throws EE_Error
2646
+	 */
2647
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2648
+	{
2649
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2650
+		$relation_settings = $this->related_settings_for($model_name);
2651
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2652
+	}
2653
+
2654
+
2655
+
2656
+	/**
2657
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2658
+	 * unless otherwise specified in the $query_params
2659
+	 *
2660
+	 * @param        int             /EE_Base_Class $id_or_obj
2661
+	 * @param string $model_name     like 'Event', or 'Registration'
2662
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2663
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2664
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2665
+	 *                               that by the setting $distinct to TRUE;
2666
+	 * @return int
2667
+	 * @throws EE_Error
2668
+	 */
2669
+	public function count_related(
2670
+		$id_or_obj,
2671
+		$model_name,
2672
+		$query_params = array(),
2673
+		$field_to_count = null,
2674
+		$distinct = false
2675
+	) {
2676
+		$related_model = $this->get_related_model_obj($model_name);
2677
+		// we're just going to use the query params on the related model's normal get_all query,
2678
+		// except add a condition to say to match the current mod
2679
+		if (! isset($query_params['default_where_conditions'])) {
2680
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2681
+		}
2682
+		$this_model_name = $this->get_this_model_name();
2683
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2684
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2685
+		return $related_model->count($query_params, $field_to_count, $distinct);
2686
+	}
2687
+
2688
+
2689
+
2690
+	/**
2691
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2692
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2693
+	 *
2694
+	 * @param        int           /EE_Base_Class $id_or_obj
2695
+	 * @param string $model_name   like 'Event', or 'Registration'
2696
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2697
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2698
+	 * @return float
2699
+	 * @throws EE_Error
2700
+	 */
2701
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2702
+	{
2703
+		$related_model = $this->get_related_model_obj($model_name);
2704
+		if (! is_array($query_params)) {
2705
+			EE_Error::doing_it_wrong(
2706
+				'EEM_Base::sum_related',
2707
+				sprintf(
2708
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2709
+					gettype($query_params)
2710
+				),
2711
+				'4.6.0'
2712
+			);
2713
+			$query_params = array();
2714
+		}
2715
+		// we're just going to use the query params on the related model's normal get_all query,
2716
+		// except add a condition to say to match the current mod
2717
+		if (! isset($query_params['default_where_conditions'])) {
2718
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2719
+		}
2720
+		$this_model_name = $this->get_this_model_name();
2721
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2722
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2723
+		return $related_model->sum($query_params, $field_to_sum);
2724
+	}
2725
+
2726
+
2727
+
2728
+	/**
2729
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2730
+	 * $modelObject
2731
+	 *
2732
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2733
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2734
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2735
+	 * @return EE_Base_Class
2736
+	 * @throws EE_Error
2737
+	 */
2738
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2739
+	{
2740
+		$query_params['limit'] = 1;
2741
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2742
+		if ($results) {
2743
+			return array_shift($results);
2744
+		}
2745
+		return null;
2746
+	}
2747
+
2748
+
2749
+
2750
+	/**
2751
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2752
+	 *
2753
+	 * @return string
2754
+	 */
2755
+	public function get_this_model_name()
2756
+	{
2757
+		return str_replace("EEM_", "", get_class($this));
2758
+	}
2759
+
2760
+
2761
+
2762
+	/**
2763
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2764
+	 *
2765
+	 * @return EE_Any_Foreign_Model_Name_Field
2766
+	 * @throws EE_Error
2767
+	 */
2768
+	public function get_field_containing_related_model_name()
2769
+	{
2770
+		foreach ($this->field_settings(true) as $field) {
2771
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2772
+				$field_with_model_name = $field;
2773
+			}
2774
+		}
2775
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2776
+			throw new EE_Error(sprintf(
2777
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2778
+				$this->get_this_model_name()
2779
+			));
2780
+		}
2781
+		return $field_with_model_name;
2782
+	}
2783
+
2784
+
2785
+
2786
+	/**
2787
+	 * Inserts a new entry into the database, for each table.
2788
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2789
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2790
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2791
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2792
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2793
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2794
+	 *
2795
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2796
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2797
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2798
+	 *                              of EEM_Base)
2799
+	 * @return int|string new primary key on main table that got inserted
2800
+	 * @throws EE_Error
2801
+	 */
2802
+	public function insert($field_n_values)
2803
+	{
2804
+		/**
2805
+		 * Filters the fields and their values before inserting an item using the models
2806
+		 *
2807
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2808
+		 * @param EEM_Base $model           the model used
2809
+		 */
2810
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2811
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2812
+			$main_table = $this->_get_main_table();
2813
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2814
+			if ($new_id !== false) {
2815
+				foreach ($this->_get_other_tables() as $other_table) {
2816
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2817
+				}
2818
+			}
2819
+			/**
2820
+			 * Done just after attempting to insert a new model object
2821
+			 *
2822
+			 * @param EEM_Base   $model           used
2823
+			 * @param array      $fields_n_values fields and their values
2824
+			 * @param int|string the              ID of the newly-inserted model object
2825
+			 */
2826
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2827
+			return $new_id;
2828
+		}
2829
+		return false;
2830
+	}
2831
+
2832
+
2833
+
2834
+	/**
2835
+	 * Checks that the result would satisfy the unique indexes on this model
2836
+	 *
2837
+	 * @param array  $field_n_values
2838
+	 * @param string $action
2839
+	 * @return boolean
2840
+	 * @throws EE_Error
2841
+	 */
2842
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2843
+	{
2844
+		foreach ($this->unique_indexes() as $index_name => $index) {
2845
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2846
+			if ($this->exists(array($uniqueness_where_params))) {
2847
+				EE_Error::add_error(
2848
+					sprintf(
2849
+						__(
2850
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2851
+							"event_espresso"
2852
+						),
2853
+						$action,
2854
+						$this->_get_class_name(),
2855
+						$index_name,
2856
+						implode(",", $index->field_names()),
2857
+						http_build_query($uniqueness_where_params)
2858
+					),
2859
+					__FILE__,
2860
+					__FUNCTION__,
2861
+					__LINE__
2862
+				);
2863
+				return false;
2864
+			}
2865
+		}
2866
+		return true;
2867
+	}
2868
+
2869
+
2870
+
2871
+	/**
2872
+	 * Checks the database for an item that conflicts (ie, if this item were
2873
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2874
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2875
+	 * can be either an EE_Base_Class or an array of fields n values
2876
+	 *
2877
+	 * @param EE_Base_Class|array $obj_or_fields_array
2878
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2879
+	 *                                                 when looking for conflicts
2880
+	 *                                                 (ie, if false, we ignore the model object's primary key
2881
+	 *                                                 when finding "conflicts". If true, it's also considered).
2882
+	 *                                                 Only works for INT primary key,
2883
+	 *                                                 STRING primary keys cannot be ignored
2884
+	 * @throws EE_Error
2885
+	 * @return EE_Base_Class|array
2886
+	 */
2887
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2888
+	{
2889
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2890
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2891
+		} elseif (is_array($obj_or_fields_array)) {
2892
+			$fields_n_values = $obj_or_fields_array;
2893
+		} else {
2894
+			throw new EE_Error(
2895
+				sprintf(
2896
+					__(
2897
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2898
+						"event_espresso"
2899
+					),
2900
+					get_class($this),
2901
+					$obj_or_fields_array
2902
+				)
2903
+			);
2904
+		}
2905
+		$query_params = array();
2906
+		if (
2907
+			$this->has_primary_key_field()
2908
+			&& ($include_primary_key
2909
+				|| $this->get_primary_key_field()
2910
+				   instanceof
2911
+				   EE_Primary_Key_String_Field)
2912
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2913
+		) {
2914
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2915
+		}
2916
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2917
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2918
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2919
+		}
2920
+		// if there is nothing to base this search on, then we shouldn't find anything
2921
+		if (empty($query_params)) {
2922
+			return array();
2923
+		}
2924
+		return $this->get_one($query_params);
2925
+	}
2926
+
2927
+
2928
+
2929
+	/**
2930
+	 * Like count, but is optimized and returns a boolean instead of an int
2931
+	 *
2932
+	 * @param array $query_params
2933
+	 * @return boolean
2934
+	 * @throws EE_Error
2935
+	 */
2936
+	public function exists($query_params)
2937
+	{
2938
+		$query_params['limit'] = 1;
2939
+		return $this->count($query_params) > 0;
2940
+	}
2941
+
2942
+
2943
+
2944
+	/**
2945
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2946
+	 *
2947
+	 * @param int|string $id
2948
+	 * @return boolean
2949
+	 * @throws EE_Error
2950
+	 */
2951
+	public function exists_by_ID($id)
2952
+	{
2953
+		return $this->exists(
2954
+			array(
2955
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2956
+				array(
2957
+					$this->primary_key_name() => $id,
2958
+				),
2959
+			)
2960
+		);
2961
+	}
2962
+
2963
+
2964
+
2965
+	/**
2966
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2967
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2968
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2969
+	 * on the main table)
2970
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2971
+	 * cases where we want to call it directly rather than via insert().
2972
+	 *
2973
+	 * @access   protected
2974
+	 * @param EE_Table_Base $table
2975
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2976
+	 *                                       float
2977
+	 * @param int           $new_id          for now we assume only int keys
2978
+	 * @throws EE_Error
2979
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2980
+	 * @return int ID of new row inserted, or FALSE on failure
2981
+	 */
2982
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2983
+	{
2984
+		global $wpdb;
2985
+		$insertion_col_n_values = array();
2986
+		$format_for_insertion = array();
2987
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2988
+		foreach ($fields_on_table as $field_name => $field_obj) {
2989
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2990
+			if ($field_obj->is_auto_increment()) {
2991
+				continue;
2992
+			}
2993
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2994
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2995
+			if ($prepared_value !== null) {
2996
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2997
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2998
+			}
2999
+		}
3000
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3001
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3002
+			// so add the fk to the main table as a column
3003
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3004
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3005
+		}
3006
+		// insert the new entry
3007
+		$result = $this->_do_wpdb_query(
3008
+			'insert',
3009
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3010
+		);
3011
+		if ($result === false) {
3012
+			return false;
3013
+		}
3014
+		// ok, now what do we return for the ID of the newly-inserted thing?
3015
+		if ($this->has_primary_key_field()) {
3016
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3017
+				return $wpdb->insert_id;
3018
+			}
3019
+			// it's not an auto-increment primary key, so
3020
+			// it must have been supplied
3021
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3022
+		}
3023
+		// we can't return a  primary key because there is none. instead return
3024
+		// a unique string indicating this model
3025
+		return $this->get_index_primary_key_string($fields_n_values);
3026
+	}
3027
+
3028
+
3029
+
3030
+	/**
3031
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3032
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3033
+	 * and there is no default, we pass it along. WPDB will take care of it)
3034
+	 *
3035
+	 * @param EE_Model_Field_Base $field_obj
3036
+	 * @param array               $fields_n_values
3037
+	 * @return mixed string|int|float depending on what the table column will be expecting
3038
+	 * @throws EE_Error
3039
+	 */
3040
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3041
+	{
3042
+		// if this field doesn't allow nullable, don't allow it
3043
+		if (
3044
+			! $field_obj->is_nullable()
3045
+			&& (
3046
+				! isset($fields_n_values[ $field_obj->get_name() ])
3047
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3048
+			)
3049
+		) {
3050
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3051
+		}
3052
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3053
+			? $fields_n_values[ $field_obj->get_name() ]
3054
+			: null;
3055
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3056
+	}
3057
+
3058
+
3059
+
3060
+	/**
3061
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3062
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3063
+	 * the field's prepare_for_set() method.
3064
+	 *
3065
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3066
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3067
+	 *                                   top of file)
3068
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3069
+	 *                                   $value is a custom selection
3070
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3071
+	 */
3072
+	private function _prepare_value_for_use_in_db($value, $field)
3073
+	{
3074
+		if ($field && $field instanceof EE_Model_Field_Base) {
3075
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3076
+			switch ($this->_values_already_prepared_by_model_object) {
3077
+				/** @noinspection PhpMissingBreakStatementInspection */
3078
+				case self::not_prepared_by_model_object:
3079
+					$value = $field->prepare_for_set($value);
3080
+				// purposefully left out "return"
3081
+				case self::prepared_by_model_object:
3082
+					/** @noinspection SuspiciousAssignmentsInspection */
3083
+					$value = $field->prepare_for_use_in_db($value);
3084
+				case self::prepared_for_use_in_db:
3085
+					// leave the value alone
3086
+			}
3087
+			return $value;
3088
+			// phpcs:enable
3089
+		}
3090
+		return $value;
3091
+	}
3092
+
3093
+
3094
+
3095
+	/**
3096
+	 * Returns the main table on this model
3097
+	 *
3098
+	 * @return EE_Primary_Table
3099
+	 * @throws EE_Error
3100
+	 */
3101
+	protected function _get_main_table()
3102
+	{
3103
+		foreach ($this->_tables as $table) {
3104
+			if ($table instanceof EE_Primary_Table) {
3105
+				return $table;
3106
+			}
3107
+		}
3108
+		throw new EE_Error(sprintf(__(
3109
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3110
+			'event_espresso'
3111
+		), get_class($this)));
3112
+	}
3113
+
3114
+
3115
+
3116
+	/**
3117
+	 * table
3118
+	 * returns EE_Primary_Table table name
3119
+	 *
3120
+	 * @return string
3121
+	 * @throws EE_Error
3122
+	 */
3123
+	public function table()
3124
+	{
3125
+		return $this->_get_main_table()->get_table_name();
3126
+	}
3127
+
3128
+
3129
+
3130
+	/**
3131
+	 * table
3132
+	 * returns first EE_Secondary_Table table name
3133
+	 *
3134
+	 * @return string
3135
+	 */
3136
+	public function second_table()
3137
+	{
3138
+		// grab second table from tables array
3139
+		$second_table = end($this->_tables);
3140
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3141
+	}
3142
+
3143
+
3144
+
3145
+	/**
3146
+	 * get_table_obj_by_alias
3147
+	 * returns table name given it's alias
3148
+	 *
3149
+	 * @param string $table_alias
3150
+	 * @return EE_Primary_Table | EE_Secondary_Table
3151
+	 */
3152
+	public function get_table_obj_by_alias($table_alias = '')
3153
+	{
3154
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3155
+	}
3156
+
3157
+
3158
+
3159
+	/**
3160
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3161
+	 *
3162
+	 * @return EE_Secondary_Table[]
3163
+	 */
3164
+	protected function _get_other_tables()
3165
+	{
3166
+		$other_tables = array();
3167
+		foreach ($this->_tables as $table_alias => $table) {
3168
+			if ($table instanceof EE_Secondary_Table) {
3169
+				$other_tables[ $table_alias ] = $table;
3170
+			}
3171
+		}
3172
+		return $other_tables;
3173
+	}
3174
+
3175
+
3176
+
3177
+	/**
3178
+	 * Finds all the fields that correspond to the given table
3179
+	 *
3180
+	 * @param string $table_alias , array key in EEM_Base::_tables
3181
+	 * @return EE_Model_Field_Base[]
3182
+	 */
3183
+	public function _get_fields_for_table($table_alias)
3184
+	{
3185
+		return $this->_fields[ $table_alias ];
3186
+	}
3187
+
3188
+
3189
+
3190
+	/**
3191
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3192
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3193
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3194
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3195
+	 * related Registration, Transaction, and Payment models.
3196
+	 *
3197
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3198
+	 * @return EE_Model_Query_Info_Carrier
3199
+	 * @throws EE_Error
3200
+	 */
3201
+	public function _extract_related_models_from_query($query_params)
3202
+	{
3203
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3204
+		if (array_key_exists(0, $query_params)) {
3205
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3206
+		}
3207
+		if (array_key_exists('group_by', $query_params)) {
3208
+			if (is_array($query_params['group_by'])) {
3209
+				$this->_extract_related_models_from_sub_params_array_values(
3210
+					$query_params['group_by'],
3211
+					$query_info_carrier,
3212
+					'group_by'
3213
+				);
3214
+			} elseif (! empty($query_params['group_by'])) {
3215
+				$this->_extract_related_model_info_from_query_param(
3216
+					$query_params['group_by'],
3217
+					$query_info_carrier,
3218
+					'group_by'
3219
+				);
3220
+			}
3221
+		}
3222
+		if (array_key_exists('having', $query_params)) {
3223
+			$this->_extract_related_models_from_sub_params_array_keys(
3224
+				$query_params[0],
3225
+				$query_info_carrier,
3226
+				'having'
3227
+			);
3228
+		}
3229
+		if (array_key_exists('order_by', $query_params)) {
3230
+			if (is_array($query_params['order_by'])) {
3231
+				$this->_extract_related_models_from_sub_params_array_keys(
3232
+					$query_params['order_by'],
3233
+					$query_info_carrier,
3234
+					'order_by'
3235
+				);
3236
+			} elseif (! empty($query_params['order_by'])) {
3237
+				$this->_extract_related_model_info_from_query_param(
3238
+					$query_params['order_by'],
3239
+					$query_info_carrier,
3240
+					'order_by'
3241
+				);
3242
+			}
3243
+		}
3244
+		if (array_key_exists('force_join', $query_params)) {
3245
+			$this->_extract_related_models_from_sub_params_array_values(
3246
+				$query_params['force_join'],
3247
+				$query_info_carrier,
3248
+				'force_join'
3249
+			);
3250
+		}
3251
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3252
+		return $query_info_carrier;
3253
+	}
3254
+
3255
+
3256
+
3257
+	/**
3258
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3259
+	 *
3260
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3261
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3262
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3263
+	 * @throws EE_Error
3264
+	 * @return \EE_Model_Query_Info_Carrier
3265
+	 */
3266
+	private function _extract_related_models_from_sub_params_array_keys(
3267
+		$sub_query_params,
3268
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3269
+		$query_param_type
3270
+	) {
3271
+		if (! empty($sub_query_params)) {
3272
+			$sub_query_params = (array) $sub_query_params;
3273
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3274
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3275
+				$this->_extract_related_model_info_from_query_param(
3276
+					$param,
3277
+					$model_query_info_carrier,
3278
+					$query_param_type
3279
+				);
3280
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3281
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3282
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3283
+				// of array('Registration.TXN_ID'=>23)
3284
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3285
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3286
+					if (! is_array($possibly_array_of_params)) {
3287
+						throw new EE_Error(sprintf(
3288
+							__(
3289
+								"You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3290
+								"event_espresso"
3291
+							),
3292
+							$param,
3293
+							$possibly_array_of_params
3294
+						));
3295
+					}
3296
+					$this->_extract_related_models_from_sub_params_array_keys(
3297
+						$possibly_array_of_params,
3298
+						$model_query_info_carrier,
3299
+						$query_param_type
3300
+					);
3301
+				} elseif (
3302
+					$query_param_type === 0 // ie WHERE
3303
+						  && is_array($possibly_array_of_params)
3304
+						  && isset($possibly_array_of_params[2])
3305
+						  && $possibly_array_of_params[2] == true
3306
+				) {
3307
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3308
+					// indicating that $possible_array_of_params[1] is actually a field name,
3309
+					// from which we should extract query parameters!
3310
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3311
+						throw new EE_Error(sprintf(__(
3312
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3313
+							"event_espresso"
3314
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3315
+					}
3316
+					$this->_extract_related_model_info_from_query_param(
3317
+						$possibly_array_of_params[1],
3318
+						$model_query_info_carrier,
3319
+						$query_param_type
3320
+					);
3321
+				}
3322
+			}
3323
+		}
3324
+		return $model_query_info_carrier;
3325
+	}
3326
+
3327
+
3328
+
3329
+	/**
3330
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3331
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3332
+	 *
3333
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3334
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3335
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3336
+	 * @throws EE_Error
3337
+	 * @return \EE_Model_Query_Info_Carrier
3338
+	 */
3339
+	private function _extract_related_models_from_sub_params_array_values(
3340
+		$sub_query_params,
3341
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3342
+		$query_param_type
3343
+	) {
3344
+		if (! empty($sub_query_params)) {
3345
+			if (! is_array($sub_query_params)) {
3346
+				throw new EE_Error(sprintf(
3347
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3348
+					$sub_query_params
3349
+				));
3350
+			}
3351
+			foreach ($sub_query_params as $param) {
3352
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3353
+				$this->_extract_related_model_info_from_query_param(
3354
+					$param,
3355
+					$model_query_info_carrier,
3356
+					$query_param_type
3357
+				);
3358
+			}
3359
+		}
3360
+		return $model_query_info_carrier;
3361
+	}
3362
+
3363
+
3364
+	/**
3365
+	 * Extract all the query parts from  model query params
3366
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3367
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3368
+	 * but use them in a different order. Eg, we need to know what models we are querying
3369
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3370
+	 * other models before we can finalize the where clause SQL.
3371
+	 *
3372
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3373
+	 * @throws EE_Error
3374
+	 * @return EE_Model_Query_Info_Carrier
3375
+	 * @throws ModelConfigurationException
3376
+	 */
3377
+	public function _create_model_query_info_carrier($query_params)
3378
+	{
3379
+		if (! is_array($query_params)) {
3380
+			EE_Error::doing_it_wrong(
3381
+				'EEM_Base::_create_model_query_info_carrier',
3382
+				sprintf(
3383
+					__(
3384
+						'$query_params should be an array, you passed a variable of type %s',
3385
+						'event_espresso'
3386
+					),
3387
+					gettype($query_params)
3388
+				),
3389
+				'4.6.0'
3390
+			);
3391
+			$query_params = array();
3392
+		}
3393
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3394
+		// first check if we should alter the query to account for caps or not
3395
+		// because the caps might require us to do extra joins
3396
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3397
+			$query_params[0] = array_replace_recursive(
3398
+				$query_params[0],
3399
+				$this->caps_where_conditions(
3400
+					$query_params['caps']
3401
+				)
3402
+			);
3403
+		}
3404
+
3405
+		// check if we should alter the query to remove data related to protected
3406
+		// custom post types
3407
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3408
+			$where_param_key_for_password = $this->modelChainAndPassword();
3409
+			// only include if related to a cpt where no password has been set
3410
+			$query_params[0]['OR*nopassword'] = array(
3411
+				$where_param_key_for_password => '',
3412
+				$where_param_key_for_password . '*' => array('IS_NULL')
3413
+			);
3414
+		}
3415
+		$query_object = $this->_extract_related_models_from_query($query_params);
3416
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3417
+		foreach ($query_params[0] as $key => $value) {
3418
+			if (is_int($key)) {
3419
+				throw new EE_Error(
3420
+					sprintf(
3421
+						__(
3422
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3423
+							"event_espresso"
3424
+						),
3425
+						$key,
3426
+						var_export($value, true),
3427
+						var_export($query_params, true),
3428
+						get_class($this)
3429
+					)
3430
+				);
3431
+			}
3432
+		}
3433
+		if (
3434
+			array_key_exists('default_where_conditions', $query_params)
3435
+			&& ! empty($query_params['default_where_conditions'])
3436
+		) {
3437
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3438
+		} else {
3439
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3440
+		}
3441
+		$query_params[0] = array_merge(
3442
+			$this->_get_default_where_conditions_for_models_in_query(
3443
+				$query_object,
3444
+				$use_default_where_conditions,
3445
+				$query_params[0]
3446
+			),
3447
+			$query_params[0]
3448
+		);
3449
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3450
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3451
+		// So we need to setup a subquery and use that for the main join.
3452
+		// Note for now this only works on the primary table for the model.
3453
+		// So for instance, you could set the limit array like this:
3454
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3455
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3456
+			$query_object->set_main_model_join_sql(
3457
+				$this->_construct_limit_join_select(
3458
+					$query_params['on_join_limit'][0],
3459
+					$query_params['on_join_limit'][1]
3460
+				)
3461
+			);
3462
+		}
3463
+		// set limit
3464
+		if (array_key_exists('limit', $query_params)) {
3465
+			if (is_array($query_params['limit'])) {
3466
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3467
+					$e = sprintf(
3468
+						__(
3469
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3470
+							"event_espresso"
3471
+						),
3472
+						http_build_query($query_params['limit'])
3473
+					);
3474
+					throw new EE_Error($e . "|" . $e);
3475
+				}
3476
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3477
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3478
+			} elseif (! empty($query_params['limit'])) {
3479
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3480
+			}
3481
+		}
3482
+		// set order by
3483
+		if (array_key_exists('order_by', $query_params)) {
3484
+			if (is_array($query_params['order_by'])) {
3485
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3486
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3487
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3488
+				if (array_key_exists('order', $query_params)) {
3489
+					throw new EE_Error(
3490
+						sprintf(
3491
+							__(
3492
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3493
+								"event_espresso"
3494
+							),
3495
+							get_class($this),
3496
+							implode(", ", array_keys($query_params['order_by'])),
3497
+							implode(", ", $query_params['order_by']),
3498
+							$query_params['order']
3499
+						)
3500
+					);
3501
+				}
3502
+				$this->_extract_related_models_from_sub_params_array_keys(
3503
+					$query_params['order_by'],
3504
+					$query_object,
3505
+					'order_by'
3506
+				);
3507
+				// assume it's an array of fields to order by
3508
+				$order_array = array();
3509
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3510
+					$order = $this->_extract_order($order);
3511
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3512
+				}
3513
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3514
+			} elseif (! empty($query_params['order_by'])) {
3515
+				$this->_extract_related_model_info_from_query_param(
3516
+					$query_params['order_by'],
3517
+					$query_object,
3518
+					'order',
3519
+					$query_params['order_by']
3520
+				);
3521
+				$order = isset($query_params['order'])
3522
+					? $this->_extract_order($query_params['order'])
3523
+					: 'DESC';
3524
+				$query_object->set_order_by_sql(
3525
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3526
+				);
3527
+			}
3528
+		}
3529
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3530
+		if (
3531
+			! array_key_exists('order_by', $query_params)
3532
+			&& array_key_exists('order', $query_params)
3533
+			&& ! empty($query_params['order'])
3534
+		) {
3535
+			$pk_field = $this->get_primary_key_field();
3536
+			$order = $this->_extract_order($query_params['order']);
3537
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3538
+		}
3539
+		// set group by
3540
+		if (array_key_exists('group_by', $query_params)) {
3541
+			if (is_array($query_params['group_by'])) {
3542
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3543
+				$group_by_array = array();
3544
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3545
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3546
+				}
3547
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3548
+			} elseif (! empty($query_params['group_by'])) {
3549
+				$query_object->set_group_by_sql(
3550
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3551
+				);
3552
+			}
3553
+		}
3554
+		// set having
3555
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3556
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3557
+		}
3558
+		// now, just verify they didn't pass anything wack
3559
+		foreach ($query_params as $query_key => $query_value) {
3560
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3561
+				throw new EE_Error(
3562
+					sprintf(
3563
+						__(
3564
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3565
+							'event_espresso'
3566
+						),
3567
+						$query_key,
3568
+						get_class($this),
3569
+						//                      print_r( $this->_allowed_query_params, TRUE )
3570
+						implode(',', $this->_allowed_query_params)
3571
+					)
3572
+				);
3573
+			}
3574
+		}
3575
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3576
+		if (empty($main_model_join_sql)) {
3577
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3578
+		}
3579
+		return $query_object;
3580
+	}
3581
+
3582
+
3583
+
3584
+	/**
3585
+	 * Gets the where conditions that should be imposed on the query based on the
3586
+	 * context (eg reading frontend, backend, edit or delete).
3587
+	 *
3588
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3589
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3590
+	 * @throws EE_Error
3591
+	 */
3592
+	public function caps_where_conditions($context = self::caps_read)
3593
+	{
3594
+		EEM_Base::verify_is_valid_cap_context($context);
3595
+		$cap_where_conditions = array();
3596
+		$cap_restrictions = $this->caps_missing($context);
3597
+		/**
3598
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3599
+		 */
3600
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3601
+			$cap_where_conditions = array_replace_recursive(
3602
+				$cap_where_conditions,
3603
+				$restriction_if_no_cap->get_default_where_conditions()
3604
+			);
3605
+		}
3606
+		return apply_filters(
3607
+			'FHEE__EEM_Base__caps_where_conditions__return',
3608
+			$cap_where_conditions,
3609
+			$this,
3610
+			$context,
3611
+			$cap_restrictions
3612
+		);
3613
+	}
3614
+
3615
+
3616
+
3617
+	/**
3618
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3619
+	 * otherwise throws an exception
3620
+	 *
3621
+	 * @param string $should_be_order_string
3622
+	 * @return string either ASC, asc, DESC or desc
3623
+	 * @throws EE_Error
3624
+	 */
3625
+	private function _extract_order($should_be_order_string)
3626
+	{
3627
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3628
+			return $should_be_order_string;
3629
+		}
3630
+		throw new EE_Error(
3631
+			sprintf(
3632
+				__(
3633
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3634
+					"event_espresso"
3635
+				),
3636
+				get_class($this),
3637
+				$should_be_order_string
3638
+			)
3639
+		);
3640
+	}
3641
+
3642
+
3643
+
3644
+	/**
3645
+	 * Looks at all the models which are included in this query, and asks each
3646
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3647
+	 * so they can be merged
3648
+	 *
3649
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3650
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3651
+	 *                                                                  'none' means NO default where conditions will
3652
+	 *                                                                  be used AT ALL during this query.
3653
+	 *                                                                  'other_models_only' means default where
3654
+	 *                                                                  conditions from other models will be used, but
3655
+	 *                                                                  not for this primary model. 'all', the default,
3656
+	 *                                                                  means default where conditions will apply as
3657
+	 *                                                                  normal
3658
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3659
+	 * @throws EE_Error
3660
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3661
+	 */
3662
+	private function _get_default_where_conditions_for_models_in_query(
3663
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3664
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3665
+		$where_query_params = array()
3666
+	) {
3667
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3668
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3669
+			throw new EE_Error(sprintf(
3670
+				__(
3671
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3672
+					"event_espresso"
3673
+				),
3674
+				$use_default_where_conditions,
3675
+				implode(", ", $allowed_used_default_where_conditions_values)
3676
+			));
3677
+		}
3678
+		$universal_query_params = array();
3679
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3680
+			$universal_query_params = $this->_get_default_where_conditions();
3681
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3682
+			$universal_query_params = $this->_get_minimum_where_conditions();
3683
+		}
3684
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3685
+			$related_model = $this->get_related_model_obj($model_name);
3686
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3687
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3688
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3689
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3690
+			} else {
3691
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3692
+				continue;
3693
+			}
3694
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3695
+				$related_model_universal_where_params,
3696
+				$where_query_params,
3697
+				$related_model,
3698
+				$model_relation_path
3699
+			);
3700
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3701
+				$universal_query_params,
3702
+				$overrides
3703
+			);
3704
+		}
3705
+		return $universal_query_params;
3706
+	}
3707
+
3708
+
3709
+
3710
+	/**
3711
+	 * Determines whether or not we should use default where conditions for the model in question
3712
+	 * (this model, or other related models).
3713
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3714
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3715
+	 * We should use default where conditions on related models when they requested to use default where conditions
3716
+	 * on all models, or specifically just on other related models
3717
+	 * @param      $default_where_conditions_value
3718
+	 * @param bool $for_this_model false means this is for OTHER related models
3719
+	 * @return bool
3720
+	 */
3721
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3722
+	{
3723
+		return (
3724
+				   $for_this_model
3725
+				   && in_array(
3726
+					   $default_where_conditions_value,
3727
+					   array(
3728
+						   EEM_Base::default_where_conditions_all,
3729
+						   EEM_Base::default_where_conditions_this_only,
3730
+						   EEM_Base::default_where_conditions_minimum_others,
3731
+					   ),
3732
+					   true
3733
+				   )
3734
+			   )
3735
+			   || (
3736
+				   ! $for_this_model
3737
+				   && in_array(
3738
+					   $default_where_conditions_value,
3739
+					   array(
3740
+						   EEM_Base::default_where_conditions_all,
3741
+						   EEM_Base::default_where_conditions_others_only,
3742
+					   ),
3743
+					   true
3744
+				   )
3745
+			   );
3746
+	}
3747
+
3748
+	/**
3749
+	 * Determines whether or not we should use default minimum conditions for the model in question
3750
+	 * (this model, or other related models).
3751
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3752
+	 * where conditions.
3753
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3754
+	 * on this model or others
3755
+	 * @param      $default_where_conditions_value
3756
+	 * @param bool $for_this_model false means this is for OTHER related models
3757
+	 * @return bool
3758
+	 */
3759
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3760
+	{
3761
+		return (
3762
+				   $for_this_model
3763
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3764
+			   )
3765
+			   || (
3766
+				   ! $for_this_model
3767
+				   && in_array(
3768
+					   $default_where_conditions_value,
3769
+					   array(
3770
+						   EEM_Base::default_where_conditions_minimum_others,
3771
+						   EEM_Base::default_where_conditions_minimum_all,
3772
+					   ),
3773
+					   true
3774
+				   )
3775
+			   );
3776
+	}
3777
+
3778
+
3779
+	/**
3780
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3781
+	 * then we also add a special where condition which allows for that model's primary key
3782
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3783
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3784
+	 *
3785
+	 * @param array    $default_where_conditions
3786
+	 * @param array    $provided_where_conditions
3787
+	 * @param EEM_Base $model
3788
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3789
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3790
+	 * @throws EE_Error
3791
+	 */
3792
+	private function _override_defaults_or_make_null_friendly(
3793
+		$default_where_conditions,
3794
+		$provided_where_conditions,
3795
+		$model,
3796
+		$model_relation_path
3797
+	) {
3798
+		$null_friendly_where_conditions = array();
3799
+		$none_overridden = true;
3800
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3801
+		foreach ($default_where_conditions as $key => $val) {
3802
+			if (isset($provided_where_conditions[ $key ])) {
3803
+				$none_overridden = false;
3804
+			} else {
3805
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3806
+			}
3807
+		}
3808
+		if ($none_overridden && $default_where_conditions) {
3809
+			if ($model->has_primary_key_field()) {
3810
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3811
+																				. "."
3812
+																				. $model->primary_key_name() ] = array('IS NULL');
3813
+			}/*else{
3814 3814
                 //@todo NO PK, use other defaults
3815 3815
             }*/
3816
-        }
3817
-        return $null_friendly_where_conditions;
3818
-    }
3819
-
3820
-
3821
-
3822
-    /**
3823
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3824
-     * default where conditions on all get_all, update, and delete queries done by this model.
3825
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3826
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3827
-     *
3828
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3829
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3830
-     */
3831
-    private function _get_default_where_conditions($model_relation_path = '')
3832
-    {
3833
-        if ($this->_ignore_where_strategy) {
3834
-            return array();
3835
-        }
3836
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3837
-    }
3838
-
3839
-
3840
-
3841
-    /**
3842
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3843
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3844
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3845
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3846
-     * Similar to _get_default_where_conditions
3847
-     *
3848
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3849
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3850
-     */
3851
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3852
-    {
3853
-        if ($this->_ignore_where_strategy) {
3854
-            return array();
3855
-        }
3856
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3857
-    }
3858
-
3859
-
3860
-
3861
-    /**
3862
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3863
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3864
-     *
3865
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3866
-     * @return string
3867
-     * @throws EE_Error
3868
-     */
3869
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3870
-    {
3871
-        $selects = $this->_get_columns_to_select_for_this_model();
3872
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included) {
3873
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3874
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3875
-            foreach ($other_model_selects as $key => $value) {
3876
-                $selects[] = $value;
3877
-            }
3878
-        }
3879
-        return implode(", ", $selects);
3880
-    }
3881
-
3882
-
3883
-
3884
-    /**
3885
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3886
-     * So that's going to be the columns for all the fields on the model
3887
-     *
3888
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3889
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3890
-     */
3891
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3892
-    {
3893
-        $fields = $this->field_settings();
3894
-        $selects = array();
3895
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3896
-            $model_relation_chain,
3897
-            $this->get_this_model_name()
3898
-        );
3899
-        foreach ($fields as $field_obj) {
3900
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3901
-                         . $field_obj->get_table_alias()
3902
-                         . "."
3903
-                         . $field_obj->get_table_column()
3904
-                         . " AS '"
3905
-                         . $table_alias_with_model_relation_chain_prefix
3906
-                         . $field_obj->get_table_alias()
3907
-                         . "."
3908
-                         . $field_obj->get_table_column()
3909
-                         . "'";
3910
-        }
3911
-        // make sure we are also getting the PKs of each table
3912
-        $tables = $this->get_tables();
3913
-        if (count($tables) > 1) {
3914
-            foreach ($tables as $table_obj) {
3915
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3916
-                                       . $table_obj->get_fully_qualified_pk_column();
3917
-                if (! in_array($qualified_pk_column, $selects)) {
3918
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3919
-                }
3920
-            }
3921
-        }
3922
-        return $selects;
3923
-    }
3924
-
3925
-
3926
-
3927
-    /**
3928
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3929
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3930
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3931
-     * SQL for joining, and the data types
3932
-     *
3933
-     * @param null|string                 $original_query_param
3934
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3935
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3936
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3937
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3938
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3939
-     *                                                          or 'Registration's
3940
-     * @param string                      $original_query_param what it originally was (eg
3941
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3942
-     *                                                          matches $query_param
3943
-     * @throws EE_Error
3944
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3945
-     */
3946
-    private function _extract_related_model_info_from_query_param(
3947
-        $query_param,
3948
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3949
-        $query_param_type,
3950
-        $original_query_param = null
3951
-    ) {
3952
-        if ($original_query_param === null) {
3953
-            $original_query_param = $query_param;
3954
-        }
3955
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3956
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3957
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3958
-        $allow_fields = in_array(
3959
-            $query_param_type,
3960
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3961
-            true
3962
-        );
3963
-        // check to see if we have a field on this model
3964
-        $this_model_fields = $this->field_settings(true);
3965
-        if (array_key_exists($query_param, $this_model_fields)) {
3966
-            if ($allow_fields) {
3967
-                return;
3968
-            }
3969
-            throw new EE_Error(
3970
-                sprintf(
3971
-                    __(
3972
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3973
-                        "event_espresso"
3974
-                    ),
3975
-                    $query_param,
3976
-                    get_class($this),
3977
-                    $query_param_type,
3978
-                    $original_query_param
3979
-                )
3980
-            );
3981
-        }
3982
-        // check if this is a special logic query param
3983
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3984
-            if ($allow_logic_query_params) {
3985
-                return;
3986
-            }
3987
-            throw new EE_Error(
3988
-                sprintf(
3989
-                    __(
3990
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3991
-                        'event_espresso'
3992
-                    ),
3993
-                    implode('", "', $this->_logic_query_param_keys),
3994
-                    $query_param,
3995
-                    get_class($this),
3996
-                    '<br />',
3997
-                    "\t"
3998
-                    . ' $passed_in_query_info = <pre>'
3999
-                    . print_r($passed_in_query_info, true)
4000
-                    . '</pre>'
4001
-                    . "\n\t"
4002
-                    . ' $query_param_type = '
4003
-                    . $query_param_type
4004
-                    . "\n\t"
4005
-                    . ' $original_query_param = '
4006
-                    . $original_query_param
4007
-                )
4008
-            );
4009
-        }
4010
-        // check if it's a custom selection
4011
-        if (
4012
-            $this->_custom_selections instanceof CustomSelects
4013
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4014
-        ) {
4015
-            return;
4016
-        }
4017
-        // check if has a model name at the beginning
4018
-        // and
4019
-        // check if it's a field on a related model
4020
-        if (
4021
-            $this->extractJoinModelFromQueryParams(
4022
-                $passed_in_query_info,
4023
-                $query_param,
4024
-                $original_query_param,
4025
-                $query_param_type
4026
-            )
4027
-        ) {
4028
-            return;
4029
-        }
4030
-
4031
-        // ok so $query_param didn't start with a model name
4032
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4033
-        // it's wack, that's what it is
4034
-        throw new EE_Error(
4035
-            sprintf(
4036
-                esc_html__(
4037
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4038
-                    "event_espresso"
4039
-                ),
4040
-                $query_param,
4041
-                get_class($this),
4042
-                $query_param_type,
4043
-                $original_query_param
4044
-            )
4045
-        );
4046
-    }
4047
-
4048
-
4049
-    /**
4050
-     * Extracts any possible join model information from the provided possible_join_string.
4051
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4052
-     * parts that should be added to the query.
4053
-     *
4054
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4055
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4056
-     * @param null|string                 $original_query_param
4057
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4058
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4059
-     * @return bool  returns true if a join was added and false if not.
4060
-     * @throws EE_Error
4061
-     */
4062
-    private function extractJoinModelFromQueryParams(
4063
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4064
-        $possible_join_string,
4065
-        $original_query_param,
4066
-        $query_parameter_type
4067
-    ) {
4068
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4069
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4070
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4071
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4072
-                if ($possible_join_string === '') {
4073
-                    // nothing left to $query_param
4074
-                    // we should actually end in a field name, not a model like this!
4075
-                    throw new EE_Error(
4076
-                        sprintf(
4077
-                            esc_html__(
4078
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4079
-                                "event_espresso"
4080
-                            ),
4081
-                            $possible_join_string,
4082
-                            $query_parameter_type,
4083
-                            get_class($this),
4084
-                            $valid_related_model_name
4085
-                        )
4086
-                    );
4087
-                }
4088
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4089
-                $related_model_obj->_extract_related_model_info_from_query_param(
4090
-                    $possible_join_string,
4091
-                    $query_info_carrier,
4092
-                    $query_parameter_type,
4093
-                    $original_query_param
4094
-                );
4095
-                return true;
4096
-            }
4097
-            if ($possible_join_string === $valid_related_model_name) {
4098
-                $this->_add_join_to_model(
4099
-                    $valid_related_model_name,
4100
-                    $query_info_carrier,
4101
-                    $original_query_param
4102
-                );
4103
-                return true;
4104
-            }
4105
-        }
4106
-        return false;
4107
-    }
4108
-
4109
-
4110
-    /**
4111
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4112
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4113
-     * @throws EE_Error
4114
-     */
4115
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4116
-    {
4117
-        if (
4118
-            $this->_custom_selections instanceof CustomSelects
4119
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4120
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4121
-            )
4122
-        ) {
4123
-            $original_selects = $this->_custom_selections->originalSelects();
4124
-            foreach ($original_selects as $alias => $select_configuration) {
4125
-                $this->extractJoinModelFromQueryParams(
4126
-                    $query_info_carrier,
4127
-                    $select_configuration[0],
4128
-                    $select_configuration[0],
4129
-                    'custom_selects'
4130
-                );
4131
-            }
4132
-        }
4133
-    }
4134
-
4135
-
4136
-
4137
-    /**
4138
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4139
-     * and store it on $passed_in_query_info
4140
-     *
4141
-     * @param string                      $model_name
4142
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4143
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4144
-     *                                                          model and $model_name. Eg, if we are querying Event,
4145
-     *                                                          and are adding a join to 'Payment' with the original
4146
-     *                                                          query param key
4147
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4148
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4149
-     *                                                          Payment wants to add default query params so that it
4150
-     *                                                          will know what models to prepend onto its default query
4151
-     *                                                          params or in case it wants to rename tables (in case
4152
-     *                                                          there are multiple joins to the same table)
4153
-     * @return void
4154
-     * @throws EE_Error
4155
-     */
4156
-    private function _add_join_to_model(
4157
-        $model_name,
4158
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4159
-        $original_query_param
4160
-    ) {
4161
-        $relation_obj = $this->related_settings_for($model_name);
4162
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4163
-        // check if the relation is HABTM, because then we're essentially doing two joins
4164
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4165
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4166
-            $join_model_obj = $relation_obj->get_join_model();
4167
-            // replace the model specified with the join model for this relation chain, whi
4168
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4169
-                $model_name,
4170
-                $join_model_obj->get_this_model_name(),
4171
-                $model_relation_chain
4172
-            );
4173
-            $passed_in_query_info->merge(
4174
-                new EE_Model_Query_Info_Carrier(
4175
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4176
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4177
-                )
4178
-            );
4179
-        }
4180
-        // now just join to the other table pointed to by the relation object, and add its data types
4181
-        $passed_in_query_info->merge(
4182
-            new EE_Model_Query_Info_Carrier(
4183
-                array($model_relation_chain => $model_name),
4184
-                $relation_obj->get_join_statement($model_relation_chain)
4185
-            )
4186
-        );
4187
-    }
4188
-
4189
-
4190
-
4191
-    /**
4192
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4193
-     *
4194
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4195
-     * @return string of SQL
4196
-     * @throws EE_Error
4197
-     */
4198
-    private function _construct_where_clause($where_params)
4199
-    {
4200
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4201
-        if ($SQL) {
4202
-            return " WHERE " . $SQL;
4203
-        }
4204
-        return '';
4205
-    }
4206
-
4207
-
4208
-
4209
-    /**
4210
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4211
-     * and should be passed HAVING parameters, not WHERE parameters
4212
-     *
4213
-     * @param array $having_params
4214
-     * @return string
4215
-     * @throws EE_Error
4216
-     */
4217
-    private function _construct_having_clause($having_params)
4218
-    {
4219
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4220
-        if ($SQL) {
4221
-            return " HAVING " . $SQL;
4222
-        }
4223
-        return '';
4224
-    }
4225
-
4226
-
4227
-    /**
4228
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4229
-     * Event_Meta.meta_value = 'foo'))"
4230
-     *
4231
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4232
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4233
-     * @throws EE_Error
4234
-     * @return string of SQL
4235
-     */
4236
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4237
-    {
4238
-        $where_clauses = array();
4239
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4240
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4241
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4242
-                switch ($query_param) {
4243
-                    case 'not':
4244
-                    case 'NOT':
4245
-                        $where_clauses[] = "! ("
4246
-                                           . $this->_construct_condition_clause_recursive(
4247
-                                               $op_and_value_or_sub_condition,
4248
-                                               $glue
4249
-                                           )
4250
-                                           . ")";
4251
-                        break;
4252
-                    case 'and':
4253
-                    case 'AND':
4254
-                        $where_clauses[] = " ("
4255
-                                           . $this->_construct_condition_clause_recursive(
4256
-                                               $op_and_value_or_sub_condition,
4257
-                                               ' AND '
4258
-                                           )
4259
-                                           . ")";
4260
-                        break;
4261
-                    case 'or':
4262
-                    case 'OR':
4263
-                        $where_clauses[] = " ("
4264
-                                           . $this->_construct_condition_clause_recursive(
4265
-                                               $op_and_value_or_sub_condition,
4266
-                                               ' OR '
4267
-                                           )
4268
-                                           . ")";
4269
-                        break;
4270
-                }
4271
-            } else {
4272
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4273
-                // if it's not a normal field, maybe it's a custom selection?
4274
-                if (! $field_obj) {
4275
-                    if ($this->_custom_selections instanceof CustomSelects) {
4276
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4277
-                    } else {
4278
-                        throw new EE_Error(sprintf(__(
4279
-                            "%s is neither a valid model field name, nor a custom selection",
4280
-                            "event_espresso"
4281
-                        ), $query_param));
4282
-                    }
4283
-                }
4284
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4285
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4286
-            }
4287
-        }
4288
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4289
-    }
4290
-
4291
-
4292
-
4293
-    /**
4294
-     * Takes the input parameter and extract the table name (alias) and column name
4295
-     *
4296
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4297
-     * @throws EE_Error
4298
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4299
-     */
4300
-    private function _deduce_column_name_from_query_param($query_param)
4301
-    {
4302
-        $field = $this->_deduce_field_from_query_param($query_param);
4303
-        if ($field) {
4304
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4305
-                $field->get_model_name(),
4306
-                $query_param
4307
-            );
4308
-            return $table_alias_prefix . $field->get_qualified_column();
4309
-        }
4310
-        if (
4311
-            $this->_custom_selections instanceof CustomSelects
4312
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4313
-        ) {
4314
-            // maybe it's custom selection item?
4315
-            // if so, just use it as the "column name"
4316
-            return $query_param;
4317
-        }
4318
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4319
-            ? implode(',', $this->_custom_selections->columnAliases())
4320
-            : '';
4321
-        throw new EE_Error(
4322
-            sprintf(
4323
-                __(
4324
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4325
-                    "event_espresso"
4326
-                ),
4327
-                $query_param,
4328
-                $custom_select_aliases
4329
-            )
4330
-        );
4331
-    }
4332
-
4333
-
4334
-
4335
-    /**
4336
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4337
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4338
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4339
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4340
-     *
4341
-     * @param string $condition_query_param_key
4342
-     * @return string
4343
-     */
4344
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4345
-    {
4346
-        $pos_of_star = strpos($condition_query_param_key, '*');
4347
-        if ($pos_of_star === false) {
4348
-            return $condition_query_param_key;
4349
-        }
4350
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4351
-        return $condition_query_param_sans_star;
4352
-    }
4353
-
4354
-
4355
-
4356
-    /**
4357
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4358
-     *
4359
-     * @param                            mixed      array | string    $op_and_value
4360
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4361
-     * @throws EE_Error
4362
-     * @return string
4363
-     */
4364
-    private function _construct_op_and_value($op_and_value, $field_obj)
4365
-    {
4366
-        if (is_array($op_and_value)) {
4367
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4368
-            if (! $operator) {
4369
-                $php_array_like_string = array();
4370
-                foreach ($op_and_value as $key => $value) {
4371
-                    $php_array_like_string[] = "$key=>$value";
4372
-                }
4373
-                throw new EE_Error(
4374
-                    sprintf(
4375
-                        __(
4376
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4377
-                            "event_espresso"
4378
-                        ),
4379
-                        implode(",", $php_array_like_string)
4380
-                    )
4381
-                );
4382
-            }
4383
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4384
-        } else {
4385
-            $operator = '=';
4386
-            $value = $op_and_value;
4387
-        }
4388
-        // check to see if the value is actually another field
4389
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4390
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4391
-        }
4392
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4393
-            // in this case, the value should be an array, or at least a comma-separated list
4394
-            // it will need to handle a little differently
4395
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4396
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4397
-            return $operator . SP . $cleaned_value;
4398
-        }
4399
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4400
-            // the value should be an array with count of two.
4401
-            if (count($value) !== 2) {
4402
-                throw new EE_Error(
4403
-                    sprintf(
4404
-                        __(
4405
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4406
-                            'event_espresso'
4407
-                        ),
4408
-                        "BETWEEN"
4409
-                    )
4410
-                );
4411
-            }
4412
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4413
-            return $operator . SP . $cleaned_value;
4414
-        }
4415
-        if (in_array($operator, $this->valid_null_style_operators())) {
4416
-            if ($value !== null) {
4417
-                throw new EE_Error(
4418
-                    sprintf(
4419
-                        __(
4420
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4421
-                            "event_espresso"
4422
-                        ),
4423
-                        $value,
4424
-                        $operator
4425
-                    )
4426
-                );
4427
-            }
4428
-            return $operator;
4429
-        }
4430
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4431
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4432
-            // remove other junk. So just treat it as a string.
4433
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4434
-        }
4435
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4436
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4437
-        }
4438
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
-            throw new EE_Error(
4440
-                sprintf(
4441
-                    __(
4442
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4443
-                        'event_espresso'
4444
-                    ),
4445
-                    $operator,
4446
-                    $operator
4447
-                )
4448
-            );
4449
-        }
4450
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4451
-            throw new EE_Error(
4452
-                sprintf(
4453
-                    __(
4454
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4455
-                        'event_espresso'
4456
-                    ),
4457
-                    $operator,
4458
-                    $operator
4459
-                )
4460
-            );
4461
-        }
4462
-        throw new EE_Error(
4463
-            sprintf(
4464
-                __(
4465
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4466
-                    "event_espresso"
4467
-                ),
4468
-                http_build_query($op_and_value)
4469
-            )
4470
-        );
4471
-    }
4472
-
4473
-
4474
-
4475
-    /**
4476
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4477
-     *
4478
-     * @param array                      $values
4479
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4480
-     *                                              '%s'
4481
-     * @return string
4482
-     * @throws EE_Error
4483
-     */
4484
-    public function _construct_between_value($values, $field_obj)
4485
-    {
4486
-        $cleaned_values = array();
4487
-        foreach ($values as $value) {
4488
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4489
-        }
4490
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4491
-    }
4492
-
4493
-
4494
-
4495
-    /**
4496
-     * Takes an array or a comma-separated list of $values and cleans them
4497
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4498
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4499
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4500
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4501
-     *
4502
-     * @param mixed                      $values    array or comma-separated string
4503
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4504
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4505
-     * @throws EE_Error
4506
-     */
4507
-    public function _construct_in_value($values, $field_obj)
4508
-    {
4509
-        // check if the value is a CSV list
4510
-        if (is_string($values)) {
4511
-            // in which case, turn it into an array
4512
-            $values = explode(",", $values);
4513
-        }
4514
-        $cleaned_values = array();
4515
-        foreach ($values as $value) {
4516
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4517
-        }
4518
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4519
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4520
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4521
-        if (empty($cleaned_values)) {
4522
-            $all_fields = $this->field_settings();
4523
-            $a_field = array_shift($all_fields);
4524
-            $main_table = $this->_get_main_table();
4525
-            $cleaned_values[] = "SELECT "
4526
-                                . $a_field->get_table_column()
4527
-                                . " FROM "
4528
-                                . $main_table->get_table_name()
4529
-                                . " WHERE FALSE";
4530
-        }
4531
-        return "(" . implode(",", $cleaned_values) . ")";
4532
-    }
4533
-
4534
-
4535
-
4536
-    /**
4537
-     * @param mixed                      $value
4538
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4539
-     * @throws EE_Error
4540
-     * @return false|null|string
4541
-     */
4542
-    private function _wpdb_prepare_using_field($value, $field_obj)
4543
-    {
4544
-        /** @type WPDB $wpdb */
4545
-        global $wpdb;
4546
-        if ($field_obj instanceof EE_Model_Field_Base) {
4547
-            return $wpdb->prepare(
4548
-                $field_obj->get_wpdb_data_type(),
4549
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4550
-            );
4551
-        } //$field_obj should really just be a data type
4552
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4553
-            throw new EE_Error(
4554
-                sprintf(
4555
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4556
-                    $field_obj,
4557
-                    implode(",", $this->_valid_wpdb_data_types)
4558
-                )
4559
-            );
4560
-        }
4561
-        return $wpdb->prepare($field_obj, $value);
4562
-    }
4563
-
4564
-
4565
-
4566
-    /**
4567
-     * Takes the input parameter and finds the model field that it indicates.
4568
-     *
4569
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4570
-     * @throws EE_Error
4571
-     * @return EE_Model_Field_Base
4572
-     */
4573
-    protected function _deduce_field_from_query_param($query_param_name)
4574
-    {
4575
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4576
-        // which will help us find the database table and column
4577
-        $query_param_parts = explode(".", $query_param_name);
4578
-        if (empty($query_param_parts)) {
4579
-            throw new EE_Error(sprintf(__(
4580
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4581
-                'event_espresso'
4582
-            ), $query_param_name));
4583
-        }
4584
-        $number_of_parts = count($query_param_parts);
4585
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4586
-        if ($number_of_parts === 1) {
4587
-            $field_name = $last_query_param_part;
4588
-            $model_obj = $this;
4589
-        } else {// $number_of_parts >= 2
4590
-            // the last part is the column name, and there are only 2parts. therefore...
4591
-            $field_name = $last_query_param_part;
4592
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4593
-        }
4594
-        try {
4595
-            return $model_obj->field_settings_for($field_name);
4596
-        } catch (EE_Error $e) {
4597
-            return null;
4598
-        }
4599
-    }
4600
-
4601
-
4602
-
4603
-    /**
4604
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4605
-     * alias and column which corresponds to it
4606
-     *
4607
-     * @param string $field_name
4608
-     * @throws EE_Error
4609
-     * @return string
4610
-     */
4611
-    public function _get_qualified_column_for_field($field_name)
4612
-    {
4613
-        $all_fields = $this->field_settings();
4614
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4615
-        if ($field) {
4616
-            return $field->get_qualified_column();
4617
-        }
4618
-        throw new EE_Error(
4619
-            sprintf(
4620
-                __(
4621
-                    "There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4622
-                    'event_espresso'
4623
-                ),
4624
-                $field_name,
4625
-                get_class($this)
4626
-            )
4627
-        );
4628
-    }
4629
-
4630
-
4631
-
4632
-    /**
4633
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4634
-     * Example usage:
4635
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4636
-     *      array(),
4637
-     *      ARRAY_A,
4638
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4639
-     *  );
4640
-     * is equivalent to
4641
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4642
-     * and
4643
-     *  EEM_Event::instance()->get_all_wpdb_results(
4644
-     *      array(
4645
-     *          array(
4646
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4647
-     *          ),
4648
-     *          ARRAY_A,
4649
-     *          implode(
4650
-     *              ', ',
4651
-     *              array_merge(
4652
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4653
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4654
-     *              )
4655
-     *          )
4656
-     *      )
4657
-     *  );
4658
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4659
-     *
4660
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4661
-     *                                            and the one whose fields you are selecting for example: when querying
4662
-     *                                            tickets model and selecting fields from the tickets model you would
4663
-     *                                            leave this parameter empty, because no models are needed to join
4664
-     *                                            between the queried model and the selected one. Likewise when
4665
-     *                                            querying the datetime model and selecting fields from the tickets
4666
-     *                                            model, it would also be left empty, because there is a direct
4667
-     *                                            relation from datetimes to tickets, so no model is needed to join
4668
-     *                                            them together. However, when querying from the event model and
4669
-     *                                            selecting fields from the ticket model, you should provide the string
4670
-     *                                            'Datetime', indicating that the event model must first join to the
4671
-     *                                            datetime model in order to find its relation to ticket model.
4672
-     *                                            Also, when querying from the venue model and selecting fields from
4673
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4674
-     *                                            indicating you need to join the venue model to the event model,
4675
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4676
-     *                                            This string is used to deduce the prefix that gets added onto the
4677
-     *                                            models' tables qualified columns
4678
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4679
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4680
-     *                                            qualified column names
4681
-     * @return array|string
4682
-     */
4683
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4684
-    {
4685
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4686
-        $qualified_columns = array();
4687
-        foreach ($this->field_settings() as $field_name => $field) {
4688
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4689
-        }
4690
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4691
-    }
4692
-
4693
-
4694
-
4695
-    /**
4696
-     * constructs the select use on special limit joins
4697
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4698
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4699
-     * (as that is typically where the limits would be set).
4700
-     *
4701
-     * @param  string       $table_alias The table the select is being built for
4702
-     * @param  mixed|string $limit       The limit for this select
4703
-     * @return string                The final select join element for the query.
4704
-     */
4705
-    public function _construct_limit_join_select($table_alias, $limit)
4706
-    {
4707
-        $SQL = '';
4708
-        foreach ($this->_tables as $table_obj) {
4709
-            if ($table_obj instanceof EE_Primary_Table) {
4710
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4711
-                    ? $table_obj->get_select_join_limit($limit)
4712
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4713
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4714
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4715
-                    ? $table_obj->get_select_join_limit_join($limit)
4716
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4717
-            }
4718
-        }
4719
-        return $SQL;
4720
-    }
4721
-
4722
-
4723
-
4724
-    /**
4725
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4726
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4727
-     *
4728
-     * @return string SQL
4729
-     * @throws EE_Error
4730
-     */
4731
-    public function _construct_internal_join()
4732
-    {
4733
-        $SQL = $this->_get_main_table()->get_table_sql();
4734
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4735
-        return $SQL;
4736
-    }
4737
-
4738
-
4739
-
4740
-    /**
4741
-     * Constructs the SQL for joining all the tables on this model.
4742
-     * Normally $alias should be the primary table's alias, but in cases where
4743
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4744
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4745
-     * alias, this will construct SQL like:
4746
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
-     * With $alias being a secondary table's alias, this will construct SQL like:
4748
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4749
-     *
4750
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4751
-     * @return string
4752
-     */
4753
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4754
-    {
4755
-        $SQL = '';
4756
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4757
-        foreach ($this->_tables as $table_obj) {
4758
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4759
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4760
-                    // so we're joining to this table, meaning the table is already in
4761
-                    // the FROM statement, BUT the primary table isn't. So we want
4762
-                    // to add the inverse join sql
4763
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4764
-                } else {
4765
-                    // just add a regular JOIN to this table from the primary table
4766
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4767
-                }
4768
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4769
-        }
4770
-        return $SQL;
4771
-    }
4772
-
4773
-
4774
-
4775
-    /**
4776
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4777
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4778
-     * their data type (eg, '%s', '%d', etc)
4779
-     *
4780
-     * @return array
4781
-     */
4782
-    public function _get_data_types()
4783
-    {
4784
-        $data_types = array();
4785
-        foreach ($this->field_settings() as $field_obj) {
4786
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4787
-            /** @var $field_obj EE_Model_Field_Base */
4788
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4789
-        }
4790
-        return $data_types;
4791
-    }
4792
-
4793
-
4794
-
4795
-    /**
4796
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4797
-     *
4798
-     * @param string $model_name
4799
-     * @throws EE_Error
4800
-     * @return EEM_Base
4801
-     */
4802
-    public function get_related_model_obj($model_name)
4803
-    {
4804
-        $model_classname = "EEM_" . $model_name;
4805
-        if (! class_exists($model_classname)) {
4806
-            throw new EE_Error(sprintf(__(
4807
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4808
-                'event_espresso'
4809
-            ), $model_name, $model_classname));
4810
-        }
4811
-        return call_user_func($model_classname . "::instance");
4812
-    }
4813
-
4814
-
4815
-
4816
-    /**
4817
-     * Returns the array of EE_ModelRelations for this model.
4818
-     *
4819
-     * @return EE_Model_Relation_Base[]
4820
-     */
4821
-    public function relation_settings()
4822
-    {
4823
-        return $this->_model_relations;
4824
-    }
4825
-
4826
-
4827
-
4828
-    /**
4829
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4830
-     * because without THOSE models, this model probably doesn't have much purpose.
4831
-     * (Eg, without an event, datetimes have little purpose.)
4832
-     *
4833
-     * @return EE_Belongs_To_Relation[]
4834
-     */
4835
-    public function belongs_to_relations()
4836
-    {
4837
-        $belongs_to_relations = array();
4838
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4839
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4840
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4841
-            }
4842
-        }
4843
-        return $belongs_to_relations;
4844
-    }
4845
-
4846
-
4847
-
4848
-    /**
4849
-     * Returns the specified EE_Model_Relation, or throws an exception
4850
-     *
4851
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4852
-     * @throws EE_Error
4853
-     * @return EE_Model_Relation_Base
4854
-     */
4855
-    public function related_settings_for($relation_name)
4856
-    {
4857
-        $relatedModels = $this->relation_settings();
4858
-        if (! array_key_exists($relation_name, $relatedModels)) {
4859
-            throw new EE_Error(
4860
-                sprintf(
4861
-                    __(
4862
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4863
-                        'event_espresso'
4864
-                    ),
4865
-                    $relation_name,
4866
-                    $this->_get_class_name(),
4867
-                    implode(', ', array_keys($relatedModels))
4868
-                )
4869
-            );
4870
-        }
4871
-        return $relatedModels[ $relation_name ];
4872
-    }
4873
-
4874
-
4875
-
4876
-    /**
4877
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4878
-     * fields
4879
-     *
4880
-     * @param string $fieldName
4881
-     * @param boolean $include_db_only_fields
4882
-     * @throws EE_Error
4883
-     * @return EE_Model_Field_Base
4884
-     */
4885
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4886
-    {
4887
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4888
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4889
-            throw new EE_Error(sprintf(
4890
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4891
-                $fieldName,
4892
-                get_class($this)
4893
-            ));
4894
-        }
4895
-        return $fieldSettings[ $fieldName ];
4896
-    }
4897
-
4898
-
4899
-
4900
-    /**
4901
-     * Checks if this field exists on this model
4902
-     *
4903
-     * @param string $fieldName a key in the model's _field_settings array
4904
-     * @return boolean
4905
-     */
4906
-    public function has_field($fieldName)
4907
-    {
4908
-        $fieldSettings = $this->field_settings(true);
4909
-        if (isset($fieldSettings[ $fieldName ])) {
4910
-            return true;
4911
-        }
4912
-        return false;
4913
-    }
4914
-
4915
-
4916
-
4917
-    /**
4918
-     * Returns whether or not this model has a relation to the specified model
4919
-     *
4920
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4921
-     * @return boolean
4922
-     */
4923
-    public function has_relation($relation_name)
4924
-    {
4925
-        $relations = $this->relation_settings();
4926
-        if (isset($relations[ $relation_name ])) {
4927
-            return true;
4928
-        }
4929
-        return false;
4930
-    }
4931
-
4932
-
4933
-
4934
-    /**
4935
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4936
-     * Eg, on EE_Answer that would be ANS_ID field object
4937
-     *
4938
-     * @param $field_obj
4939
-     * @return boolean
4940
-     */
4941
-    public function is_primary_key_field($field_obj)
4942
-    {
4943
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4944
-    }
4945
-
4946
-
4947
-
4948
-    /**
4949
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4950
-     * Eg, on EE_Answer that would be ANS_ID field object
4951
-     *
4952
-     * @return EE_Model_Field_Base
4953
-     * @throws EE_Error
4954
-     */
4955
-    public function get_primary_key_field()
4956
-    {
4957
-        if ($this->_primary_key_field === null) {
4958
-            foreach ($this->field_settings(true) as $field_obj) {
4959
-                if ($this->is_primary_key_field($field_obj)) {
4960
-                    $this->_primary_key_field = $field_obj;
4961
-                    break;
4962
-                }
4963
-            }
4964
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4965
-                throw new EE_Error(sprintf(
4966
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
4967
-                    get_class($this)
4968
-                ));
4969
-            }
4970
-        }
4971
-        return $this->_primary_key_field;
4972
-    }
4973
-
4974
-
4975
-
4976
-    /**
4977
-     * Returns whether or not not there is a primary key on this model.
4978
-     * Internally does some caching.
4979
-     *
4980
-     * @return boolean
4981
-     */
4982
-    public function has_primary_key_field()
4983
-    {
4984
-        if ($this->_has_primary_key_field === null) {
4985
-            try {
4986
-                $this->get_primary_key_field();
4987
-                $this->_has_primary_key_field = true;
4988
-            } catch (EE_Error $e) {
4989
-                $this->_has_primary_key_field = false;
4990
-            }
4991
-        }
4992
-        return $this->_has_primary_key_field;
4993
-    }
4994
-
4995
-
4996
-
4997
-    /**
4998
-     * Finds the first field of type $field_class_name.
4999
-     *
5000
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5001
-     *                                 EE_Foreign_Key_Field, etc
5002
-     * @return EE_Model_Field_Base or null if none is found
5003
-     */
5004
-    public function get_a_field_of_type($field_class_name)
5005
-    {
5006
-        foreach ($this->field_settings() as $field) {
5007
-            if ($field instanceof $field_class_name) {
5008
-                return $field;
5009
-            }
5010
-        }
5011
-        return null;
5012
-    }
5013
-
5014
-
5015
-
5016
-    /**
5017
-     * Gets a foreign key field pointing to model.
5018
-     *
5019
-     * @param string $model_name eg Event, Registration, not EEM_Event
5020
-     * @return EE_Foreign_Key_Field_Base
5021
-     * @throws EE_Error
5022
-     */
5023
-    public function get_foreign_key_to($model_name)
5024
-    {
5025
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5026
-            foreach ($this->field_settings() as $field) {
5027
-                if (
5028
-                    $field instanceof EE_Foreign_Key_Field_Base
5029
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5030
-                ) {
5031
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5032
-                    break;
5033
-                }
5034
-            }
5035
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5036
-                throw new EE_Error(sprintf(__(
5037
-                    "There is no foreign key field pointing to model %s on model %s",
5038
-                    'event_espresso'
5039
-                ), $model_name, get_class($this)));
5040
-            }
5041
-        }
5042
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5043
-    }
5044
-
5045
-
5046
-
5047
-    /**
5048
-     * Gets the table name (including $wpdb->prefix) for the table alias
5049
-     *
5050
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5051
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5052
-     *                            Either one works
5053
-     * @return string
5054
-     */
5055
-    public function get_table_for_alias($table_alias)
5056
-    {
5057
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5058
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5059
-    }
5060
-
5061
-
5062
-
5063
-    /**
5064
-     * Returns a flat array of all field son this model, instead of organizing them
5065
-     * by table_alias as they are in the constructor.
5066
-     *
5067
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5068
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5069
-     */
5070
-    public function field_settings($include_db_only_fields = false)
5071
-    {
5072
-        if ($include_db_only_fields) {
5073
-            if ($this->_cached_fields === null) {
5074
-                $this->_cached_fields = array();
5075
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5076
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5077
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5078
-                    }
5079
-                }
5080
-            }
5081
-            return $this->_cached_fields;
5082
-        }
5083
-        if ($this->_cached_fields_non_db_only === null) {
5084
-            $this->_cached_fields_non_db_only = array();
5085
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5086
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5087
-                    /** @var $field_obj EE_Model_Field_Base */
5088
-                    if (! $field_obj->is_db_only_field()) {
5089
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5090
-                    }
5091
-                }
5092
-            }
5093
-        }
5094
-        return $this->_cached_fields_non_db_only;
5095
-    }
5096
-
5097
-
5098
-
5099
-    /**
5100
-     *        cycle though array of attendees and create objects out of each item
5101
-     *
5102
-     * @access        private
5103
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5104
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5105
-     *                           numerically indexed)
5106
-     * @throws EE_Error
5107
-     */
5108
-    protected function _create_objects($rows = array())
5109
-    {
5110
-        $array_of_objects = array();
5111
-        if (empty($rows)) {
5112
-            return array();
5113
-        }
5114
-        $count_if_model_has_no_primary_key = 0;
5115
-        $has_primary_key = $this->has_primary_key_field();
5116
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5117
-        foreach ((array) $rows as $row) {
5118
-            if (empty($row)) {
5119
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5120
-                return array();
5121
-            }
5122
-            // check if we've already set this object in the results array,
5123
-            // in which case there's no need to process it further (again)
5124
-            if ($has_primary_key) {
5125
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5126
-                    $row,
5127
-                    $primary_key_field->get_qualified_column(),
5128
-                    $primary_key_field->get_table_column()
5129
-                );
5130
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5131
-                    continue;
5132
-                }
5133
-            }
5134
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5135
-            if (! $classInstance) {
5136
-                throw new EE_Error(
5137
-                    sprintf(
5138
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5139
-                        $this->get_this_model_name(),
5140
-                        http_build_query($row)
5141
-                    )
5142
-                );
5143
-            }
5144
-            // set the timezone on the instantiated objects
5145
-            $classInstance->set_timezone($this->_timezone);
5146
-            // make sure if there is any timezone setting present that we set the timezone for the object
5147
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5148
-            $array_of_objects[ $key ] = $classInstance;
5149
-            // also, for all the relations of type BelongsTo, see if we can cache
5150
-            // those related models
5151
-            // (we could do this for other relations too, but if there are conditions
5152
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5153
-            // so it requires a little more thought than just caching them immediately...)
5154
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5155
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5156
-                    // check if this model's INFO is present. If so, cache it on the model
5157
-                    $other_model = $relation_obj->get_other_model();
5158
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5159
-                    // if we managed to make a model object from the results, cache it on the main model object
5160
-                    if ($other_model_obj_maybe) {
5161
-                        // set timezone on these other model objects if they are present
5162
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5163
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5164
-                    }
5165
-                }
5166
-            }
5167
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5168
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5169
-            // the field in the CustomSelects object
5170
-            if ($this->_custom_selections instanceof CustomSelects) {
5171
-                $classInstance->setCustomSelectsValues(
5172
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5173
-                );
5174
-            }
5175
-        }
5176
-        return $array_of_objects;
5177
-    }
5178
-
5179
-
5180
-    /**
5181
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5182
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5183
-     *
5184
-     * @param array $db_results_row
5185
-     * @return array
5186
-     */
5187
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5188
-    {
5189
-        $results = array();
5190
-        if ($this->_custom_selections instanceof CustomSelects) {
5191
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5192
-                if (isset($db_results_row[ $alias ])) {
5193
-                    $results[ $alias ] = $this->convertValueToDataType(
5194
-                        $db_results_row[ $alias ],
5195
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5196
-                    );
5197
-                }
5198
-            }
5199
-        }
5200
-        return $results;
5201
-    }
5202
-
5203
-
5204
-    /**
5205
-     * This will set the value for the given alias
5206
-     * @param string $value
5207
-     * @param string $datatype (one of %d, %s, %f)
5208
-     * @return int|string|float (int for %d, string for %s, float for %f)
5209
-     */
5210
-    protected function convertValueToDataType($value, $datatype)
5211
-    {
5212
-        switch ($datatype) {
5213
-            case '%f':
5214
-                return (float) $value;
5215
-            case '%d':
5216
-                return (int) $value;
5217
-            default:
5218
-                return (string) $value;
5219
-        }
5220
-    }
5221
-
5222
-
5223
-    /**
5224
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5225
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5226
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5227
-     * object (as set in the model_field!).
5228
-     *
5229
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5230
-     */
5231
-    public function create_default_object()
5232
-    {
5233
-        $this_model_fields_and_values = array();
5234
-        // setup the row using default values;
5235
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5236
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5237
-        }
5238
-        $className = $this->_get_class_name();
5239
-        $classInstance = EE_Registry::instance()
5240
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5241
-        return $classInstance;
5242
-    }
5243
-
5244
-
5245
-
5246
-    /**
5247
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5248
-     *                             or an stdClass where each property is the name of a column,
5249
-     * @return EE_Base_Class
5250
-     * @throws EE_Error
5251
-     */
5252
-    public function instantiate_class_from_array_or_object($cols_n_values)
5253
-    {
5254
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5255
-            $cols_n_values = get_object_vars($cols_n_values);
5256
-        }
5257
-        $primary_key = null;
5258
-        // make sure the array only has keys that are fields/columns on this model
5259
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5260
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5261
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5262
-        }
5263
-        $className = $this->_get_class_name();
5264
-        // check we actually found results that we can use to build our model object
5265
-        // if not, return null
5266
-        if ($this->has_primary_key_field()) {
5267
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5268
-                return null;
5269
-            }
5270
-        } elseif ($this->unique_indexes()) {
5271
-            $first_column = reset($this_model_fields_n_values);
5272
-            if (empty($first_column)) {
5273
-                return null;
5274
-            }
5275
-        }
5276
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5277
-        if ($primary_key) {
5278
-            $classInstance = $this->get_from_entity_map($primary_key);
5279
-            if (! $classInstance) {
5280
-                $classInstance = EE_Registry::instance()
5281
-                                            ->load_class(
5282
-                                                $className,
5283
-                                                array($this_model_fields_n_values, $this->_timezone),
5284
-                                                true,
5285
-                                                false
5286
-                                            );
5287
-                // add this new object to the entity map
5288
-                $classInstance = $this->add_to_entity_map($classInstance);
5289
-            }
5290
-        } else {
5291
-            $classInstance = EE_Registry::instance()
5292
-                                        ->load_class(
5293
-                                            $className,
5294
-                                            array($this_model_fields_n_values, $this->_timezone),
5295
-                                            true,
5296
-                                            false
5297
-                                        );
5298
-        }
5299
-        return $classInstance;
5300
-    }
5301
-
5302
-
5303
-
5304
-    /**
5305
-     * Gets the model object from the  entity map if it exists
5306
-     *
5307
-     * @param int|string $id the ID of the model object
5308
-     * @return EE_Base_Class
5309
-     */
5310
-    public function get_from_entity_map($id)
5311
-    {
5312
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5313
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5314
-    }
5315
-
5316
-
5317
-
5318
-    /**
5319
-     * add_to_entity_map
5320
-     * Adds the object to the model's entity mappings
5321
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5322
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5323
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5324
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5325
-     *        then this method should be called immediately after the update query
5326
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5327
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5328
-     *
5329
-     * @param    EE_Base_Class $object
5330
-     * @throws EE_Error
5331
-     * @return \EE_Base_Class
5332
-     */
5333
-    public function add_to_entity_map(EE_Base_Class $object)
5334
-    {
5335
-        $className = $this->_get_class_name();
5336
-        if (! $object instanceof $className) {
5337
-            throw new EE_Error(sprintf(
5338
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5339
-                is_object($object) ? get_class($object) : $object,
5340
-                $className
5341
-            ));
5342
-        }
5343
-        /** @var $object EE_Base_Class */
5344
-        if (! $object->ID()) {
5345
-            throw new EE_Error(sprintf(__(
5346
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5347
-                "event_espresso"
5348
-            ), get_class($this)));
5349
-        }
5350
-        // double check it's not already there
5351
-        $classInstance = $this->get_from_entity_map($object->ID());
5352
-        if ($classInstance) {
5353
-            return $classInstance;
5354
-        }
5355
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5356
-        return $object;
5357
-    }
5358
-
5359
-
5360
-
5361
-    /**
5362
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5363
-     * if no identifier is provided, then the entire entity map is emptied
5364
-     *
5365
-     * @param int|string $id the ID of the model object
5366
-     * @return boolean
5367
-     */
5368
-    public function clear_entity_map($id = null)
5369
-    {
5370
-        if (empty($id)) {
5371
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5372
-            return true;
5373
-        }
5374
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5375
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5376
-            return true;
5377
-        }
5378
-        return false;
5379
-    }
5380
-
5381
-
5382
-
5383
-    /**
5384
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5385
-     * Given an array where keys are column (or column alias) names and values,
5386
-     * returns an array of their corresponding field names and database values
5387
-     *
5388
-     * @param array $cols_n_values
5389
-     * @return array
5390
-     */
5391
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5392
-    {
5393
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5394
-    }
5395
-
5396
-
5397
-
5398
-    /**
5399
-     * _deduce_fields_n_values_from_cols_n_values
5400
-     * Given an array where keys are column (or column alias) names and values,
5401
-     * returns an array of their corresponding field names and database values
5402
-     *
5403
-     * @param string $cols_n_values
5404
-     * @return array
5405
-     */
5406
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5407
-    {
5408
-        $this_model_fields_n_values = array();
5409
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5410
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5411
-                $cols_n_values,
5412
-                $table_obj->get_fully_qualified_pk_column(),
5413
-                $table_obj->get_pk_column()
5414
-            );
5415
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5416
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5417
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5418
-                    if (! $field_obj->is_db_only_field()) {
5419
-                        // prepare field as if its coming from db
5420
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5421
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5422
-                    }
5423
-                }
5424
-            } else {
5425
-                // the table's rows existed. Use their values
5426
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5427
-                    if (! $field_obj->is_db_only_field()) {
5428
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5429
-                            $cols_n_values,
5430
-                            $field_obj->get_qualified_column(),
5431
-                            $field_obj->get_table_column()
5432
-                        );
5433
-                    }
5434
-                }
5435
-            }
5436
-        }
5437
-        return $this_model_fields_n_values;
5438
-    }
5439
-
5440
-
5441
-    /**
5442
-     * @param $cols_n_values
5443
-     * @param $qualified_column
5444
-     * @param $regular_column
5445
-     * @return null
5446
-     * @throws EE_Error
5447
-     * @throws ReflectionException
5448
-     */
5449
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5450
-    {
5451
-        $value = null;
5452
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5453
-        // does the field on the model relate to this column retrieved from the db?
5454
-        // or is it a db-only field? (not relating to the model)
5455
-        if (isset($cols_n_values[ $qualified_column ])) {
5456
-            $value = $cols_n_values[ $qualified_column ];
5457
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5458
-            $value = $cols_n_values[ $regular_column ];
5459
-        } elseif (! empty($this->foreign_key_aliases)) {
5460
-            // no PK?  ok check if there is a foreign key alias set for this table
5461
-            // then check if that alias exists in the incoming data
5462
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5463
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5464
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5465
-                    $value = $cols_n_values[ $FK_alias ];
5466
-                    list($pk_class) = explode('.', $PK_column);
5467
-                    $pk_model_name = "EEM_{$pk_class}";
5468
-                    /** @var EEM_Base $pk_model */
5469
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5470
-                    if ($pk_model instanceof EEM_Base) {
5471
-                        // make sure object is pulled from db and added to entity map
5472
-                        $pk_model->get_one_by_ID($value);
5473
-                    }
5474
-                    break;
5475
-                }
5476
-            }
5477
-        }
5478
-        return $value;
5479
-    }
5480
-
5481
-
5482
-
5483
-    /**
5484
-     * refresh_entity_map_from_db
5485
-     * Makes sure the model object in the entity map at $id assumes the values
5486
-     * of the database (opposite of EE_base_Class::save())
5487
-     *
5488
-     * @param int|string $id
5489
-     * @return EE_Base_Class
5490
-     * @throws EE_Error
5491
-     */
5492
-    public function refresh_entity_map_from_db($id)
5493
-    {
5494
-        $obj_in_map = $this->get_from_entity_map($id);
5495
-        if ($obj_in_map) {
5496
-            $wpdb_results = $this->_get_all_wpdb_results(
5497
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5498
-            );
5499
-            if ($wpdb_results && is_array($wpdb_results)) {
5500
-                $one_row = reset($wpdb_results);
5501
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5502
-                    $obj_in_map->set_from_db($field_name, $db_value);
5503
-                }
5504
-                // clear the cache of related model objects
5505
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5506
-                    $obj_in_map->clear_cache($relation_name, null, true);
5507
-                }
5508
-            }
5509
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5510
-            return $obj_in_map;
5511
-        }
5512
-        return $this->get_one_by_ID($id);
5513
-    }
5514
-
5515
-
5516
-
5517
-    /**
5518
-     * refresh_entity_map_with
5519
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5520
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5521
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5522
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5523
-     *
5524
-     * @param int|string    $id
5525
-     * @param EE_Base_Class $replacing_model_obj
5526
-     * @return \EE_Base_Class
5527
-     * @throws EE_Error
5528
-     */
5529
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5530
-    {
5531
-        $obj_in_map = $this->get_from_entity_map($id);
5532
-        if ($obj_in_map) {
5533
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5534
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5535
-                    $obj_in_map->set($field_name, $value);
5536
-                }
5537
-                // make the model object in the entity map's cache match the $replacing_model_obj
5538
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5539
-                    $obj_in_map->clear_cache($relation_name, null, true);
5540
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5541
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5542
-                    }
5543
-                }
5544
-            }
5545
-            return $obj_in_map;
5546
-        }
5547
-        $this->add_to_entity_map($replacing_model_obj);
5548
-        return $replacing_model_obj;
5549
-    }
5550
-
5551
-
5552
-
5553
-    /**
5554
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5555
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5556
-     * require_once($this->_getClassName().".class.php");
5557
-     *
5558
-     * @return string
5559
-     */
5560
-    private function _get_class_name()
5561
-    {
5562
-        return "EE_" . $this->get_this_model_name();
5563
-    }
5564
-
5565
-
5566
-
5567
-    /**
5568
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5569
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5570
-     * it would be 'Events'.
5571
-     *
5572
-     * @param int $quantity
5573
-     * @return string
5574
-     */
5575
-    public function item_name($quantity = 1)
5576
-    {
5577
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5578
-    }
5579
-
5580
-
5581
-
5582
-    /**
5583
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5584
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5585
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5586
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5587
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5588
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5589
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5590
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5591
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5592
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5593
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5594
-     *        return $previousReturnValue.$returnString;
5595
-     * }
5596
-     * require('EEM_Answer.model.php');
5597
-     * $answer=EEM_Answer::instance();
5598
-     * echo $answer->my_callback('monkeys',100);
5599
-     * //will output "you called my_callback! and passed args:monkeys,100"
5600
-     *
5601
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5602
-     * @param array  $args       array of original arguments passed to the function
5603
-     * @throws EE_Error
5604
-     * @return mixed whatever the plugin which calls add_filter decides
5605
-     */
5606
-    public function __call($methodName, $args)
5607
-    {
5608
-        $className = get_class($this);
5609
-        $tagName = "FHEE__{$className}__{$methodName}";
5610
-        if (! has_filter($tagName)) {
5611
-            throw new EE_Error(
5612
-                sprintf(
5613
-                    __(
5614
-                        'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5615
-                        'event_espresso'
5616
-                    ),
5617
-                    $methodName,
5618
-                    $className,
5619
-                    $tagName,
5620
-                    '<br />'
5621
-                )
5622
-            );
5623
-        }
5624
-        return apply_filters($tagName, null, $this, $args);
5625
-    }
5626
-
5627
-
5628
-
5629
-    /**
5630
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5631
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5632
-     *
5633
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5634
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5635
-     *                                                       the object's class name
5636
-     *                                                       or object's ID
5637
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5638
-     *                                                       exists in the database. If it does not, we add it
5639
-     * @throws EE_Error
5640
-     * @return EE_Base_Class
5641
-     */
5642
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5643
-    {
5644
-        $className = $this->_get_class_name();
5645
-        if ($base_class_obj_or_id instanceof $className) {
5646
-            $model_object = $base_class_obj_or_id;
5647
-        } else {
5648
-            $primary_key_field = $this->get_primary_key_field();
5649
-            if (
5650
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5651
-                && (
5652
-                    is_int($base_class_obj_or_id)
5653
-                    || is_string($base_class_obj_or_id)
5654
-                )
5655
-            ) {
5656
-                // assume it's an ID.
5657
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5658
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5659
-            } elseif (
5660
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5661
-                && is_string($base_class_obj_or_id)
5662
-            ) {
5663
-                // assume its a string representation of the object
5664
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5665
-            } else {
5666
-                throw new EE_Error(
5667
-                    sprintf(
5668
-                        __(
5669
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5670
-                            'event_espresso'
5671
-                        ),
5672
-                        $base_class_obj_or_id,
5673
-                        $this->_get_class_name(),
5674
-                        print_r($base_class_obj_or_id, true)
5675
-                    )
5676
-                );
5677
-            }
5678
-        }
5679
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5680
-            $model_object->save();
5681
-        }
5682
-        return $model_object;
5683
-    }
5684
-
5685
-
5686
-
5687
-    /**
5688
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5689
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5690
-     * returns it ID.
5691
-     *
5692
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5693
-     * @return int|string depending on the type of this model object's ID
5694
-     * @throws EE_Error
5695
-     */
5696
-    public function ensure_is_ID($base_class_obj_or_id)
5697
-    {
5698
-        $className = $this->_get_class_name();
5699
-        if ($base_class_obj_or_id instanceof $className) {
5700
-            /** @var $base_class_obj_or_id EE_Base_Class */
5701
-            $id = $base_class_obj_or_id->ID();
5702
-        } elseif (is_int($base_class_obj_or_id)) {
5703
-            // assume it's an ID
5704
-            $id = $base_class_obj_or_id;
5705
-        } elseif (is_string($base_class_obj_or_id)) {
5706
-            // assume its a string representation of the object
5707
-            $id = $base_class_obj_or_id;
5708
-        } else {
5709
-            throw new EE_Error(sprintf(
5710
-                __(
5711
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5712
-                    'event_espresso'
5713
-                ),
5714
-                $base_class_obj_or_id,
5715
-                $this->_get_class_name(),
5716
-                print_r($base_class_obj_or_id, true)
5717
-            ));
5718
-        }
5719
-        return $id;
5720
-    }
5721
-
5722
-
5723
-
5724
-    /**
5725
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5726
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5727
-     * been sanitized and converted into the appropriate domain.
5728
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5729
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5730
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5731
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5732
-     * $EVT = EEM_Event::instance(); $old_setting =
5733
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5734
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5735
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5736
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5737
-     *
5738
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5739
-     * @return void
5740
-     */
5741
-    public function assume_values_already_prepared_by_model_object(
5742
-        $values_already_prepared = self::not_prepared_by_model_object
5743
-    ) {
5744
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5745
-    }
5746
-
5747
-
5748
-
5749
-    /**
5750
-     * Read comments for assume_values_already_prepared_by_model_object()
5751
-     *
5752
-     * @return int
5753
-     */
5754
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5755
-    {
5756
-        return $this->_values_already_prepared_by_model_object;
5757
-    }
5758
-
5759
-
5760
-
5761
-    /**
5762
-     * Gets all the indexes on this model
5763
-     *
5764
-     * @return EE_Index[]
5765
-     */
5766
-    public function indexes()
5767
-    {
5768
-        return $this->_indexes;
5769
-    }
5770
-
5771
-
5772
-
5773
-    /**
5774
-     * Gets all the Unique Indexes on this model
5775
-     *
5776
-     * @return EE_Unique_Index[]
5777
-     */
5778
-    public function unique_indexes()
5779
-    {
5780
-        $unique_indexes = array();
5781
-        foreach ($this->_indexes as $name => $index) {
5782
-            if ($index instanceof EE_Unique_Index) {
5783
-                $unique_indexes [ $name ] = $index;
5784
-            }
5785
-        }
5786
-        return $unique_indexes;
5787
-    }
5788
-
5789
-
5790
-
5791
-    /**
5792
-     * Gets all the fields which, when combined, make the primary key.
5793
-     * This is usually just an array with 1 element (the primary key), but in cases
5794
-     * where there is no primary key, it's a combination of fields as defined
5795
-     * on a primary index
5796
-     *
5797
-     * @return EE_Model_Field_Base[] indexed by the field's name
5798
-     * @throws EE_Error
5799
-     */
5800
-    public function get_combined_primary_key_fields()
5801
-    {
5802
-        foreach ($this->indexes() as $index) {
5803
-            if ($index instanceof EE_Primary_Key_Index) {
5804
-                return $index->fields();
5805
-            }
5806
-        }
5807
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5808
-    }
5809
-
5810
-
5811
-
5812
-    /**
5813
-     * Used to build a primary key string (when the model has no primary key),
5814
-     * which can be used a unique string to identify this model object.
5815
-     *
5816
-     * @param array $fields_n_values keys are field names, values are their values.
5817
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5818
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5819
-     *                               before passing it to this function (that will convert it from columns-n-values
5820
-     *                               to field-names-n-values).
5821
-     * @return string
5822
-     * @throws EE_Error
5823
-     */
5824
-    public function get_index_primary_key_string($fields_n_values)
5825
-    {
5826
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5827
-            $fields_n_values,
5828
-            $this->get_combined_primary_key_fields()
5829
-        );
5830
-        return http_build_query($cols_n_values_for_primary_key_index);
5831
-    }
5832
-
5833
-
5834
-
5835
-    /**
5836
-     * Gets the field values from the primary key string
5837
-     *
5838
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5839
-     * @param string $index_primary_key_string
5840
-     * @return null|array
5841
-     * @throws EE_Error
5842
-     */
5843
-    public function parse_index_primary_key_string($index_primary_key_string)
5844
-    {
5845
-        $key_fields = $this->get_combined_primary_key_fields();
5846
-        // check all of them are in the $id
5847
-        $key_vals_in_combined_pk = array();
5848
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5849
-        foreach ($key_fields as $key_field_name => $field_obj) {
5850
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5851
-                return null;
5852
-            }
5853
-        }
5854
-        return $key_vals_in_combined_pk;
5855
-    }
5856
-
5857
-
5858
-
5859
-    /**
5860
-     * verifies that an array of key-value pairs for model fields has a key
5861
-     * for each field comprising the primary key index
5862
-     *
5863
-     * @param array $key_vals
5864
-     * @return boolean
5865
-     * @throws EE_Error
5866
-     */
5867
-    public function has_all_combined_primary_key_fields($key_vals)
5868
-    {
5869
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5870
-        foreach ($keys_it_should_have as $key) {
5871
-            if (! isset($key_vals[ $key ])) {
5872
-                return false;
5873
-            }
5874
-        }
5875
-        return true;
5876
-    }
5877
-
5878
-
5879
-
5880
-    /**
5881
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5882
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5883
-     *
5884
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5885
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5886
-     * @throws EE_Error
5887
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5888
-     *                                                              indexed)
5889
-     */
5890
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5891
-    {
5892
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5893
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5894
-        } elseif (is_array($model_object_or_attributes_array)) {
5895
-            $attributes_array = $model_object_or_attributes_array;
5896
-        } else {
5897
-            throw new EE_Error(sprintf(__(
5898
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5899
-                "event_espresso"
5900
-            ), $model_object_or_attributes_array));
5901
-        }
5902
-        // even copies obviously won't have the same ID, so remove the primary key
5903
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5904
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5905
-            unset($attributes_array[ $this->primary_key_name() ]);
5906
-        }
5907
-        if (isset($query_params[0])) {
5908
-            $query_params[0] = array_merge($attributes_array, $query_params);
5909
-        } else {
5910
-            $query_params[0] = $attributes_array;
5911
-        }
5912
-        return $this->get_all($query_params);
5913
-    }
5914
-
5915
-
5916
-
5917
-    /**
5918
-     * Gets the first copy we find. See get_all_copies for more details
5919
-     *
5920
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5921
-     * @param array $query_params
5922
-     * @return EE_Base_Class
5923
-     * @throws EE_Error
5924
-     */
5925
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5926
-    {
5927
-        if (! is_array($query_params)) {
5928
-            EE_Error::doing_it_wrong(
5929
-                'EEM_Base::get_one_copy',
5930
-                sprintf(
5931
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5932
-                    gettype($query_params)
5933
-                ),
5934
-                '4.6.0'
5935
-            );
5936
-            $query_params = array();
5937
-        }
5938
-        $query_params['limit'] = 1;
5939
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5940
-        if (is_array($copies)) {
5941
-            return array_shift($copies);
5942
-        }
5943
-        return null;
5944
-    }
5945
-
5946
-
5947
-
5948
-    /**
5949
-     * Updates the item with the specified id. Ignores default query parameters because
5950
-     * we have specified the ID, and its assumed we KNOW what we're doing
5951
-     *
5952
-     * @param array      $fields_n_values keys are field names, values are their new values
5953
-     * @param int|string $id              the value of the primary key to update
5954
-     * @return int number of rows updated
5955
-     * @throws EE_Error
5956
-     */
5957
-    public function update_by_ID($fields_n_values, $id)
5958
-    {
5959
-        $query_params = array(
5960
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5961
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5962
-        );
5963
-        return $this->update($fields_n_values, $query_params);
5964
-    }
5965
-
5966
-
5967
-
5968
-    /**
5969
-     * Changes an operator which was supplied to the models into one usable in SQL
5970
-     *
5971
-     * @param string $operator_supplied
5972
-     * @return string an operator which can be used in SQL
5973
-     * @throws EE_Error
5974
-     */
5975
-    private function _prepare_operator_for_sql($operator_supplied)
5976
-    {
5977
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5978
-            : null;
5979
-        if ($sql_operator) {
5980
-            return $sql_operator;
5981
-        }
5982
-        throw new EE_Error(
5983
-            sprintf(
5984
-                __(
5985
-                    "The operator '%s' is not in the list of valid operators: %s",
5986
-                    "event_espresso"
5987
-                ),
5988
-                $operator_supplied,
5989
-                implode(",", array_keys($this->_valid_operators))
5990
-            )
5991
-        );
5992
-    }
5993
-
5994
-
5995
-
5996
-    /**
5997
-     * Gets the valid operators
5998
-     * @return array keys are accepted strings, values are the SQL they are converted to
5999
-     */
6000
-    public function valid_operators()
6001
-    {
6002
-        return $this->_valid_operators;
6003
-    }
6004
-
6005
-
6006
-
6007
-    /**
6008
-     * Gets the between-style operators (take 2 arguments).
6009
-     * @return array keys are accepted strings, values are the SQL they are converted to
6010
-     */
6011
-    public function valid_between_style_operators()
6012
-    {
6013
-        return array_intersect(
6014
-            $this->valid_operators(),
6015
-            $this->_between_style_operators
6016
-        );
6017
-    }
6018
-
6019
-    /**
6020
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6021
-     * @return array keys are accepted strings, values are the SQL they are converted to
6022
-     */
6023
-    public function valid_like_style_operators()
6024
-    {
6025
-        return array_intersect(
6026
-            $this->valid_operators(),
6027
-            $this->_like_style_operators
6028
-        );
6029
-    }
6030
-
6031
-    /**
6032
-     * Gets the "in"-style operators
6033
-     * @return array keys are accepted strings, values are the SQL they are converted to
6034
-     */
6035
-    public function valid_in_style_operators()
6036
-    {
6037
-        return array_intersect(
6038
-            $this->valid_operators(),
6039
-            $this->_in_style_operators
6040
-        );
6041
-    }
6042
-
6043
-    /**
6044
-     * Gets the "null"-style operators (accept no arguments)
6045
-     * @return array keys are accepted strings, values are the SQL they are converted to
6046
-     */
6047
-    public function valid_null_style_operators()
6048
-    {
6049
-        return array_intersect(
6050
-            $this->valid_operators(),
6051
-            $this->_null_style_operators
6052
-        );
6053
-    }
6054
-
6055
-    /**
6056
-     * Gets an array where keys are the primary keys and values are their 'names'
6057
-     * (as determined by the model object's name() function, which is often overridden)
6058
-     *
6059
-     * @param array $query_params like get_all's
6060
-     * @return string[]
6061
-     * @throws EE_Error
6062
-     */
6063
-    public function get_all_names($query_params = array())
6064
-    {
6065
-        $objs = $this->get_all($query_params);
6066
-        $names = array();
6067
-        foreach ($objs as $obj) {
6068
-            $names[ $obj->ID() ] = $obj->name();
6069
-        }
6070
-        return $names;
6071
-    }
6072
-
6073
-
6074
-
6075
-    /**
6076
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6077
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6078
-     * this is duplicated effort and reduces efficiency) you would be better to use
6079
-     * array_keys() on $model_objects.
6080
-     *
6081
-     * @param \EE_Base_Class[] $model_objects
6082
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6083
-     *                                               in the returned array
6084
-     * @return array
6085
-     * @throws EE_Error
6086
-     */
6087
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6088
-    {
6089
-        if (! $this->has_primary_key_field()) {
6090
-            if (WP_DEBUG) {
6091
-                EE_Error::add_error(
6092
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6093
-                    __FILE__,
6094
-                    __FUNCTION__,
6095
-                    __LINE__
6096
-                );
6097
-            }
6098
-        }
6099
-        $IDs = array();
6100
-        foreach ($model_objects as $model_object) {
6101
-            $id = $model_object->ID();
6102
-            if (! $id) {
6103
-                if ($filter_out_empty_ids) {
6104
-                    continue;
6105
-                }
6106
-                if (WP_DEBUG) {
6107
-                    EE_Error::add_error(
6108
-                        __(
6109
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6110
-                            'event_espresso'
6111
-                        ),
6112
-                        __FILE__,
6113
-                        __FUNCTION__,
6114
-                        __LINE__
6115
-                    );
6116
-                }
6117
-            }
6118
-            $IDs[] = $id;
6119
-        }
6120
-        return $IDs;
6121
-    }
6122
-
6123
-
6124
-
6125
-    /**
6126
-     * Returns the string used in capabilities relating to this model. If there
6127
-     * are no capabilities that relate to this model returns false
6128
-     *
6129
-     * @return string|false
6130
-     */
6131
-    public function cap_slug()
6132
-    {
6133
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6134
-    }
6135
-
6136
-
6137
-
6138
-    /**
6139
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6140
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6141
-     * only returns the cap restrictions array in that context (ie, the array
6142
-     * at that key)
6143
-     *
6144
-     * @param string $context
6145
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6146
-     * @throws EE_Error
6147
-     */
6148
-    public function cap_restrictions($context = EEM_Base::caps_read)
6149
-    {
6150
-        EEM_Base::verify_is_valid_cap_context($context);
6151
-        // check if we ought to run the restriction generator first
6152
-        if (
6153
-            isset($this->_cap_restriction_generators[ $context ])
6154
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6155
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6156
-        ) {
6157
-            $this->_cap_restrictions[ $context ] = array_merge(
6158
-                $this->_cap_restrictions[ $context ],
6159
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6160
-            );
6161
-        }
6162
-        // and make sure we've finalized the construction of each restriction
6163
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6164
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6165
-                $where_conditions_obj->_finalize_construct($this);
6166
-            }
6167
-        }
6168
-        return $this->_cap_restrictions[ $context ];
6169
-    }
6170
-
6171
-
6172
-
6173
-    /**
6174
-     * Indicating whether or not this model thinks its a wp core model
6175
-     *
6176
-     * @return boolean
6177
-     */
6178
-    public function is_wp_core_model()
6179
-    {
6180
-        return $this->_wp_core_model;
6181
-    }
6182
-
6183
-
6184
-
6185
-    /**
6186
-     * Gets all the caps that are missing which impose a restriction on
6187
-     * queries made in this context
6188
-     *
6189
-     * @param string $context one of EEM_Base::caps_ constants
6190
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6191
-     * @throws EE_Error
6192
-     */
6193
-    public function caps_missing($context = EEM_Base::caps_read)
6194
-    {
6195
-        $missing_caps = array();
6196
-        $cap_restrictions = $this->cap_restrictions($context);
6197
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6198
-            if (
6199
-                ! EE_Capabilities::instance()
6200
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6201
-            ) {
6202
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6203
-            }
6204
-        }
6205
-        return $missing_caps;
6206
-    }
6207
-
6208
-
6209
-
6210
-    /**
6211
-     * Gets the mapping from capability contexts to action strings used in capability names
6212
-     *
6213
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6214
-     * one of 'read', 'edit', or 'delete'
6215
-     */
6216
-    public function cap_contexts_to_cap_action_map()
6217
-    {
6218
-        return apply_filters(
6219
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6220
-            $this->_cap_contexts_to_cap_action_map,
6221
-            $this
6222
-        );
6223
-    }
6224
-
6225
-
6226
-
6227
-    /**
6228
-     * Gets the action string for the specified capability context
6229
-     *
6230
-     * @param string $context
6231
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6232
-     * @throws EE_Error
6233
-     */
6234
-    public function cap_action_for_context($context)
6235
-    {
6236
-        $mapping = $this->cap_contexts_to_cap_action_map();
6237
-        if (isset($mapping[ $context ])) {
6238
-            return $mapping[ $context ];
6239
-        }
6240
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6241
-            return $action;
6242
-        }
6243
-        throw new EE_Error(
6244
-            sprintf(
6245
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6246
-                $context,
6247
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6248
-            )
6249
-        );
6250
-    }
6251
-
6252
-
6253
-
6254
-    /**
6255
-     * Returns all the capability contexts which are valid when querying models
6256
-     *
6257
-     * @return array
6258
-     */
6259
-    public static function valid_cap_contexts()
6260
-    {
6261
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6262
-            self::caps_read,
6263
-            self::caps_read_admin,
6264
-            self::caps_edit,
6265
-            self::caps_delete,
6266
-        ));
6267
-    }
6268
-
6269
-
6270
-
6271
-    /**
6272
-     * Returns all valid options for 'default_where_conditions'
6273
-     *
6274
-     * @return array
6275
-     */
6276
-    public static function valid_default_where_conditions()
6277
-    {
6278
-        return array(
6279
-            EEM_Base::default_where_conditions_all,
6280
-            EEM_Base::default_where_conditions_this_only,
6281
-            EEM_Base::default_where_conditions_others_only,
6282
-            EEM_Base::default_where_conditions_minimum_all,
6283
-            EEM_Base::default_where_conditions_minimum_others,
6284
-            EEM_Base::default_where_conditions_none
6285
-        );
6286
-    }
6287
-
6288
-    // public static function default_where_conditions_full
6289
-    /**
6290
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6291
-     *
6292
-     * @param string $context
6293
-     * @return bool
6294
-     * @throws EE_Error
6295
-     */
6296
-    public static function verify_is_valid_cap_context($context)
6297
-    {
6298
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6299
-        if (in_array($context, $valid_cap_contexts)) {
6300
-            return true;
6301
-        }
6302
-        throw new EE_Error(
6303
-            sprintf(
6304
-                __(
6305
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6306
-                    'event_espresso'
6307
-                ),
6308
-                $context,
6309
-                'EEM_Base',
6310
-                implode(',', $valid_cap_contexts)
6311
-            )
6312
-        );
6313
-    }
6314
-
6315
-
6316
-
6317
-    /**
6318
-     * Clears all the models field caches. This is only useful when a sub-class
6319
-     * might have added a field or something and these caches might be invalidated
6320
-     */
6321
-    protected function _invalidate_field_caches()
6322
-    {
6323
-        $this->_cache_foreign_key_to_fields = array();
6324
-        $this->_cached_fields = null;
6325
-        $this->_cached_fields_non_db_only = null;
6326
-    }
6327
-
6328
-
6329
-
6330
-    /**
6331
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6332
-     * (eg "and", "or", "not").
6333
-     *
6334
-     * @return array
6335
-     */
6336
-    public function logic_query_param_keys()
6337
-    {
6338
-        return $this->_logic_query_param_keys;
6339
-    }
6340
-
6341
-
6342
-
6343
-    /**
6344
-     * Determines whether or not the where query param array key is for a logic query param.
6345
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6346
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6347
-     *
6348
-     * @param $query_param_key
6349
-     * @return bool
6350
-     */
6351
-    public function is_logic_query_param_key($query_param_key)
6352
-    {
6353
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6354
-            if (
6355
-                $query_param_key === $logic_query_param_key
6356
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6357
-            ) {
6358
-                return true;
6359
-            }
6360
-        }
6361
-        return false;
6362
-    }
6363
-
6364
-    /**
6365
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6366
-     * @since 4.9.74.p
6367
-     * @return boolean
6368
-     */
6369
-    public function hasPassword()
6370
-    {
6371
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6372
-        if ($this->has_password_field === null) {
6373
-            $password_field = $this->getPasswordField();
6374
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6375
-        }
6376
-        return $this->has_password_field;
6377
-    }
6378
-
6379
-    /**
6380
-     * Returns the password field on this model, if there is one
6381
-     * @since 4.9.74.p
6382
-     * @return EE_Password_Field|null
6383
-     */
6384
-    public function getPasswordField()
6385
-    {
6386
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6387
-        // there's no need to search for it. If we don't know yet, then find out
6388
-        if ($this->has_password_field === null && $this->password_field === null) {
6389
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6390
-        }
6391
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6392
-        return $this->password_field;
6393
-    }
6394
-
6395
-
6396
-    /**
6397
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6398
-     * @since 4.9.74.p
6399
-     * @return EE_Model_Field_Base[]
6400
-     * @throws EE_Error
6401
-     */
6402
-    public function getPasswordProtectedFields()
6403
-    {
6404
-        $password_field = $this->getPasswordField();
6405
-        $fields = array();
6406
-        if ($password_field instanceof EE_Password_Field) {
6407
-            $field_names = $password_field->protectedFields();
6408
-            foreach ($field_names as $field_name) {
6409
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6410
-            }
6411
-        }
6412
-        return $fields;
6413
-    }
6414
-
6415
-
6416
-    /**
6417
-     * Checks if the current user can perform the requested action on this model
6418
-     * @since 4.9.74.p
6419
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6420
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6421
-     * @return bool
6422
-     * @throws EE_Error
6423
-     * @throws InvalidArgumentException
6424
-     * @throws InvalidDataTypeException
6425
-     * @throws InvalidInterfaceException
6426
-     * @throws ReflectionException
6427
-     * @throws UnexpectedEntityException
6428
-     */
6429
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6430
-    {
6431
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6432
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6433
-        }
6434
-        if (!is_array($model_obj_or_fields_n_values)) {
6435
-            throw new UnexpectedEntityException(
6436
-                $model_obj_or_fields_n_values,
6437
-                'EE_Base_Class',
6438
-                sprintf(
6439
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6440
-                    __FUNCTION__
6441
-                )
6442
-            );
6443
-        }
6444
-        return $this->exists(
6445
-            $this->alter_query_params_to_restrict_by_ID(
6446
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6447
-                array(
6448
-                    'default_where_conditions' => 'none',
6449
-                    'caps'                     => $cap_to_check,
6450
-                )
6451
-            )
6452
-        );
6453
-    }
6454
-
6455
-    /**
6456
-     * Returns the query param where conditions key to the password affecting this model.
6457
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6458
-     * @since 4.9.74.p
6459
-     * @return null|string
6460
-     * @throws EE_Error
6461
-     * @throws InvalidArgumentException
6462
-     * @throws InvalidDataTypeException
6463
-     * @throws InvalidInterfaceException
6464
-     * @throws ModelConfigurationException
6465
-     * @throws ReflectionException
6466
-     */
6467
-    public function modelChainAndPassword()
6468
-    {
6469
-        if ($this->model_chain_to_password === null) {
6470
-            throw new ModelConfigurationException(
6471
-                $this,
6472
-                esc_html_x(
6473
-                // @codingStandardsIgnoreStart
6474
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6475
-                    // @codingStandardsIgnoreEnd
6476
-                    '1: model name',
6477
-                    'event_espresso'
6478
-                )
6479
-            );
6480
-        }
6481
-        if ($this->model_chain_to_password === '') {
6482
-            $model_with_password = $this;
6483
-        } else {
6484
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6485
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6486
-            } else {
6487
-                $last_model_in_chain = $this->model_chain_to_password;
6488
-            }
6489
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6490
-        }
6491
-
6492
-        $password_field = $model_with_password->getPasswordField();
6493
-        if ($password_field instanceof EE_Password_Field) {
6494
-            $password_field_name = $password_field->get_name();
6495
-        } else {
6496
-            throw new ModelConfigurationException(
6497
-                $this,
6498
-                sprintf(
6499
-                    esc_html_x(
6500
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6501
-                        '1: model name, 2: special string',
6502
-                        'event_espresso'
6503
-                    ),
6504
-                    $model_with_password->get_this_model_name(),
6505
-                    $this->model_chain_to_password
6506
-                )
6507
-            );
6508
-        }
6509
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6510
-    }
6511
-
6512
-    /**
6513
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6514
-     * or if this model itself has a password affecting access to some of its other fields.
6515
-     * @since 4.9.74.p
6516
-     * @return boolean
6517
-     */
6518
-    public function restrictedByRelatedModelPassword()
6519
-    {
6520
-        return $this->model_chain_to_password !== null;
6521
-    }
3816
+		}
3817
+		return $null_friendly_where_conditions;
3818
+	}
3819
+
3820
+
3821
+
3822
+	/**
3823
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3824
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3825
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3826
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3827
+	 *
3828
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3829
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3830
+	 */
3831
+	private function _get_default_where_conditions($model_relation_path = '')
3832
+	{
3833
+		if ($this->_ignore_where_strategy) {
3834
+			return array();
3835
+		}
3836
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3837
+	}
3838
+
3839
+
3840
+
3841
+	/**
3842
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3843
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3844
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3845
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3846
+	 * Similar to _get_default_where_conditions
3847
+	 *
3848
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3849
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3850
+	 */
3851
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3852
+	{
3853
+		if ($this->_ignore_where_strategy) {
3854
+			return array();
3855
+		}
3856
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3857
+	}
3858
+
3859
+
3860
+
3861
+	/**
3862
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3863
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3864
+	 *
3865
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3866
+	 * @return string
3867
+	 * @throws EE_Error
3868
+	 */
3869
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3870
+	{
3871
+		$selects = $this->_get_columns_to_select_for_this_model();
3872
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included) {
3873
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3874
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3875
+			foreach ($other_model_selects as $key => $value) {
3876
+				$selects[] = $value;
3877
+			}
3878
+		}
3879
+		return implode(", ", $selects);
3880
+	}
3881
+
3882
+
3883
+
3884
+	/**
3885
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3886
+	 * So that's going to be the columns for all the fields on the model
3887
+	 *
3888
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3889
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3890
+	 */
3891
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3892
+	{
3893
+		$fields = $this->field_settings();
3894
+		$selects = array();
3895
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3896
+			$model_relation_chain,
3897
+			$this->get_this_model_name()
3898
+		);
3899
+		foreach ($fields as $field_obj) {
3900
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3901
+						 . $field_obj->get_table_alias()
3902
+						 . "."
3903
+						 . $field_obj->get_table_column()
3904
+						 . " AS '"
3905
+						 . $table_alias_with_model_relation_chain_prefix
3906
+						 . $field_obj->get_table_alias()
3907
+						 . "."
3908
+						 . $field_obj->get_table_column()
3909
+						 . "'";
3910
+		}
3911
+		// make sure we are also getting the PKs of each table
3912
+		$tables = $this->get_tables();
3913
+		if (count($tables) > 1) {
3914
+			foreach ($tables as $table_obj) {
3915
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3916
+									   . $table_obj->get_fully_qualified_pk_column();
3917
+				if (! in_array($qualified_pk_column, $selects)) {
3918
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3919
+				}
3920
+			}
3921
+		}
3922
+		return $selects;
3923
+	}
3924
+
3925
+
3926
+
3927
+	/**
3928
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3929
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3930
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3931
+	 * SQL for joining, and the data types
3932
+	 *
3933
+	 * @param null|string                 $original_query_param
3934
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3935
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3936
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3937
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3938
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3939
+	 *                                                          or 'Registration's
3940
+	 * @param string                      $original_query_param what it originally was (eg
3941
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3942
+	 *                                                          matches $query_param
3943
+	 * @throws EE_Error
3944
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3945
+	 */
3946
+	private function _extract_related_model_info_from_query_param(
3947
+		$query_param,
3948
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3949
+		$query_param_type,
3950
+		$original_query_param = null
3951
+	) {
3952
+		if ($original_query_param === null) {
3953
+			$original_query_param = $query_param;
3954
+		}
3955
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3956
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3957
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3958
+		$allow_fields = in_array(
3959
+			$query_param_type,
3960
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3961
+			true
3962
+		);
3963
+		// check to see if we have a field on this model
3964
+		$this_model_fields = $this->field_settings(true);
3965
+		if (array_key_exists($query_param, $this_model_fields)) {
3966
+			if ($allow_fields) {
3967
+				return;
3968
+			}
3969
+			throw new EE_Error(
3970
+				sprintf(
3971
+					__(
3972
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3973
+						"event_espresso"
3974
+					),
3975
+					$query_param,
3976
+					get_class($this),
3977
+					$query_param_type,
3978
+					$original_query_param
3979
+				)
3980
+			);
3981
+		}
3982
+		// check if this is a special logic query param
3983
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3984
+			if ($allow_logic_query_params) {
3985
+				return;
3986
+			}
3987
+			throw new EE_Error(
3988
+				sprintf(
3989
+					__(
3990
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3991
+						'event_espresso'
3992
+					),
3993
+					implode('", "', $this->_logic_query_param_keys),
3994
+					$query_param,
3995
+					get_class($this),
3996
+					'<br />',
3997
+					"\t"
3998
+					. ' $passed_in_query_info = <pre>'
3999
+					. print_r($passed_in_query_info, true)
4000
+					. '</pre>'
4001
+					. "\n\t"
4002
+					. ' $query_param_type = '
4003
+					. $query_param_type
4004
+					. "\n\t"
4005
+					. ' $original_query_param = '
4006
+					. $original_query_param
4007
+				)
4008
+			);
4009
+		}
4010
+		// check if it's a custom selection
4011
+		if (
4012
+			$this->_custom_selections instanceof CustomSelects
4013
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4014
+		) {
4015
+			return;
4016
+		}
4017
+		// check if has a model name at the beginning
4018
+		// and
4019
+		// check if it's a field on a related model
4020
+		if (
4021
+			$this->extractJoinModelFromQueryParams(
4022
+				$passed_in_query_info,
4023
+				$query_param,
4024
+				$original_query_param,
4025
+				$query_param_type
4026
+			)
4027
+		) {
4028
+			return;
4029
+		}
4030
+
4031
+		// ok so $query_param didn't start with a model name
4032
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4033
+		// it's wack, that's what it is
4034
+		throw new EE_Error(
4035
+			sprintf(
4036
+				esc_html__(
4037
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4038
+					"event_espresso"
4039
+				),
4040
+				$query_param,
4041
+				get_class($this),
4042
+				$query_param_type,
4043
+				$original_query_param
4044
+			)
4045
+		);
4046
+	}
4047
+
4048
+
4049
+	/**
4050
+	 * Extracts any possible join model information from the provided possible_join_string.
4051
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4052
+	 * parts that should be added to the query.
4053
+	 *
4054
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4055
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4056
+	 * @param null|string                 $original_query_param
4057
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4058
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4059
+	 * @return bool  returns true if a join was added and false if not.
4060
+	 * @throws EE_Error
4061
+	 */
4062
+	private function extractJoinModelFromQueryParams(
4063
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4064
+		$possible_join_string,
4065
+		$original_query_param,
4066
+		$query_parameter_type
4067
+	) {
4068
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4069
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4070
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4071
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4072
+				if ($possible_join_string === '') {
4073
+					// nothing left to $query_param
4074
+					// we should actually end in a field name, not a model like this!
4075
+					throw new EE_Error(
4076
+						sprintf(
4077
+							esc_html__(
4078
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4079
+								"event_espresso"
4080
+							),
4081
+							$possible_join_string,
4082
+							$query_parameter_type,
4083
+							get_class($this),
4084
+							$valid_related_model_name
4085
+						)
4086
+					);
4087
+				}
4088
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4089
+				$related_model_obj->_extract_related_model_info_from_query_param(
4090
+					$possible_join_string,
4091
+					$query_info_carrier,
4092
+					$query_parameter_type,
4093
+					$original_query_param
4094
+				);
4095
+				return true;
4096
+			}
4097
+			if ($possible_join_string === $valid_related_model_name) {
4098
+				$this->_add_join_to_model(
4099
+					$valid_related_model_name,
4100
+					$query_info_carrier,
4101
+					$original_query_param
4102
+				);
4103
+				return true;
4104
+			}
4105
+		}
4106
+		return false;
4107
+	}
4108
+
4109
+
4110
+	/**
4111
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4112
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4113
+	 * @throws EE_Error
4114
+	 */
4115
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4116
+	{
4117
+		if (
4118
+			$this->_custom_selections instanceof CustomSelects
4119
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4120
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4121
+			)
4122
+		) {
4123
+			$original_selects = $this->_custom_selections->originalSelects();
4124
+			foreach ($original_selects as $alias => $select_configuration) {
4125
+				$this->extractJoinModelFromQueryParams(
4126
+					$query_info_carrier,
4127
+					$select_configuration[0],
4128
+					$select_configuration[0],
4129
+					'custom_selects'
4130
+				);
4131
+			}
4132
+		}
4133
+	}
4134
+
4135
+
4136
+
4137
+	/**
4138
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4139
+	 * and store it on $passed_in_query_info
4140
+	 *
4141
+	 * @param string                      $model_name
4142
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4143
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4144
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4145
+	 *                                                          and are adding a join to 'Payment' with the original
4146
+	 *                                                          query param key
4147
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4148
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4149
+	 *                                                          Payment wants to add default query params so that it
4150
+	 *                                                          will know what models to prepend onto its default query
4151
+	 *                                                          params or in case it wants to rename tables (in case
4152
+	 *                                                          there are multiple joins to the same table)
4153
+	 * @return void
4154
+	 * @throws EE_Error
4155
+	 */
4156
+	private function _add_join_to_model(
4157
+		$model_name,
4158
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4159
+		$original_query_param
4160
+	) {
4161
+		$relation_obj = $this->related_settings_for($model_name);
4162
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4163
+		// check if the relation is HABTM, because then we're essentially doing two joins
4164
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4165
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4166
+			$join_model_obj = $relation_obj->get_join_model();
4167
+			// replace the model specified with the join model for this relation chain, whi
4168
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4169
+				$model_name,
4170
+				$join_model_obj->get_this_model_name(),
4171
+				$model_relation_chain
4172
+			);
4173
+			$passed_in_query_info->merge(
4174
+				new EE_Model_Query_Info_Carrier(
4175
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4176
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4177
+				)
4178
+			);
4179
+		}
4180
+		// now just join to the other table pointed to by the relation object, and add its data types
4181
+		$passed_in_query_info->merge(
4182
+			new EE_Model_Query_Info_Carrier(
4183
+				array($model_relation_chain => $model_name),
4184
+				$relation_obj->get_join_statement($model_relation_chain)
4185
+			)
4186
+		);
4187
+	}
4188
+
4189
+
4190
+
4191
+	/**
4192
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4193
+	 *
4194
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4195
+	 * @return string of SQL
4196
+	 * @throws EE_Error
4197
+	 */
4198
+	private function _construct_where_clause($where_params)
4199
+	{
4200
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4201
+		if ($SQL) {
4202
+			return " WHERE " . $SQL;
4203
+		}
4204
+		return '';
4205
+	}
4206
+
4207
+
4208
+
4209
+	/**
4210
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4211
+	 * and should be passed HAVING parameters, not WHERE parameters
4212
+	 *
4213
+	 * @param array $having_params
4214
+	 * @return string
4215
+	 * @throws EE_Error
4216
+	 */
4217
+	private function _construct_having_clause($having_params)
4218
+	{
4219
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4220
+		if ($SQL) {
4221
+			return " HAVING " . $SQL;
4222
+		}
4223
+		return '';
4224
+	}
4225
+
4226
+
4227
+	/**
4228
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4229
+	 * Event_Meta.meta_value = 'foo'))"
4230
+	 *
4231
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4232
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4233
+	 * @throws EE_Error
4234
+	 * @return string of SQL
4235
+	 */
4236
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4237
+	{
4238
+		$where_clauses = array();
4239
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4240
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4241
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4242
+				switch ($query_param) {
4243
+					case 'not':
4244
+					case 'NOT':
4245
+						$where_clauses[] = "! ("
4246
+										   . $this->_construct_condition_clause_recursive(
4247
+											   $op_and_value_or_sub_condition,
4248
+											   $glue
4249
+										   )
4250
+										   . ")";
4251
+						break;
4252
+					case 'and':
4253
+					case 'AND':
4254
+						$where_clauses[] = " ("
4255
+										   . $this->_construct_condition_clause_recursive(
4256
+											   $op_and_value_or_sub_condition,
4257
+											   ' AND '
4258
+										   )
4259
+										   . ")";
4260
+						break;
4261
+					case 'or':
4262
+					case 'OR':
4263
+						$where_clauses[] = " ("
4264
+										   . $this->_construct_condition_clause_recursive(
4265
+											   $op_and_value_or_sub_condition,
4266
+											   ' OR '
4267
+										   )
4268
+										   . ")";
4269
+						break;
4270
+				}
4271
+			} else {
4272
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4273
+				// if it's not a normal field, maybe it's a custom selection?
4274
+				if (! $field_obj) {
4275
+					if ($this->_custom_selections instanceof CustomSelects) {
4276
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4277
+					} else {
4278
+						throw new EE_Error(sprintf(__(
4279
+							"%s is neither a valid model field name, nor a custom selection",
4280
+							"event_espresso"
4281
+						), $query_param));
4282
+					}
4283
+				}
4284
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4285
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4286
+			}
4287
+		}
4288
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4289
+	}
4290
+
4291
+
4292
+
4293
+	/**
4294
+	 * Takes the input parameter and extract the table name (alias) and column name
4295
+	 *
4296
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4297
+	 * @throws EE_Error
4298
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4299
+	 */
4300
+	private function _deduce_column_name_from_query_param($query_param)
4301
+	{
4302
+		$field = $this->_deduce_field_from_query_param($query_param);
4303
+		if ($field) {
4304
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4305
+				$field->get_model_name(),
4306
+				$query_param
4307
+			);
4308
+			return $table_alias_prefix . $field->get_qualified_column();
4309
+		}
4310
+		if (
4311
+			$this->_custom_selections instanceof CustomSelects
4312
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4313
+		) {
4314
+			// maybe it's custom selection item?
4315
+			// if so, just use it as the "column name"
4316
+			return $query_param;
4317
+		}
4318
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4319
+			? implode(',', $this->_custom_selections->columnAliases())
4320
+			: '';
4321
+		throw new EE_Error(
4322
+			sprintf(
4323
+				__(
4324
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4325
+					"event_espresso"
4326
+				),
4327
+				$query_param,
4328
+				$custom_select_aliases
4329
+			)
4330
+		);
4331
+	}
4332
+
4333
+
4334
+
4335
+	/**
4336
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4337
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4338
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4339
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4340
+	 *
4341
+	 * @param string $condition_query_param_key
4342
+	 * @return string
4343
+	 */
4344
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4345
+	{
4346
+		$pos_of_star = strpos($condition_query_param_key, '*');
4347
+		if ($pos_of_star === false) {
4348
+			return $condition_query_param_key;
4349
+		}
4350
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4351
+		return $condition_query_param_sans_star;
4352
+	}
4353
+
4354
+
4355
+
4356
+	/**
4357
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4358
+	 *
4359
+	 * @param                            mixed      array | string    $op_and_value
4360
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4361
+	 * @throws EE_Error
4362
+	 * @return string
4363
+	 */
4364
+	private function _construct_op_and_value($op_and_value, $field_obj)
4365
+	{
4366
+		if (is_array($op_and_value)) {
4367
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4368
+			if (! $operator) {
4369
+				$php_array_like_string = array();
4370
+				foreach ($op_and_value as $key => $value) {
4371
+					$php_array_like_string[] = "$key=>$value";
4372
+				}
4373
+				throw new EE_Error(
4374
+					sprintf(
4375
+						__(
4376
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4377
+							"event_espresso"
4378
+						),
4379
+						implode(",", $php_array_like_string)
4380
+					)
4381
+				);
4382
+			}
4383
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4384
+		} else {
4385
+			$operator = '=';
4386
+			$value = $op_and_value;
4387
+		}
4388
+		// check to see if the value is actually another field
4389
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4390
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4391
+		}
4392
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4393
+			// in this case, the value should be an array, or at least a comma-separated list
4394
+			// it will need to handle a little differently
4395
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4396
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4397
+			return $operator . SP . $cleaned_value;
4398
+		}
4399
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4400
+			// the value should be an array with count of two.
4401
+			if (count($value) !== 2) {
4402
+				throw new EE_Error(
4403
+					sprintf(
4404
+						__(
4405
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4406
+							'event_espresso'
4407
+						),
4408
+						"BETWEEN"
4409
+					)
4410
+				);
4411
+			}
4412
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4413
+			return $operator . SP . $cleaned_value;
4414
+		}
4415
+		if (in_array($operator, $this->valid_null_style_operators())) {
4416
+			if ($value !== null) {
4417
+				throw new EE_Error(
4418
+					sprintf(
4419
+						__(
4420
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4421
+							"event_espresso"
4422
+						),
4423
+						$value,
4424
+						$operator
4425
+					)
4426
+				);
4427
+			}
4428
+			return $operator;
4429
+		}
4430
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4431
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4432
+			// remove other junk. So just treat it as a string.
4433
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4434
+		}
4435
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4436
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4437
+		}
4438
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
+			throw new EE_Error(
4440
+				sprintf(
4441
+					__(
4442
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4443
+						'event_espresso'
4444
+					),
4445
+					$operator,
4446
+					$operator
4447
+				)
4448
+			);
4449
+		}
4450
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4451
+			throw new EE_Error(
4452
+				sprintf(
4453
+					__(
4454
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4455
+						'event_espresso'
4456
+					),
4457
+					$operator,
4458
+					$operator
4459
+				)
4460
+			);
4461
+		}
4462
+		throw new EE_Error(
4463
+			sprintf(
4464
+				__(
4465
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4466
+					"event_espresso"
4467
+				),
4468
+				http_build_query($op_and_value)
4469
+			)
4470
+		);
4471
+	}
4472
+
4473
+
4474
+
4475
+	/**
4476
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4477
+	 *
4478
+	 * @param array                      $values
4479
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4480
+	 *                                              '%s'
4481
+	 * @return string
4482
+	 * @throws EE_Error
4483
+	 */
4484
+	public function _construct_between_value($values, $field_obj)
4485
+	{
4486
+		$cleaned_values = array();
4487
+		foreach ($values as $value) {
4488
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4489
+		}
4490
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4491
+	}
4492
+
4493
+
4494
+
4495
+	/**
4496
+	 * Takes an array or a comma-separated list of $values and cleans them
4497
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4498
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4499
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4500
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4501
+	 *
4502
+	 * @param mixed                      $values    array or comma-separated string
4503
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4504
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4505
+	 * @throws EE_Error
4506
+	 */
4507
+	public function _construct_in_value($values, $field_obj)
4508
+	{
4509
+		// check if the value is a CSV list
4510
+		if (is_string($values)) {
4511
+			// in which case, turn it into an array
4512
+			$values = explode(",", $values);
4513
+		}
4514
+		$cleaned_values = array();
4515
+		foreach ($values as $value) {
4516
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4517
+		}
4518
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4519
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4520
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4521
+		if (empty($cleaned_values)) {
4522
+			$all_fields = $this->field_settings();
4523
+			$a_field = array_shift($all_fields);
4524
+			$main_table = $this->_get_main_table();
4525
+			$cleaned_values[] = "SELECT "
4526
+								. $a_field->get_table_column()
4527
+								. " FROM "
4528
+								. $main_table->get_table_name()
4529
+								. " WHERE FALSE";
4530
+		}
4531
+		return "(" . implode(",", $cleaned_values) . ")";
4532
+	}
4533
+
4534
+
4535
+
4536
+	/**
4537
+	 * @param mixed                      $value
4538
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4539
+	 * @throws EE_Error
4540
+	 * @return false|null|string
4541
+	 */
4542
+	private function _wpdb_prepare_using_field($value, $field_obj)
4543
+	{
4544
+		/** @type WPDB $wpdb */
4545
+		global $wpdb;
4546
+		if ($field_obj instanceof EE_Model_Field_Base) {
4547
+			return $wpdb->prepare(
4548
+				$field_obj->get_wpdb_data_type(),
4549
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4550
+			);
4551
+		} //$field_obj should really just be a data type
4552
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4553
+			throw new EE_Error(
4554
+				sprintf(
4555
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4556
+					$field_obj,
4557
+					implode(",", $this->_valid_wpdb_data_types)
4558
+				)
4559
+			);
4560
+		}
4561
+		return $wpdb->prepare($field_obj, $value);
4562
+	}
4563
+
4564
+
4565
+
4566
+	/**
4567
+	 * Takes the input parameter and finds the model field that it indicates.
4568
+	 *
4569
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4570
+	 * @throws EE_Error
4571
+	 * @return EE_Model_Field_Base
4572
+	 */
4573
+	protected function _deduce_field_from_query_param($query_param_name)
4574
+	{
4575
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4576
+		// which will help us find the database table and column
4577
+		$query_param_parts = explode(".", $query_param_name);
4578
+		if (empty($query_param_parts)) {
4579
+			throw new EE_Error(sprintf(__(
4580
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4581
+				'event_espresso'
4582
+			), $query_param_name));
4583
+		}
4584
+		$number_of_parts = count($query_param_parts);
4585
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4586
+		if ($number_of_parts === 1) {
4587
+			$field_name = $last_query_param_part;
4588
+			$model_obj = $this;
4589
+		} else {// $number_of_parts >= 2
4590
+			// the last part is the column name, and there are only 2parts. therefore...
4591
+			$field_name = $last_query_param_part;
4592
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4593
+		}
4594
+		try {
4595
+			return $model_obj->field_settings_for($field_name);
4596
+		} catch (EE_Error $e) {
4597
+			return null;
4598
+		}
4599
+	}
4600
+
4601
+
4602
+
4603
+	/**
4604
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4605
+	 * alias and column which corresponds to it
4606
+	 *
4607
+	 * @param string $field_name
4608
+	 * @throws EE_Error
4609
+	 * @return string
4610
+	 */
4611
+	public function _get_qualified_column_for_field($field_name)
4612
+	{
4613
+		$all_fields = $this->field_settings();
4614
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4615
+		if ($field) {
4616
+			return $field->get_qualified_column();
4617
+		}
4618
+		throw new EE_Error(
4619
+			sprintf(
4620
+				__(
4621
+					"There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4622
+					'event_espresso'
4623
+				),
4624
+				$field_name,
4625
+				get_class($this)
4626
+			)
4627
+		);
4628
+	}
4629
+
4630
+
4631
+
4632
+	/**
4633
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4634
+	 * Example usage:
4635
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4636
+	 *      array(),
4637
+	 *      ARRAY_A,
4638
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4639
+	 *  );
4640
+	 * is equivalent to
4641
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4642
+	 * and
4643
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4644
+	 *      array(
4645
+	 *          array(
4646
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4647
+	 *          ),
4648
+	 *          ARRAY_A,
4649
+	 *          implode(
4650
+	 *              ', ',
4651
+	 *              array_merge(
4652
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4653
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4654
+	 *              )
4655
+	 *          )
4656
+	 *      )
4657
+	 *  );
4658
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4659
+	 *
4660
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4661
+	 *                                            and the one whose fields you are selecting for example: when querying
4662
+	 *                                            tickets model and selecting fields from the tickets model you would
4663
+	 *                                            leave this parameter empty, because no models are needed to join
4664
+	 *                                            between the queried model and the selected one. Likewise when
4665
+	 *                                            querying the datetime model and selecting fields from the tickets
4666
+	 *                                            model, it would also be left empty, because there is a direct
4667
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4668
+	 *                                            them together. However, when querying from the event model and
4669
+	 *                                            selecting fields from the ticket model, you should provide the string
4670
+	 *                                            'Datetime', indicating that the event model must first join to the
4671
+	 *                                            datetime model in order to find its relation to ticket model.
4672
+	 *                                            Also, when querying from the venue model and selecting fields from
4673
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4674
+	 *                                            indicating you need to join the venue model to the event model,
4675
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4676
+	 *                                            This string is used to deduce the prefix that gets added onto the
4677
+	 *                                            models' tables qualified columns
4678
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4679
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4680
+	 *                                            qualified column names
4681
+	 * @return array|string
4682
+	 */
4683
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4684
+	{
4685
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4686
+		$qualified_columns = array();
4687
+		foreach ($this->field_settings() as $field_name => $field) {
4688
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4689
+		}
4690
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4691
+	}
4692
+
4693
+
4694
+
4695
+	/**
4696
+	 * constructs the select use on special limit joins
4697
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4698
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4699
+	 * (as that is typically where the limits would be set).
4700
+	 *
4701
+	 * @param  string       $table_alias The table the select is being built for
4702
+	 * @param  mixed|string $limit       The limit for this select
4703
+	 * @return string                The final select join element for the query.
4704
+	 */
4705
+	public function _construct_limit_join_select($table_alias, $limit)
4706
+	{
4707
+		$SQL = '';
4708
+		foreach ($this->_tables as $table_obj) {
4709
+			if ($table_obj instanceof EE_Primary_Table) {
4710
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4711
+					? $table_obj->get_select_join_limit($limit)
4712
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4713
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4714
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4715
+					? $table_obj->get_select_join_limit_join($limit)
4716
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4717
+			}
4718
+		}
4719
+		return $SQL;
4720
+	}
4721
+
4722
+
4723
+
4724
+	/**
4725
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4726
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4727
+	 *
4728
+	 * @return string SQL
4729
+	 * @throws EE_Error
4730
+	 */
4731
+	public function _construct_internal_join()
4732
+	{
4733
+		$SQL = $this->_get_main_table()->get_table_sql();
4734
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4735
+		return $SQL;
4736
+	}
4737
+
4738
+
4739
+
4740
+	/**
4741
+	 * Constructs the SQL for joining all the tables on this model.
4742
+	 * Normally $alias should be the primary table's alias, but in cases where
4743
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4744
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4745
+	 * alias, this will construct SQL like:
4746
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4748
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4749
+	 *
4750
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4751
+	 * @return string
4752
+	 */
4753
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4754
+	{
4755
+		$SQL = '';
4756
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4757
+		foreach ($this->_tables as $table_obj) {
4758
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4759
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4760
+					// so we're joining to this table, meaning the table is already in
4761
+					// the FROM statement, BUT the primary table isn't. So we want
4762
+					// to add the inverse join sql
4763
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4764
+				} else {
4765
+					// just add a regular JOIN to this table from the primary table
4766
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4767
+				}
4768
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4769
+		}
4770
+		return $SQL;
4771
+	}
4772
+
4773
+
4774
+
4775
+	/**
4776
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4777
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4778
+	 * their data type (eg, '%s', '%d', etc)
4779
+	 *
4780
+	 * @return array
4781
+	 */
4782
+	public function _get_data_types()
4783
+	{
4784
+		$data_types = array();
4785
+		foreach ($this->field_settings() as $field_obj) {
4786
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4787
+			/** @var $field_obj EE_Model_Field_Base */
4788
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4789
+		}
4790
+		return $data_types;
4791
+	}
4792
+
4793
+
4794
+
4795
+	/**
4796
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4797
+	 *
4798
+	 * @param string $model_name
4799
+	 * @throws EE_Error
4800
+	 * @return EEM_Base
4801
+	 */
4802
+	public function get_related_model_obj($model_name)
4803
+	{
4804
+		$model_classname = "EEM_" . $model_name;
4805
+		if (! class_exists($model_classname)) {
4806
+			throw new EE_Error(sprintf(__(
4807
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4808
+				'event_espresso'
4809
+			), $model_name, $model_classname));
4810
+		}
4811
+		return call_user_func($model_classname . "::instance");
4812
+	}
4813
+
4814
+
4815
+
4816
+	/**
4817
+	 * Returns the array of EE_ModelRelations for this model.
4818
+	 *
4819
+	 * @return EE_Model_Relation_Base[]
4820
+	 */
4821
+	public function relation_settings()
4822
+	{
4823
+		return $this->_model_relations;
4824
+	}
4825
+
4826
+
4827
+
4828
+	/**
4829
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4830
+	 * because without THOSE models, this model probably doesn't have much purpose.
4831
+	 * (Eg, without an event, datetimes have little purpose.)
4832
+	 *
4833
+	 * @return EE_Belongs_To_Relation[]
4834
+	 */
4835
+	public function belongs_to_relations()
4836
+	{
4837
+		$belongs_to_relations = array();
4838
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4839
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4840
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4841
+			}
4842
+		}
4843
+		return $belongs_to_relations;
4844
+	}
4845
+
4846
+
4847
+
4848
+	/**
4849
+	 * Returns the specified EE_Model_Relation, or throws an exception
4850
+	 *
4851
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4852
+	 * @throws EE_Error
4853
+	 * @return EE_Model_Relation_Base
4854
+	 */
4855
+	public function related_settings_for($relation_name)
4856
+	{
4857
+		$relatedModels = $this->relation_settings();
4858
+		if (! array_key_exists($relation_name, $relatedModels)) {
4859
+			throw new EE_Error(
4860
+				sprintf(
4861
+					__(
4862
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4863
+						'event_espresso'
4864
+					),
4865
+					$relation_name,
4866
+					$this->_get_class_name(),
4867
+					implode(', ', array_keys($relatedModels))
4868
+				)
4869
+			);
4870
+		}
4871
+		return $relatedModels[ $relation_name ];
4872
+	}
4873
+
4874
+
4875
+
4876
+	/**
4877
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4878
+	 * fields
4879
+	 *
4880
+	 * @param string $fieldName
4881
+	 * @param boolean $include_db_only_fields
4882
+	 * @throws EE_Error
4883
+	 * @return EE_Model_Field_Base
4884
+	 */
4885
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4886
+	{
4887
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4888
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4889
+			throw new EE_Error(sprintf(
4890
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4891
+				$fieldName,
4892
+				get_class($this)
4893
+			));
4894
+		}
4895
+		return $fieldSettings[ $fieldName ];
4896
+	}
4897
+
4898
+
4899
+
4900
+	/**
4901
+	 * Checks if this field exists on this model
4902
+	 *
4903
+	 * @param string $fieldName a key in the model's _field_settings array
4904
+	 * @return boolean
4905
+	 */
4906
+	public function has_field($fieldName)
4907
+	{
4908
+		$fieldSettings = $this->field_settings(true);
4909
+		if (isset($fieldSettings[ $fieldName ])) {
4910
+			return true;
4911
+		}
4912
+		return false;
4913
+	}
4914
+
4915
+
4916
+
4917
+	/**
4918
+	 * Returns whether or not this model has a relation to the specified model
4919
+	 *
4920
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4921
+	 * @return boolean
4922
+	 */
4923
+	public function has_relation($relation_name)
4924
+	{
4925
+		$relations = $this->relation_settings();
4926
+		if (isset($relations[ $relation_name ])) {
4927
+			return true;
4928
+		}
4929
+		return false;
4930
+	}
4931
+
4932
+
4933
+
4934
+	/**
4935
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4936
+	 * Eg, on EE_Answer that would be ANS_ID field object
4937
+	 *
4938
+	 * @param $field_obj
4939
+	 * @return boolean
4940
+	 */
4941
+	public function is_primary_key_field($field_obj)
4942
+	{
4943
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4944
+	}
4945
+
4946
+
4947
+
4948
+	/**
4949
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4950
+	 * Eg, on EE_Answer that would be ANS_ID field object
4951
+	 *
4952
+	 * @return EE_Model_Field_Base
4953
+	 * @throws EE_Error
4954
+	 */
4955
+	public function get_primary_key_field()
4956
+	{
4957
+		if ($this->_primary_key_field === null) {
4958
+			foreach ($this->field_settings(true) as $field_obj) {
4959
+				if ($this->is_primary_key_field($field_obj)) {
4960
+					$this->_primary_key_field = $field_obj;
4961
+					break;
4962
+				}
4963
+			}
4964
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4965
+				throw new EE_Error(sprintf(
4966
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
4967
+					get_class($this)
4968
+				));
4969
+			}
4970
+		}
4971
+		return $this->_primary_key_field;
4972
+	}
4973
+
4974
+
4975
+
4976
+	/**
4977
+	 * Returns whether or not not there is a primary key on this model.
4978
+	 * Internally does some caching.
4979
+	 *
4980
+	 * @return boolean
4981
+	 */
4982
+	public function has_primary_key_field()
4983
+	{
4984
+		if ($this->_has_primary_key_field === null) {
4985
+			try {
4986
+				$this->get_primary_key_field();
4987
+				$this->_has_primary_key_field = true;
4988
+			} catch (EE_Error $e) {
4989
+				$this->_has_primary_key_field = false;
4990
+			}
4991
+		}
4992
+		return $this->_has_primary_key_field;
4993
+	}
4994
+
4995
+
4996
+
4997
+	/**
4998
+	 * Finds the first field of type $field_class_name.
4999
+	 *
5000
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5001
+	 *                                 EE_Foreign_Key_Field, etc
5002
+	 * @return EE_Model_Field_Base or null if none is found
5003
+	 */
5004
+	public function get_a_field_of_type($field_class_name)
5005
+	{
5006
+		foreach ($this->field_settings() as $field) {
5007
+			if ($field instanceof $field_class_name) {
5008
+				return $field;
5009
+			}
5010
+		}
5011
+		return null;
5012
+	}
5013
+
5014
+
5015
+
5016
+	/**
5017
+	 * Gets a foreign key field pointing to model.
5018
+	 *
5019
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5020
+	 * @return EE_Foreign_Key_Field_Base
5021
+	 * @throws EE_Error
5022
+	 */
5023
+	public function get_foreign_key_to($model_name)
5024
+	{
5025
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5026
+			foreach ($this->field_settings() as $field) {
5027
+				if (
5028
+					$field instanceof EE_Foreign_Key_Field_Base
5029
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5030
+				) {
5031
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5032
+					break;
5033
+				}
5034
+			}
5035
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5036
+				throw new EE_Error(sprintf(__(
5037
+					"There is no foreign key field pointing to model %s on model %s",
5038
+					'event_espresso'
5039
+				), $model_name, get_class($this)));
5040
+			}
5041
+		}
5042
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5043
+	}
5044
+
5045
+
5046
+
5047
+	/**
5048
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5049
+	 *
5050
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5051
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5052
+	 *                            Either one works
5053
+	 * @return string
5054
+	 */
5055
+	public function get_table_for_alias($table_alias)
5056
+	{
5057
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5058
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5059
+	}
5060
+
5061
+
5062
+
5063
+	/**
5064
+	 * Returns a flat array of all field son this model, instead of organizing them
5065
+	 * by table_alias as they are in the constructor.
5066
+	 *
5067
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5068
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5069
+	 */
5070
+	public function field_settings($include_db_only_fields = false)
5071
+	{
5072
+		if ($include_db_only_fields) {
5073
+			if ($this->_cached_fields === null) {
5074
+				$this->_cached_fields = array();
5075
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5076
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5077
+						$this->_cached_fields[ $field_name ] = $field_obj;
5078
+					}
5079
+				}
5080
+			}
5081
+			return $this->_cached_fields;
5082
+		}
5083
+		if ($this->_cached_fields_non_db_only === null) {
5084
+			$this->_cached_fields_non_db_only = array();
5085
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5086
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5087
+					/** @var $field_obj EE_Model_Field_Base */
5088
+					if (! $field_obj->is_db_only_field()) {
5089
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5090
+					}
5091
+				}
5092
+			}
5093
+		}
5094
+		return $this->_cached_fields_non_db_only;
5095
+	}
5096
+
5097
+
5098
+
5099
+	/**
5100
+	 *        cycle though array of attendees and create objects out of each item
5101
+	 *
5102
+	 * @access        private
5103
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5104
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5105
+	 *                           numerically indexed)
5106
+	 * @throws EE_Error
5107
+	 */
5108
+	protected function _create_objects($rows = array())
5109
+	{
5110
+		$array_of_objects = array();
5111
+		if (empty($rows)) {
5112
+			return array();
5113
+		}
5114
+		$count_if_model_has_no_primary_key = 0;
5115
+		$has_primary_key = $this->has_primary_key_field();
5116
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5117
+		foreach ((array) $rows as $row) {
5118
+			if (empty($row)) {
5119
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5120
+				return array();
5121
+			}
5122
+			// check if we've already set this object in the results array,
5123
+			// in which case there's no need to process it further (again)
5124
+			if ($has_primary_key) {
5125
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5126
+					$row,
5127
+					$primary_key_field->get_qualified_column(),
5128
+					$primary_key_field->get_table_column()
5129
+				);
5130
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5131
+					continue;
5132
+				}
5133
+			}
5134
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5135
+			if (! $classInstance) {
5136
+				throw new EE_Error(
5137
+					sprintf(
5138
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5139
+						$this->get_this_model_name(),
5140
+						http_build_query($row)
5141
+					)
5142
+				);
5143
+			}
5144
+			// set the timezone on the instantiated objects
5145
+			$classInstance->set_timezone($this->_timezone);
5146
+			// make sure if there is any timezone setting present that we set the timezone for the object
5147
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5148
+			$array_of_objects[ $key ] = $classInstance;
5149
+			// also, for all the relations of type BelongsTo, see if we can cache
5150
+			// those related models
5151
+			// (we could do this for other relations too, but if there are conditions
5152
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5153
+			// so it requires a little more thought than just caching them immediately...)
5154
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5155
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5156
+					// check if this model's INFO is present. If so, cache it on the model
5157
+					$other_model = $relation_obj->get_other_model();
5158
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5159
+					// if we managed to make a model object from the results, cache it on the main model object
5160
+					if ($other_model_obj_maybe) {
5161
+						// set timezone on these other model objects if they are present
5162
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5163
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5164
+					}
5165
+				}
5166
+			}
5167
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5168
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5169
+			// the field in the CustomSelects object
5170
+			if ($this->_custom_selections instanceof CustomSelects) {
5171
+				$classInstance->setCustomSelectsValues(
5172
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5173
+				);
5174
+			}
5175
+		}
5176
+		return $array_of_objects;
5177
+	}
5178
+
5179
+
5180
+	/**
5181
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5182
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5183
+	 *
5184
+	 * @param array $db_results_row
5185
+	 * @return array
5186
+	 */
5187
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5188
+	{
5189
+		$results = array();
5190
+		if ($this->_custom_selections instanceof CustomSelects) {
5191
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5192
+				if (isset($db_results_row[ $alias ])) {
5193
+					$results[ $alias ] = $this->convertValueToDataType(
5194
+						$db_results_row[ $alias ],
5195
+						$this->_custom_selections->getDataTypeForAlias($alias)
5196
+					);
5197
+				}
5198
+			}
5199
+		}
5200
+		return $results;
5201
+	}
5202
+
5203
+
5204
+	/**
5205
+	 * This will set the value for the given alias
5206
+	 * @param string $value
5207
+	 * @param string $datatype (one of %d, %s, %f)
5208
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5209
+	 */
5210
+	protected function convertValueToDataType($value, $datatype)
5211
+	{
5212
+		switch ($datatype) {
5213
+			case '%f':
5214
+				return (float) $value;
5215
+			case '%d':
5216
+				return (int) $value;
5217
+			default:
5218
+				return (string) $value;
5219
+		}
5220
+	}
5221
+
5222
+
5223
+	/**
5224
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5225
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5226
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5227
+	 * object (as set in the model_field!).
5228
+	 *
5229
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5230
+	 */
5231
+	public function create_default_object()
5232
+	{
5233
+		$this_model_fields_and_values = array();
5234
+		// setup the row using default values;
5235
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5236
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5237
+		}
5238
+		$className = $this->_get_class_name();
5239
+		$classInstance = EE_Registry::instance()
5240
+									->load_class($className, array($this_model_fields_and_values), false, false);
5241
+		return $classInstance;
5242
+	}
5243
+
5244
+
5245
+
5246
+	/**
5247
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5248
+	 *                             or an stdClass where each property is the name of a column,
5249
+	 * @return EE_Base_Class
5250
+	 * @throws EE_Error
5251
+	 */
5252
+	public function instantiate_class_from_array_or_object($cols_n_values)
5253
+	{
5254
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5255
+			$cols_n_values = get_object_vars($cols_n_values);
5256
+		}
5257
+		$primary_key = null;
5258
+		// make sure the array only has keys that are fields/columns on this model
5259
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5260
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5261
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5262
+		}
5263
+		$className = $this->_get_class_name();
5264
+		// check we actually found results that we can use to build our model object
5265
+		// if not, return null
5266
+		if ($this->has_primary_key_field()) {
5267
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5268
+				return null;
5269
+			}
5270
+		} elseif ($this->unique_indexes()) {
5271
+			$first_column = reset($this_model_fields_n_values);
5272
+			if (empty($first_column)) {
5273
+				return null;
5274
+			}
5275
+		}
5276
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5277
+		if ($primary_key) {
5278
+			$classInstance = $this->get_from_entity_map($primary_key);
5279
+			if (! $classInstance) {
5280
+				$classInstance = EE_Registry::instance()
5281
+											->load_class(
5282
+												$className,
5283
+												array($this_model_fields_n_values, $this->_timezone),
5284
+												true,
5285
+												false
5286
+											);
5287
+				// add this new object to the entity map
5288
+				$classInstance = $this->add_to_entity_map($classInstance);
5289
+			}
5290
+		} else {
5291
+			$classInstance = EE_Registry::instance()
5292
+										->load_class(
5293
+											$className,
5294
+											array($this_model_fields_n_values, $this->_timezone),
5295
+											true,
5296
+											false
5297
+										);
5298
+		}
5299
+		return $classInstance;
5300
+	}
5301
+
5302
+
5303
+
5304
+	/**
5305
+	 * Gets the model object from the  entity map if it exists
5306
+	 *
5307
+	 * @param int|string $id the ID of the model object
5308
+	 * @return EE_Base_Class
5309
+	 */
5310
+	public function get_from_entity_map($id)
5311
+	{
5312
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5313
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5314
+	}
5315
+
5316
+
5317
+
5318
+	/**
5319
+	 * add_to_entity_map
5320
+	 * Adds the object to the model's entity mappings
5321
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5322
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5323
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5324
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5325
+	 *        then this method should be called immediately after the update query
5326
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5327
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5328
+	 *
5329
+	 * @param    EE_Base_Class $object
5330
+	 * @throws EE_Error
5331
+	 * @return \EE_Base_Class
5332
+	 */
5333
+	public function add_to_entity_map(EE_Base_Class $object)
5334
+	{
5335
+		$className = $this->_get_class_name();
5336
+		if (! $object instanceof $className) {
5337
+			throw new EE_Error(sprintf(
5338
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5339
+				is_object($object) ? get_class($object) : $object,
5340
+				$className
5341
+			));
5342
+		}
5343
+		/** @var $object EE_Base_Class */
5344
+		if (! $object->ID()) {
5345
+			throw new EE_Error(sprintf(__(
5346
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5347
+				"event_espresso"
5348
+			), get_class($this)));
5349
+		}
5350
+		// double check it's not already there
5351
+		$classInstance = $this->get_from_entity_map($object->ID());
5352
+		if ($classInstance) {
5353
+			return $classInstance;
5354
+		}
5355
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5356
+		return $object;
5357
+	}
5358
+
5359
+
5360
+
5361
+	/**
5362
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5363
+	 * if no identifier is provided, then the entire entity map is emptied
5364
+	 *
5365
+	 * @param int|string $id the ID of the model object
5366
+	 * @return boolean
5367
+	 */
5368
+	public function clear_entity_map($id = null)
5369
+	{
5370
+		if (empty($id)) {
5371
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5372
+			return true;
5373
+		}
5374
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5375
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5376
+			return true;
5377
+		}
5378
+		return false;
5379
+	}
5380
+
5381
+
5382
+
5383
+	/**
5384
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5385
+	 * Given an array where keys are column (or column alias) names and values,
5386
+	 * returns an array of their corresponding field names and database values
5387
+	 *
5388
+	 * @param array $cols_n_values
5389
+	 * @return array
5390
+	 */
5391
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5392
+	{
5393
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5394
+	}
5395
+
5396
+
5397
+
5398
+	/**
5399
+	 * _deduce_fields_n_values_from_cols_n_values
5400
+	 * Given an array where keys are column (or column alias) names and values,
5401
+	 * returns an array of their corresponding field names and database values
5402
+	 *
5403
+	 * @param string $cols_n_values
5404
+	 * @return array
5405
+	 */
5406
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5407
+	{
5408
+		$this_model_fields_n_values = array();
5409
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5410
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5411
+				$cols_n_values,
5412
+				$table_obj->get_fully_qualified_pk_column(),
5413
+				$table_obj->get_pk_column()
5414
+			);
5415
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5416
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5417
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5418
+					if (! $field_obj->is_db_only_field()) {
5419
+						// prepare field as if its coming from db
5420
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5421
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5422
+					}
5423
+				}
5424
+			} else {
5425
+				// the table's rows existed. Use their values
5426
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5427
+					if (! $field_obj->is_db_only_field()) {
5428
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5429
+							$cols_n_values,
5430
+							$field_obj->get_qualified_column(),
5431
+							$field_obj->get_table_column()
5432
+						);
5433
+					}
5434
+				}
5435
+			}
5436
+		}
5437
+		return $this_model_fields_n_values;
5438
+	}
5439
+
5440
+
5441
+	/**
5442
+	 * @param $cols_n_values
5443
+	 * @param $qualified_column
5444
+	 * @param $regular_column
5445
+	 * @return null
5446
+	 * @throws EE_Error
5447
+	 * @throws ReflectionException
5448
+	 */
5449
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5450
+	{
5451
+		$value = null;
5452
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5453
+		// does the field on the model relate to this column retrieved from the db?
5454
+		// or is it a db-only field? (not relating to the model)
5455
+		if (isset($cols_n_values[ $qualified_column ])) {
5456
+			$value = $cols_n_values[ $qualified_column ];
5457
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5458
+			$value = $cols_n_values[ $regular_column ];
5459
+		} elseif (! empty($this->foreign_key_aliases)) {
5460
+			// no PK?  ok check if there is a foreign key alias set for this table
5461
+			// then check if that alias exists in the incoming data
5462
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5463
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5464
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5465
+					$value = $cols_n_values[ $FK_alias ];
5466
+					list($pk_class) = explode('.', $PK_column);
5467
+					$pk_model_name = "EEM_{$pk_class}";
5468
+					/** @var EEM_Base $pk_model */
5469
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5470
+					if ($pk_model instanceof EEM_Base) {
5471
+						// make sure object is pulled from db and added to entity map
5472
+						$pk_model->get_one_by_ID($value);
5473
+					}
5474
+					break;
5475
+				}
5476
+			}
5477
+		}
5478
+		return $value;
5479
+	}
5480
+
5481
+
5482
+
5483
+	/**
5484
+	 * refresh_entity_map_from_db
5485
+	 * Makes sure the model object in the entity map at $id assumes the values
5486
+	 * of the database (opposite of EE_base_Class::save())
5487
+	 *
5488
+	 * @param int|string $id
5489
+	 * @return EE_Base_Class
5490
+	 * @throws EE_Error
5491
+	 */
5492
+	public function refresh_entity_map_from_db($id)
5493
+	{
5494
+		$obj_in_map = $this->get_from_entity_map($id);
5495
+		if ($obj_in_map) {
5496
+			$wpdb_results = $this->_get_all_wpdb_results(
5497
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5498
+			);
5499
+			if ($wpdb_results && is_array($wpdb_results)) {
5500
+				$one_row = reset($wpdb_results);
5501
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5502
+					$obj_in_map->set_from_db($field_name, $db_value);
5503
+				}
5504
+				// clear the cache of related model objects
5505
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5506
+					$obj_in_map->clear_cache($relation_name, null, true);
5507
+				}
5508
+			}
5509
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5510
+			return $obj_in_map;
5511
+		}
5512
+		return $this->get_one_by_ID($id);
5513
+	}
5514
+
5515
+
5516
+
5517
+	/**
5518
+	 * refresh_entity_map_with
5519
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5520
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5521
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5522
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5523
+	 *
5524
+	 * @param int|string    $id
5525
+	 * @param EE_Base_Class $replacing_model_obj
5526
+	 * @return \EE_Base_Class
5527
+	 * @throws EE_Error
5528
+	 */
5529
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5530
+	{
5531
+		$obj_in_map = $this->get_from_entity_map($id);
5532
+		if ($obj_in_map) {
5533
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5534
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5535
+					$obj_in_map->set($field_name, $value);
5536
+				}
5537
+				// make the model object in the entity map's cache match the $replacing_model_obj
5538
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5539
+					$obj_in_map->clear_cache($relation_name, null, true);
5540
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5541
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5542
+					}
5543
+				}
5544
+			}
5545
+			return $obj_in_map;
5546
+		}
5547
+		$this->add_to_entity_map($replacing_model_obj);
5548
+		return $replacing_model_obj;
5549
+	}
5550
+
5551
+
5552
+
5553
+	/**
5554
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5555
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5556
+	 * require_once($this->_getClassName().".class.php");
5557
+	 *
5558
+	 * @return string
5559
+	 */
5560
+	private function _get_class_name()
5561
+	{
5562
+		return "EE_" . $this->get_this_model_name();
5563
+	}
5564
+
5565
+
5566
+
5567
+	/**
5568
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5569
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5570
+	 * it would be 'Events'.
5571
+	 *
5572
+	 * @param int $quantity
5573
+	 * @return string
5574
+	 */
5575
+	public function item_name($quantity = 1)
5576
+	{
5577
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5578
+	}
5579
+
5580
+
5581
+
5582
+	/**
5583
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5584
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5585
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5586
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5587
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5588
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5589
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5590
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5591
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5592
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5593
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5594
+	 *        return $previousReturnValue.$returnString;
5595
+	 * }
5596
+	 * require('EEM_Answer.model.php');
5597
+	 * $answer=EEM_Answer::instance();
5598
+	 * echo $answer->my_callback('monkeys',100);
5599
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5600
+	 *
5601
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5602
+	 * @param array  $args       array of original arguments passed to the function
5603
+	 * @throws EE_Error
5604
+	 * @return mixed whatever the plugin which calls add_filter decides
5605
+	 */
5606
+	public function __call($methodName, $args)
5607
+	{
5608
+		$className = get_class($this);
5609
+		$tagName = "FHEE__{$className}__{$methodName}";
5610
+		if (! has_filter($tagName)) {
5611
+			throw new EE_Error(
5612
+				sprintf(
5613
+					__(
5614
+						'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5615
+						'event_espresso'
5616
+					),
5617
+					$methodName,
5618
+					$className,
5619
+					$tagName,
5620
+					'<br />'
5621
+				)
5622
+			);
5623
+		}
5624
+		return apply_filters($tagName, null, $this, $args);
5625
+	}
5626
+
5627
+
5628
+
5629
+	/**
5630
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5631
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5632
+	 *
5633
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5634
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5635
+	 *                                                       the object's class name
5636
+	 *                                                       or object's ID
5637
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5638
+	 *                                                       exists in the database. If it does not, we add it
5639
+	 * @throws EE_Error
5640
+	 * @return EE_Base_Class
5641
+	 */
5642
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5643
+	{
5644
+		$className = $this->_get_class_name();
5645
+		if ($base_class_obj_or_id instanceof $className) {
5646
+			$model_object = $base_class_obj_or_id;
5647
+		} else {
5648
+			$primary_key_field = $this->get_primary_key_field();
5649
+			if (
5650
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5651
+				&& (
5652
+					is_int($base_class_obj_or_id)
5653
+					|| is_string($base_class_obj_or_id)
5654
+				)
5655
+			) {
5656
+				// assume it's an ID.
5657
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5658
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5659
+			} elseif (
5660
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5661
+				&& is_string($base_class_obj_or_id)
5662
+			) {
5663
+				// assume its a string representation of the object
5664
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5665
+			} else {
5666
+				throw new EE_Error(
5667
+					sprintf(
5668
+						__(
5669
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5670
+							'event_espresso'
5671
+						),
5672
+						$base_class_obj_or_id,
5673
+						$this->_get_class_name(),
5674
+						print_r($base_class_obj_or_id, true)
5675
+					)
5676
+				);
5677
+			}
5678
+		}
5679
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5680
+			$model_object->save();
5681
+		}
5682
+		return $model_object;
5683
+	}
5684
+
5685
+
5686
+
5687
+	/**
5688
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5689
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5690
+	 * returns it ID.
5691
+	 *
5692
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5693
+	 * @return int|string depending on the type of this model object's ID
5694
+	 * @throws EE_Error
5695
+	 */
5696
+	public function ensure_is_ID($base_class_obj_or_id)
5697
+	{
5698
+		$className = $this->_get_class_name();
5699
+		if ($base_class_obj_or_id instanceof $className) {
5700
+			/** @var $base_class_obj_or_id EE_Base_Class */
5701
+			$id = $base_class_obj_or_id->ID();
5702
+		} elseif (is_int($base_class_obj_or_id)) {
5703
+			// assume it's an ID
5704
+			$id = $base_class_obj_or_id;
5705
+		} elseif (is_string($base_class_obj_or_id)) {
5706
+			// assume its a string representation of the object
5707
+			$id = $base_class_obj_or_id;
5708
+		} else {
5709
+			throw new EE_Error(sprintf(
5710
+				__(
5711
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5712
+					'event_espresso'
5713
+				),
5714
+				$base_class_obj_or_id,
5715
+				$this->_get_class_name(),
5716
+				print_r($base_class_obj_or_id, true)
5717
+			));
5718
+		}
5719
+		return $id;
5720
+	}
5721
+
5722
+
5723
+
5724
+	/**
5725
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5726
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5727
+	 * been sanitized and converted into the appropriate domain.
5728
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5729
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5730
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5731
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5732
+	 * $EVT = EEM_Event::instance(); $old_setting =
5733
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5734
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5735
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5736
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5737
+	 *
5738
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5739
+	 * @return void
5740
+	 */
5741
+	public function assume_values_already_prepared_by_model_object(
5742
+		$values_already_prepared = self::not_prepared_by_model_object
5743
+	) {
5744
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5745
+	}
5746
+
5747
+
5748
+
5749
+	/**
5750
+	 * Read comments for assume_values_already_prepared_by_model_object()
5751
+	 *
5752
+	 * @return int
5753
+	 */
5754
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5755
+	{
5756
+		return $this->_values_already_prepared_by_model_object;
5757
+	}
5758
+
5759
+
5760
+
5761
+	/**
5762
+	 * Gets all the indexes on this model
5763
+	 *
5764
+	 * @return EE_Index[]
5765
+	 */
5766
+	public function indexes()
5767
+	{
5768
+		return $this->_indexes;
5769
+	}
5770
+
5771
+
5772
+
5773
+	/**
5774
+	 * Gets all the Unique Indexes on this model
5775
+	 *
5776
+	 * @return EE_Unique_Index[]
5777
+	 */
5778
+	public function unique_indexes()
5779
+	{
5780
+		$unique_indexes = array();
5781
+		foreach ($this->_indexes as $name => $index) {
5782
+			if ($index instanceof EE_Unique_Index) {
5783
+				$unique_indexes [ $name ] = $index;
5784
+			}
5785
+		}
5786
+		return $unique_indexes;
5787
+	}
5788
+
5789
+
5790
+
5791
+	/**
5792
+	 * Gets all the fields which, when combined, make the primary key.
5793
+	 * This is usually just an array with 1 element (the primary key), but in cases
5794
+	 * where there is no primary key, it's a combination of fields as defined
5795
+	 * on a primary index
5796
+	 *
5797
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5798
+	 * @throws EE_Error
5799
+	 */
5800
+	public function get_combined_primary_key_fields()
5801
+	{
5802
+		foreach ($this->indexes() as $index) {
5803
+			if ($index instanceof EE_Primary_Key_Index) {
5804
+				return $index->fields();
5805
+			}
5806
+		}
5807
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5808
+	}
5809
+
5810
+
5811
+
5812
+	/**
5813
+	 * Used to build a primary key string (when the model has no primary key),
5814
+	 * which can be used a unique string to identify this model object.
5815
+	 *
5816
+	 * @param array $fields_n_values keys are field names, values are their values.
5817
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5818
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5819
+	 *                               before passing it to this function (that will convert it from columns-n-values
5820
+	 *                               to field-names-n-values).
5821
+	 * @return string
5822
+	 * @throws EE_Error
5823
+	 */
5824
+	public function get_index_primary_key_string($fields_n_values)
5825
+	{
5826
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5827
+			$fields_n_values,
5828
+			$this->get_combined_primary_key_fields()
5829
+		);
5830
+		return http_build_query($cols_n_values_for_primary_key_index);
5831
+	}
5832
+
5833
+
5834
+
5835
+	/**
5836
+	 * Gets the field values from the primary key string
5837
+	 *
5838
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5839
+	 * @param string $index_primary_key_string
5840
+	 * @return null|array
5841
+	 * @throws EE_Error
5842
+	 */
5843
+	public function parse_index_primary_key_string($index_primary_key_string)
5844
+	{
5845
+		$key_fields = $this->get_combined_primary_key_fields();
5846
+		// check all of them are in the $id
5847
+		$key_vals_in_combined_pk = array();
5848
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5849
+		foreach ($key_fields as $key_field_name => $field_obj) {
5850
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5851
+				return null;
5852
+			}
5853
+		}
5854
+		return $key_vals_in_combined_pk;
5855
+	}
5856
+
5857
+
5858
+
5859
+	/**
5860
+	 * verifies that an array of key-value pairs for model fields has a key
5861
+	 * for each field comprising the primary key index
5862
+	 *
5863
+	 * @param array $key_vals
5864
+	 * @return boolean
5865
+	 * @throws EE_Error
5866
+	 */
5867
+	public function has_all_combined_primary_key_fields($key_vals)
5868
+	{
5869
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5870
+		foreach ($keys_it_should_have as $key) {
5871
+			if (! isset($key_vals[ $key ])) {
5872
+				return false;
5873
+			}
5874
+		}
5875
+		return true;
5876
+	}
5877
+
5878
+
5879
+
5880
+	/**
5881
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5882
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5883
+	 *
5884
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5885
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5886
+	 * @throws EE_Error
5887
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5888
+	 *                                                              indexed)
5889
+	 */
5890
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5891
+	{
5892
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5893
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5894
+		} elseif (is_array($model_object_or_attributes_array)) {
5895
+			$attributes_array = $model_object_or_attributes_array;
5896
+		} else {
5897
+			throw new EE_Error(sprintf(__(
5898
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5899
+				"event_espresso"
5900
+			), $model_object_or_attributes_array));
5901
+		}
5902
+		// even copies obviously won't have the same ID, so remove the primary key
5903
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5904
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5905
+			unset($attributes_array[ $this->primary_key_name() ]);
5906
+		}
5907
+		if (isset($query_params[0])) {
5908
+			$query_params[0] = array_merge($attributes_array, $query_params);
5909
+		} else {
5910
+			$query_params[0] = $attributes_array;
5911
+		}
5912
+		return $this->get_all($query_params);
5913
+	}
5914
+
5915
+
5916
+
5917
+	/**
5918
+	 * Gets the first copy we find. See get_all_copies for more details
5919
+	 *
5920
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5921
+	 * @param array $query_params
5922
+	 * @return EE_Base_Class
5923
+	 * @throws EE_Error
5924
+	 */
5925
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5926
+	{
5927
+		if (! is_array($query_params)) {
5928
+			EE_Error::doing_it_wrong(
5929
+				'EEM_Base::get_one_copy',
5930
+				sprintf(
5931
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5932
+					gettype($query_params)
5933
+				),
5934
+				'4.6.0'
5935
+			);
5936
+			$query_params = array();
5937
+		}
5938
+		$query_params['limit'] = 1;
5939
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5940
+		if (is_array($copies)) {
5941
+			return array_shift($copies);
5942
+		}
5943
+		return null;
5944
+	}
5945
+
5946
+
5947
+
5948
+	/**
5949
+	 * Updates the item with the specified id. Ignores default query parameters because
5950
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5951
+	 *
5952
+	 * @param array      $fields_n_values keys are field names, values are their new values
5953
+	 * @param int|string $id              the value of the primary key to update
5954
+	 * @return int number of rows updated
5955
+	 * @throws EE_Error
5956
+	 */
5957
+	public function update_by_ID($fields_n_values, $id)
5958
+	{
5959
+		$query_params = array(
5960
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5961
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5962
+		);
5963
+		return $this->update($fields_n_values, $query_params);
5964
+	}
5965
+
5966
+
5967
+
5968
+	/**
5969
+	 * Changes an operator which was supplied to the models into one usable in SQL
5970
+	 *
5971
+	 * @param string $operator_supplied
5972
+	 * @return string an operator which can be used in SQL
5973
+	 * @throws EE_Error
5974
+	 */
5975
+	private function _prepare_operator_for_sql($operator_supplied)
5976
+	{
5977
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5978
+			: null;
5979
+		if ($sql_operator) {
5980
+			return $sql_operator;
5981
+		}
5982
+		throw new EE_Error(
5983
+			sprintf(
5984
+				__(
5985
+					"The operator '%s' is not in the list of valid operators: %s",
5986
+					"event_espresso"
5987
+				),
5988
+				$operator_supplied,
5989
+				implode(",", array_keys($this->_valid_operators))
5990
+			)
5991
+		);
5992
+	}
5993
+
5994
+
5995
+
5996
+	/**
5997
+	 * Gets the valid operators
5998
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5999
+	 */
6000
+	public function valid_operators()
6001
+	{
6002
+		return $this->_valid_operators;
6003
+	}
6004
+
6005
+
6006
+
6007
+	/**
6008
+	 * Gets the between-style operators (take 2 arguments).
6009
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6010
+	 */
6011
+	public function valid_between_style_operators()
6012
+	{
6013
+		return array_intersect(
6014
+			$this->valid_operators(),
6015
+			$this->_between_style_operators
6016
+		);
6017
+	}
6018
+
6019
+	/**
6020
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6021
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6022
+	 */
6023
+	public function valid_like_style_operators()
6024
+	{
6025
+		return array_intersect(
6026
+			$this->valid_operators(),
6027
+			$this->_like_style_operators
6028
+		);
6029
+	}
6030
+
6031
+	/**
6032
+	 * Gets the "in"-style operators
6033
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6034
+	 */
6035
+	public function valid_in_style_operators()
6036
+	{
6037
+		return array_intersect(
6038
+			$this->valid_operators(),
6039
+			$this->_in_style_operators
6040
+		);
6041
+	}
6042
+
6043
+	/**
6044
+	 * Gets the "null"-style operators (accept no arguments)
6045
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6046
+	 */
6047
+	public function valid_null_style_operators()
6048
+	{
6049
+		return array_intersect(
6050
+			$this->valid_operators(),
6051
+			$this->_null_style_operators
6052
+		);
6053
+	}
6054
+
6055
+	/**
6056
+	 * Gets an array where keys are the primary keys and values are their 'names'
6057
+	 * (as determined by the model object's name() function, which is often overridden)
6058
+	 *
6059
+	 * @param array $query_params like get_all's
6060
+	 * @return string[]
6061
+	 * @throws EE_Error
6062
+	 */
6063
+	public function get_all_names($query_params = array())
6064
+	{
6065
+		$objs = $this->get_all($query_params);
6066
+		$names = array();
6067
+		foreach ($objs as $obj) {
6068
+			$names[ $obj->ID() ] = $obj->name();
6069
+		}
6070
+		return $names;
6071
+	}
6072
+
6073
+
6074
+
6075
+	/**
6076
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6077
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6078
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6079
+	 * array_keys() on $model_objects.
6080
+	 *
6081
+	 * @param \EE_Base_Class[] $model_objects
6082
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6083
+	 *                                               in the returned array
6084
+	 * @return array
6085
+	 * @throws EE_Error
6086
+	 */
6087
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6088
+	{
6089
+		if (! $this->has_primary_key_field()) {
6090
+			if (WP_DEBUG) {
6091
+				EE_Error::add_error(
6092
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6093
+					__FILE__,
6094
+					__FUNCTION__,
6095
+					__LINE__
6096
+				);
6097
+			}
6098
+		}
6099
+		$IDs = array();
6100
+		foreach ($model_objects as $model_object) {
6101
+			$id = $model_object->ID();
6102
+			if (! $id) {
6103
+				if ($filter_out_empty_ids) {
6104
+					continue;
6105
+				}
6106
+				if (WP_DEBUG) {
6107
+					EE_Error::add_error(
6108
+						__(
6109
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6110
+							'event_espresso'
6111
+						),
6112
+						__FILE__,
6113
+						__FUNCTION__,
6114
+						__LINE__
6115
+					);
6116
+				}
6117
+			}
6118
+			$IDs[] = $id;
6119
+		}
6120
+		return $IDs;
6121
+	}
6122
+
6123
+
6124
+
6125
+	/**
6126
+	 * Returns the string used in capabilities relating to this model. If there
6127
+	 * are no capabilities that relate to this model returns false
6128
+	 *
6129
+	 * @return string|false
6130
+	 */
6131
+	public function cap_slug()
6132
+	{
6133
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6134
+	}
6135
+
6136
+
6137
+
6138
+	/**
6139
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6140
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6141
+	 * only returns the cap restrictions array in that context (ie, the array
6142
+	 * at that key)
6143
+	 *
6144
+	 * @param string $context
6145
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6146
+	 * @throws EE_Error
6147
+	 */
6148
+	public function cap_restrictions($context = EEM_Base::caps_read)
6149
+	{
6150
+		EEM_Base::verify_is_valid_cap_context($context);
6151
+		// check if we ought to run the restriction generator first
6152
+		if (
6153
+			isset($this->_cap_restriction_generators[ $context ])
6154
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6155
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6156
+		) {
6157
+			$this->_cap_restrictions[ $context ] = array_merge(
6158
+				$this->_cap_restrictions[ $context ],
6159
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6160
+			);
6161
+		}
6162
+		// and make sure we've finalized the construction of each restriction
6163
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6164
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6165
+				$where_conditions_obj->_finalize_construct($this);
6166
+			}
6167
+		}
6168
+		return $this->_cap_restrictions[ $context ];
6169
+	}
6170
+
6171
+
6172
+
6173
+	/**
6174
+	 * Indicating whether or not this model thinks its a wp core model
6175
+	 *
6176
+	 * @return boolean
6177
+	 */
6178
+	public function is_wp_core_model()
6179
+	{
6180
+		return $this->_wp_core_model;
6181
+	}
6182
+
6183
+
6184
+
6185
+	/**
6186
+	 * Gets all the caps that are missing which impose a restriction on
6187
+	 * queries made in this context
6188
+	 *
6189
+	 * @param string $context one of EEM_Base::caps_ constants
6190
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6191
+	 * @throws EE_Error
6192
+	 */
6193
+	public function caps_missing($context = EEM_Base::caps_read)
6194
+	{
6195
+		$missing_caps = array();
6196
+		$cap_restrictions = $this->cap_restrictions($context);
6197
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6198
+			if (
6199
+				! EE_Capabilities::instance()
6200
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6201
+			) {
6202
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6203
+			}
6204
+		}
6205
+		return $missing_caps;
6206
+	}
6207
+
6208
+
6209
+
6210
+	/**
6211
+	 * Gets the mapping from capability contexts to action strings used in capability names
6212
+	 *
6213
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6214
+	 * one of 'read', 'edit', or 'delete'
6215
+	 */
6216
+	public function cap_contexts_to_cap_action_map()
6217
+	{
6218
+		return apply_filters(
6219
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6220
+			$this->_cap_contexts_to_cap_action_map,
6221
+			$this
6222
+		);
6223
+	}
6224
+
6225
+
6226
+
6227
+	/**
6228
+	 * Gets the action string for the specified capability context
6229
+	 *
6230
+	 * @param string $context
6231
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6232
+	 * @throws EE_Error
6233
+	 */
6234
+	public function cap_action_for_context($context)
6235
+	{
6236
+		$mapping = $this->cap_contexts_to_cap_action_map();
6237
+		if (isset($mapping[ $context ])) {
6238
+			return $mapping[ $context ];
6239
+		}
6240
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6241
+			return $action;
6242
+		}
6243
+		throw new EE_Error(
6244
+			sprintf(
6245
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6246
+				$context,
6247
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6248
+			)
6249
+		);
6250
+	}
6251
+
6252
+
6253
+
6254
+	/**
6255
+	 * Returns all the capability contexts which are valid when querying models
6256
+	 *
6257
+	 * @return array
6258
+	 */
6259
+	public static function valid_cap_contexts()
6260
+	{
6261
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6262
+			self::caps_read,
6263
+			self::caps_read_admin,
6264
+			self::caps_edit,
6265
+			self::caps_delete,
6266
+		));
6267
+	}
6268
+
6269
+
6270
+
6271
+	/**
6272
+	 * Returns all valid options for 'default_where_conditions'
6273
+	 *
6274
+	 * @return array
6275
+	 */
6276
+	public static function valid_default_where_conditions()
6277
+	{
6278
+		return array(
6279
+			EEM_Base::default_where_conditions_all,
6280
+			EEM_Base::default_where_conditions_this_only,
6281
+			EEM_Base::default_where_conditions_others_only,
6282
+			EEM_Base::default_where_conditions_minimum_all,
6283
+			EEM_Base::default_where_conditions_minimum_others,
6284
+			EEM_Base::default_where_conditions_none
6285
+		);
6286
+	}
6287
+
6288
+	// public static function default_where_conditions_full
6289
+	/**
6290
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6291
+	 *
6292
+	 * @param string $context
6293
+	 * @return bool
6294
+	 * @throws EE_Error
6295
+	 */
6296
+	public static function verify_is_valid_cap_context($context)
6297
+	{
6298
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6299
+		if (in_array($context, $valid_cap_contexts)) {
6300
+			return true;
6301
+		}
6302
+		throw new EE_Error(
6303
+			sprintf(
6304
+				__(
6305
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6306
+					'event_espresso'
6307
+				),
6308
+				$context,
6309
+				'EEM_Base',
6310
+				implode(',', $valid_cap_contexts)
6311
+			)
6312
+		);
6313
+	}
6314
+
6315
+
6316
+
6317
+	/**
6318
+	 * Clears all the models field caches. This is only useful when a sub-class
6319
+	 * might have added a field or something and these caches might be invalidated
6320
+	 */
6321
+	protected function _invalidate_field_caches()
6322
+	{
6323
+		$this->_cache_foreign_key_to_fields = array();
6324
+		$this->_cached_fields = null;
6325
+		$this->_cached_fields_non_db_only = null;
6326
+	}
6327
+
6328
+
6329
+
6330
+	/**
6331
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6332
+	 * (eg "and", "or", "not").
6333
+	 *
6334
+	 * @return array
6335
+	 */
6336
+	public function logic_query_param_keys()
6337
+	{
6338
+		return $this->_logic_query_param_keys;
6339
+	}
6340
+
6341
+
6342
+
6343
+	/**
6344
+	 * Determines whether or not the where query param array key is for a logic query param.
6345
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6346
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6347
+	 *
6348
+	 * @param $query_param_key
6349
+	 * @return bool
6350
+	 */
6351
+	public function is_logic_query_param_key($query_param_key)
6352
+	{
6353
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6354
+			if (
6355
+				$query_param_key === $logic_query_param_key
6356
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6357
+			) {
6358
+				return true;
6359
+			}
6360
+		}
6361
+		return false;
6362
+	}
6363
+
6364
+	/**
6365
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6366
+	 * @since 4.9.74.p
6367
+	 * @return boolean
6368
+	 */
6369
+	public function hasPassword()
6370
+	{
6371
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6372
+		if ($this->has_password_field === null) {
6373
+			$password_field = $this->getPasswordField();
6374
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6375
+		}
6376
+		return $this->has_password_field;
6377
+	}
6378
+
6379
+	/**
6380
+	 * Returns the password field on this model, if there is one
6381
+	 * @since 4.9.74.p
6382
+	 * @return EE_Password_Field|null
6383
+	 */
6384
+	public function getPasswordField()
6385
+	{
6386
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6387
+		// there's no need to search for it. If we don't know yet, then find out
6388
+		if ($this->has_password_field === null && $this->password_field === null) {
6389
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6390
+		}
6391
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6392
+		return $this->password_field;
6393
+	}
6394
+
6395
+
6396
+	/**
6397
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6398
+	 * @since 4.9.74.p
6399
+	 * @return EE_Model_Field_Base[]
6400
+	 * @throws EE_Error
6401
+	 */
6402
+	public function getPasswordProtectedFields()
6403
+	{
6404
+		$password_field = $this->getPasswordField();
6405
+		$fields = array();
6406
+		if ($password_field instanceof EE_Password_Field) {
6407
+			$field_names = $password_field->protectedFields();
6408
+			foreach ($field_names as $field_name) {
6409
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6410
+			}
6411
+		}
6412
+		return $fields;
6413
+	}
6414
+
6415
+
6416
+	/**
6417
+	 * Checks if the current user can perform the requested action on this model
6418
+	 * @since 4.9.74.p
6419
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6420
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6421
+	 * @return bool
6422
+	 * @throws EE_Error
6423
+	 * @throws InvalidArgumentException
6424
+	 * @throws InvalidDataTypeException
6425
+	 * @throws InvalidInterfaceException
6426
+	 * @throws ReflectionException
6427
+	 * @throws UnexpectedEntityException
6428
+	 */
6429
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6430
+	{
6431
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6432
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6433
+		}
6434
+		if (!is_array($model_obj_or_fields_n_values)) {
6435
+			throw new UnexpectedEntityException(
6436
+				$model_obj_or_fields_n_values,
6437
+				'EE_Base_Class',
6438
+				sprintf(
6439
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6440
+					__FUNCTION__
6441
+				)
6442
+			);
6443
+		}
6444
+		return $this->exists(
6445
+			$this->alter_query_params_to_restrict_by_ID(
6446
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6447
+				array(
6448
+					'default_where_conditions' => 'none',
6449
+					'caps'                     => $cap_to_check,
6450
+				)
6451
+			)
6452
+		);
6453
+	}
6454
+
6455
+	/**
6456
+	 * Returns the query param where conditions key to the password affecting this model.
6457
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6458
+	 * @since 4.9.74.p
6459
+	 * @return null|string
6460
+	 * @throws EE_Error
6461
+	 * @throws InvalidArgumentException
6462
+	 * @throws InvalidDataTypeException
6463
+	 * @throws InvalidInterfaceException
6464
+	 * @throws ModelConfigurationException
6465
+	 * @throws ReflectionException
6466
+	 */
6467
+	public function modelChainAndPassword()
6468
+	{
6469
+		if ($this->model_chain_to_password === null) {
6470
+			throw new ModelConfigurationException(
6471
+				$this,
6472
+				esc_html_x(
6473
+				// @codingStandardsIgnoreStart
6474
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6475
+					// @codingStandardsIgnoreEnd
6476
+					'1: model name',
6477
+					'event_espresso'
6478
+				)
6479
+			);
6480
+		}
6481
+		if ($this->model_chain_to_password === '') {
6482
+			$model_with_password = $this;
6483
+		} else {
6484
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6485
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6486
+			} else {
6487
+				$last_model_in_chain = $this->model_chain_to_password;
6488
+			}
6489
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6490
+		}
6491
+
6492
+		$password_field = $model_with_password->getPasswordField();
6493
+		if ($password_field instanceof EE_Password_Field) {
6494
+			$password_field_name = $password_field->get_name();
6495
+		} else {
6496
+			throw new ModelConfigurationException(
6497
+				$this,
6498
+				sprintf(
6499
+					esc_html_x(
6500
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6501
+						'1: model name, 2: special string',
6502
+						'event_espresso'
6503
+					),
6504
+					$model_with_password->get_this_model_name(),
6505
+					$this->model_chain_to_password
6506
+				)
6507
+			);
6508
+		}
6509
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6510
+	}
6511
+
6512
+	/**
6513
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6514
+	 * or if this model itself has a password affecting access to some of its other fields.
6515
+	 * @since 4.9.74.p
6516
+	 * @return boolean
6517
+	 */
6518
+	public function restrictedByRelatedModelPassword()
6519
+	{
6520
+		return $this->model_chain_to_password !== null;
6521
+	}
6522 6522
 }
Please login to merge, or discard this patch.
Spacing   +226 added lines, -226 removed lines patch added patch discarded remove patch
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
     protected function __construct($timezone = null)
555 555
     {
556 556
         // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
557
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
558 558
             throw new EE_Error(
559 559
                 sprintf(
560 560
                     __(
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
          *
578 578
          * @var EE_Table_Base[] $_tables
579 579
          */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
580
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
581 581
         foreach ($this->_tables as $table_alias => $table_obj) {
582 582
             /** @var $table_obj EE_Table_Base */
583 583
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -592,10 +592,10 @@  discard block
 block discarded – undo
592 592
          *
593 593
          * @param EE_Model_Field_Base[] $_fields
594 594
          */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
595
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
596 596
         $this->_invalidate_field_caches();
597 597
         foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
598
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
599 599
                 throw new EE_Error(sprintf(__(
600 600
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601 601
                     'event_espresso'
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
          * @param EE_Model_Relation_Base[] $_model_relations
627 627
          */
628 628
         $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
629
+            'FHEE__'.get_class($this).'__construct__model_relations',
630 630
             $this->_model_relations
631 631
         );
632 632
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
         }
640 640
         $this->set_timezone($timezone);
641 641
         // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
642
+        if ( ! $this->_default_where_conditions_strategy) {
643 643
             // nothing was set during child constructor, so set default
644 644
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645 645
         }
646 646
         $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
647
+        if ( ! $this->_minimum_where_conditions_strategy) {
648 648
             // nothing was set during child constructor, so set default
649 649
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650 650
         }
@@ -657,8 +657,8 @@  discard block
 block discarded – undo
657 657
         // initialize the standard cap restriction generators if none were specified by the child constructor
658 658
         if ($this->_cap_restriction_generators !== false) {
659 659
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
660
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
661
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
662 662
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663 663
                         new EE_Restriction_Generator_Protected(),
664 664
                         $cap_context,
@@ -670,10 +670,10 @@  discard block
 block discarded – undo
670 670
         // if there are cap restriction generators, use them to make the default cap restrictions
671 671
         if ($this->_cap_restriction_generators !== false) {
672 672
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
673
+                if ( ! $generator_object) {
674 674
                     continue;
675 675
                 }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
676
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
677 677
                     throw new EE_Error(
678 678
                         sprintf(
679 679
                             __(
@@ -686,12 +686,12 @@  discard block
 block discarded – undo
686 686
                     );
687 687
                 }
688 688
                 $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
689
+                if ( ! $generator_object->construction_finalized()) {
690 690
                     $generator_object->_construct_finalize($this, $action);
691 691
                 }
692 692
             }
693 693
         }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
694
+        do_action('AHEE__'.get_class($this).'__construct__end');
695 695
     }
696 696
 
697 697
 
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
     public static function instance($timezone = null)
739 739
     {
740 740
         // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
741
+        if ( ! static::$_instance instanceof static) {
742 742
             // instantiate Espresso_model
743 743
             static::$_instance = new static(
744 744
                 $timezone,
@@ -777,7 +777,7 @@  discard block
 block discarded – undo
777 777
             foreach ($r->getDefaultProperties() as $property => $value) {
778 778
                 // don't set instance to null like it was originally,
779 779
                 // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
780
+                if ( ! isset($static_properties[$property])) {
781 781
                     static::$_instance->{$property} = $value;
782 782
                 }
783 783
             }
@@ -801,7 +801,7 @@  discard block
 block discarded – undo
801 801
      */
802 802
     private static function getLoader()
803 803
     {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
804
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
805 805
             EEM_Base::$loader = LoaderFactory::getLoader();
806 806
         }
807 807
         return EEM_Base::$loader;
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
      */
822 822
     public function status_array($translated = false)
823 823
     {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
824
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
825 825
             return array();
826 826
         }
827 827
         $model_name = $this->get_this_model_name();
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830 830
         $status_array = array();
831 831
         foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
832
+            $status_array[$status->ID()] = $status->get('STS_code');
833 833
         }
834 834
         return $translated
835 835
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -890,7 +890,7 @@  discard block
 block discarded – undo
890 890
     {
891 891
         $wp_user_field_name = $this->wp_user_field_name();
892 892
         if ($wp_user_field_name) {
893
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
893
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
894 894
         }
895 895
         return $query_params;
896 896
     }
@@ -908,17 +908,17 @@  discard block
 block discarded – undo
908 908
     public function wp_user_field_name()
909 909
     {
910 910
         try {
911
-            if (! empty($this->_model_chain_to_wp_user)) {
911
+            if ( ! empty($this->_model_chain_to_wp_user)) {
912 912
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
913 913
                 $last_model_name = end($models_to_follow_to_wp_users);
914 914
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
915
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
915
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
916 916
             } else {
917 917
                 $model_with_fk_to_wp_users = $this;
918 918
                 $model_chain_to_wp_user = '';
919 919
             }
920 920
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
921
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
921
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
922 922
         } catch (EE_Error $e) {
923 923
             return false;
924 924
         }
@@ -995,11 +995,11 @@  discard block
 block discarded – undo
995 995
         if ($this->_custom_selections instanceof CustomSelects) {
996 996
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
997 997
             $select_expressions .= $select_expressions
998
-                ? ', ' . $custom_expressions
998
+                ? ', '.$custom_expressions
999 999
                 : $custom_expressions;
1000 1000
         }
1001 1001
 
1002
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1002
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1003 1003
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1004 1004
     }
1005 1005
 
@@ -1016,7 +1016,7 @@  discard block
 block discarded – undo
1016 1016
      */
1017 1017
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1018 1018
     {
1019
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020 1020
             return null;
1021 1021
         }
1022 1022
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1065,7 +1065,7 @@  discard block
 block discarded – undo
1065 1065
         if (is_array($columns_to_select)) {
1066 1066
             $select_sql_array = array();
1067 1067
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1068
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069 1069
                     throw new EE_Error(
1070 1070
                         sprintf(
1071 1071
                             __(
@@ -1077,7 +1077,7 @@  discard block
 block discarded – undo
1077 1077
                         )
1078 1078
                     );
1079 1079
                 }
1080
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081 1081
                     throw new EE_Error(
1082 1082
                         sprintf(
1083 1083
                             esc_html__(
@@ -1156,12 +1156,12 @@  discard block
 block discarded – undo
1156 1156
      */
1157 1157
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1158 1158
     {
1159
-        if (! isset($query_params[0])) {
1159
+        if ( ! isset($query_params[0])) {
1160 1160
             $query_params[0] = array();
1161 1161
         }
1162 1162
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1163 1163
         if ($conditions_from_id === null) {
1164
-            $query_params[0][ $this->primary_key_name() ] = $id;
1164
+            $query_params[0][$this->primary_key_name()] = $id;
1165 1165
         } else {
1166 1166
             // no primary key, so the $id must be from the get_index_primary_key_string()
1167 1167
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1181,7 +1181,7 @@  discard block
 block discarded – undo
1181 1181
      */
1182 1182
     public function get_one($query_params = array())
1183 1183
     {
1184
-        if (! is_array($query_params)) {
1184
+        if ( ! is_array($query_params)) {
1185 1185
             EE_Error::doing_it_wrong(
1186 1186
                 'EEM_Base::get_one',
1187 1187
                 sprintf(
@@ -1379,7 +1379,7 @@  discard block
 block discarded – undo
1379 1379
                 return array();
1380 1380
             }
1381 1381
         }
1382
-        if (! is_array($query_params)) {
1382
+        if ( ! is_array($query_params)) {
1383 1383
             EE_Error::doing_it_wrong(
1384 1384
                 'EEM_Base::_get_consecutive',
1385 1385
                 sprintf(
@@ -1391,7 +1391,7 @@  discard block
 block discarded – undo
1391 1391
             $query_params = array();
1392 1392
         }
1393 1393
         // let's add the where query param for consecutive look up.
1394
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1394
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1395 1395
         $query_params['limit'] = $limit;
1396 1396
         // set direction
1397 1397
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1472,7 +1472,7 @@  discard block
 block discarded – undo
1472 1472
     {
1473 1473
         $field_settings = $this->field_settings_for($field_name);
1474 1474
         // if not a valid EE_Datetime_Field then throw error
1475
-        if (! $field_settings instanceof EE_Datetime_Field) {
1475
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1476 1476
             throw new EE_Error(sprintf(__(
1477 1477
                 'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1478 1478
                 'event_espresso'
@@ -1621,7 +1621,7 @@  discard block
 block discarded – undo
1621 1621
      */
1622 1622
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1623 1623
     {
1624
-        if (! is_array($query_params)) {
1624
+        if ( ! is_array($query_params)) {
1625 1625
             EE_Error::doing_it_wrong(
1626 1626
                 'EEM_Base::update',
1627 1627
                 sprintf(
@@ -1669,7 +1669,7 @@  discard block
 block discarded – undo
1669 1669
             $wpdb_result = (array) $wpdb_result;
1670 1670
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1671 1671
             if ($this->has_primary_key_field()) {
1672
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1672
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1673 1673
             } else {
1674 1674
                 // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1675 1675
                 $main_table_pk_value = null;
@@ -1685,7 +1685,7 @@  discard block
 block discarded – undo
1685 1685
                     // in this table, right? so insert a row in the current table, using any fields available
1686 1686
                     if (
1687 1687
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1688
-                           && $wpdb_result[ $this_table_pk_column ])
1688
+                           && $wpdb_result[$this_table_pk_column])
1689 1689
                     ) {
1690 1690
                         $success = $this->_insert_into_specific_table(
1691 1691
                             $table_obj,
@@ -1693,7 +1693,7 @@  discard block
 block discarded – undo
1693 1693
                             $main_table_pk_value
1694 1694
                         );
1695 1695
                         // if we died here, report the error
1696
-                        if (! $success) {
1696
+                        if ( ! $success) {
1697 1697
                             return false;
1698 1698
                         }
1699 1699
                     }
@@ -1721,10 +1721,10 @@  discard block
 block discarded – undo
1721 1721
                 $model_objs_affected_ids = array();
1722 1722
                 foreach ($models_affected_key_columns as $row) {
1723 1723
                     $combined_index_key = $this->get_index_primary_key_string($row);
1724
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1724
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1725 1725
                 }
1726 1726
             }
1727
-            if (! $model_objs_affected_ids) {
1727
+            if ( ! $model_objs_affected_ids) {
1728 1728
                 // wait wait wait- if nothing was affected let's stop here
1729 1729
                 return 0;
1730 1730
             }
@@ -1751,7 +1751,7 @@  discard block
 block discarded – undo
1751 1751
                . $model_query_info->get_full_join_sql()
1752 1752
                . " SET "
1753 1753
                . $this->_construct_update_sql($fields_n_values)
1754
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1754
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1755 1755
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1756 1756
         /**
1757 1757
          * Action called after a model update call has been made.
@@ -1762,7 +1762,7 @@  discard block
 block discarded – undo
1762 1762
          * @param int      $rows_affected
1763 1763
          */
1764 1764
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1765
-        return $rows_affected;// how many supposedly got updated
1765
+        return $rows_affected; // how many supposedly got updated
1766 1766
     }
1767 1767
 
1768 1768
 
@@ -1790,7 +1790,7 @@  discard block
 block discarded – undo
1790 1790
         }
1791 1791
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1792 1792
         $select_expressions = $field->get_qualified_column();
1793
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1793
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1794 1794
         return $this->_do_wpdb_query('get_col', array($SQL));
1795 1795
     }
1796 1796
 
@@ -1808,7 +1808,7 @@  discard block
 block discarded – undo
1808 1808
     {
1809 1809
         $query_params['limit'] = 1;
1810 1810
         $col = $this->get_col($query_params, $field_to_select);
1811
-        if (! empty($col)) {
1811
+        if ( ! empty($col)) {
1812 1812
             return reset($col);
1813 1813
         }
1814 1814
         return null;
@@ -1839,7 +1839,7 @@  discard block
 block discarded – undo
1839 1839
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1840 1840
             $value_sql = $prepared_value === null ? 'NULL'
1841 1841
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1842
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1842
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1843 1843
         }
1844 1844
         return implode(",", $cols_n_values);
1845 1845
     }
@@ -1983,12 +1983,12 @@  discard block
 block discarded – undo
1983 1983
         if (
1984 1984
             $this->has_primary_key_field()
1985 1985
             && $rows_deleted !== false
1986
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1986
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1987 1987
         ) {
1988
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1988
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1989 1989
             foreach ($ids_for_removal as $id) {
1990
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1991
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1990
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1991
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1992 1992
                 }
1993 1993
             }
1994 1994
 
@@ -2025,7 +2025,7 @@  discard block
 block discarded – undo
2025 2025
          * @param int      $rows_deleted
2026 2026
          */
2027 2027
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2028
-        return $rows_deleted;// how many supposedly got deleted
2028
+        return $rows_deleted; // how many supposedly got deleted
2029 2029
     }
2030 2030
 
2031 2031
 
@@ -2119,15 +2119,15 @@  discard block
 block discarded – undo
2119 2119
                 if (
2120 2120
                     $allow_blocking
2121 2121
                     && $this->delete_is_blocked_by_related_models(
2122
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2122
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2123 2123
                     )
2124 2124
                 ) {
2125 2125
                     continue;
2126 2126
                 }
2127 2127
                 // primary table deletes
2128
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2129
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2130
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2128
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2129
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2130
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2131 2131
                 }
2132 2132
             }
2133 2133
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2136,8 +2136,8 @@  discard block
 block discarded – undo
2136 2136
                 $ids_to_delete_indexed_by_column_for_row = array();
2137 2137
                 foreach ($fields as $cpk_field) {
2138 2138
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2139
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2140
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2139
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2140
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2141 2141
                     }
2142 2142
                 }
2143 2143
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2177,7 +2177,7 @@  discard block
 block discarded – undo
2177 2177
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2178 2178
                 // make sure we have unique $ids
2179 2179
                 $ids = array_unique($ids);
2180
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2180
+                $query[] = $column.' IN('.implode(',', $ids).')';
2181 2181
             }
2182 2182
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2183 2183
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2185,7 +2185,7 @@  discard block
 block discarded – undo
2185 2185
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2186 2186
                 $values_for_each_combined_primary_key_for_a_row = array();
2187 2187
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2188
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2188
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2189 2189
                 }
2190 2190
                 $ways_to_identify_a_row[] = '('
2191 2191
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2257,8 +2257,8 @@  discard block
 block discarded – undo
2257 2257
                 $column_to_count = '*';
2258 2258
             }
2259 2259
         }
2260
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2261
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2260
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2261
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2262 2262
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2263 2263
     }
2264 2264
 
@@ -2281,7 +2281,7 @@  discard block
 block discarded – undo
2281 2281
             $field_obj = $this->get_primary_key_field();
2282 2282
         }
2283 2283
         $column_to_count = $field_obj->get_qualified_column();
2284
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2284
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2285 2285
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2286 2286
         $data_type = $field_obj->get_wpdb_data_type();
2287 2287
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2308,7 +2308,7 @@  discard block
 block discarded – undo
2308 2308
         // if we're in maintenance mode level 2, DON'T run any queries
2309 2309
         // because level 2 indicates the database needs updating and
2310 2310
         // is probably out of sync with the code
2311
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2311
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2312 2312
             throw new EE_Error(sprintf(__(
2313 2313
                 "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2314 2314
                 "event_espresso"
@@ -2316,7 +2316,7 @@  discard block
 block discarded – undo
2316 2316
         }
2317 2317
         /** @type WPDB $wpdb */
2318 2318
         global $wpdb;
2319
-        if (! method_exists($wpdb, $wpdb_method)) {
2319
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2320 2320
             throw new EE_Error(sprintf(__(
2321 2321
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2322 2322
                 'event_espresso'
@@ -2330,7 +2330,7 @@  discard block
 block discarded – undo
2330 2330
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2331 2331
         if (WP_DEBUG) {
2332 2332
             $wpdb->show_errors($old_show_errors_value);
2333
-            if (! empty($wpdb->last_error)) {
2333
+            if ( ! empty($wpdb->last_error)) {
2334 2334
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2335 2335
             }
2336 2336
             if ($result === false) {
@@ -2396,7 +2396,7 @@  discard block
 block discarded – undo
2396 2396
                     return $result;
2397 2397
                     break;
2398 2398
             }
2399
-            if (! empty($error_message)) {
2399
+            if ( ! empty($error_message)) {
2400 2400
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2401 2401
                 trigger_error($error_message);
2402 2402
             }
@@ -2476,11 +2476,11 @@  discard block
 block discarded – undo
2476 2476
      */
2477 2477
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2478 2478
     {
2479
-        return " FROM " . $model_query_info->get_full_join_sql() .
2480
-               $model_query_info->get_where_sql() .
2481
-               $model_query_info->get_group_by_sql() .
2482
-               $model_query_info->get_having_sql() .
2483
-               $model_query_info->get_order_by_sql() .
2479
+        return " FROM ".$model_query_info->get_full_join_sql().
2480
+               $model_query_info->get_where_sql().
2481
+               $model_query_info->get_group_by_sql().
2482
+               $model_query_info->get_having_sql().
2483
+               $model_query_info->get_order_by_sql().
2484 2484
                $model_query_info->get_limit_sql();
2485 2485
     }
2486 2486
 
@@ -2676,12 +2676,12 @@  discard block
 block discarded – undo
2676 2676
         $related_model = $this->get_related_model_obj($model_name);
2677 2677
         // we're just going to use the query params on the related model's normal get_all query,
2678 2678
         // except add a condition to say to match the current mod
2679
-        if (! isset($query_params['default_where_conditions'])) {
2679
+        if ( ! isset($query_params['default_where_conditions'])) {
2680 2680
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2681 2681
         }
2682 2682
         $this_model_name = $this->get_this_model_name();
2683 2683
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2684
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2684
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2685 2685
         return $related_model->count($query_params, $field_to_count, $distinct);
2686 2686
     }
2687 2687
 
@@ -2701,7 +2701,7 @@  discard block
 block discarded – undo
2701 2701
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2702 2702
     {
2703 2703
         $related_model = $this->get_related_model_obj($model_name);
2704
-        if (! is_array($query_params)) {
2704
+        if ( ! is_array($query_params)) {
2705 2705
             EE_Error::doing_it_wrong(
2706 2706
                 'EEM_Base::sum_related',
2707 2707
                 sprintf(
@@ -2714,12 +2714,12 @@  discard block
 block discarded – undo
2714 2714
         }
2715 2715
         // we're just going to use the query params on the related model's normal get_all query,
2716 2716
         // except add a condition to say to match the current mod
2717
-        if (! isset($query_params['default_where_conditions'])) {
2717
+        if ( ! isset($query_params['default_where_conditions'])) {
2718 2718
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2719 2719
         }
2720 2720
         $this_model_name = $this->get_this_model_name();
2721 2721
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2722
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2722
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2723 2723
         return $related_model->sum($query_params, $field_to_sum);
2724 2724
     }
2725 2725
 
@@ -2772,7 +2772,7 @@  discard block
 block discarded – undo
2772 2772
                 $field_with_model_name = $field;
2773 2773
             }
2774 2774
         }
2775
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2775
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2776 2776
             throw new EE_Error(sprintf(
2777 2777
                 __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2778 2778
                 $this->get_this_model_name()
@@ -2909,13 +2909,13 @@  discard block
 block discarded – undo
2909 2909
                 || $this->get_primary_key_field()
2910 2910
                    instanceof
2911 2911
                    EE_Primary_Key_String_Field)
2912
-            && isset($fields_n_values[ $this->primary_key_name() ])
2912
+            && isset($fields_n_values[$this->primary_key_name()])
2913 2913
         ) {
2914
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2914
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2915 2915
         }
2916 2916
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2917 2917
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2918
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2918
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2919 2919
         }
2920 2920
         // if there is nothing to base this search on, then we shouldn't find anything
2921 2921
         if (empty($query_params)) {
@@ -2993,15 +2993,15 @@  discard block
 block discarded – undo
2993 2993
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2994 2994
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
2995 2995
             if ($prepared_value !== null) {
2996
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2996
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2997 2997
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2998 2998
             }
2999 2999
         }
3000 3000
         if ($table instanceof EE_Secondary_Table && $new_id) {
3001 3001
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3002 3002
             // so add the fk to the main table as a column
3003
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3004
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3003
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3004
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
3005 3005
         }
3006 3006
         // insert the new entry
3007 3007
         $result = $this->_do_wpdb_query(
@@ -3018,7 +3018,7 @@  discard block
 block discarded – undo
3018 3018
             }
3019 3019
             // it's not an auto-increment primary key, so
3020 3020
             // it must have been supplied
3021
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3021
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3022 3022
         }
3023 3023
         // we can't return a  primary key because there is none. instead return
3024 3024
         // a unique string indicating this model
@@ -3043,14 +3043,14 @@  discard block
 block discarded – undo
3043 3043
         if (
3044 3044
             ! $field_obj->is_nullable()
3045 3045
             && (
3046
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3047
-                || $fields_n_values[ $field_obj->get_name() ] === null
3046
+                ! isset($fields_n_values[$field_obj->get_name()])
3047
+                || $fields_n_values[$field_obj->get_name()] === null
3048 3048
             )
3049 3049
         ) {
3050
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3050
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3051 3051
         }
3052
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3053
-            ? $fields_n_values[ $field_obj->get_name() ]
3052
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3053
+            ? $fields_n_values[$field_obj->get_name()]
3054 3054
             : null;
3055 3055
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3056 3056
     }
@@ -3151,7 +3151,7 @@  discard block
 block discarded – undo
3151 3151
      */
3152 3152
     public function get_table_obj_by_alias($table_alias = '')
3153 3153
     {
3154
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3154
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3155 3155
     }
3156 3156
 
3157 3157
 
@@ -3166,7 +3166,7 @@  discard block
 block discarded – undo
3166 3166
         $other_tables = array();
3167 3167
         foreach ($this->_tables as $table_alias => $table) {
3168 3168
             if ($table instanceof EE_Secondary_Table) {
3169
-                $other_tables[ $table_alias ] = $table;
3169
+                $other_tables[$table_alias] = $table;
3170 3170
             }
3171 3171
         }
3172 3172
         return $other_tables;
@@ -3182,7 +3182,7 @@  discard block
 block discarded – undo
3182 3182
      */
3183 3183
     public function _get_fields_for_table($table_alias)
3184 3184
     {
3185
-        return $this->_fields[ $table_alias ];
3185
+        return $this->_fields[$table_alias];
3186 3186
     }
3187 3187
 
3188 3188
 
@@ -3211,7 +3211,7 @@  discard block
 block discarded – undo
3211 3211
                     $query_info_carrier,
3212 3212
                     'group_by'
3213 3213
                 );
3214
-            } elseif (! empty($query_params['group_by'])) {
3214
+            } elseif ( ! empty($query_params['group_by'])) {
3215 3215
                 $this->_extract_related_model_info_from_query_param(
3216 3216
                     $query_params['group_by'],
3217 3217
                     $query_info_carrier,
@@ -3233,7 +3233,7 @@  discard block
 block discarded – undo
3233 3233
                     $query_info_carrier,
3234 3234
                     'order_by'
3235 3235
                 );
3236
-            } elseif (! empty($query_params['order_by'])) {
3236
+            } elseif ( ! empty($query_params['order_by'])) {
3237 3237
                 $this->_extract_related_model_info_from_query_param(
3238 3238
                     $query_params['order_by'],
3239 3239
                     $query_info_carrier,
@@ -3268,7 +3268,7 @@  discard block
 block discarded – undo
3268 3268
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3269 3269
         $query_param_type
3270 3270
     ) {
3271
-        if (! empty($sub_query_params)) {
3271
+        if ( ! empty($sub_query_params)) {
3272 3272
             $sub_query_params = (array) $sub_query_params;
3273 3273
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3274 3274
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3283,7 +3283,7 @@  discard block
 block discarded – undo
3283 3283
                 // of array('Registration.TXN_ID'=>23)
3284 3284
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3285 3285
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3286
-                    if (! is_array($possibly_array_of_params)) {
3286
+                    if ( ! is_array($possibly_array_of_params)) {
3287 3287
                         throw new EE_Error(sprintf(
3288 3288
                             __(
3289 3289
                                 "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
@@ -3307,7 +3307,7 @@  discard block
 block discarded – undo
3307 3307
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3308 3308
                     // indicating that $possible_array_of_params[1] is actually a field name,
3309 3309
                     // from which we should extract query parameters!
3310
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3310
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3311 3311
                         throw new EE_Error(sprintf(__(
3312 3312
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3313 3313
                             "event_espresso"
@@ -3341,8 +3341,8 @@  discard block
 block discarded – undo
3341 3341
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3342 3342
         $query_param_type
3343 3343
     ) {
3344
-        if (! empty($sub_query_params)) {
3345
-            if (! is_array($sub_query_params)) {
3344
+        if ( ! empty($sub_query_params)) {
3345
+            if ( ! is_array($sub_query_params)) {
3346 3346
                 throw new EE_Error(sprintf(
3347 3347
                     __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3348 3348
                     $sub_query_params
@@ -3376,7 +3376,7 @@  discard block
 block discarded – undo
3376 3376
      */
3377 3377
     public function _create_model_query_info_carrier($query_params)
3378 3378
     {
3379
-        if (! is_array($query_params)) {
3379
+        if ( ! is_array($query_params)) {
3380 3380
             EE_Error::doing_it_wrong(
3381 3381
                 'EEM_Base::_create_model_query_info_carrier',
3382 3382
                 sprintf(
@@ -3409,7 +3409,7 @@  discard block
 block discarded – undo
3409 3409
             // only include if related to a cpt where no password has been set
3410 3410
             $query_params[0]['OR*nopassword'] = array(
3411 3411
                 $where_param_key_for_password => '',
3412
-                $where_param_key_for_password . '*' => array('IS_NULL')
3412
+                $where_param_key_for_password.'*' => array('IS_NULL')
3413 3413
             );
3414 3414
         }
3415 3415
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3463,7 +3463,7 @@  discard block
 block discarded – undo
3463 3463
         // set limit
3464 3464
         if (array_key_exists('limit', $query_params)) {
3465 3465
             if (is_array($query_params['limit'])) {
3466
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3466
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3467 3467
                     $e = sprintf(
3468 3468
                         __(
3469 3469
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3471,12 +3471,12 @@  discard block
 block discarded – undo
3471 3471
                         ),
3472 3472
                         http_build_query($query_params['limit'])
3473 3473
                     );
3474
-                    throw new EE_Error($e . "|" . $e);
3474
+                    throw new EE_Error($e."|".$e);
3475 3475
                 }
3476 3476
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3477
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3478
-            } elseif (! empty($query_params['limit'])) {
3479
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3477
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3478
+            } elseif ( ! empty($query_params['limit'])) {
3479
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3480 3480
             }
3481 3481
         }
3482 3482
         // set order by
@@ -3508,10 +3508,10 @@  discard block
 block discarded – undo
3508 3508
                 $order_array = array();
3509 3509
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3510 3510
                     $order = $this->_extract_order($order);
3511
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3511
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3512 3512
                 }
3513
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3514
-            } elseif (! empty($query_params['order_by'])) {
3513
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3514
+            } elseif ( ! empty($query_params['order_by'])) {
3515 3515
                 $this->_extract_related_model_info_from_query_param(
3516 3516
                     $query_params['order_by'],
3517 3517
                     $query_object,
@@ -3522,7 +3522,7 @@  discard block
 block discarded – undo
3522 3522
                     ? $this->_extract_order($query_params['order'])
3523 3523
                     : 'DESC';
3524 3524
                 $query_object->set_order_by_sql(
3525
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3525
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3526 3526
                 );
3527 3527
             }
3528 3528
         }
@@ -3534,7 +3534,7 @@  discard block
 block discarded – undo
3534 3534
         ) {
3535 3535
             $pk_field = $this->get_primary_key_field();
3536 3536
             $order = $this->_extract_order($query_params['order']);
3537
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3537
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3538 3538
         }
3539 3539
         // set group by
3540 3540
         if (array_key_exists('group_by', $query_params)) {
@@ -3544,10 +3544,10 @@  discard block
 block discarded – undo
3544 3544
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3545 3545
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3546 3546
                 }
3547
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3548
-            } elseif (! empty($query_params['group_by'])) {
3547
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3548
+            } elseif ( ! empty($query_params['group_by'])) {
3549 3549
                 $query_object->set_group_by_sql(
3550
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3550
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3551 3551
                 );
3552 3552
             }
3553 3553
         }
@@ -3557,7 +3557,7 @@  discard block
 block discarded – undo
3557 3557
         }
3558 3558
         // now, just verify they didn't pass anything wack
3559 3559
         foreach ($query_params as $query_key => $query_value) {
3560
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3560
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3561 3561
                 throw new EE_Error(
3562 3562
                     sprintf(
3563 3563
                         __(
@@ -3665,7 +3665,7 @@  discard block
 block discarded – undo
3665 3665
         $where_query_params = array()
3666 3666
     ) {
3667 3667
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3668
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3668
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3669 3669
             throw new EE_Error(sprintf(
3670 3670
                 __(
3671 3671
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3797,19 +3797,19 @@  discard block
 block discarded – undo
3797 3797
     ) {
3798 3798
         $null_friendly_where_conditions = array();
3799 3799
         $none_overridden = true;
3800
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3800
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3801 3801
         foreach ($default_where_conditions as $key => $val) {
3802
-            if (isset($provided_where_conditions[ $key ])) {
3802
+            if (isset($provided_where_conditions[$key])) {
3803 3803
                 $none_overridden = false;
3804 3804
             } else {
3805
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3805
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3806 3806
             }
3807 3807
         }
3808 3808
         if ($none_overridden && $default_where_conditions) {
3809 3809
             if ($model->has_primary_key_field()) {
3810
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3810
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3811 3811
                                                                                 . "."
3812
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3812
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3813 3813
             }/*else{
3814 3814
                 //@todo NO PK, use other defaults
3815 3815
             }*/
@@ -3914,7 +3914,7 @@  discard block
 block discarded – undo
3914 3914
             foreach ($tables as $table_obj) {
3915 3915
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3916 3916
                                        . $table_obj->get_fully_qualified_pk_column();
3917
-                if (! in_array($qualified_pk_column, $selects)) {
3917
+                if ( ! in_array($qualified_pk_column, $selects)) {
3918 3918
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3919 3919
                 }
3920 3920
             }
@@ -4066,9 +4066,9 @@  discard block
 block discarded – undo
4066 4066
         $query_parameter_type
4067 4067
     ) {
4068 4068
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4069
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4069
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4070 4070
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4071
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4071
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4072 4072
                 if ($possible_join_string === '') {
4073 4073
                     // nothing left to $query_param
4074 4074
                     // we should actually end in a field name, not a model like this!
@@ -4199,7 +4199,7 @@  discard block
 block discarded – undo
4199 4199
     {
4200 4200
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4201 4201
         if ($SQL) {
4202
-            return " WHERE " . $SQL;
4202
+            return " WHERE ".$SQL;
4203 4203
         }
4204 4204
         return '';
4205 4205
     }
@@ -4218,7 +4218,7 @@  discard block
 block discarded – undo
4218 4218
     {
4219 4219
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4220 4220
         if ($SQL) {
4221
-            return " HAVING " . $SQL;
4221
+            return " HAVING ".$SQL;
4222 4222
         }
4223 4223
         return '';
4224 4224
     }
@@ -4237,7 +4237,7 @@  discard block
 block discarded – undo
4237 4237
     {
4238 4238
         $where_clauses = array();
4239 4239
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4240
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4240
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4241 4241
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4242 4242
                 switch ($query_param) {
4243 4243
                     case 'not':
@@ -4271,7 +4271,7 @@  discard block
 block discarded – undo
4271 4271
             } else {
4272 4272
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4273 4273
                 // if it's not a normal field, maybe it's a custom selection?
4274
-                if (! $field_obj) {
4274
+                if ( ! $field_obj) {
4275 4275
                     if ($this->_custom_selections instanceof CustomSelects) {
4276 4276
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4277 4277
                     } else {
@@ -4282,7 +4282,7 @@  discard block
 block discarded – undo
4282 4282
                     }
4283 4283
                 }
4284 4284
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4285
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4285
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4286 4286
             }
4287 4287
         }
4288 4288
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4305,7 +4305,7 @@  discard block
 block discarded – undo
4305 4305
                 $field->get_model_name(),
4306 4306
                 $query_param
4307 4307
             );
4308
-            return $table_alias_prefix . $field->get_qualified_column();
4308
+            return $table_alias_prefix.$field->get_qualified_column();
4309 4309
         }
4310 4310
         if (
4311 4311
             $this->_custom_selections instanceof CustomSelects
@@ -4365,7 +4365,7 @@  discard block
 block discarded – undo
4365 4365
     {
4366 4366
         if (is_array($op_and_value)) {
4367 4367
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4368
-            if (! $operator) {
4368
+            if ( ! $operator) {
4369 4369
                 $php_array_like_string = array();
4370 4370
                 foreach ($op_and_value as $key => $value) {
4371 4371
                     $php_array_like_string[] = "$key=>$value";
@@ -4387,14 +4387,14 @@  discard block
 block discarded – undo
4387 4387
         }
4388 4388
         // check to see if the value is actually another field
4389 4389
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4390
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4390
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4391 4391
         }
4392 4392
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4393 4393
             // in this case, the value should be an array, or at least a comma-separated list
4394 4394
             // it will need to handle a little differently
4395 4395
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4396 4396
             // note: $cleaned_value has already been run through $wpdb->prepare()
4397
-            return $operator . SP . $cleaned_value;
4397
+            return $operator.SP.$cleaned_value;
4398 4398
         }
4399 4399
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4400 4400
             // the value should be an array with count of two.
@@ -4410,7 +4410,7 @@  discard block
 block discarded – undo
4410 4410
                 );
4411 4411
             }
4412 4412
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4413
-            return $operator . SP . $cleaned_value;
4413
+            return $operator.SP.$cleaned_value;
4414 4414
         }
4415 4415
         if (in_array($operator, $this->valid_null_style_operators())) {
4416 4416
             if ($value !== null) {
@@ -4430,10 +4430,10 @@  discard block
 block discarded – undo
4430 4430
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4431 4431
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4432 4432
             // remove other junk. So just treat it as a string.
4433
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4433
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4434 4434
         }
4435
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4436
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4435
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4436
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4437 4437
         }
4438 4438
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439 4439
             throw new EE_Error(
@@ -4447,7 +4447,7 @@  discard block
 block discarded – undo
4447 4447
                 )
4448 4448
             );
4449 4449
         }
4450
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4450
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4451 4451
             throw new EE_Error(
4452 4452
                 sprintf(
4453 4453
                     __(
@@ -4487,7 +4487,7 @@  discard block
 block discarded – undo
4487 4487
         foreach ($values as $value) {
4488 4488
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4489 4489
         }
4490
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4490
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4491 4491
     }
4492 4492
 
4493 4493
 
@@ -4528,7 +4528,7 @@  discard block
 block discarded – undo
4528 4528
                                 . $main_table->get_table_name()
4529 4529
                                 . " WHERE FALSE";
4530 4530
         }
4531
-        return "(" . implode(",", $cleaned_values) . ")";
4531
+        return "(".implode(",", $cleaned_values).")";
4532 4532
     }
4533 4533
 
4534 4534
 
@@ -4549,7 +4549,7 @@  discard block
 block discarded – undo
4549 4549
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4550 4550
             );
4551 4551
         } //$field_obj should really just be a data type
4552
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4552
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4553 4553
             throw new EE_Error(
4554 4554
                 sprintf(
4555 4555
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4582,14 +4582,14 @@  discard block
 block discarded – undo
4582 4582
             ), $query_param_name));
4583 4583
         }
4584 4584
         $number_of_parts = count($query_param_parts);
4585
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4585
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4586 4586
         if ($number_of_parts === 1) {
4587 4587
             $field_name = $last_query_param_part;
4588 4588
             $model_obj = $this;
4589 4589
         } else {// $number_of_parts >= 2
4590 4590
             // the last part is the column name, and there are only 2parts. therefore...
4591 4591
             $field_name = $last_query_param_part;
4592
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4592
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4593 4593
         }
4594 4594
         try {
4595 4595
             return $model_obj->field_settings_for($field_name);
@@ -4611,7 +4611,7 @@  discard block
 block discarded – undo
4611 4611
     public function _get_qualified_column_for_field($field_name)
4612 4612
     {
4613 4613
         $all_fields = $this->field_settings();
4614
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4614
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4615 4615
         if ($field) {
4616 4616
             return $field->get_qualified_column();
4617 4617
         }
@@ -4682,10 +4682,10 @@  discard block
 block discarded – undo
4682 4682
      */
4683 4683
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4684 4684
     {
4685
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4685
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4686 4686
         $qualified_columns = array();
4687 4687
         foreach ($this->field_settings() as $field_name => $field) {
4688
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4688
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4689 4689
         }
4690 4690
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4691 4691
     }
@@ -4709,11 +4709,11 @@  discard block
 block discarded – undo
4709 4709
             if ($table_obj instanceof EE_Primary_Table) {
4710 4710
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4711 4711
                     ? $table_obj->get_select_join_limit($limit)
4712
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4712
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4713 4713
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4714 4714
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4715 4715
                     ? $table_obj->get_select_join_limit_join($limit)
4716
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4716
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4717 4717
             }
4718 4718
         }
4719 4719
         return $SQL;
@@ -4785,7 +4785,7 @@  discard block
 block discarded – undo
4785 4785
         foreach ($this->field_settings() as $field_obj) {
4786 4786
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4787 4787
             /** @var $field_obj EE_Model_Field_Base */
4788
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4788
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4789 4789
         }
4790 4790
         return $data_types;
4791 4791
     }
@@ -4801,14 +4801,14 @@  discard block
 block discarded – undo
4801 4801
      */
4802 4802
     public function get_related_model_obj($model_name)
4803 4803
     {
4804
-        $model_classname = "EEM_" . $model_name;
4805
-        if (! class_exists($model_classname)) {
4804
+        $model_classname = "EEM_".$model_name;
4805
+        if ( ! class_exists($model_classname)) {
4806 4806
             throw new EE_Error(sprintf(__(
4807 4807
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4808 4808
                 'event_espresso'
4809 4809
             ), $model_name, $model_classname));
4810 4810
         }
4811
-        return call_user_func($model_classname . "::instance");
4811
+        return call_user_func($model_classname."::instance");
4812 4812
     }
4813 4813
 
4814 4814
 
@@ -4837,7 +4837,7 @@  discard block
 block discarded – undo
4837 4837
         $belongs_to_relations = array();
4838 4838
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4839 4839
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4840
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4840
+                $belongs_to_relations[$model_name] = $relation_obj;
4841 4841
             }
4842 4842
         }
4843 4843
         return $belongs_to_relations;
@@ -4855,7 +4855,7 @@  discard block
 block discarded – undo
4855 4855
     public function related_settings_for($relation_name)
4856 4856
     {
4857 4857
         $relatedModels = $this->relation_settings();
4858
-        if (! array_key_exists($relation_name, $relatedModels)) {
4858
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4859 4859
             throw new EE_Error(
4860 4860
                 sprintf(
4861 4861
                     __(
@@ -4868,7 +4868,7 @@  discard block
 block discarded – undo
4868 4868
                 )
4869 4869
             );
4870 4870
         }
4871
-        return $relatedModels[ $relation_name ];
4871
+        return $relatedModels[$relation_name];
4872 4872
     }
4873 4873
 
4874 4874
 
@@ -4885,14 +4885,14 @@  discard block
 block discarded – undo
4885 4885
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4886 4886
     {
4887 4887
         $fieldSettings = $this->field_settings($include_db_only_fields);
4888
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4888
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4889 4889
             throw new EE_Error(sprintf(
4890 4890
                 __("There is no field/column '%s' on '%s'", 'event_espresso'),
4891 4891
                 $fieldName,
4892 4892
                 get_class($this)
4893 4893
             ));
4894 4894
         }
4895
-        return $fieldSettings[ $fieldName ];
4895
+        return $fieldSettings[$fieldName];
4896 4896
     }
4897 4897
 
4898 4898
 
@@ -4906,7 +4906,7 @@  discard block
 block discarded – undo
4906 4906
     public function has_field($fieldName)
4907 4907
     {
4908 4908
         $fieldSettings = $this->field_settings(true);
4909
-        if (isset($fieldSettings[ $fieldName ])) {
4909
+        if (isset($fieldSettings[$fieldName])) {
4910 4910
             return true;
4911 4911
         }
4912 4912
         return false;
@@ -4923,7 +4923,7 @@  discard block
 block discarded – undo
4923 4923
     public function has_relation($relation_name)
4924 4924
     {
4925 4925
         $relations = $this->relation_settings();
4926
-        if (isset($relations[ $relation_name ])) {
4926
+        if (isset($relations[$relation_name])) {
4927 4927
             return true;
4928 4928
         }
4929 4929
         return false;
@@ -4961,7 +4961,7 @@  discard block
 block discarded – undo
4961 4961
                     break;
4962 4962
                 }
4963 4963
             }
4964
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4964
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4965 4965
                 throw new EE_Error(sprintf(
4966 4966
                     __("There is no Primary Key defined on model %s", 'event_espresso'),
4967 4967
                     get_class($this)
@@ -5022,24 +5022,24 @@  discard block
 block discarded – undo
5022 5022
      */
5023 5023
     public function get_foreign_key_to($model_name)
5024 5024
     {
5025
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5025
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5026 5026
             foreach ($this->field_settings() as $field) {
5027 5027
                 if (
5028 5028
                     $field instanceof EE_Foreign_Key_Field_Base
5029 5029
                     && in_array($model_name, $field->get_model_names_pointed_to())
5030 5030
                 ) {
5031
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5031
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5032 5032
                     break;
5033 5033
                 }
5034 5034
             }
5035
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5035
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5036 5036
                 throw new EE_Error(sprintf(__(
5037 5037
                     "There is no foreign key field pointing to model %s on model %s",
5038 5038
                     'event_espresso'
5039 5039
                 ), $model_name, get_class($this)));
5040 5040
             }
5041 5041
         }
5042
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5042
+        return $this->_cache_foreign_key_to_fields[$model_name];
5043 5043
     }
5044 5044
 
5045 5045
 
@@ -5055,7 +5055,7 @@  discard block
 block discarded – undo
5055 5055
     public function get_table_for_alias($table_alias)
5056 5056
     {
5057 5057
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5058
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5058
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5059 5059
     }
5060 5060
 
5061 5061
 
@@ -5074,7 +5074,7 @@  discard block
 block discarded – undo
5074 5074
                 $this->_cached_fields = array();
5075 5075
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5076 5076
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5077
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5077
+                        $this->_cached_fields[$field_name] = $field_obj;
5078 5078
                     }
5079 5079
                 }
5080 5080
             }
@@ -5085,8 +5085,8 @@  discard block
 block discarded – undo
5085 5085
             foreach ($this->_fields as $fields_corresponding_to_table) {
5086 5086
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5087 5087
                     /** @var $field_obj EE_Model_Field_Base */
5088
-                    if (! $field_obj->is_db_only_field()) {
5089
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5088
+                    if ( ! $field_obj->is_db_only_field()) {
5089
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5090 5090
                     }
5091 5091
                 }
5092 5092
             }
@@ -5127,12 +5127,12 @@  discard block
 block discarded – undo
5127 5127
                     $primary_key_field->get_qualified_column(),
5128 5128
                     $primary_key_field->get_table_column()
5129 5129
                 );
5130
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5130
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5131 5131
                     continue;
5132 5132
                 }
5133 5133
             }
5134 5134
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5135
-            if (! $classInstance) {
5135
+            if ( ! $classInstance) {
5136 5136
                 throw new EE_Error(
5137 5137
                     sprintf(
5138 5138
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5145,7 +5145,7 @@  discard block
 block discarded – undo
5145 5145
             $classInstance->set_timezone($this->_timezone);
5146 5146
             // make sure if there is any timezone setting present that we set the timezone for the object
5147 5147
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5148
-            $array_of_objects[ $key ] = $classInstance;
5148
+            $array_of_objects[$key] = $classInstance;
5149 5149
             // also, for all the relations of type BelongsTo, see if we can cache
5150 5150
             // those related models
5151 5151
             // (we could do this for other relations too, but if there are conditions
@@ -5189,9 +5189,9 @@  discard block
 block discarded – undo
5189 5189
         $results = array();
5190 5190
         if ($this->_custom_selections instanceof CustomSelects) {
5191 5191
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5192
-                if (isset($db_results_row[ $alias ])) {
5193
-                    $results[ $alias ] = $this->convertValueToDataType(
5194
-                        $db_results_row[ $alias ],
5192
+                if (isset($db_results_row[$alias])) {
5193
+                    $results[$alias] = $this->convertValueToDataType(
5194
+                        $db_results_row[$alias],
5195 5195
                         $this->_custom_selections->getDataTypeForAlias($alias)
5196 5196
                     );
5197 5197
                 }
@@ -5233,7 +5233,7 @@  discard block
 block discarded – undo
5233 5233
         $this_model_fields_and_values = array();
5234 5234
         // setup the row using default values;
5235 5235
         foreach ($this->field_settings() as $field_name => $field_obj) {
5236
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5236
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5237 5237
         }
5238 5238
         $className = $this->_get_class_name();
5239 5239
         $classInstance = EE_Registry::instance()
@@ -5251,20 +5251,20 @@  discard block
 block discarded – undo
5251 5251
      */
5252 5252
     public function instantiate_class_from_array_or_object($cols_n_values)
5253 5253
     {
5254
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5254
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5255 5255
             $cols_n_values = get_object_vars($cols_n_values);
5256 5256
         }
5257 5257
         $primary_key = null;
5258 5258
         // make sure the array only has keys that are fields/columns on this model
5259 5259
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5260
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5261
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5260
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5261
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5262 5262
         }
5263 5263
         $className = $this->_get_class_name();
5264 5264
         // check we actually found results that we can use to build our model object
5265 5265
         // if not, return null
5266 5266
         if ($this->has_primary_key_field()) {
5267
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5267
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5268 5268
                 return null;
5269 5269
             }
5270 5270
         } elseif ($this->unique_indexes()) {
@@ -5276,7 +5276,7 @@  discard block
 block discarded – undo
5276 5276
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5277 5277
         if ($primary_key) {
5278 5278
             $classInstance = $this->get_from_entity_map($primary_key);
5279
-            if (! $classInstance) {
5279
+            if ( ! $classInstance) {
5280 5280
                 $classInstance = EE_Registry::instance()
5281 5281
                                             ->load_class(
5282 5282
                                                 $className,
@@ -5309,8 +5309,8 @@  discard block
 block discarded – undo
5309 5309
      */
5310 5310
     public function get_from_entity_map($id)
5311 5311
     {
5312
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5313
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5312
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5313
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5314 5314
     }
5315 5315
 
5316 5316
 
@@ -5333,7 +5333,7 @@  discard block
 block discarded – undo
5333 5333
     public function add_to_entity_map(EE_Base_Class $object)
5334 5334
     {
5335 5335
         $className = $this->_get_class_name();
5336
-        if (! $object instanceof $className) {
5336
+        if ( ! $object instanceof $className) {
5337 5337
             throw new EE_Error(sprintf(
5338 5338
                 __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5339 5339
                 is_object($object) ? get_class($object) : $object,
@@ -5341,7 +5341,7 @@  discard block
 block discarded – undo
5341 5341
             ));
5342 5342
         }
5343 5343
         /** @var $object EE_Base_Class */
5344
-        if (! $object->ID()) {
5344
+        if ( ! $object->ID()) {
5345 5345
             throw new EE_Error(sprintf(__(
5346 5346
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5347 5347
                 "event_espresso"
@@ -5352,7 +5352,7 @@  discard block
 block discarded – undo
5352 5352
         if ($classInstance) {
5353 5353
             return $classInstance;
5354 5354
         }
5355
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5355
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5356 5356
         return $object;
5357 5357
     }
5358 5358
 
@@ -5368,11 +5368,11 @@  discard block
 block discarded – undo
5368 5368
     public function clear_entity_map($id = null)
5369 5369
     {
5370 5370
         if (empty($id)) {
5371
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5371
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5372 5372
             return true;
5373 5373
         }
5374
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5375
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5374
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5375
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5376 5376
             return true;
5377 5377
         }
5378 5378
         return false;
@@ -5415,17 +5415,17 @@  discard block
 block discarded – undo
5415 5415
             // there is a primary key on this table and its not set. Use defaults for all its columns
5416 5416
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5417 5417
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5418
-                    if (! $field_obj->is_db_only_field()) {
5418
+                    if ( ! $field_obj->is_db_only_field()) {
5419 5419
                         // prepare field as if its coming from db
5420 5420
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5421
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5421
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5422 5422
                     }
5423 5423
                 }
5424 5424
             } else {
5425 5425
                 // the table's rows existed. Use their values
5426 5426
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5427
-                    if (! $field_obj->is_db_only_field()) {
5428
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5427
+                    if ( ! $field_obj->is_db_only_field()) {
5428
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5429 5429
                             $cols_n_values,
5430 5430
                             $field_obj->get_qualified_column(),
5431 5431
                             $field_obj->get_table_column()
@@ -5452,17 +5452,17 @@  discard block
 block discarded – undo
5452 5452
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5453 5453
         // does the field on the model relate to this column retrieved from the db?
5454 5454
         // or is it a db-only field? (not relating to the model)
5455
-        if (isset($cols_n_values[ $qualified_column ])) {
5456
-            $value = $cols_n_values[ $qualified_column ];
5457
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5458
-            $value = $cols_n_values[ $regular_column ];
5459
-        } elseif (! empty($this->foreign_key_aliases)) {
5455
+        if (isset($cols_n_values[$qualified_column])) {
5456
+            $value = $cols_n_values[$qualified_column];
5457
+        } elseif (isset($cols_n_values[$regular_column])) {
5458
+            $value = $cols_n_values[$regular_column];
5459
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5460 5460
             // no PK?  ok check if there is a foreign key alias set for this table
5461 5461
             // then check if that alias exists in the incoming data
5462 5462
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5463 5463
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5464
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5465
-                    $value = $cols_n_values[ $FK_alias ];
5464
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5465
+                    $value = $cols_n_values[$FK_alias];
5466 5466
                     list($pk_class) = explode('.', $PK_column);
5467 5467
                     $pk_model_name = "EEM_{$pk_class}";
5468 5468
                     /** @var EEM_Base $pk_model */
@@ -5506,7 +5506,7 @@  discard block
 block discarded – undo
5506 5506
                     $obj_in_map->clear_cache($relation_name, null, true);
5507 5507
                 }
5508 5508
             }
5509
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5509
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5510 5510
             return $obj_in_map;
5511 5511
         }
5512 5512
         return $this->get_one_by_ID($id);
@@ -5559,7 +5559,7 @@  discard block
 block discarded – undo
5559 5559
      */
5560 5560
     private function _get_class_name()
5561 5561
     {
5562
-        return "EE_" . $this->get_this_model_name();
5562
+        return "EE_".$this->get_this_model_name();
5563 5563
     }
5564 5564
 
5565 5565
 
@@ -5607,7 +5607,7 @@  discard block
 block discarded – undo
5607 5607
     {
5608 5608
         $className = get_class($this);
5609 5609
         $tagName = "FHEE__{$className}__{$methodName}";
5610
-        if (! has_filter($tagName)) {
5610
+        if ( ! has_filter($tagName)) {
5611 5611
             throw new EE_Error(
5612 5612
                 sprintf(
5613 5613
                     __(
@@ -5780,7 +5780,7 @@  discard block
 block discarded – undo
5780 5780
         $unique_indexes = array();
5781 5781
         foreach ($this->_indexes as $name => $index) {
5782 5782
             if ($index instanceof EE_Unique_Index) {
5783
-                $unique_indexes [ $name ] = $index;
5783
+                $unique_indexes [$name] = $index;
5784 5784
             }
5785 5785
         }
5786 5786
         return $unique_indexes;
@@ -5847,7 +5847,7 @@  discard block
 block discarded – undo
5847 5847
         $key_vals_in_combined_pk = array();
5848 5848
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5849 5849
         foreach ($key_fields as $key_field_name => $field_obj) {
5850
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5850
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5851 5851
                 return null;
5852 5852
             }
5853 5853
         }
@@ -5868,7 +5868,7 @@  discard block
 block discarded – undo
5868 5868
     {
5869 5869
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5870 5870
         foreach ($keys_it_should_have as $key) {
5871
-            if (! isset($key_vals[ $key ])) {
5871
+            if ( ! isset($key_vals[$key])) {
5872 5872
                 return false;
5873 5873
             }
5874 5874
         }
@@ -5901,8 +5901,8 @@  discard block
 block discarded – undo
5901 5901
         }
5902 5902
         // even copies obviously won't have the same ID, so remove the primary key
5903 5903
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5904
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5905
-            unset($attributes_array[ $this->primary_key_name() ]);
5904
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5905
+            unset($attributes_array[$this->primary_key_name()]);
5906 5906
         }
5907 5907
         if (isset($query_params[0])) {
5908 5908
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5924,7 +5924,7 @@  discard block
 block discarded – undo
5924 5924
      */
5925 5925
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5926 5926
     {
5927
-        if (! is_array($query_params)) {
5927
+        if ( ! is_array($query_params)) {
5928 5928
             EE_Error::doing_it_wrong(
5929 5929
                 'EEM_Base::get_one_copy',
5930 5930
                 sprintf(
@@ -5974,7 +5974,7 @@  discard block
 block discarded – undo
5974 5974
      */
5975 5975
     private function _prepare_operator_for_sql($operator_supplied)
5976 5976
     {
5977
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5977
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5978 5978
             : null;
5979 5979
         if ($sql_operator) {
5980 5980
             return $sql_operator;
@@ -6065,7 +6065,7 @@  discard block
 block discarded – undo
6065 6065
         $objs = $this->get_all($query_params);
6066 6066
         $names = array();
6067 6067
         foreach ($objs as $obj) {
6068
-            $names[ $obj->ID() ] = $obj->name();
6068
+            $names[$obj->ID()] = $obj->name();
6069 6069
         }
6070 6070
         return $names;
6071 6071
     }
@@ -6086,7 +6086,7 @@  discard block
 block discarded – undo
6086 6086
      */
6087 6087
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6088 6088
     {
6089
-        if (! $this->has_primary_key_field()) {
6089
+        if ( ! $this->has_primary_key_field()) {
6090 6090
             if (WP_DEBUG) {
6091 6091
                 EE_Error::add_error(
6092 6092
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6099,7 +6099,7 @@  discard block
 block discarded – undo
6099 6099
         $IDs = array();
6100 6100
         foreach ($model_objects as $model_object) {
6101 6101
             $id = $model_object->ID();
6102
-            if (! $id) {
6102
+            if ( ! $id) {
6103 6103
                 if ($filter_out_empty_ids) {
6104 6104
                     continue;
6105 6105
                 }
@@ -6150,22 +6150,22 @@  discard block
 block discarded – undo
6150 6150
         EEM_Base::verify_is_valid_cap_context($context);
6151 6151
         // check if we ought to run the restriction generator first
6152 6152
         if (
6153
-            isset($this->_cap_restriction_generators[ $context ])
6154
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6155
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6153
+            isset($this->_cap_restriction_generators[$context])
6154
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6155
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6156 6156
         ) {
6157
-            $this->_cap_restrictions[ $context ] = array_merge(
6158
-                $this->_cap_restrictions[ $context ],
6159
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6157
+            $this->_cap_restrictions[$context] = array_merge(
6158
+                $this->_cap_restrictions[$context],
6159
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6160 6160
             );
6161 6161
         }
6162 6162
         // and make sure we've finalized the construction of each restriction
6163
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6163
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6164 6164
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6165 6165
                 $where_conditions_obj->_finalize_construct($this);
6166 6166
             }
6167 6167
         }
6168
-        return $this->_cap_restrictions[ $context ];
6168
+        return $this->_cap_restrictions[$context];
6169 6169
     }
6170 6170
 
6171 6171
 
@@ -6197,9 +6197,9 @@  discard block
 block discarded – undo
6197 6197
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6198 6198
             if (
6199 6199
                 ! EE_Capabilities::instance()
6200
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6200
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6201 6201
             ) {
6202
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6202
+                $missing_caps[$cap] = $restriction_if_no_cap;
6203 6203
             }
6204 6204
         }
6205 6205
         return $missing_caps;
@@ -6234,8 +6234,8 @@  discard block
 block discarded – undo
6234 6234
     public function cap_action_for_context($context)
6235 6235
     {
6236 6236
         $mapping = $this->cap_contexts_to_cap_action_map();
6237
-        if (isset($mapping[ $context ])) {
6238
-            return $mapping[ $context ];
6237
+        if (isset($mapping[$context])) {
6238
+            return $mapping[$context];
6239 6239
         }
6240 6240
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6241 6241
             return $action;
@@ -6353,7 +6353,7 @@  discard block
 block discarded – undo
6353 6353
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6354 6354
             if (
6355 6355
                 $query_param_key === $logic_query_param_key
6356
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6356
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6357 6357
             ) {
6358 6358
                 return true;
6359 6359
             }
@@ -6406,7 +6406,7 @@  discard block
 block discarded – undo
6406 6406
         if ($password_field instanceof EE_Password_Field) {
6407 6407
             $field_names = $password_field->protectedFields();
6408 6408
             foreach ($field_names as $field_name) {
6409
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6409
+                $fields[$field_name] = $this->field_settings_for($field_name);
6410 6410
             }
6411 6411
         }
6412 6412
         return $fields;
@@ -6431,7 +6431,7 @@  discard block
 block discarded – undo
6431 6431
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6432 6432
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6433 6433
         }
6434
-        if (!is_array($model_obj_or_fields_n_values)) {
6434
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6435 6435
             throw new UnexpectedEntityException(
6436 6436
                 $model_obj_or_fields_n_values,
6437 6437
                 'EE_Base_Class',
@@ -6506,7 +6506,7 @@  discard block
 block discarded – undo
6506 6506
                 )
6507 6507
             );
6508 6508
         }
6509
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6509
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6510 6510
     }
6511 6511
 
6512 6512
     /**
Please login to merge, or discard this patch.
admin/extend/registration_form/Extend_Registration_Form_Admin_Page.core.php 1 patch
Indentation   +1442 added lines, -1442 removed lines patch added patch discarded remove patch
@@ -14,1446 +14,1446 @@
 block discarded – undo
14 14
 class Extend_Registration_Form_Admin_Page extends Registration_Form_Admin_Page
15 15
 {
16 16
 
17
-    /**
18
-     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
19
-     */
20
-    public function __construct($routing = true)
21
-    {
22
-        define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND . 'registration_form/');
23
-        define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN . 'assets/');
24
-        define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/assets/');
25
-        define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN . 'templates/');
26
-        define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/templates/');
27
-        parent::__construct($routing);
28
-    }
29
-
30
-
31
-    /**
32
-     * @return void
33
-     */
34
-    protected function _extend_page_config()
35
-    {
36
-        $this->_admin_base_path = REGISTRATION_FORM_CAF_ADMIN;
37
-        $qst_id = ! empty($this->_req_data['QST_ID']) && ! is_array($this->_req_data['QST_ID'])
38
-            ? $this->_req_data['QST_ID'] : 0;
39
-        $qsg_id = ! empty($this->_req_data['QSG_ID']) && ! is_array($this->_req_data['QSG_ID'])
40
-            ? $this->_req_data['QSG_ID'] : 0;
41
-
42
-        $new_page_routes = array(
43
-            'question_groups'    => array(
44
-                'func'       => '_question_groups_overview_list_table',
45
-                'capability' => 'ee_read_question_groups',
46
-            ),
47
-            'add_question'       => array(
48
-                'func'       => '_edit_question',
49
-                'capability' => 'ee_edit_questions',
50
-            ),
51
-            'insert_question'    => array(
52
-                'func'       => '_insert_or_update_question',
53
-                'args'       => array('new_question' => true),
54
-                'capability' => 'ee_edit_questions',
55
-                'noheader'   => true,
56
-            ),
57
-            'duplicate_question' => array(
58
-                'func'       => '_duplicate_question',
59
-                'capability' => 'ee_edit_questions',
60
-                'noheader'   => true,
61
-            ),
62
-            'trash_question'     => array(
63
-                'func'       => '_trash_question',
64
-                'capability' => 'ee_delete_question',
65
-                'obj_id'     => $qst_id,
66
-                'noheader'   => true,
67
-            ),
68
-
69
-            'restore_question' => array(
70
-                'func'       => '_trash_or_restore_questions',
71
-                'capability' => 'ee_delete_question',
72
-                'obj_id'     => $qst_id,
73
-                'args'       => array('trash' => false),
74
-                'noheader'   => true,
75
-            ),
76
-
77
-            'delete_question' => array(
78
-                'func'       => '_delete_question',
79
-                'capability' => 'ee_delete_question',
80
-                'obj_id'     => $qst_id,
81
-                'noheader'   => true,
82
-            ),
83
-
84
-            'trash_questions' => array(
85
-                'func'       => '_trash_or_restore_questions',
86
-                'capability' => 'ee_delete_questions',
87
-                'args'       => array('trash' => true),
88
-                'noheader'   => true,
89
-            ),
90
-
91
-            'restore_questions' => array(
92
-                'func'       => '_trash_or_restore_questions',
93
-                'capability' => 'ee_delete_questions',
94
-                'args'       => array('trash' => false),
95
-                'noheader'   => true,
96
-            ),
97
-
98
-            'delete_questions' => array(
99
-                'func'       => '_delete_questions',
100
-                'args'       => array(),
101
-                'capability' => 'ee_delete_questions',
102
-                'noheader'   => true,
103
-            ),
104
-
105
-            'add_question_group' => array(
106
-                'func'       => '_edit_question_group',
107
-                'capability' => 'ee_edit_question_groups',
108
-            ),
109
-
110
-            'edit_question_group' => array(
111
-                'func'       => '_edit_question_group',
112
-                'capability' => 'ee_edit_question_group',
113
-                'obj_id'     => $qsg_id,
114
-                'args'       => array('edit'),
115
-            ),
116
-
117
-            'delete_question_groups' => array(
118
-                'func'       => '_delete_question_groups',
119
-                'capability' => 'ee_delete_question_groups',
120
-                'noheader'   => true,
121
-            ),
122
-
123
-            'delete_question_group' => array(
124
-                'func'       => '_delete_question_groups',
125
-                'capability' => 'ee_delete_question_group',
126
-                'obj_id'     => $qsg_id,
127
-                'noheader'   => true,
128
-            ),
129
-
130
-            'trash_question_group' => array(
131
-                'func'       => '_trash_or_restore_question_groups',
132
-                'args'       => array('trash' => true),
133
-                'capability' => 'ee_delete_question_group',
134
-                'obj_id'     => $qsg_id,
135
-                'noheader'   => true,
136
-            ),
137
-
138
-            'restore_question_group' => array(
139
-                'func'       => '_trash_or_restore_question_groups',
140
-                'args'       => array('trash' => false),
141
-                'capability' => 'ee_delete_question_group',
142
-                'obj_id'     => $qsg_id,
143
-                'noheader'   => true,
144
-            ),
145
-
146
-            'insert_question_group' => array(
147
-                'func'       => '_insert_or_update_question_group',
148
-                'args'       => array('new_question_group' => true),
149
-                'capability' => 'ee_edit_question_groups',
150
-                'noheader'   => true,
151
-            ),
152
-
153
-            'update_question_group' => array(
154
-                'func'       => '_insert_or_update_question_group',
155
-                'args'       => array('new_question_group' => false),
156
-                'capability' => 'ee_edit_question_group',
157
-                'obj_id'     => $qsg_id,
158
-                'noheader'   => true,
159
-            ),
160
-
161
-            'trash_question_groups' => array(
162
-                'func'       => '_trash_or_restore_question_groups',
163
-                'args'       => array('trash' => true),
164
-                'capability' => 'ee_delete_question_groups',
165
-                'noheader'   => array('trash' => false),
166
-            ),
167
-
168
-            'restore_question_groups' => array(
169
-                'func'       => '_trash_or_restore_question_groups',
170
-                'args'       => array('trash' => false),
171
-                'capability' => 'ee_delete_question_groups',
172
-                'noheader'   => true,
173
-            ),
174
-
175
-
176
-            'espresso_update_question_group_order' => array(
177
-                'func'       => 'update_question_group_order',
178
-                'capability' => 'ee_edit_question_groups',
179
-                'noheader'   => true,
180
-            ),
181
-
182
-            'view_reg_form_settings' => array(
183
-                'func'       => '_reg_form_settings',
184
-                'capability' => 'manage_options',
185
-            ),
186
-
187
-            'update_reg_form_settings' => array(
188
-                'func'       => '_update_reg_form_settings',
189
-                'capability' => 'manage_options',
190
-                'noheader'   => true,
191
-            ),
192
-        );
193
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
194
-
195
-        $new_page_config = array(
196
-
197
-            'question_groups' => array(
198
-                'nav'           => array(
199
-                    'label' => esc_html__('Question Groups', 'event_espresso'),
200
-                    'order' => 20,
201
-                ),
202
-                'list_table'    => 'Registration_Form_Question_Groups_Admin_List_Table',
203
-                'help_tabs'     => array(
204
-                    'registration_form_question_groups_help_tab'                           => array(
205
-                        'title'    => esc_html__('Question Groups', 'event_espresso'),
206
-                        'filename' => 'registration_form_question_groups',
207
-                    ),
208
-                    'registration_form_question_groups_table_column_headings_help_tab'     => array(
209
-                        'title'    => esc_html__('Question Groups Table Column Headings', 'event_espresso'),
210
-                        'filename' => 'registration_form_question_groups_table_column_headings',
211
-                    ),
212
-                    'registration_form_question_groups_views_bulk_actions_search_help_tab' => array(
213
-                        'title'    => esc_html__('Question Groups Views & Bulk Actions & Search', 'event_espresso'),
214
-                        'filename' => 'registration_form_question_groups_views_bulk_actions_search',
215
-                    ),
216
-                ),
217
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
218
-                // 'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
219
-                'metaboxes'     => $this->_default_espresso_metaboxes,
220
-                'require_nonce' => false,
221
-                'qtips'         => array(
222
-                    'EE_Registration_Form_Tips',
223
-                ),
224
-            ),
225
-
226
-            'add_question' => array(
227
-                'nav'           => array(
228
-                    'label'      => esc_html__('Add Question', 'event_espresso'),
229
-                    'order'      => 5,
230
-                    'persistent' => false,
231
-                ),
232
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
233
-                'help_tabs'     => array(
234
-                    'registration_form_add_question_help_tab' => array(
235
-                        'title'    => esc_html__('Add Question', 'event_espresso'),
236
-                        'filename' => 'registration_form_add_question',
237
-                    ),
238
-                ),
239
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
240
-                // 'help_tour'     => array('Registration_Form_Add_Question_Help_Tour'),
241
-                'require_nonce' => false,
242
-            ),
243
-
244
-            'add_question_group' => array(
245
-                'nav'           => array(
246
-                    'label'      => esc_html__('Add Question Group', 'event_espresso'),
247
-                    'order'      => 5,
248
-                    'persistent' => false,
249
-                ),
250
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
251
-                'help_tabs'     => array(
252
-                    'registration_form_add_question_group_help_tab' => array(
253
-                        'title'    => esc_html__('Add Question Group', 'event_espresso'),
254
-                        'filename' => 'registration_form_add_question_group',
255
-                    ),
256
-                ),
257
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
258
-                // 'help_tour'     => array('Registration_Form_Add_Question_Group_Help_Tour'),
259
-                'require_nonce' => false,
260
-            ),
261
-
262
-            'edit_question_group' => array(
263
-                'nav'           => array(
264
-                    'label'      => esc_html__('Edit Question Group', 'event_espresso'),
265
-                    'order'      => 5,
266
-                    'persistent' => false,
267
-                    'url'        => isset($this->_req_data['question_group_id']) ? add_query_arg(
268
-                        array('question_group_id' => $this->_req_data['question_group_id']),
269
-                        $this->_current_page_view_url
270
-                    ) : $this->_admin_base_url,
271
-                ),
272
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
273
-                'help_tabs'     => array(
274
-                    'registration_form_edit_question_group_help_tab' => array(
275
-                        'title'    => esc_html__('Edit Question Group', 'event_espresso'),
276
-                        'filename' => 'registration_form_edit_question_group',
277
-                    ),
278
-                ),
279
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
280
-                // 'help_tour'     => array('Registration_Form_Edit_Question_Group_Help_Tour'),
281
-                'require_nonce' => false,
282
-            ),
283
-
284
-            'view_reg_form_settings' => array(
285
-                'nav'           => array(
286
-                    'label' => esc_html__('Reg Form Settings', 'event_espresso'),
287
-                    'order' => 40,
288
-                ),
289
-                'labels'        => array(
290
-                    'publishbox' => esc_html__('Update Settings', 'event_espresso'),
291
-                ),
292
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
293
-                'help_tabs'     => array(
294
-                    'registration_form_reg_form_settings_help_tab' => array(
295
-                        'title'    => esc_html__('Registration Form Settings', 'event_espresso'),
296
-                        'filename' => 'registration_form_reg_form_settings',
297
-                    ),
298
-                ),
299
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
300
-                // 'help_tour'     => array('Registration_Form_Settings_Help_Tour'),
301
-                'require_nonce' => false,
302
-            ),
303
-
304
-        );
305
-        $this->_page_config = array_merge($this->_page_config, $new_page_config);
306
-
307
-        // change the list table we're going to use so it's the NEW list table!
308
-        $this->_page_config['default']['list_table'] = 'Extend_Registration_Form_Questions_Admin_List_Table';
309
-
310
-
311
-        // additional labels
312
-        $new_labels = array(
313
-            'add_question'          => esc_html__('Add New Question', 'event_espresso'),
314
-            'delete_question'       => esc_html__('Delete Question', 'event_espresso'),
315
-            'add_question_group'    => esc_html__('Add New Question Group', 'event_espresso'),
316
-            'edit_question_group'   => esc_html__('Edit Question Group', 'event_espresso'),
317
-            'delete_question_group' => esc_html__('Delete Question Group', 'event_espresso'),
318
-        );
319
-        $this->_labels['buttons'] = array_merge($this->_labels['buttons'], $new_labels);
320
-    }
321
-
322
-
323
-    /**
324
-     * @return void
325
-     */
326
-    protected function _ajax_hooks()
327
-    {
328
-        add_action('wp_ajax_espresso_update_question_group_order', array($this, 'update_question_group_order'));
329
-    }
330
-
331
-
332
-    /**
333
-     * @return void
334
-     */
335
-    public function load_scripts_styles_question_groups()
336
-    {
337
-        wp_enqueue_script('espresso_ajax_table_sorting');
338
-    }
339
-
340
-
341
-    /**
342
-     * @return void
343
-     */
344
-    public function load_scripts_styles_add_question_group()
345
-    {
346
-        $this->load_scripts_styles_forms();
347
-        $this->load_sortable_question_script();
348
-    }
349
-
350
-
351
-    /**
352
-     * @return void
353
-     */
354
-    public function load_scripts_styles_edit_question_group()
355
-    {
356
-        $this->load_scripts_styles_forms();
357
-        $this->load_sortable_question_script();
358
-    }
359
-
360
-
361
-    /**
362
-     * registers and enqueues script for questions
363
-     *
364
-     * @return void
365
-     */
366
-    public function load_sortable_question_script()
367
-    {
368
-        wp_register_script(
369
-            'ee-question-sortable',
370
-            REGISTRATION_FORM_CAF_ASSETS_URL . 'ee_question_order.js',
371
-            array('jquery-ui-sortable'),
372
-            EVENT_ESPRESSO_VERSION,
373
-            true
374
-        );
375
-        wp_enqueue_script('ee-question-sortable');
376
-    }
377
-
378
-
379
-    /**
380
-     * @return void
381
-     */
382
-    protected function _set_list_table_views_default()
383
-    {
384
-        $this->_views = array(
385
-            'all' => array(
386
-                'slug'        => 'all',
387
-                'label'       => esc_html__('View All Questions', 'event_espresso'),
388
-                'count'       => 0,
389
-                'bulk_action' => array(
390
-                    'trash_questions' => esc_html__('Trash', 'event_espresso'),
391
-                ),
392
-            ),
393
-        );
394
-
395
-        if (
396
-            EE_Registry::instance()->CAP->current_user_can(
397
-                'ee_delete_questions',
398
-                'espresso_registration_form_trash_questions'
399
-            )
400
-        ) {
401
-            $this->_views['trash'] = array(
402
-                'slug'        => 'trash',
403
-                'label'       => esc_html__('Trash', 'event_espresso'),
404
-                'count'       => 0,
405
-                'bulk_action' => array(
406
-                    'delete_questions'  => esc_html__('Delete Permanently', 'event_espresso'),
407
-                    'restore_questions' => esc_html__('Restore', 'event_espresso'),
408
-                ),
409
-            );
410
-        }
411
-    }
412
-
413
-
414
-    /**
415
-     * @return void
416
-     */
417
-    protected function _set_list_table_views_question_groups()
418
-    {
419
-        $this->_views = array(
420
-            'all' => array(
421
-                'slug'        => 'all',
422
-                'label'       => esc_html__('All', 'event_espresso'),
423
-                'count'       => 0,
424
-                'bulk_action' => array(
425
-                    'trash_question_groups' => esc_html__('Trash', 'event_espresso'),
426
-                ),
427
-            ),
428
-        );
429
-
430
-        if (
431
-            EE_Registry::instance()->CAP->current_user_can(
432
-                'ee_delete_question_groups',
433
-                'espresso_registration_form_trash_question_groups'
434
-            )
435
-        ) {
436
-            $this->_views['trash'] = array(
437
-                'slug'        => 'trash',
438
-                'label'       => esc_html__('Trash', 'event_espresso'),
439
-                'count'       => 0,
440
-                'bulk_action' => array(
441
-                    'delete_question_groups'  => esc_html__('Delete Permanently', 'event_espresso'),
442
-                    'restore_question_groups' => esc_html__('Restore', 'event_espresso'),
443
-                ),
444
-            );
445
-        }
446
-    }
447
-
448
-
449
-    /**
450
-     * @return void
451
-     * @throws EE_Error
452
-     * @throws InvalidArgumentException
453
-     * @throws InvalidDataTypeException
454
-     * @throws InvalidInterfaceException
455
-     */
456
-    protected function _questions_overview_list_table()
457
-    {
458
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
459
-            'add_question',
460
-            'add_question',
461
-            array(),
462
-            'add-new-h2'
463
-        );
464
-        parent::_questions_overview_list_table();
465
-    }
466
-
467
-
468
-    /**
469
-     * @return void
470
-     * @throws DomainException
471
-     * @throws EE_Error
472
-     * @throws InvalidArgumentException
473
-     * @throws InvalidDataTypeException
474
-     * @throws InvalidInterfaceException
475
-     */
476
-    protected function _question_groups_overview_list_table()
477
-    {
478
-        $this->_search_btn_label = esc_html__('Question Groups', 'event_espresso');
479
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
480
-            'add_question_group',
481
-            'add_question_group',
482
-            array(),
483
-            'add-new-h2'
484
-        );
485
-        $this->display_admin_list_table_page_with_sidebar();
486
-    }
487
-
488
-
489
-    /**
490
-     * @return void
491
-     * @throws EE_Error
492
-     * @throws InvalidArgumentException
493
-     * @throws InvalidDataTypeException
494
-     * @throws InvalidInterfaceException
495
-     */
496
-    protected function _delete_question()
497
-    {
498
-        $success = $this->_delete_items($this->_question_model);
499
-        $this->_redirect_after_action(
500
-            $success,
501
-            $this->_question_model->item_name($success),
502
-            'deleted',
503
-            array('action' => 'default', 'status' => 'all')
504
-        );
505
-    }
506
-
507
-
508
-    /**
509
-     * @return void
510
-     * @throws EE_Error
511
-     * @throws InvalidArgumentException
512
-     * @throws InvalidDataTypeException
513
-     * @throws InvalidInterfaceException
514
-     */
515
-    protected function _delete_questions()
516
-    {
517
-        $success = $this->_delete_items($this->_question_model);
518
-        $this->_redirect_after_action(
519
-            $success,
520
-            $this->_question_model->item_name($success),
521
-            'deleted permanently',
522
-            array('action' => 'default', 'status' => 'trash')
523
-        );
524
-    }
525
-
526
-
527
-    /**
528
-     * Performs the deletion of a single or multiple questions or question groups.
529
-     *
530
-     * @param EEM_Soft_Delete_Base $model
531
-     * @return int number of items deleted permanently
532
-     * @throws EE_Error
533
-     * @throws InvalidArgumentException
534
-     * @throws InvalidDataTypeException
535
-     * @throws InvalidInterfaceException
536
-     */
537
-    private function _delete_items(EEM_Soft_Delete_Base $model)
538
-    {
539
-        $success = 0;
540
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
541
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
542
-            // if array has more than one element than success message should be plural
543
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
544
-            // cycle thru bulk action checkboxes
545
-            while (list($ID, $value) = each($this->_req_data['checkbox'])) {
546
-                if (! $this->_delete_item($ID, $model)) {
547
-                    $success = 0;
548
-                }
549
-            }
550
-        } elseif (! empty($this->_req_data['QSG_ID'])) {
551
-            $success = $this->_delete_item($this->_req_data['QSG_ID'], $model);
552
-        } elseif (! empty($this->_req_data['QST_ID'])) {
553
-            $success = $this->_delete_item($this->_req_data['QST_ID'], $model);
554
-        } else {
555
-            EE_Error::add_error(
556
-                sprintf(
557
-                    esc_html__(
558
-                        "No Questions or Question Groups were selected for deleting. This error usually shows when you've attempted to delete via bulk action but there were no selections.",
559
-                        "event_espresso"
560
-                    )
561
-                ),
562
-                __FILE__,
563
-                __FUNCTION__,
564
-                __LINE__
565
-            );
566
-        }
567
-        return $success;
568
-    }
569
-
570
-
571
-    /**
572
-     * Deletes the specified question (and its associated question options) or question group
573
-     *
574
-     * @param int                  $id
575
-     * @param EEM_Soft_Delete_Base $model
576
-     * @return boolean
577
-     * @throws EE_Error
578
-     * @throws InvalidArgumentException
579
-     * @throws InvalidDataTypeException
580
-     * @throws InvalidInterfaceException
581
-     */
582
-    protected function _delete_item($id, $model)
583
-    {
584
-        if ($model instanceof EEM_Question) {
585
-            EEM_Question_Option::instance()->delete_permanently(array(array('QST_ID' => absint($id))));
586
-        }
587
-        return $model->delete_permanently_by_ID(absint($id));
588
-    }
589
-
590
-
591
-    /******************************    QUESTION GROUPS    ******************************/
592
-
593
-
594
-    /**
595
-     * @param string $type
596
-     * @return void
597
-     * @throws DomainException
598
-     * @throws EE_Error
599
-     * @throws InvalidArgumentException
600
-     * @throws InvalidDataTypeException
601
-     * @throws InvalidInterfaceException
602
-     */
603
-    protected function _edit_question_group($type = 'add')
604
-    {
605
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
606
-        $ID = isset($this->_req_data['QSG_ID']) && ! empty($this->_req_data['QSG_ID'])
607
-            ? absint($this->_req_data['QSG_ID'])
608
-            : false;
609
-
610
-        switch ($this->_req_action) {
611
-            case 'add_question_group':
612
-                $this->_admin_page_title = esc_html__('Add Question Group', 'event_espresso');
613
-                break;
614
-            case 'edit_question_group':
615
-                $this->_admin_page_title = esc_html__('Edit Question Group', 'event_espresso');
616
-                break;
617
-            default:
618
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
619
-        }
620
-        // add ID to title if editing
621
-        $this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
622
-        if ($ID) {
623
-            /** @var EE_Question_Group $questionGroup */
624
-            $questionGroup = $this->_question_group_model->get_one_by_ID($ID);
625
-            $additional_hidden_fields = array('QSG_ID' => array('type' => 'hidden', 'value' => $ID));
626
-            $this->_set_add_edit_form_tags('update_question_group', $additional_hidden_fields);
627
-        } else {
628
-            /** @var EE_Question_Group $questionGroup */
629
-            $questionGroup = EEM_Question_Group::instance()->create_default_object();
630
-            $questionGroup->set_order_to_latest();
631
-            $this->_set_add_edit_form_tags('insert_question_group');
632
-        }
633
-        $this->_template_args['values'] = $this->_yes_no_values;
634
-        $this->_template_args['all_questions'] = $questionGroup->questions_in_and_not_in_group();
635
-        $this->_template_args['QSG_ID'] = $ID ? $ID : true;
636
-        $this->_template_args['question_group'] = $questionGroup;
637
-
638
-        $redirect_URL = add_query_arg(array('action' => 'question_groups'), $this->_admin_base_url);
639
-        $this->_set_publish_post_box_vars('id', $ID, false, $redirect_URL);
640
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
641
-            REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'question_groups_main_meta_box.template.php',
642
-            $this->_template_args,
643
-            true
644
-        );
645
-
646
-        // the details template wrapper
647
-        $this->display_admin_page_with_sidebar();
648
-    }
649
-
650
-
651
-    /**
652
-     * @return void
653
-     * @throws EE_Error
654
-     * @throws InvalidArgumentException
655
-     * @throws InvalidDataTypeException
656
-     * @throws InvalidInterfaceException
657
-     */
658
-    protected function _delete_question_groups()
659
-    {
660
-        $success = $this->_delete_items($this->_question_group_model);
661
-        $this->_redirect_after_action(
662
-            $success,
663
-            $this->_question_group_model->item_name($success),
664
-            'deleted permanently',
665
-            array('action' => 'question_groups', 'status' => 'trash')
666
-        );
667
-    }
668
-
669
-
670
-    /**
671
-     * @param bool $new_question_group
672
-     * @throws EE_Error
673
-     * @throws InvalidArgumentException
674
-     * @throws InvalidDataTypeException
675
-     * @throws InvalidInterfaceException
676
-     */
677
-    protected function _insert_or_update_question_group($new_question_group = true)
678
-    {
679
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
680
-        $set_column_values = $this->_set_column_values_for($this->_question_group_model);
681
-        if ($new_question_group) {
682
-            // make sure identifier is unique
683
-            $identifier_value = isset($set_column_values['QSG_identifier']) ? $set_column_values['QSG_identifier'] : '';
684
-            $identifier_exists = ! empty($identifier_value)
685
-                ? $this->_question_group_model->count([['QSG_identifier' => $set_column_values['QSG_identifier']]]) > 0
686
-                : false;
687
-            if ($identifier_exists) {
688
-                $set_column_values['QSG_identifier'] .= uniqid('id', true);
689
-            }
690
-            $QSG_ID = $this->_question_group_model->insert($set_column_values);
691
-            $success = $QSG_ID ? 1 : 0;
692
-            if ($success === 0) {
693
-                EE_Error::add_error(
694
-                    esc_html__('Something went wrong saving the question group.', 'event_espresso'),
695
-                    __FILE__,
696
-                    __FUNCTION__,
697
-                    __LINE__
698
-                );
699
-                $this->_redirect_after_action(
700
-                    false,
701
-                    '',
702
-                    '',
703
-                    array('action' => 'edit_question_group', 'QSG_ID' => $QSG_ID),
704
-                    true
705
-                );
706
-            }
707
-        } else {
708
-            $QSG_ID = absint($this->_req_data['QSG_ID']);
709
-            unset($set_column_values['QSG_ID']);
710
-            $success = $this->_question_group_model->update($set_column_values, array(array('QSG_ID' => $QSG_ID)));
711
-        }
712
-
713
-        $phone_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(
714
-            EEM_Attendee::system_question_phone
715
-        );
716
-        // update the existing related questions
717
-        // BUT FIRST...  delete the phone question from the Question_Group_Question
718
-        // if it is being added to this question group (therefore removed from the existing group)
719
-        if (isset($this->_req_data['questions'], $this->_req_data['questions'][ $phone_question_id ])) {
720
-            // delete where QST ID = system phone question ID and Question Group ID is NOT this group
721
-            EEM_Question_Group_Question::instance()->delete(
722
-                array(
723
-                    array(
724
-                        'QST_ID' => $phone_question_id,
725
-                        'QSG_ID' => array('!=', $QSG_ID),
726
-                    ),
727
-                )
728
-            );
729
-        }
730
-        /** @type EE_Question_Group $question_group */
731
-        $question_group = $this->_question_group_model->get_one_by_ID($QSG_ID);
732
-        $questions = $question_group->questions();
733
-        // make sure system phone question is added to list of questions for this group
734
-        if (! isset($questions[ $phone_question_id ])) {
735
-            $questions[ $phone_question_id ] = EEM_Question::instance()->get_one_by_ID($phone_question_id);
736
-        }
737
-
738
-        foreach ($questions as $question_ID => $question) {
739
-            // first we always check for order.
740
-            if (! empty($this->_req_data['question_orders'][ $question_ID ])) {
741
-                // update question order
742
-                $question_group->update_question_order(
743
-                    $question_ID,
744
-                    $this->_req_data['question_orders'][ $question_ID ]
745
-                );
746
-            }
747
-
748
-            // then we always check if adding or removing.
749
-            if (isset($this->_req_data['questions'], $this->_req_data['questions'][ $question_ID ])) {
750
-                $question_group->add_question($question_ID);
751
-            } else {
752
-                // not found, remove it (but only if not a system question for the personal group
753
-                // with the exception of lname system question - we allow removal of it)
754
-                if (
755
-                    in_array(
756
-                        $question->system_ID(),
757
-                        EEM_Question::instance()->required_system_questions_in_system_question_group(
758
-                            $question_group->system_group()
759
-                        )
760
-                    )
761
-                ) {
762
-                    continue;
763
-                } else {
764
-                    $question_group->remove_question($question_ID);
765
-                }
766
-            }
767
-        }
768
-        // save new related questions
769
-        if (isset($this->_req_data['questions'])) {
770
-            foreach ($this->_req_data['questions'] as $QST_ID) {
771
-                $question_group->add_question($QST_ID);
772
-                if (isset($this->_req_data['question_orders'][ $QST_ID ])) {
773
-                    $question_group->update_question_order($QST_ID, $this->_req_data['question_orders'][ $QST_ID ]);
774
-                }
775
-            }
776
-        }
777
-
778
-        if ($success !== false) {
779
-            $msg = $new_question_group
780
-                ? sprintf(
781
-                    esc_html__('The %s has been created', 'event_espresso'),
782
-                    $this->_question_group_model->item_name()
783
-                )
784
-                : sprintf(
785
-                    esc_html__(
786
-                        'The %s has been updated',
787
-                        'event_espresso'
788
-                    ),
789
-                    $this->_question_group_model->item_name()
790
-                );
791
-            EE_Error::add_success($msg);
792
-        }
793
-        $this->_redirect_after_action(
794
-            false,
795
-            '',
796
-            '',
797
-            array('action' => 'edit_question_group', 'QSG_ID' => $QSG_ID),
798
-            true
799
-        );
800
-    }
801
-
802
-
803
-    /**
804
-     * duplicates a question and all its question options and redirects to the new question.
805
-     *
806
-     * @return void
807
-     * @throws EE_Error
808
-     * @throws InvalidArgumentException
809
-     * @throws ReflectionException
810
-     * @throws InvalidDataTypeException
811
-     * @throws InvalidInterfaceException
812
-     */
813
-    public function _duplicate_question()
814
-    {
815
-        $question_ID = (int) $this->_req_data['QST_ID'];
816
-        $question = EEM_Question::instance()->get_one_by_ID($question_ID);
817
-        if ($question instanceof EE_Question) {
818
-            $new_question = $question->duplicate();
819
-            if ($new_question instanceof EE_Question) {
820
-                $this->_redirect_after_action(
821
-                    true,
822
-                    esc_html__('Question', 'event_espresso'),
823
-                    esc_html__('Duplicated', 'event_espresso'),
824
-                    array('action' => 'edit_question', 'QST_ID' => $new_question->ID()),
825
-                    true
826
-                );
827
-            } else {
828
-                global $wpdb;
829
-                EE_Error::add_error(
830
-                    sprintf(
831
-                        esc_html__(
832
-                            'Could not duplicate question with ID %1$d because: %2$s',
833
-                            'event_espresso'
834
-                        ),
835
-                        $question_ID,
836
-                        $wpdb->last_error
837
-                    ),
838
-                    __FILE__,
839
-                    __FUNCTION__,
840
-                    __LINE__
841
-                );
842
-                $this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
843
-            }
844
-        } else {
845
-            EE_Error::add_error(
846
-                sprintf(
847
-                    esc_html__(
848
-                        'Could not duplicate question with ID %d because it didn\'t exist!',
849
-                        'event_espresso'
850
-                    ),
851
-                    $question_ID
852
-                ),
853
-                __FILE__,
854
-                __FUNCTION__,
855
-                __LINE__
856
-            );
857
-            $this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
858
-        }
859
-    }
860
-
861
-
862
-    /**
863
-     * @param bool $trash
864
-     * @throws EE_Error
865
-     */
866
-    protected function _trash_or_restore_question_groups($trash = true)
867
-    {
868
-        $this->_trash_or_restore_items($this->_question_group_model, $trash);
869
-    }
870
-
871
-
872
-    /**
873
-     *_trash_question
874
-     *
875
-     * @return void
876
-     * @throws EE_Error
877
-     */
878
-    protected function _trash_question()
879
-    {
880
-        $success = $this->_question_model->delete_by_ID((int) $this->_req_data['QST_ID']);
881
-        $query_args = array('action' => 'default', 'status' => 'all');
882
-        $this->_redirect_after_action($success, $this->_question_model->item_name($success), 'trashed', $query_args);
883
-    }
884
-
885
-
886
-    /**
887
-     * @param bool $trash
888
-     * @throws EE_Error
889
-     */
890
-    protected function _trash_or_restore_questions($trash = true)
891
-    {
892
-        $this->_trash_or_restore_items($this->_question_model, $trash);
893
-    }
894
-
895
-
896
-    /**
897
-     * Internally used to delete or restore items, using the request data. Meant to be
898
-     * flexible between question or question groups
899
-     *
900
-     * @param EEM_Soft_Delete_Base $model
901
-     * @param boolean              $trash whether to trash or restore
902
-     * @throws EE_Error
903
-     */
904
-    private function _trash_or_restore_items(EEM_Soft_Delete_Base $model, $trash = true)
905
-    {
906
-
907
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
908
-
909
-        $success = 1;
910
-        // Checkboxes
911
-        // echo "trash $trash";
912
-        // var_dump($this->_req_data['checkbox']);die;
913
-        if (isset($this->_req_data['checkbox'])) {
914
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
915
-                // if array has more than one element than success message should be plural
916
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
917
-                // cycle thru bulk action checkboxes
918
-                while (list($ID, $value) = each($this->_req_data['checkbox'])) {
919
-                    if (! $model->delete_or_restore_by_ID($trash, absint($ID))) {
920
-                        $success = 0;
921
-                    }
922
-                }
923
-            } else {
924
-                // grab single id and delete
925
-                $ID = absint($this->_req_data['checkbox']);
926
-                if (! $model->delete_or_restore_by_ID($trash, $ID)) {
927
-                    $success = 0;
928
-                }
929
-            }
930
-        } else {
931
-            // delete via trash link
932
-            // grab single id and delete
933
-            $ID = absint($this->_req_data[ $model->primary_key_name() ]);
934
-            if (! $model->delete_or_restore_by_ID($trash, $ID)) {
935
-                $success = 0;
936
-            }
937
-        }
938
-
939
-
940
-        $action = $model instanceof EEM_Question ? 'default' : 'question_groups';// strtolower( $model->item_name(2) );
941
-        // echo "action :$action";
942
-        // $action = 'questions' ? 'default' : $action;
943
-        if ($trash) {
944
-            $action_desc = 'trashed';
945
-            $status = 'trash';
946
-        } else {
947
-            $action_desc = 'restored';
948
-            $status = 'all';
949
-        }
950
-        $this->_redirect_after_action(
951
-            $success,
952
-            $model->item_name($success),
953
-            $action_desc,
954
-            array('action' => $action, 'status' => $status)
955
-        );
956
-    }
957
-
958
-
959
-    /**
960
-     * @param            $per_page
961
-     * @param int        $current_page
962
-     * @param bool|false $count
963
-     * @return EE_Soft_Delete_Base_Class[]|int
964
-     * @throws EE_Error
965
-     * @throws InvalidArgumentException
966
-     * @throws InvalidDataTypeException
967
-     * @throws InvalidInterfaceException
968
-     */
969
-    public function get_trashed_questions($per_page, $current_page = 1, $count = false)
970
-    {
971
-        $query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
972
-
973
-        if ($count) {
974
-            // note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
975
-            $where = isset($query_params[0]) ? array($query_params[0]) : array();
976
-            $results = $this->_question_model->count_deleted($where);
977
-        } else {
978
-            // note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
979
-            $results = $this->_question_model->get_all_deleted($query_params);
980
-        }
981
-        return $results;
982
-    }
983
-
984
-
985
-    /**
986
-     * @param            $per_page
987
-     * @param int        $current_page
988
-     * @param bool|false $count
989
-     * @return EE_Soft_Delete_Base_Class[]|int
990
-     * @throws EE_Error
991
-     * @throws InvalidArgumentException
992
-     * @throws InvalidDataTypeException
993
-     * @throws InvalidInterfaceException
994
-     */
995
-    public function get_question_groups($per_page, $current_page = 1, $count = false)
996
-    {
997
-        $questionGroupModel = EEM_Question_Group::instance();
998
-        $query_params = $this->get_query_params($questionGroupModel, $per_page, $current_page);
999
-        if ($count) {
1000
-            $where = isset($query_params[0]) ? array($query_params[0]) : array();
1001
-            $results = $questionGroupModel->count($where);
1002
-        } else {
1003
-            $results = $questionGroupModel->get_all($query_params);
1004
-        }
1005
-        return $results;
1006
-    }
1007
-
1008
-
1009
-    /**
1010
-     * @param      $per_page
1011
-     * @param int  $current_page
1012
-     * @param bool $count
1013
-     * @return EE_Soft_Delete_Base_Class[]|int
1014
-     * @throws EE_Error
1015
-     * @throws InvalidArgumentException
1016
-     * @throws InvalidDataTypeException
1017
-     * @throws InvalidInterfaceException
1018
-     */
1019
-    public function get_trashed_question_groups($per_page, $current_page = 1, $count = false)
1020
-    {
1021
-        $questionGroupModel = EEM_Question_Group::instance();
1022
-        $query_params = $this->get_query_params($questionGroupModel, $per_page, $current_page);
1023
-        if ($count) {
1024
-            $where = isset($query_params[0]) ? array($query_params[0]) : array();
1025
-            $query_params['limit'] = null;
1026
-            $results = $questionGroupModel->count_deleted($where);
1027
-        } else {
1028
-            $results = $questionGroupModel->get_all_deleted($query_params);
1029
-        }
1030
-        return $results;
1031
-    }
1032
-
1033
-
1034
-    /**
1035
-     * method for performing updates to question order
1036
-     *
1037
-     * @return void results array
1038
-     * @throws EE_Error
1039
-     * @throws InvalidArgumentException
1040
-     * @throws InvalidDataTypeException
1041
-     * @throws InvalidInterfaceException
1042
-     */
1043
-    public function update_question_group_order()
1044
-    {
1045
-
1046
-        $success = esc_html__('Question group order was updated successfully.', 'event_espresso');
1047
-
1048
-        // grab our row IDs
1049
-        $row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids'])
1050
-            ? explode(',', rtrim($this->_req_data['row_ids'], ','))
1051
-            : array();
1052
-
1053
-        $perpage = ! empty($this->_req_data['perpage'])
1054
-            ? (int) $this->_req_data['perpage']
1055
-            : null;
1056
-        $curpage = ! empty($this->_req_data['curpage'])
1057
-            ? (int) $this->_req_data['curpage']
1058
-            : null;
1059
-
1060
-        if (! empty($row_ids)) {
1061
-            // figure out where we start the row_id count at for the current page.
1062
-            $qsgcount = empty($curpage) ? 0 : ($curpage - 1) * $perpage;
1063
-
1064
-            $row_count = count($row_ids);
1065
-            for ($i = 0; $i < $row_count; $i++) {
1066
-                // Update the questions when re-ordering
1067
-                $updated = EEM_Question_Group::instance()->update(
1068
-                    array('QSG_order' => $qsgcount),
1069
-                    array(array('QSG_ID' => $row_ids[ $i ]))
1070
-                );
1071
-                if ($updated === false) {
1072
-                    $success = false;
1073
-                }
1074
-                $qsgcount++;
1075
-            }
1076
-        } else {
1077
-            $success = false;
1078
-        }
1079
-
1080
-        $errors = ! $success
1081
-            ? esc_html__('An error occurred. The question group order was not updated.', 'event_espresso')
1082
-            : false;
1083
-
1084
-        echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
1085
-        die();
1086
-    }
1087
-
1088
-
1089
-
1090
-    /***************************************       REGISTRATION SETTINGS       ***************************************/
1091
-
1092
-
1093
-    /**
1094
-     * @throws DomainException
1095
-     * @throws EE_Error
1096
-     * @throws InvalidArgumentException
1097
-     * @throws InvalidDataTypeException
1098
-     * @throws InvalidInterfaceException
1099
-     */
1100
-    protected function _reg_form_settings()
1101
-    {
1102
-        $this->_template_args['values'] = $this->_yes_no_values;
1103
-        add_action(
1104
-            'AHEE__Extend_Registration_Form_Admin_Page___reg_form_settings_template',
1105
-            array($this, 'email_validation_settings_form'),
1106
-            2
1107
-        );
1108
-        add_action(
1109
-            'AHEE__Extend_Registration_Form_Admin_Page___reg_form_settings_template',
1110
-            array($this, 'copy_attendee_info_settings_form'),
1111
-            4
1112
-        );
1113
-        $this->_template_args = (array) apply_filters(
1114
-            'FHEE__Extend_Registration_Form_Admin_Page___reg_form_settings___template_args',
1115
-            $this->_template_args
1116
-        );
1117
-        $this->_set_add_edit_form_tags('update_reg_form_settings');
1118
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
1119
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1120
-            REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'reg_form_settings.template.php',
1121
-            $this->_template_args,
1122
-            true
1123
-        );
1124
-        $this->display_admin_page_with_sidebar();
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * @return void
1130
-     * @throws EE_Error
1131
-     * @throws InvalidArgumentException
1132
-     * @throws ReflectionException
1133
-     * @throws InvalidDataTypeException
1134
-     * @throws InvalidInterfaceException
1135
-     */
1136
-    protected function _update_reg_form_settings()
1137
-    {
1138
-        EE_Registry::instance()->CFG->registration = $this->update_email_validation_settings_form(
1139
-            EE_Registry::instance()->CFG->registration
1140
-        );
1141
-        EE_Registry::instance()->CFG->registration = $this->update_copy_attendee_info_settings_form(
1142
-            EE_Registry::instance()->CFG->registration
1143
-        );
1144
-        EE_Registry::instance()->CFG->registration = apply_filters(
1145
-            'FHEE__Extend_Registration_Form_Admin_Page___update_reg_form_settings__CFG_registration',
1146
-            EE_Registry::instance()->CFG->registration
1147
-        );
1148
-        $success = $this->_update_espresso_configuration(
1149
-            esc_html__('Registration Form Options', 'event_espresso'),
1150
-            EE_Registry::instance()->CFG,
1151
-            __FILE__,
1152
-            __FUNCTION__,
1153
-            __LINE__
1154
-        );
1155
-        $this->_redirect_after_action(
1156
-            $success,
1157
-            esc_html__('Registration Form Options', 'event_espresso'),
1158
-            'updated',
1159
-            array('action' => 'view_reg_form_settings')
1160
-        );
1161
-    }
1162
-
1163
-
1164
-    /**
1165
-     * @return void
1166
-     * @throws EE_Error
1167
-     * @throws InvalidArgumentException
1168
-     * @throws InvalidDataTypeException
1169
-     * @throws InvalidInterfaceException
1170
-     */
1171
-    public function copy_attendee_info_settings_form()
1172
-    {
1173
-        echo $this->_copy_attendee_info_settings_form()->get_html();
1174
-    }
1175
-
1176
-    /**
1177
-     * _copy_attendee_info_settings_form
1178
-     *
1179
-     * @access protected
1180
-     * @return EE_Form_Section_Proper
1181
-     * @throws \EE_Error
1182
-     */
1183
-    protected function _copy_attendee_info_settings_form()
1184
-    {
1185
-        return new EE_Form_Section_Proper(
1186
-            array(
1187
-                'name'            => 'copy_attendee_info_settings',
1188
-                'html_id'         => 'copy_attendee_info_settings',
1189
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1190
-                'subsections'     => apply_filters(
1191
-                    'FHEE__Extend_Registration_Form_Admin_Page___copy_attendee_info_settings_form__form_subsections',
1192
-                    array(
1193
-                        'copy_attendee_info_hdr'   => new EE_Form_Section_HTML(
1194
-                            EEH_HTML::h2(esc_html__('Copy Attendee Info Settings', 'event_espresso'))
1195
-                        ),
1196
-                        'copy_attendee_info' => new EE_Yes_No_Input(
1197
-                            array(
1198
-                                'html_label_text' => esc_html__(
1199
-                                    'Allow copy #1 attendee info to extra attendees?',
1200
-                                    'event_espresso'
1201
-                                ),
1202
-                                'html_help_text'  => esc_html__(
1203
-                                    'Set to yes if you want to enable the copy of #1 attendee info to extra attendees at Registration Form.',
1204
-                                    'event_espresso'
1205
-                                ),
1206
-                                'default'         => EE_Registry::instance()->CFG->registration->copyAttendeeInfo(),
1207
-                                'required'        => false,
1208
-                                'display_html_label_text' => false,
1209
-                            )
1210
-                        ),
1211
-                    )
1212
-                ),
1213
-            )
1214
-        );
1215
-    }
1216
-
1217
-    /**
1218
-     * @param EE_Registration_Config $EE_Registration_Config
1219
-     * @return EE_Registration_Config
1220
-     * @throws EE_Error
1221
-     * @throws InvalidArgumentException
1222
-     * @throws ReflectionException
1223
-     * @throws InvalidDataTypeException
1224
-     * @throws InvalidInterfaceException
1225
-     */
1226
-    public function update_copy_attendee_info_settings_form(EE_Registration_Config $EE_Registration_Config)
1227
-    {
1228
-        $prev_copy_attendee_info = $EE_Registration_Config->copyAttendeeInfo();
1229
-        try {
1230
-            $copy_attendee_info_settings_form = $this->_copy_attendee_info_settings_form();
1231
-            // if not displaying a form, then check for form submission
1232
-            if ($copy_attendee_info_settings_form->was_submitted()) {
1233
-                // capture form data
1234
-                $copy_attendee_info_settings_form->receive_form_submission();
1235
-                // validate form data
1236
-                if ($copy_attendee_info_settings_form->is_valid()) {
1237
-                    // grab validated data from form
1238
-                    $valid_data = $copy_attendee_info_settings_form->valid_data();
1239
-                    if (isset($valid_data['copy_attendee_info'])) {
1240
-                        $EE_Registration_Config->setCopyAttendeeInfo($valid_data['copy_attendee_info']);
1241
-                    } else {
1242
-                        EE_Error::add_error(
1243
-                            esc_html__(
1244
-                                'Invalid or missing Copy Attendee Info settings. Please refresh the form and try again.',
1245
-                                'event_espresso'
1246
-                            ),
1247
-                            __FILE__,
1248
-                            __FUNCTION__,
1249
-                            __LINE__
1250
-                        );
1251
-                    }
1252
-                } else {
1253
-                    if ($copy_attendee_info_settings_form->submission_error_message() !== '') {
1254
-                        EE_Error::add_error(
1255
-                            $copy_attendee_info_settings_form->submission_error_message(),
1256
-                            __FILE__,
1257
-                            __FUNCTION__,
1258
-                            __LINE__
1259
-                        );
1260
-                    }
1261
-                }
1262
-            }
1263
-        } catch (EE_Error $e) {
1264
-            $e->get_error();
1265
-        }
1266
-        return $EE_Registration_Config;
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * @return void
1272
-     * @throws EE_Error
1273
-     * @throws InvalidArgumentException
1274
-     * @throws InvalidDataTypeException
1275
-     * @throws InvalidInterfaceException
1276
-     */
1277
-    public function email_validation_settings_form()
1278
-    {
1279
-        echo $this->_email_validation_settings_form()->get_html();
1280
-    }
1281
-
1282
-
1283
-    /**
1284
-     * _email_validation_settings_form
1285
-     *
1286
-     * @access protected
1287
-     * @return EE_Form_Section_Proper
1288
-     * @throws \EE_Error
1289
-     */
1290
-    protected function _email_validation_settings_form()
1291
-    {
1292
-        return new EE_Form_Section_Proper(
1293
-            array(
1294
-                'name'            => 'email_validation_settings',
1295
-                'html_id'         => 'email_validation_settings',
1296
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1297
-                'subsections'     => apply_filters(
1298
-                    'FHEE__Extend_Registration_Form_Admin_Page___email_validation_settings_form__form_subsections',
1299
-                    array(
1300
-                        'email_validation_hdr'   => new EE_Form_Section_HTML(
1301
-                            EEH_HTML::h2(esc_html__('Email Validation Settings', 'event_espresso'))
1302
-                        ),
1303
-                        'email_validation_level' => new EE_Select_Input(
1304
-                            array(
1305
-                                'basic'      => esc_html__('Basic', 'event_espresso'),
1306
-                                'wp_default' => esc_html__('WordPress Default', 'event_espresso'),
1307
-                                'i18n'       => esc_html__('International', 'event_espresso'),
1308
-                                'i18n_dns'   => esc_html__('International + DNS Check', 'event_espresso'),
1309
-                            ),
1310
-                            array(
1311
-                                'html_label_text' => esc_html__('Email Validation Level', 'event_espresso')
1312
-                                                     . EEH_Template::get_help_tab_link('email_validation_info'),
1313
-                                'html_help_text'  => esc_html__(
1314
-                                    'These levels range from basic validation ( ie: [email protected] ) to more advanced checks against international email addresses (ie: üñîçøðé@example.com ) with additional MX and A record checks to confirm the domain actually exists. More information on on each level can be found within the help section.',
1315
-                                    'event_espresso'
1316
-                                ),
1317
-                                'default'         => isset(
1318
-                                    EE_Registry::instance()->CFG->registration->email_validation_level
1319
-                                )
1320
-                                    ? EE_Registry::instance()->CFG->registration->email_validation_level
1321
-                                    : 'wp_default',
1322
-                                'required'        => false,
1323
-                            )
1324
-                        ),
1325
-                    )
1326
-                ),
1327
-            )
1328
-        );
1329
-    }
1330
-
1331
-
1332
-    /**
1333
-     * @param EE_Registration_Config $EE_Registration_Config
1334
-     * @return EE_Registration_Config
1335
-     * @throws EE_Error
1336
-     * @throws InvalidArgumentException
1337
-     * @throws ReflectionException
1338
-     * @throws InvalidDataTypeException
1339
-     * @throws InvalidInterfaceException
1340
-     */
1341
-    public function update_email_validation_settings_form(EE_Registration_Config $EE_Registration_Config)
1342
-    {
1343
-        $prev_email_validation_level = $EE_Registration_Config->email_validation_level;
1344
-        try {
1345
-            $email_validation_settings_form = $this->_email_validation_settings_form();
1346
-            // if not displaying a form, then check for form submission
1347
-            if ($email_validation_settings_form->was_submitted()) {
1348
-                // capture form data
1349
-                $email_validation_settings_form->receive_form_submission();
1350
-                // validate form data
1351
-                if ($email_validation_settings_form->is_valid()) {
1352
-                    // grab validated data from form
1353
-                    $valid_data = $email_validation_settings_form->valid_data();
1354
-                    if (isset($valid_data['email_validation_level'])) {
1355
-                        $email_validation_level = $valid_data['email_validation_level'];
1356
-                        // now if they want to use international email addresses
1357
-                        if ($email_validation_level === 'i18n' || $email_validation_level === 'i18n_dns') {
1358
-                            // in case we need to reset their email validation level,
1359
-                            // make sure that the previous value wasn't already set to one of the i18n options.
1360
-                            if ($prev_email_validation_level === 'i18n' || $prev_email_validation_level === 'i18n_dns') {
1361
-                                // if so, then reset it back to "basic" since that is the only other option that,
1362
-                                // despite offering poor validation, supports i18n email addresses
1363
-                                $prev_email_validation_level = 'basic';
1364
-                            }
1365
-                            // confirm our i18n email validation will work on the server
1366
-                            if (! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1367
-                                // or reset email validation level to previous value
1368
-                                $email_validation_level = $prev_email_validation_level;
1369
-                            }
1370
-                        }
1371
-                        $EE_Registration_Config->email_validation_level = $email_validation_level;
1372
-                    } else {
1373
-                        EE_Error::add_error(
1374
-                            esc_html__(
1375
-                                'Invalid or missing Email Validation settings. Please refresh the form and try again.',
1376
-                                'event_espresso'
1377
-                            ),
1378
-                            __FILE__,
1379
-                            __FUNCTION__,
1380
-                            __LINE__
1381
-                        );
1382
-                    }
1383
-                } else {
1384
-                    if ($email_validation_settings_form->submission_error_message() !== '') {
1385
-                        EE_Error::add_error(
1386
-                            $email_validation_settings_form->submission_error_message(),
1387
-                            __FILE__,
1388
-                            __FUNCTION__,
1389
-                            __LINE__
1390
-                        );
1391
-                    }
1392
-                }
1393
-            }
1394
-        } catch (EE_Error $e) {
1395
-            $e->get_error();
1396
-        }
1397
-        return $EE_Registration_Config;
1398
-    }
1399
-
1400
-
1401
-    /**
1402
-     * confirms that the server's PHP version has the PCRE module enabled,
1403
-     * and that the PCRE version works with our i18n email validation
1404
-     *
1405
-     * @param EE_Registration_Config $EE_Registration_Config
1406
-     * @param string                 $email_validation_level
1407
-     * @return bool
1408
-     */
1409
-    private function _verify_pcre_support(EE_Registration_Config $EE_Registration_Config, $email_validation_level)
1410
-    {
1411
-        // first check that PCRE is enabled
1412
-        if (! defined('PREG_BAD_UTF8_ERROR')) {
1413
-            EE_Error::add_error(
1414
-                sprintf(
1415
-                    esc_html__(
1416
-                        'We\'re sorry, but it appears that your server\'s version of PHP was not compiled with PCRE unicode support.%1$sPlease contact your hosting company and ask them whether the PCRE compiled with your version of PHP on your server can be been built with the "--enable-unicode-properties" and "--enable-utf8" configuration switches to enable more complex regex expressions.%1$sIf they are unable, or unwilling to do so, then your server will not support international email addresses using UTF-8 unicode characters. This means you will either have to lower your email validation level to "Basic" or "WordPress Default", or switch to a hosting company that has/can enable PCRE unicode support on the server.',
1417
-                        'event_espresso'
1418
-                    ),
1419
-                    '<br />'
1420
-                ),
1421
-                __FILE__,
1422
-                __FUNCTION__,
1423
-                __LINE__
1424
-            );
1425
-            return false;
1426
-        } else {
1427
-            // PCRE support is enabled, but let's still
1428
-            // perform a test to see if the server will support it.
1429
-            // but first, save the updated validation level to the config,
1430
-            // so that the validation strategy picks it up.
1431
-            // this will get bumped back down if it doesn't work
1432
-            $EE_Registration_Config->email_validation_level = $email_validation_level;
1433
-            try {
1434
-                $email_validator = new EE_Email_Validation_Strategy();
1435
-                $i18n_email_address = apply_filters(
1436
-                    'FHEE__Extend_Registration_Form_Admin_Page__update_email_validation_settings_form__i18n_email_address',
1437
-                    'jägerjü[email protected]'
1438
-                );
1439
-                $email_validator->validate($i18n_email_address);
1440
-            } catch (Exception $e) {
1441
-                EE_Error::add_error(
1442
-                    sprintf(
1443
-                        esc_html__(
1444
-                            'We\'re sorry, but it appears that your server\'s configuration will not support the "International" or "International + DNS Check" email validation levels.%1$sTo correct this issue, please consult with your hosting company regarding your server\'s PCRE settings.%1$sIt is recommended that your PHP version be configured to use PCRE 8.10 or newer.%1$sMore information regarding PCRE versions and installation can be found here: %2$s',
1445
-                            'event_espresso'
1446
-                        ),
1447
-                        '<br />',
1448
-                        '<a href="http://php.net/manual/en/pcre.installation.php" target="_blank" rel="noopener noreferrer">http://php.net/manual/en/pcre.installation.php</a>'
1449
-                    ),
1450
-                    __FILE__,
1451
-                    __FUNCTION__,
1452
-                    __LINE__
1453
-                );
1454
-                return false;
1455
-            }
1456
-        }
1457
-        return true;
1458
-    }
17
+	/**
18
+	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
19
+	 */
20
+	public function __construct($routing = true)
21
+	{
22
+		define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND . 'registration_form/');
23
+		define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN . 'assets/');
24
+		define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/assets/');
25
+		define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN . 'templates/');
26
+		define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/templates/');
27
+		parent::__construct($routing);
28
+	}
29
+
30
+
31
+	/**
32
+	 * @return void
33
+	 */
34
+	protected function _extend_page_config()
35
+	{
36
+		$this->_admin_base_path = REGISTRATION_FORM_CAF_ADMIN;
37
+		$qst_id = ! empty($this->_req_data['QST_ID']) && ! is_array($this->_req_data['QST_ID'])
38
+			? $this->_req_data['QST_ID'] : 0;
39
+		$qsg_id = ! empty($this->_req_data['QSG_ID']) && ! is_array($this->_req_data['QSG_ID'])
40
+			? $this->_req_data['QSG_ID'] : 0;
41
+
42
+		$new_page_routes = array(
43
+			'question_groups'    => array(
44
+				'func'       => '_question_groups_overview_list_table',
45
+				'capability' => 'ee_read_question_groups',
46
+			),
47
+			'add_question'       => array(
48
+				'func'       => '_edit_question',
49
+				'capability' => 'ee_edit_questions',
50
+			),
51
+			'insert_question'    => array(
52
+				'func'       => '_insert_or_update_question',
53
+				'args'       => array('new_question' => true),
54
+				'capability' => 'ee_edit_questions',
55
+				'noheader'   => true,
56
+			),
57
+			'duplicate_question' => array(
58
+				'func'       => '_duplicate_question',
59
+				'capability' => 'ee_edit_questions',
60
+				'noheader'   => true,
61
+			),
62
+			'trash_question'     => array(
63
+				'func'       => '_trash_question',
64
+				'capability' => 'ee_delete_question',
65
+				'obj_id'     => $qst_id,
66
+				'noheader'   => true,
67
+			),
68
+
69
+			'restore_question' => array(
70
+				'func'       => '_trash_or_restore_questions',
71
+				'capability' => 'ee_delete_question',
72
+				'obj_id'     => $qst_id,
73
+				'args'       => array('trash' => false),
74
+				'noheader'   => true,
75
+			),
76
+
77
+			'delete_question' => array(
78
+				'func'       => '_delete_question',
79
+				'capability' => 'ee_delete_question',
80
+				'obj_id'     => $qst_id,
81
+				'noheader'   => true,
82
+			),
83
+
84
+			'trash_questions' => array(
85
+				'func'       => '_trash_or_restore_questions',
86
+				'capability' => 'ee_delete_questions',
87
+				'args'       => array('trash' => true),
88
+				'noheader'   => true,
89
+			),
90
+
91
+			'restore_questions' => array(
92
+				'func'       => '_trash_or_restore_questions',
93
+				'capability' => 'ee_delete_questions',
94
+				'args'       => array('trash' => false),
95
+				'noheader'   => true,
96
+			),
97
+
98
+			'delete_questions' => array(
99
+				'func'       => '_delete_questions',
100
+				'args'       => array(),
101
+				'capability' => 'ee_delete_questions',
102
+				'noheader'   => true,
103
+			),
104
+
105
+			'add_question_group' => array(
106
+				'func'       => '_edit_question_group',
107
+				'capability' => 'ee_edit_question_groups',
108
+			),
109
+
110
+			'edit_question_group' => array(
111
+				'func'       => '_edit_question_group',
112
+				'capability' => 'ee_edit_question_group',
113
+				'obj_id'     => $qsg_id,
114
+				'args'       => array('edit'),
115
+			),
116
+
117
+			'delete_question_groups' => array(
118
+				'func'       => '_delete_question_groups',
119
+				'capability' => 'ee_delete_question_groups',
120
+				'noheader'   => true,
121
+			),
122
+
123
+			'delete_question_group' => array(
124
+				'func'       => '_delete_question_groups',
125
+				'capability' => 'ee_delete_question_group',
126
+				'obj_id'     => $qsg_id,
127
+				'noheader'   => true,
128
+			),
129
+
130
+			'trash_question_group' => array(
131
+				'func'       => '_trash_or_restore_question_groups',
132
+				'args'       => array('trash' => true),
133
+				'capability' => 'ee_delete_question_group',
134
+				'obj_id'     => $qsg_id,
135
+				'noheader'   => true,
136
+			),
137
+
138
+			'restore_question_group' => array(
139
+				'func'       => '_trash_or_restore_question_groups',
140
+				'args'       => array('trash' => false),
141
+				'capability' => 'ee_delete_question_group',
142
+				'obj_id'     => $qsg_id,
143
+				'noheader'   => true,
144
+			),
145
+
146
+			'insert_question_group' => array(
147
+				'func'       => '_insert_or_update_question_group',
148
+				'args'       => array('new_question_group' => true),
149
+				'capability' => 'ee_edit_question_groups',
150
+				'noheader'   => true,
151
+			),
152
+
153
+			'update_question_group' => array(
154
+				'func'       => '_insert_or_update_question_group',
155
+				'args'       => array('new_question_group' => false),
156
+				'capability' => 'ee_edit_question_group',
157
+				'obj_id'     => $qsg_id,
158
+				'noheader'   => true,
159
+			),
160
+
161
+			'trash_question_groups' => array(
162
+				'func'       => '_trash_or_restore_question_groups',
163
+				'args'       => array('trash' => true),
164
+				'capability' => 'ee_delete_question_groups',
165
+				'noheader'   => array('trash' => false),
166
+			),
167
+
168
+			'restore_question_groups' => array(
169
+				'func'       => '_trash_or_restore_question_groups',
170
+				'args'       => array('trash' => false),
171
+				'capability' => 'ee_delete_question_groups',
172
+				'noheader'   => true,
173
+			),
174
+
175
+
176
+			'espresso_update_question_group_order' => array(
177
+				'func'       => 'update_question_group_order',
178
+				'capability' => 'ee_edit_question_groups',
179
+				'noheader'   => true,
180
+			),
181
+
182
+			'view_reg_form_settings' => array(
183
+				'func'       => '_reg_form_settings',
184
+				'capability' => 'manage_options',
185
+			),
186
+
187
+			'update_reg_form_settings' => array(
188
+				'func'       => '_update_reg_form_settings',
189
+				'capability' => 'manage_options',
190
+				'noheader'   => true,
191
+			),
192
+		);
193
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
194
+
195
+		$new_page_config = array(
196
+
197
+			'question_groups' => array(
198
+				'nav'           => array(
199
+					'label' => esc_html__('Question Groups', 'event_espresso'),
200
+					'order' => 20,
201
+				),
202
+				'list_table'    => 'Registration_Form_Question_Groups_Admin_List_Table',
203
+				'help_tabs'     => array(
204
+					'registration_form_question_groups_help_tab'                           => array(
205
+						'title'    => esc_html__('Question Groups', 'event_espresso'),
206
+						'filename' => 'registration_form_question_groups',
207
+					),
208
+					'registration_form_question_groups_table_column_headings_help_tab'     => array(
209
+						'title'    => esc_html__('Question Groups Table Column Headings', 'event_espresso'),
210
+						'filename' => 'registration_form_question_groups_table_column_headings',
211
+					),
212
+					'registration_form_question_groups_views_bulk_actions_search_help_tab' => array(
213
+						'title'    => esc_html__('Question Groups Views & Bulk Actions & Search', 'event_espresso'),
214
+						'filename' => 'registration_form_question_groups_views_bulk_actions_search',
215
+					),
216
+				),
217
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
218
+				// 'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
219
+				'metaboxes'     => $this->_default_espresso_metaboxes,
220
+				'require_nonce' => false,
221
+				'qtips'         => array(
222
+					'EE_Registration_Form_Tips',
223
+				),
224
+			),
225
+
226
+			'add_question' => array(
227
+				'nav'           => array(
228
+					'label'      => esc_html__('Add Question', 'event_espresso'),
229
+					'order'      => 5,
230
+					'persistent' => false,
231
+				),
232
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
233
+				'help_tabs'     => array(
234
+					'registration_form_add_question_help_tab' => array(
235
+						'title'    => esc_html__('Add Question', 'event_espresso'),
236
+						'filename' => 'registration_form_add_question',
237
+					),
238
+				),
239
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
240
+				// 'help_tour'     => array('Registration_Form_Add_Question_Help_Tour'),
241
+				'require_nonce' => false,
242
+			),
243
+
244
+			'add_question_group' => array(
245
+				'nav'           => array(
246
+					'label'      => esc_html__('Add Question Group', 'event_espresso'),
247
+					'order'      => 5,
248
+					'persistent' => false,
249
+				),
250
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
251
+				'help_tabs'     => array(
252
+					'registration_form_add_question_group_help_tab' => array(
253
+						'title'    => esc_html__('Add Question Group', 'event_espresso'),
254
+						'filename' => 'registration_form_add_question_group',
255
+					),
256
+				),
257
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
258
+				// 'help_tour'     => array('Registration_Form_Add_Question_Group_Help_Tour'),
259
+				'require_nonce' => false,
260
+			),
261
+
262
+			'edit_question_group' => array(
263
+				'nav'           => array(
264
+					'label'      => esc_html__('Edit Question Group', 'event_espresso'),
265
+					'order'      => 5,
266
+					'persistent' => false,
267
+					'url'        => isset($this->_req_data['question_group_id']) ? add_query_arg(
268
+						array('question_group_id' => $this->_req_data['question_group_id']),
269
+						$this->_current_page_view_url
270
+					) : $this->_admin_base_url,
271
+				),
272
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
273
+				'help_tabs'     => array(
274
+					'registration_form_edit_question_group_help_tab' => array(
275
+						'title'    => esc_html__('Edit Question Group', 'event_espresso'),
276
+						'filename' => 'registration_form_edit_question_group',
277
+					),
278
+				),
279
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
280
+				// 'help_tour'     => array('Registration_Form_Edit_Question_Group_Help_Tour'),
281
+				'require_nonce' => false,
282
+			),
283
+
284
+			'view_reg_form_settings' => array(
285
+				'nav'           => array(
286
+					'label' => esc_html__('Reg Form Settings', 'event_espresso'),
287
+					'order' => 40,
288
+				),
289
+				'labels'        => array(
290
+					'publishbox' => esc_html__('Update Settings', 'event_espresso'),
291
+				),
292
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
293
+				'help_tabs'     => array(
294
+					'registration_form_reg_form_settings_help_tab' => array(
295
+						'title'    => esc_html__('Registration Form Settings', 'event_espresso'),
296
+						'filename' => 'registration_form_reg_form_settings',
297
+					),
298
+				),
299
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
300
+				// 'help_tour'     => array('Registration_Form_Settings_Help_Tour'),
301
+				'require_nonce' => false,
302
+			),
303
+
304
+		);
305
+		$this->_page_config = array_merge($this->_page_config, $new_page_config);
306
+
307
+		// change the list table we're going to use so it's the NEW list table!
308
+		$this->_page_config['default']['list_table'] = 'Extend_Registration_Form_Questions_Admin_List_Table';
309
+
310
+
311
+		// additional labels
312
+		$new_labels = array(
313
+			'add_question'          => esc_html__('Add New Question', 'event_espresso'),
314
+			'delete_question'       => esc_html__('Delete Question', 'event_espresso'),
315
+			'add_question_group'    => esc_html__('Add New Question Group', 'event_espresso'),
316
+			'edit_question_group'   => esc_html__('Edit Question Group', 'event_espresso'),
317
+			'delete_question_group' => esc_html__('Delete Question Group', 'event_espresso'),
318
+		);
319
+		$this->_labels['buttons'] = array_merge($this->_labels['buttons'], $new_labels);
320
+	}
321
+
322
+
323
+	/**
324
+	 * @return void
325
+	 */
326
+	protected function _ajax_hooks()
327
+	{
328
+		add_action('wp_ajax_espresso_update_question_group_order', array($this, 'update_question_group_order'));
329
+	}
330
+
331
+
332
+	/**
333
+	 * @return void
334
+	 */
335
+	public function load_scripts_styles_question_groups()
336
+	{
337
+		wp_enqueue_script('espresso_ajax_table_sorting');
338
+	}
339
+
340
+
341
+	/**
342
+	 * @return void
343
+	 */
344
+	public function load_scripts_styles_add_question_group()
345
+	{
346
+		$this->load_scripts_styles_forms();
347
+		$this->load_sortable_question_script();
348
+	}
349
+
350
+
351
+	/**
352
+	 * @return void
353
+	 */
354
+	public function load_scripts_styles_edit_question_group()
355
+	{
356
+		$this->load_scripts_styles_forms();
357
+		$this->load_sortable_question_script();
358
+	}
359
+
360
+
361
+	/**
362
+	 * registers and enqueues script for questions
363
+	 *
364
+	 * @return void
365
+	 */
366
+	public function load_sortable_question_script()
367
+	{
368
+		wp_register_script(
369
+			'ee-question-sortable',
370
+			REGISTRATION_FORM_CAF_ASSETS_URL . 'ee_question_order.js',
371
+			array('jquery-ui-sortable'),
372
+			EVENT_ESPRESSO_VERSION,
373
+			true
374
+		);
375
+		wp_enqueue_script('ee-question-sortable');
376
+	}
377
+
378
+
379
+	/**
380
+	 * @return void
381
+	 */
382
+	protected function _set_list_table_views_default()
383
+	{
384
+		$this->_views = array(
385
+			'all' => array(
386
+				'slug'        => 'all',
387
+				'label'       => esc_html__('View All Questions', 'event_espresso'),
388
+				'count'       => 0,
389
+				'bulk_action' => array(
390
+					'trash_questions' => esc_html__('Trash', 'event_espresso'),
391
+				),
392
+			),
393
+		);
394
+
395
+		if (
396
+			EE_Registry::instance()->CAP->current_user_can(
397
+				'ee_delete_questions',
398
+				'espresso_registration_form_trash_questions'
399
+			)
400
+		) {
401
+			$this->_views['trash'] = array(
402
+				'slug'        => 'trash',
403
+				'label'       => esc_html__('Trash', 'event_espresso'),
404
+				'count'       => 0,
405
+				'bulk_action' => array(
406
+					'delete_questions'  => esc_html__('Delete Permanently', 'event_espresso'),
407
+					'restore_questions' => esc_html__('Restore', 'event_espresso'),
408
+				),
409
+			);
410
+		}
411
+	}
412
+
413
+
414
+	/**
415
+	 * @return void
416
+	 */
417
+	protected function _set_list_table_views_question_groups()
418
+	{
419
+		$this->_views = array(
420
+			'all' => array(
421
+				'slug'        => 'all',
422
+				'label'       => esc_html__('All', 'event_espresso'),
423
+				'count'       => 0,
424
+				'bulk_action' => array(
425
+					'trash_question_groups' => esc_html__('Trash', 'event_espresso'),
426
+				),
427
+			),
428
+		);
429
+
430
+		if (
431
+			EE_Registry::instance()->CAP->current_user_can(
432
+				'ee_delete_question_groups',
433
+				'espresso_registration_form_trash_question_groups'
434
+			)
435
+		) {
436
+			$this->_views['trash'] = array(
437
+				'slug'        => 'trash',
438
+				'label'       => esc_html__('Trash', 'event_espresso'),
439
+				'count'       => 0,
440
+				'bulk_action' => array(
441
+					'delete_question_groups'  => esc_html__('Delete Permanently', 'event_espresso'),
442
+					'restore_question_groups' => esc_html__('Restore', 'event_espresso'),
443
+				),
444
+			);
445
+		}
446
+	}
447
+
448
+
449
+	/**
450
+	 * @return void
451
+	 * @throws EE_Error
452
+	 * @throws InvalidArgumentException
453
+	 * @throws InvalidDataTypeException
454
+	 * @throws InvalidInterfaceException
455
+	 */
456
+	protected function _questions_overview_list_table()
457
+	{
458
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
459
+			'add_question',
460
+			'add_question',
461
+			array(),
462
+			'add-new-h2'
463
+		);
464
+		parent::_questions_overview_list_table();
465
+	}
466
+
467
+
468
+	/**
469
+	 * @return void
470
+	 * @throws DomainException
471
+	 * @throws EE_Error
472
+	 * @throws InvalidArgumentException
473
+	 * @throws InvalidDataTypeException
474
+	 * @throws InvalidInterfaceException
475
+	 */
476
+	protected function _question_groups_overview_list_table()
477
+	{
478
+		$this->_search_btn_label = esc_html__('Question Groups', 'event_espresso');
479
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
480
+			'add_question_group',
481
+			'add_question_group',
482
+			array(),
483
+			'add-new-h2'
484
+		);
485
+		$this->display_admin_list_table_page_with_sidebar();
486
+	}
487
+
488
+
489
+	/**
490
+	 * @return void
491
+	 * @throws EE_Error
492
+	 * @throws InvalidArgumentException
493
+	 * @throws InvalidDataTypeException
494
+	 * @throws InvalidInterfaceException
495
+	 */
496
+	protected function _delete_question()
497
+	{
498
+		$success = $this->_delete_items($this->_question_model);
499
+		$this->_redirect_after_action(
500
+			$success,
501
+			$this->_question_model->item_name($success),
502
+			'deleted',
503
+			array('action' => 'default', 'status' => 'all')
504
+		);
505
+	}
506
+
507
+
508
+	/**
509
+	 * @return void
510
+	 * @throws EE_Error
511
+	 * @throws InvalidArgumentException
512
+	 * @throws InvalidDataTypeException
513
+	 * @throws InvalidInterfaceException
514
+	 */
515
+	protected function _delete_questions()
516
+	{
517
+		$success = $this->_delete_items($this->_question_model);
518
+		$this->_redirect_after_action(
519
+			$success,
520
+			$this->_question_model->item_name($success),
521
+			'deleted permanently',
522
+			array('action' => 'default', 'status' => 'trash')
523
+		);
524
+	}
525
+
526
+
527
+	/**
528
+	 * Performs the deletion of a single or multiple questions or question groups.
529
+	 *
530
+	 * @param EEM_Soft_Delete_Base $model
531
+	 * @return int number of items deleted permanently
532
+	 * @throws EE_Error
533
+	 * @throws InvalidArgumentException
534
+	 * @throws InvalidDataTypeException
535
+	 * @throws InvalidInterfaceException
536
+	 */
537
+	private function _delete_items(EEM_Soft_Delete_Base $model)
538
+	{
539
+		$success = 0;
540
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
541
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
542
+			// if array has more than one element than success message should be plural
543
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
544
+			// cycle thru bulk action checkboxes
545
+			while (list($ID, $value) = each($this->_req_data['checkbox'])) {
546
+				if (! $this->_delete_item($ID, $model)) {
547
+					$success = 0;
548
+				}
549
+			}
550
+		} elseif (! empty($this->_req_data['QSG_ID'])) {
551
+			$success = $this->_delete_item($this->_req_data['QSG_ID'], $model);
552
+		} elseif (! empty($this->_req_data['QST_ID'])) {
553
+			$success = $this->_delete_item($this->_req_data['QST_ID'], $model);
554
+		} else {
555
+			EE_Error::add_error(
556
+				sprintf(
557
+					esc_html__(
558
+						"No Questions or Question Groups were selected for deleting. This error usually shows when you've attempted to delete via bulk action but there were no selections.",
559
+						"event_espresso"
560
+					)
561
+				),
562
+				__FILE__,
563
+				__FUNCTION__,
564
+				__LINE__
565
+			);
566
+		}
567
+		return $success;
568
+	}
569
+
570
+
571
+	/**
572
+	 * Deletes the specified question (and its associated question options) or question group
573
+	 *
574
+	 * @param int                  $id
575
+	 * @param EEM_Soft_Delete_Base $model
576
+	 * @return boolean
577
+	 * @throws EE_Error
578
+	 * @throws InvalidArgumentException
579
+	 * @throws InvalidDataTypeException
580
+	 * @throws InvalidInterfaceException
581
+	 */
582
+	protected function _delete_item($id, $model)
583
+	{
584
+		if ($model instanceof EEM_Question) {
585
+			EEM_Question_Option::instance()->delete_permanently(array(array('QST_ID' => absint($id))));
586
+		}
587
+		return $model->delete_permanently_by_ID(absint($id));
588
+	}
589
+
590
+
591
+	/******************************    QUESTION GROUPS    ******************************/
592
+
593
+
594
+	/**
595
+	 * @param string $type
596
+	 * @return void
597
+	 * @throws DomainException
598
+	 * @throws EE_Error
599
+	 * @throws InvalidArgumentException
600
+	 * @throws InvalidDataTypeException
601
+	 * @throws InvalidInterfaceException
602
+	 */
603
+	protected function _edit_question_group($type = 'add')
604
+	{
605
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
606
+		$ID = isset($this->_req_data['QSG_ID']) && ! empty($this->_req_data['QSG_ID'])
607
+			? absint($this->_req_data['QSG_ID'])
608
+			: false;
609
+
610
+		switch ($this->_req_action) {
611
+			case 'add_question_group':
612
+				$this->_admin_page_title = esc_html__('Add Question Group', 'event_espresso');
613
+				break;
614
+			case 'edit_question_group':
615
+				$this->_admin_page_title = esc_html__('Edit Question Group', 'event_espresso');
616
+				break;
617
+			default:
618
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
619
+		}
620
+		// add ID to title if editing
621
+		$this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
622
+		if ($ID) {
623
+			/** @var EE_Question_Group $questionGroup */
624
+			$questionGroup = $this->_question_group_model->get_one_by_ID($ID);
625
+			$additional_hidden_fields = array('QSG_ID' => array('type' => 'hidden', 'value' => $ID));
626
+			$this->_set_add_edit_form_tags('update_question_group', $additional_hidden_fields);
627
+		} else {
628
+			/** @var EE_Question_Group $questionGroup */
629
+			$questionGroup = EEM_Question_Group::instance()->create_default_object();
630
+			$questionGroup->set_order_to_latest();
631
+			$this->_set_add_edit_form_tags('insert_question_group');
632
+		}
633
+		$this->_template_args['values'] = $this->_yes_no_values;
634
+		$this->_template_args['all_questions'] = $questionGroup->questions_in_and_not_in_group();
635
+		$this->_template_args['QSG_ID'] = $ID ? $ID : true;
636
+		$this->_template_args['question_group'] = $questionGroup;
637
+
638
+		$redirect_URL = add_query_arg(array('action' => 'question_groups'), $this->_admin_base_url);
639
+		$this->_set_publish_post_box_vars('id', $ID, false, $redirect_URL);
640
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
641
+			REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'question_groups_main_meta_box.template.php',
642
+			$this->_template_args,
643
+			true
644
+		);
645
+
646
+		// the details template wrapper
647
+		$this->display_admin_page_with_sidebar();
648
+	}
649
+
650
+
651
+	/**
652
+	 * @return void
653
+	 * @throws EE_Error
654
+	 * @throws InvalidArgumentException
655
+	 * @throws InvalidDataTypeException
656
+	 * @throws InvalidInterfaceException
657
+	 */
658
+	protected function _delete_question_groups()
659
+	{
660
+		$success = $this->_delete_items($this->_question_group_model);
661
+		$this->_redirect_after_action(
662
+			$success,
663
+			$this->_question_group_model->item_name($success),
664
+			'deleted permanently',
665
+			array('action' => 'question_groups', 'status' => 'trash')
666
+		);
667
+	}
668
+
669
+
670
+	/**
671
+	 * @param bool $new_question_group
672
+	 * @throws EE_Error
673
+	 * @throws InvalidArgumentException
674
+	 * @throws InvalidDataTypeException
675
+	 * @throws InvalidInterfaceException
676
+	 */
677
+	protected function _insert_or_update_question_group($new_question_group = true)
678
+	{
679
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
680
+		$set_column_values = $this->_set_column_values_for($this->_question_group_model);
681
+		if ($new_question_group) {
682
+			// make sure identifier is unique
683
+			$identifier_value = isset($set_column_values['QSG_identifier']) ? $set_column_values['QSG_identifier'] : '';
684
+			$identifier_exists = ! empty($identifier_value)
685
+				? $this->_question_group_model->count([['QSG_identifier' => $set_column_values['QSG_identifier']]]) > 0
686
+				: false;
687
+			if ($identifier_exists) {
688
+				$set_column_values['QSG_identifier'] .= uniqid('id', true);
689
+			}
690
+			$QSG_ID = $this->_question_group_model->insert($set_column_values);
691
+			$success = $QSG_ID ? 1 : 0;
692
+			if ($success === 0) {
693
+				EE_Error::add_error(
694
+					esc_html__('Something went wrong saving the question group.', 'event_espresso'),
695
+					__FILE__,
696
+					__FUNCTION__,
697
+					__LINE__
698
+				);
699
+				$this->_redirect_after_action(
700
+					false,
701
+					'',
702
+					'',
703
+					array('action' => 'edit_question_group', 'QSG_ID' => $QSG_ID),
704
+					true
705
+				);
706
+			}
707
+		} else {
708
+			$QSG_ID = absint($this->_req_data['QSG_ID']);
709
+			unset($set_column_values['QSG_ID']);
710
+			$success = $this->_question_group_model->update($set_column_values, array(array('QSG_ID' => $QSG_ID)));
711
+		}
712
+
713
+		$phone_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(
714
+			EEM_Attendee::system_question_phone
715
+		);
716
+		// update the existing related questions
717
+		// BUT FIRST...  delete the phone question from the Question_Group_Question
718
+		// if it is being added to this question group (therefore removed from the existing group)
719
+		if (isset($this->_req_data['questions'], $this->_req_data['questions'][ $phone_question_id ])) {
720
+			// delete where QST ID = system phone question ID and Question Group ID is NOT this group
721
+			EEM_Question_Group_Question::instance()->delete(
722
+				array(
723
+					array(
724
+						'QST_ID' => $phone_question_id,
725
+						'QSG_ID' => array('!=', $QSG_ID),
726
+					),
727
+				)
728
+			);
729
+		}
730
+		/** @type EE_Question_Group $question_group */
731
+		$question_group = $this->_question_group_model->get_one_by_ID($QSG_ID);
732
+		$questions = $question_group->questions();
733
+		// make sure system phone question is added to list of questions for this group
734
+		if (! isset($questions[ $phone_question_id ])) {
735
+			$questions[ $phone_question_id ] = EEM_Question::instance()->get_one_by_ID($phone_question_id);
736
+		}
737
+
738
+		foreach ($questions as $question_ID => $question) {
739
+			// first we always check for order.
740
+			if (! empty($this->_req_data['question_orders'][ $question_ID ])) {
741
+				// update question order
742
+				$question_group->update_question_order(
743
+					$question_ID,
744
+					$this->_req_data['question_orders'][ $question_ID ]
745
+				);
746
+			}
747
+
748
+			// then we always check if adding or removing.
749
+			if (isset($this->_req_data['questions'], $this->_req_data['questions'][ $question_ID ])) {
750
+				$question_group->add_question($question_ID);
751
+			} else {
752
+				// not found, remove it (but only if not a system question for the personal group
753
+				// with the exception of lname system question - we allow removal of it)
754
+				if (
755
+					in_array(
756
+						$question->system_ID(),
757
+						EEM_Question::instance()->required_system_questions_in_system_question_group(
758
+							$question_group->system_group()
759
+						)
760
+					)
761
+				) {
762
+					continue;
763
+				} else {
764
+					$question_group->remove_question($question_ID);
765
+				}
766
+			}
767
+		}
768
+		// save new related questions
769
+		if (isset($this->_req_data['questions'])) {
770
+			foreach ($this->_req_data['questions'] as $QST_ID) {
771
+				$question_group->add_question($QST_ID);
772
+				if (isset($this->_req_data['question_orders'][ $QST_ID ])) {
773
+					$question_group->update_question_order($QST_ID, $this->_req_data['question_orders'][ $QST_ID ]);
774
+				}
775
+			}
776
+		}
777
+
778
+		if ($success !== false) {
779
+			$msg = $new_question_group
780
+				? sprintf(
781
+					esc_html__('The %s has been created', 'event_espresso'),
782
+					$this->_question_group_model->item_name()
783
+				)
784
+				: sprintf(
785
+					esc_html__(
786
+						'The %s has been updated',
787
+						'event_espresso'
788
+					),
789
+					$this->_question_group_model->item_name()
790
+				);
791
+			EE_Error::add_success($msg);
792
+		}
793
+		$this->_redirect_after_action(
794
+			false,
795
+			'',
796
+			'',
797
+			array('action' => 'edit_question_group', 'QSG_ID' => $QSG_ID),
798
+			true
799
+		);
800
+	}
801
+
802
+
803
+	/**
804
+	 * duplicates a question and all its question options and redirects to the new question.
805
+	 *
806
+	 * @return void
807
+	 * @throws EE_Error
808
+	 * @throws InvalidArgumentException
809
+	 * @throws ReflectionException
810
+	 * @throws InvalidDataTypeException
811
+	 * @throws InvalidInterfaceException
812
+	 */
813
+	public function _duplicate_question()
814
+	{
815
+		$question_ID = (int) $this->_req_data['QST_ID'];
816
+		$question = EEM_Question::instance()->get_one_by_ID($question_ID);
817
+		if ($question instanceof EE_Question) {
818
+			$new_question = $question->duplicate();
819
+			if ($new_question instanceof EE_Question) {
820
+				$this->_redirect_after_action(
821
+					true,
822
+					esc_html__('Question', 'event_espresso'),
823
+					esc_html__('Duplicated', 'event_espresso'),
824
+					array('action' => 'edit_question', 'QST_ID' => $new_question->ID()),
825
+					true
826
+				);
827
+			} else {
828
+				global $wpdb;
829
+				EE_Error::add_error(
830
+					sprintf(
831
+						esc_html__(
832
+							'Could not duplicate question with ID %1$d because: %2$s',
833
+							'event_espresso'
834
+						),
835
+						$question_ID,
836
+						$wpdb->last_error
837
+					),
838
+					__FILE__,
839
+					__FUNCTION__,
840
+					__LINE__
841
+				);
842
+				$this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
843
+			}
844
+		} else {
845
+			EE_Error::add_error(
846
+				sprintf(
847
+					esc_html__(
848
+						'Could not duplicate question with ID %d because it didn\'t exist!',
849
+						'event_espresso'
850
+					),
851
+					$question_ID
852
+				),
853
+				__FILE__,
854
+				__FUNCTION__,
855
+				__LINE__
856
+			);
857
+			$this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
858
+		}
859
+	}
860
+
861
+
862
+	/**
863
+	 * @param bool $trash
864
+	 * @throws EE_Error
865
+	 */
866
+	protected function _trash_or_restore_question_groups($trash = true)
867
+	{
868
+		$this->_trash_or_restore_items($this->_question_group_model, $trash);
869
+	}
870
+
871
+
872
+	/**
873
+	 *_trash_question
874
+	 *
875
+	 * @return void
876
+	 * @throws EE_Error
877
+	 */
878
+	protected function _trash_question()
879
+	{
880
+		$success = $this->_question_model->delete_by_ID((int) $this->_req_data['QST_ID']);
881
+		$query_args = array('action' => 'default', 'status' => 'all');
882
+		$this->_redirect_after_action($success, $this->_question_model->item_name($success), 'trashed', $query_args);
883
+	}
884
+
885
+
886
+	/**
887
+	 * @param bool $trash
888
+	 * @throws EE_Error
889
+	 */
890
+	protected function _trash_or_restore_questions($trash = true)
891
+	{
892
+		$this->_trash_or_restore_items($this->_question_model, $trash);
893
+	}
894
+
895
+
896
+	/**
897
+	 * Internally used to delete or restore items, using the request data. Meant to be
898
+	 * flexible between question or question groups
899
+	 *
900
+	 * @param EEM_Soft_Delete_Base $model
901
+	 * @param boolean              $trash whether to trash or restore
902
+	 * @throws EE_Error
903
+	 */
904
+	private function _trash_or_restore_items(EEM_Soft_Delete_Base $model, $trash = true)
905
+	{
906
+
907
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
908
+
909
+		$success = 1;
910
+		// Checkboxes
911
+		// echo "trash $trash";
912
+		// var_dump($this->_req_data['checkbox']);die;
913
+		if (isset($this->_req_data['checkbox'])) {
914
+			if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
915
+				// if array has more than one element than success message should be plural
916
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
917
+				// cycle thru bulk action checkboxes
918
+				while (list($ID, $value) = each($this->_req_data['checkbox'])) {
919
+					if (! $model->delete_or_restore_by_ID($trash, absint($ID))) {
920
+						$success = 0;
921
+					}
922
+				}
923
+			} else {
924
+				// grab single id and delete
925
+				$ID = absint($this->_req_data['checkbox']);
926
+				if (! $model->delete_or_restore_by_ID($trash, $ID)) {
927
+					$success = 0;
928
+				}
929
+			}
930
+		} else {
931
+			// delete via trash link
932
+			// grab single id and delete
933
+			$ID = absint($this->_req_data[ $model->primary_key_name() ]);
934
+			if (! $model->delete_or_restore_by_ID($trash, $ID)) {
935
+				$success = 0;
936
+			}
937
+		}
938
+
939
+
940
+		$action = $model instanceof EEM_Question ? 'default' : 'question_groups';// strtolower( $model->item_name(2) );
941
+		// echo "action :$action";
942
+		// $action = 'questions' ? 'default' : $action;
943
+		if ($trash) {
944
+			$action_desc = 'trashed';
945
+			$status = 'trash';
946
+		} else {
947
+			$action_desc = 'restored';
948
+			$status = 'all';
949
+		}
950
+		$this->_redirect_after_action(
951
+			$success,
952
+			$model->item_name($success),
953
+			$action_desc,
954
+			array('action' => $action, 'status' => $status)
955
+		);
956
+	}
957
+
958
+
959
+	/**
960
+	 * @param            $per_page
961
+	 * @param int        $current_page
962
+	 * @param bool|false $count
963
+	 * @return EE_Soft_Delete_Base_Class[]|int
964
+	 * @throws EE_Error
965
+	 * @throws InvalidArgumentException
966
+	 * @throws InvalidDataTypeException
967
+	 * @throws InvalidInterfaceException
968
+	 */
969
+	public function get_trashed_questions($per_page, $current_page = 1, $count = false)
970
+	{
971
+		$query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
972
+
973
+		if ($count) {
974
+			// note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
975
+			$where = isset($query_params[0]) ? array($query_params[0]) : array();
976
+			$results = $this->_question_model->count_deleted($where);
977
+		} else {
978
+			// note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
979
+			$results = $this->_question_model->get_all_deleted($query_params);
980
+		}
981
+		return $results;
982
+	}
983
+
984
+
985
+	/**
986
+	 * @param            $per_page
987
+	 * @param int        $current_page
988
+	 * @param bool|false $count
989
+	 * @return EE_Soft_Delete_Base_Class[]|int
990
+	 * @throws EE_Error
991
+	 * @throws InvalidArgumentException
992
+	 * @throws InvalidDataTypeException
993
+	 * @throws InvalidInterfaceException
994
+	 */
995
+	public function get_question_groups($per_page, $current_page = 1, $count = false)
996
+	{
997
+		$questionGroupModel = EEM_Question_Group::instance();
998
+		$query_params = $this->get_query_params($questionGroupModel, $per_page, $current_page);
999
+		if ($count) {
1000
+			$where = isset($query_params[0]) ? array($query_params[0]) : array();
1001
+			$results = $questionGroupModel->count($where);
1002
+		} else {
1003
+			$results = $questionGroupModel->get_all($query_params);
1004
+		}
1005
+		return $results;
1006
+	}
1007
+
1008
+
1009
+	/**
1010
+	 * @param      $per_page
1011
+	 * @param int  $current_page
1012
+	 * @param bool $count
1013
+	 * @return EE_Soft_Delete_Base_Class[]|int
1014
+	 * @throws EE_Error
1015
+	 * @throws InvalidArgumentException
1016
+	 * @throws InvalidDataTypeException
1017
+	 * @throws InvalidInterfaceException
1018
+	 */
1019
+	public function get_trashed_question_groups($per_page, $current_page = 1, $count = false)
1020
+	{
1021
+		$questionGroupModel = EEM_Question_Group::instance();
1022
+		$query_params = $this->get_query_params($questionGroupModel, $per_page, $current_page);
1023
+		if ($count) {
1024
+			$where = isset($query_params[0]) ? array($query_params[0]) : array();
1025
+			$query_params['limit'] = null;
1026
+			$results = $questionGroupModel->count_deleted($where);
1027
+		} else {
1028
+			$results = $questionGroupModel->get_all_deleted($query_params);
1029
+		}
1030
+		return $results;
1031
+	}
1032
+
1033
+
1034
+	/**
1035
+	 * method for performing updates to question order
1036
+	 *
1037
+	 * @return void results array
1038
+	 * @throws EE_Error
1039
+	 * @throws InvalidArgumentException
1040
+	 * @throws InvalidDataTypeException
1041
+	 * @throws InvalidInterfaceException
1042
+	 */
1043
+	public function update_question_group_order()
1044
+	{
1045
+
1046
+		$success = esc_html__('Question group order was updated successfully.', 'event_espresso');
1047
+
1048
+		// grab our row IDs
1049
+		$row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids'])
1050
+			? explode(',', rtrim($this->_req_data['row_ids'], ','))
1051
+			: array();
1052
+
1053
+		$perpage = ! empty($this->_req_data['perpage'])
1054
+			? (int) $this->_req_data['perpage']
1055
+			: null;
1056
+		$curpage = ! empty($this->_req_data['curpage'])
1057
+			? (int) $this->_req_data['curpage']
1058
+			: null;
1059
+
1060
+		if (! empty($row_ids)) {
1061
+			// figure out where we start the row_id count at for the current page.
1062
+			$qsgcount = empty($curpage) ? 0 : ($curpage - 1) * $perpage;
1063
+
1064
+			$row_count = count($row_ids);
1065
+			for ($i = 0; $i < $row_count; $i++) {
1066
+				// Update the questions when re-ordering
1067
+				$updated = EEM_Question_Group::instance()->update(
1068
+					array('QSG_order' => $qsgcount),
1069
+					array(array('QSG_ID' => $row_ids[ $i ]))
1070
+				);
1071
+				if ($updated === false) {
1072
+					$success = false;
1073
+				}
1074
+				$qsgcount++;
1075
+			}
1076
+		} else {
1077
+			$success = false;
1078
+		}
1079
+
1080
+		$errors = ! $success
1081
+			? esc_html__('An error occurred. The question group order was not updated.', 'event_espresso')
1082
+			: false;
1083
+
1084
+		echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
1085
+		die();
1086
+	}
1087
+
1088
+
1089
+
1090
+	/***************************************       REGISTRATION SETTINGS       ***************************************/
1091
+
1092
+
1093
+	/**
1094
+	 * @throws DomainException
1095
+	 * @throws EE_Error
1096
+	 * @throws InvalidArgumentException
1097
+	 * @throws InvalidDataTypeException
1098
+	 * @throws InvalidInterfaceException
1099
+	 */
1100
+	protected function _reg_form_settings()
1101
+	{
1102
+		$this->_template_args['values'] = $this->_yes_no_values;
1103
+		add_action(
1104
+			'AHEE__Extend_Registration_Form_Admin_Page___reg_form_settings_template',
1105
+			array($this, 'email_validation_settings_form'),
1106
+			2
1107
+		);
1108
+		add_action(
1109
+			'AHEE__Extend_Registration_Form_Admin_Page___reg_form_settings_template',
1110
+			array($this, 'copy_attendee_info_settings_form'),
1111
+			4
1112
+		);
1113
+		$this->_template_args = (array) apply_filters(
1114
+			'FHEE__Extend_Registration_Form_Admin_Page___reg_form_settings___template_args',
1115
+			$this->_template_args
1116
+		);
1117
+		$this->_set_add_edit_form_tags('update_reg_form_settings');
1118
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
1119
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1120
+			REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'reg_form_settings.template.php',
1121
+			$this->_template_args,
1122
+			true
1123
+		);
1124
+		$this->display_admin_page_with_sidebar();
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * @return void
1130
+	 * @throws EE_Error
1131
+	 * @throws InvalidArgumentException
1132
+	 * @throws ReflectionException
1133
+	 * @throws InvalidDataTypeException
1134
+	 * @throws InvalidInterfaceException
1135
+	 */
1136
+	protected function _update_reg_form_settings()
1137
+	{
1138
+		EE_Registry::instance()->CFG->registration = $this->update_email_validation_settings_form(
1139
+			EE_Registry::instance()->CFG->registration
1140
+		);
1141
+		EE_Registry::instance()->CFG->registration = $this->update_copy_attendee_info_settings_form(
1142
+			EE_Registry::instance()->CFG->registration
1143
+		);
1144
+		EE_Registry::instance()->CFG->registration = apply_filters(
1145
+			'FHEE__Extend_Registration_Form_Admin_Page___update_reg_form_settings__CFG_registration',
1146
+			EE_Registry::instance()->CFG->registration
1147
+		);
1148
+		$success = $this->_update_espresso_configuration(
1149
+			esc_html__('Registration Form Options', 'event_espresso'),
1150
+			EE_Registry::instance()->CFG,
1151
+			__FILE__,
1152
+			__FUNCTION__,
1153
+			__LINE__
1154
+		);
1155
+		$this->_redirect_after_action(
1156
+			$success,
1157
+			esc_html__('Registration Form Options', 'event_espresso'),
1158
+			'updated',
1159
+			array('action' => 'view_reg_form_settings')
1160
+		);
1161
+	}
1162
+
1163
+
1164
+	/**
1165
+	 * @return void
1166
+	 * @throws EE_Error
1167
+	 * @throws InvalidArgumentException
1168
+	 * @throws InvalidDataTypeException
1169
+	 * @throws InvalidInterfaceException
1170
+	 */
1171
+	public function copy_attendee_info_settings_form()
1172
+	{
1173
+		echo $this->_copy_attendee_info_settings_form()->get_html();
1174
+	}
1175
+
1176
+	/**
1177
+	 * _copy_attendee_info_settings_form
1178
+	 *
1179
+	 * @access protected
1180
+	 * @return EE_Form_Section_Proper
1181
+	 * @throws \EE_Error
1182
+	 */
1183
+	protected function _copy_attendee_info_settings_form()
1184
+	{
1185
+		return new EE_Form_Section_Proper(
1186
+			array(
1187
+				'name'            => 'copy_attendee_info_settings',
1188
+				'html_id'         => 'copy_attendee_info_settings',
1189
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1190
+				'subsections'     => apply_filters(
1191
+					'FHEE__Extend_Registration_Form_Admin_Page___copy_attendee_info_settings_form__form_subsections',
1192
+					array(
1193
+						'copy_attendee_info_hdr'   => new EE_Form_Section_HTML(
1194
+							EEH_HTML::h2(esc_html__('Copy Attendee Info Settings', 'event_espresso'))
1195
+						),
1196
+						'copy_attendee_info' => new EE_Yes_No_Input(
1197
+							array(
1198
+								'html_label_text' => esc_html__(
1199
+									'Allow copy #1 attendee info to extra attendees?',
1200
+									'event_espresso'
1201
+								),
1202
+								'html_help_text'  => esc_html__(
1203
+									'Set to yes if you want to enable the copy of #1 attendee info to extra attendees at Registration Form.',
1204
+									'event_espresso'
1205
+								),
1206
+								'default'         => EE_Registry::instance()->CFG->registration->copyAttendeeInfo(),
1207
+								'required'        => false,
1208
+								'display_html_label_text' => false,
1209
+							)
1210
+						),
1211
+					)
1212
+				),
1213
+			)
1214
+		);
1215
+	}
1216
+
1217
+	/**
1218
+	 * @param EE_Registration_Config $EE_Registration_Config
1219
+	 * @return EE_Registration_Config
1220
+	 * @throws EE_Error
1221
+	 * @throws InvalidArgumentException
1222
+	 * @throws ReflectionException
1223
+	 * @throws InvalidDataTypeException
1224
+	 * @throws InvalidInterfaceException
1225
+	 */
1226
+	public function update_copy_attendee_info_settings_form(EE_Registration_Config $EE_Registration_Config)
1227
+	{
1228
+		$prev_copy_attendee_info = $EE_Registration_Config->copyAttendeeInfo();
1229
+		try {
1230
+			$copy_attendee_info_settings_form = $this->_copy_attendee_info_settings_form();
1231
+			// if not displaying a form, then check for form submission
1232
+			if ($copy_attendee_info_settings_form->was_submitted()) {
1233
+				// capture form data
1234
+				$copy_attendee_info_settings_form->receive_form_submission();
1235
+				// validate form data
1236
+				if ($copy_attendee_info_settings_form->is_valid()) {
1237
+					// grab validated data from form
1238
+					$valid_data = $copy_attendee_info_settings_form->valid_data();
1239
+					if (isset($valid_data['copy_attendee_info'])) {
1240
+						$EE_Registration_Config->setCopyAttendeeInfo($valid_data['copy_attendee_info']);
1241
+					} else {
1242
+						EE_Error::add_error(
1243
+							esc_html__(
1244
+								'Invalid or missing Copy Attendee Info settings. Please refresh the form and try again.',
1245
+								'event_espresso'
1246
+							),
1247
+							__FILE__,
1248
+							__FUNCTION__,
1249
+							__LINE__
1250
+						);
1251
+					}
1252
+				} else {
1253
+					if ($copy_attendee_info_settings_form->submission_error_message() !== '') {
1254
+						EE_Error::add_error(
1255
+							$copy_attendee_info_settings_form->submission_error_message(),
1256
+							__FILE__,
1257
+							__FUNCTION__,
1258
+							__LINE__
1259
+						);
1260
+					}
1261
+				}
1262
+			}
1263
+		} catch (EE_Error $e) {
1264
+			$e->get_error();
1265
+		}
1266
+		return $EE_Registration_Config;
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * @return void
1272
+	 * @throws EE_Error
1273
+	 * @throws InvalidArgumentException
1274
+	 * @throws InvalidDataTypeException
1275
+	 * @throws InvalidInterfaceException
1276
+	 */
1277
+	public function email_validation_settings_form()
1278
+	{
1279
+		echo $this->_email_validation_settings_form()->get_html();
1280
+	}
1281
+
1282
+
1283
+	/**
1284
+	 * _email_validation_settings_form
1285
+	 *
1286
+	 * @access protected
1287
+	 * @return EE_Form_Section_Proper
1288
+	 * @throws \EE_Error
1289
+	 */
1290
+	protected function _email_validation_settings_form()
1291
+	{
1292
+		return new EE_Form_Section_Proper(
1293
+			array(
1294
+				'name'            => 'email_validation_settings',
1295
+				'html_id'         => 'email_validation_settings',
1296
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1297
+				'subsections'     => apply_filters(
1298
+					'FHEE__Extend_Registration_Form_Admin_Page___email_validation_settings_form__form_subsections',
1299
+					array(
1300
+						'email_validation_hdr'   => new EE_Form_Section_HTML(
1301
+							EEH_HTML::h2(esc_html__('Email Validation Settings', 'event_espresso'))
1302
+						),
1303
+						'email_validation_level' => new EE_Select_Input(
1304
+							array(
1305
+								'basic'      => esc_html__('Basic', 'event_espresso'),
1306
+								'wp_default' => esc_html__('WordPress Default', 'event_espresso'),
1307
+								'i18n'       => esc_html__('International', 'event_espresso'),
1308
+								'i18n_dns'   => esc_html__('International + DNS Check', 'event_espresso'),
1309
+							),
1310
+							array(
1311
+								'html_label_text' => esc_html__('Email Validation Level', 'event_espresso')
1312
+													 . EEH_Template::get_help_tab_link('email_validation_info'),
1313
+								'html_help_text'  => esc_html__(
1314
+									'These levels range from basic validation ( ie: [email protected] ) to more advanced checks against international email addresses (ie: üñîçøðé@example.com ) with additional MX and A record checks to confirm the domain actually exists. More information on on each level can be found within the help section.',
1315
+									'event_espresso'
1316
+								),
1317
+								'default'         => isset(
1318
+									EE_Registry::instance()->CFG->registration->email_validation_level
1319
+								)
1320
+									? EE_Registry::instance()->CFG->registration->email_validation_level
1321
+									: 'wp_default',
1322
+								'required'        => false,
1323
+							)
1324
+						),
1325
+					)
1326
+				),
1327
+			)
1328
+		);
1329
+	}
1330
+
1331
+
1332
+	/**
1333
+	 * @param EE_Registration_Config $EE_Registration_Config
1334
+	 * @return EE_Registration_Config
1335
+	 * @throws EE_Error
1336
+	 * @throws InvalidArgumentException
1337
+	 * @throws ReflectionException
1338
+	 * @throws InvalidDataTypeException
1339
+	 * @throws InvalidInterfaceException
1340
+	 */
1341
+	public function update_email_validation_settings_form(EE_Registration_Config $EE_Registration_Config)
1342
+	{
1343
+		$prev_email_validation_level = $EE_Registration_Config->email_validation_level;
1344
+		try {
1345
+			$email_validation_settings_form = $this->_email_validation_settings_form();
1346
+			// if not displaying a form, then check for form submission
1347
+			if ($email_validation_settings_form->was_submitted()) {
1348
+				// capture form data
1349
+				$email_validation_settings_form->receive_form_submission();
1350
+				// validate form data
1351
+				if ($email_validation_settings_form->is_valid()) {
1352
+					// grab validated data from form
1353
+					$valid_data = $email_validation_settings_form->valid_data();
1354
+					if (isset($valid_data['email_validation_level'])) {
1355
+						$email_validation_level = $valid_data['email_validation_level'];
1356
+						// now if they want to use international email addresses
1357
+						if ($email_validation_level === 'i18n' || $email_validation_level === 'i18n_dns') {
1358
+							// in case we need to reset their email validation level,
1359
+							// make sure that the previous value wasn't already set to one of the i18n options.
1360
+							if ($prev_email_validation_level === 'i18n' || $prev_email_validation_level === 'i18n_dns') {
1361
+								// if so, then reset it back to "basic" since that is the only other option that,
1362
+								// despite offering poor validation, supports i18n email addresses
1363
+								$prev_email_validation_level = 'basic';
1364
+							}
1365
+							// confirm our i18n email validation will work on the server
1366
+							if (! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1367
+								// or reset email validation level to previous value
1368
+								$email_validation_level = $prev_email_validation_level;
1369
+							}
1370
+						}
1371
+						$EE_Registration_Config->email_validation_level = $email_validation_level;
1372
+					} else {
1373
+						EE_Error::add_error(
1374
+							esc_html__(
1375
+								'Invalid or missing Email Validation settings. Please refresh the form and try again.',
1376
+								'event_espresso'
1377
+							),
1378
+							__FILE__,
1379
+							__FUNCTION__,
1380
+							__LINE__
1381
+						);
1382
+					}
1383
+				} else {
1384
+					if ($email_validation_settings_form->submission_error_message() !== '') {
1385
+						EE_Error::add_error(
1386
+							$email_validation_settings_form->submission_error_message(),
1387
+							__FILE__,
1388
+							__FUNCTION__,
1389
+							__LINE__
1390
+						);
1391
+					}
1392
+				}
1393
+			}
1394
+		} catch (EE_Error $e) {
1395
+			$e->get_error();
1396
+		}
1397
+		return $EE_Registration_Config;
1398
+	}
1399
+
1400
+
1401
+	/**
1402
+	 * confirms that the server's PHP version has the PCRE module enabled,
1403
+	 * and that the PCRE version works with our i18n email validation
1404
+	 *
1405
+	 * @param EE_Registration_Config $EE_Registration_Config
1406
+	 * @param string                 $email_validation_level
1407
+	 * @return bool
1408
+	 */
1409
+	private function _verify_pcre_support(EE_Registration_Config $EE_Registration_Config, $email_validation_level)
1410
+	{
1411
+		// first check that PCRE is enabled
1412
+		if (! defined('PREG_BAD_UTF8_ERROR')) {
1413
+			EE_Error::add_error(
1414
+				sprintf(
1415
+					esc_html__(
1416
+						'We\'re sorry, but it appears that your server\'s version of PHP was not compiled with PCRE unicode support.%1$sPlease contact your hosting company and ask them whether the PCRE compiled with your version of PHP on your server can be been built with the "--enable-unicode-properties" and "--enable-utf8" configuration switches to enable more complex regex expressions.%1$sIf they are unable, or unwilling to do so, then your server will not support international email addresses using UTF-8 unicode characters. This means you will either have to lower your email validation level to "Basic" or "WordPress Default", or switch to a hosting company that has/can enable PCRE unicode support on the server.',
1417
+						'event_espresso'
1418
+					),
1419
+					'<br />'
1420
+				),
1421
+				__FILE__,
1422
+				__FUNCTION__,
1423
+				__LINE__
1424
+			);
1425
+			return false;
1426
+		} else {
1427
+			// PCRE support is enabled, but let's still
1428
+			// perform a test to see if the server will support it.
1429
+			// but first, save the updated validation level to the config,
1430
+			// so that the validation strategy picks it up.
1431
+			// this will get bumped back down if it doesn't work
1432
+			$EE_Registration_Config->email_validation_level = $email_validation_level;
1433
+			try {
1434
+				$email_validator = new EE_Email_Validation_Strategy();
1435
+				$i18n_email_address = apply_filters(
1436
+					'FHEE__Extend_Registration_Form_Admin_Page__update_email_validation_settings_form__i18n_email_address',
1437
+					'jägerjü[email protected]'
1438
+				);
1439
+				$email_validator->validate($i18n_email_address);
1440
+			} catch (Exception $e) {
1441
+				EE_Error::add_error(
1442
+					sprintf(
1443
+						esc_html__(
1444
+							'We\'re sorry, but it appears that your server\'s configuration will not support the "International" or "International + DNS Check" email validation levels.%1$sTo correct this issue, please consult with your hosting company regarding your server\'s PCRE settings.%1$sIt is recommended that your PHP version be configured to use PCRE 8.10 or newer.%1$sMore information regarding PCRE versions and installation can be found here: %2$s',
1445
+							'event_espresso'
1446
+						),
1447
+						'<br />',
1448
+						'<a href="http://php.net/manual/en/pcre.installation.php" target="_blank" rel="noopener noreferrer">http://php.net/manual/en/pcre.installation.php</a>'
1449
+					),
1450
+					__FILE__,
1451
+					__FUNCTION__,
1452
+					__LINE__
1453
+				);
1454
+				return false;
1455
+			}
1456
+		}
1457
+		return true;
1458
+	}
1459 1459
 }
Please login to merge, or discard this patch.
admin/extend/registrations/Extend_Registrations_Admin_Page.core.php 2 patches
Indentation   +1213 added lines, -1213 removed lines patch added patch discarded remove patch
@@ -16,1270 +16,1270 @@
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * This is used to hold the reports template data which is setup early in the request.
21
-     *
22
-     * @type array
23
-     */
24
-    protected $_reports_template_data = array();
19
+	/**
20
+	 * This is used to hold the reports template data which is setup early in the request.
21
+	 *
22
+	 * @type array
23
+	 */
24
+	protected $_reports_template_data = array();
25 25
 
26 26
 
27
-    /**
28
-     * Extend_Registrations_Admin_Page constructor.
29
-     *
30
-     * @param bool $routing
31
-     */
32
-    public function __construct($routing = true)
33
-    {
34
-        parent::__construct($routing);
35
-        if (! defined('REG_CAF_TEMPLATE_PATH')) {
36
-            define('REG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/templates/');
37
-            define('REG_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/assets/');
38
-            define('REG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registrations/assets/');
39
-        }
40
-    }
27
+	/**
28
+	 * Extend_Registrations_Admin_Page constructor.
29
+	 *
30
+	 * @param bool $routing
31
+	 */
32
+	public function __construct($routing = true)
33
+	{
34
+		parent::__construct($routing);
35
+		if (! defined('REG_CAF_TEMPLATE_PATH')) {
36
+			define('REG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/templates/');
37
+			define('REG_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/assets/');
38
+			define('REG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registrations/assets/');
39
+		}
40
+	}
41 41
 
42 42
 
43
-    /**
44
-     * Extending page configuration.
45
-     */
46
-    protected function _extend_page_config()
47
-    {
48
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'registrations';
49
-        $reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
50
-            ? $this->_req_data['_REG_ID']
51
-            : 0;
52
-        $new_page_routes = array(
53
-            'reports'                      => array(
54
-                'func'       => '_registration_reports',
55
-                'capability' => 'ee_read_registrations',
56
-            ),
57
-            'registration_checkins'        => array(
58
-                'func'       => '_registration_checkin_list_table',
59
-                'capability' => 'ee_read_checkins',
60
-            ),
61
-            'newsletter_selected_send'     => array(
62
-                'func'       => '_newsletter_selected_send',
63
-                'noheader'   => true,
64
-                'capability' => 'ee_send_message',
65
-            ),
66
-            'delete_checkin_rows'          => array(
67
-                'func'       => '_delete_checkin_rows',
68
-                'noheader'   => true,
69
-                'capability' => 'ee_delete_checkins',
70
-            ),
71
-            'delete_checkin_row'           => array(
72
-                'func'       => '_delete_checkin_row',
73
-                'noheader'   => true,
74
-                'capability' => 'ee_delete_checkin',
75
-                'obj_id'     => $reg_id,
76
-            ),
77
-            'toggle_checkin_status'        => array(
78
-                'func'       => '_toggle_checkin_status',
79
-                'noheader'   => true,
80
-                'capability' => 'ee_edit_checkin',
81
-                'obj_id'     => $reg_id,
82
-            ),
83
-            'toggle_checkin_status_bulk'   => array(
84
-                'func'       => '_toggle_checkin_status',
85
-                'noheader'   => true,
86
-                'capability' => 'ee_edit_checkins',
87
-            ),
88
-            'event_registrations'          => array(
89
-                'func'       => '_event_registrations_list_table',
90
-                'capability' => 'ee_read_checkins',
91
-            ),
92
-            'registrations_checkin_report' => array(
93
-                'func'       => '_registrations_checkin_report',
94
-                'noheader'   => true,
95
-                'capability' => 'ee_read_registrations',
96
-            ),
97
-        );
98
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
99
-        $new_page_config = array(
100
-            'reports'               => array(
101
-                'nav'           => array(
102
-                    'label' => esc_html__('Reports', 'event_espresso'),
103
-                    'order' => 30,
104
-                ),
105
-                'help_tabs'     => array(
106
-                    'registrations_reports_help_tab' => array(
107
-                        'title'    => esc_html__('Registration Reports', 'event_espresso'),
108
-                        'filename' => 'registrations_reports',
109
-                    ),
110
-                ),
111
-                /*'help_tour' => array( 'Registration_Reports_Help_Tour' ),*/
112
-                'require_nonce' => false,
113
-            ),
114
-            'event_registrations'   => array(
115
-                'nav'           => array(
116
-                    'label'      => esc_html__('Event Check-In', 'event_espresso'),
117
-                    'order'      => 10,
118
-                    'persistent' => true,
119
-                ),
120
-                'help_tabs'     => array(
121
-                    'registrations_event_checkin_help_tab'                       => array(
122
-                        'title'    => esc_html__('Registrations Event Check-In', 'event_espresso'),
123
-                        'filename' => 'registrations_event_checkin',
124
-                    ),
125
-                    'registrations_event_checkin_table_column_headings_help_tab' => array(
126
-                        'title'    => esc_html__('Event Check-In Table Column Headings', 'event_espresso'),
127
-                        'filename' => 'registrations_event_checkin_table_column_headings',
128
-                    ),
129
-                    'registrations_event_checkin_filters_help_tab'               => array(
130
-                        'title'    => esc_html__('Event Check-In Filters', 'event_espresso'),
131
-                        'filename' => 'registrations_event_checkin_filters',
132
-                    ),
133
-                    'registrations_event_checkin_views_help_tab'                 => array(
134
-                        'title'    => esc_html__('Event Check-In Views', 'event_espresso'),
135
-                        'filename' => 'registrations_event_checkin_views',
136
-                    ),
137
-                    'registrations_event_checkin_other_help_tab'                 => array(
138
-                        'title'    => esc_html__('Event Check-In Other', 'event_espresso'),
139
-                        'filename' => 'registrations_event_checkin_other',
140
-                    ),
141
-                ),
142
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
143
-                // 'help_tour'     => array('Event_Checkin_Help_Tour'),
144
-                'qtips'         => array('Registration_List_Table_Tips'),
145
-                'list_table'    => 'EE_Event_Registrations_List_Table',
146
-                'metaboxes'     => array(),
147
-                'require_nonce' => false,
148
-            ),
149
-            'registration_checkins' => array(
150
-                'nav'           => array(
151
-                    'label'      => esc_html__('Check-In Records', 'event_espresso'),
152
-                    'order'      => 15,
153
-                    'persistent' => false,
154
-                    'url'        => '',
155
-                ),
156
-                'list_table'    => 'EE_Registration_CheckIn_List_Table',
157
-                // 'help_tour' => array( 'Checkin_Toggle_View_Help_Tour' ),
158
-                'metaboxes'     => array(),
159
-                'require_nonce' => false,
160
-            ),
161
-        );
162
-        $this->_page_config = array_merge($this->_page_config, $new_page_config);
163
-        $this->_page_config['contact_list']['list_table'] = 'Extend_EE_Attendee_Contact_List_Table';
164
-        $this->_page_config['default']['list_table'] = 'Extend_EE_Registrations_List_Table';
165
-    }
43
+	/**
44
+	 * Extending page configuration.
45
+	 */
46
+	protected function _extend_page_config()
47
+	{
48
+		$this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'registrations';
49
+		$reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
50
+			? $this->_req_data['_REG_ID']
51
+			: 0;
52
+		$new_page_routes = array(
53
+			'reports'                      => array(
54
+				'func'       => '_registration_reports',
55
+				'capability' => 'ee_read_registrations',
56
+			),
57
+			'registration_checkins'        => array(
58
+				'func'       => '_registration_checkin_list_table',
59
+				'capability' => 'ee_read_checkins',
60
+			),
61
+			'newsletter_selected_send'     => array(
62
+				'func'       => '_newsletter_selected_send',
63
+				'noheader'   => true,
64
+				'capability' => 'ee_send_message',
65
+			),
66
+			'delete_checkin_rows'          => array(
67
+				'func'       => '_delete_checkin_rows',
68
+				'noheader'   => true,
69
+				'capability' => 'ee_delete_checkins',
70
+			),
71
+			'delete_checkin_row'           => array(
72
+				'func'       => '_delete_checkin_row',
73
+				'noheader'   => true,
74
+				'capability' => 'ee_delete_checkin',
75
+				'obj_id'     => $reg_id,
76
+			),
77
+			'toggle_checkin_status'        => array(
78
+				'func'       => '_toggle_checkin_status',
79
+				'noheader'   => true,
80
+				'capability' => 'ee_edit_checkin',
81
+				'obj_id'     => $reg_id,
82
+			),
83
+			'toggle_checkin_status_bulk'   => array(
84
+				'func'       => '_toggle_checkin_status',
85
+				'noheader'   => true,
86
+				'capability' => 'ee_edit_checkins',
87
+			),
88
+			'event_registrations'          => array(
89
+				'func'       => '_event_registrations_list_table',
90
+				'capability' => 'ee_read_checkins',
91
+			),
92
+			'registrations_checkin_report' => array(
93
+				'func'       => '_registrations_checkin_report',
94
+				'noheader'   => true,
95
+				'capability' => 'ee_read_registrations',
96
+			),
97
+		);
98
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
99
+		$new_page_config = array(
100
+			'reports'               => array(
101
+				'nav'           => array(
102
+					'label' => esc_html__('Reports', 'event_espresso'),
103
+					'order' => 30,
104
+				),
105
+				'help_tabs'     => array(
106
+					'registrations_reports_help_tab' => array(
107
+						'title'    => esc_html__('Registration Reports', 'event_espresso'),
108
+						'filename' => 'registrations_reports',
109
+					),
110
+				),
111
+				/*'help_tour' => array( 'Registration_Reports_Help_Tour' ),*/
112
+				'require_nonce' => false,
113
+			),
114
+			'event_registrations'   => array(
115
+				'nav'           => array(
116
+					'label'      => esc_html__('Event Check-In', 'event_espresso'),
117
+					'order'      => 10,
118
+					'persistent' => true,
119
+				),
120
+				'help_tabs'     => array(
121
+					'registrations_event_checkin_help_tab'                       => array(
122
+						'title'    => esc_html__('Registrations Event Check-In', 'event_espresso'),
123
+						'filename' => 'registrations_event_checkin',
124
+					),
125
+					'registrations_event_checkin_table_column_headings_help_tab' => array(
126
+						'title'    => esc_html__('Event Check-In Table Column Headings', 'event_espresso'),
127
+						'filename' => 'registrations_event_checkin_table_column_headings',
128
+					),
129
+					'registrations_event_checkin_filters_help_tab'               => array(
130
+						'title'    => esc_html__('Event Check-In Filters', 'event_espresso'),
131
+						'filename' => 'registrations_event_checkin_filters',
132
+					),
133
+					'registrations_event_checkin_views_help_tab'                 => array(
134
+						'title'    => esc_html__('Event Check-In Views', 'event_espresso'),
135
+						'filename' => 'registrations_event_checkin_views',
136
+					),
137
+					'registrations_event_checkin_other_help_tab'                 => array(
138
+						'title'    => esc_html__('Event Check-In Other', 'event_espresso'),
139
+						'filename' => 'registrations_event_checkin_other',
140
+					),
141
+				),
142
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
143
+				// 'help_tour'     => array('Event_Checkin_Help_Tour'),
144
+				'qtips'         => array('Registration_List_Table_Tips'),
145
+				'list_table'    => 'EE_Event_Registrations_List_Table',
146
+				'metaboxes'     => array(),
147
+				'require_nonce' => false,
148
+			),
149
+			'registration_checkins' => array(
150
+				'nav'           => array(
151
+					'label'      => esc_html__('Check-In Records', 'event_espresso'),
152
+					'order'      => 15,
153
+					'persistent' => false,
154
+					'url'        => '',
155
+				),
156
+				'list_table'    => 'EE_Registration_CheckIn_List_Table',
157
+				// 'help_tour' => array( 'Checkin_Toggle_View_Help_Tour' ),
158
+				'metaboxes'     => array(),
159
+				'require_nonce' => false,
160
+			),
161
+		);
162
+		$this->_page_config = array_merge($this->_page_config, $new_page_config);
163
+		$this->_page_config['contact_list']['list_table'] = 'Extend_EE_Attendee_Contact_List_Table';
164
+		$this->_page_config['default']['list_table'] = 'Extend_EE_Registrations_List_Table';
165
+	}
166 166
 
167 167
 
168
-    /**
169
-     * Ajax hooks for all routes in this page.
170
-     */
171
-    protected function _ajax_hooks()
172
-    {
173
-        parent::_ajax_hooks();
174
-        add_action('wp_ajax_get_newsletter_form_content', array($this, 'get_newsletter_form_content'));
175
-    }
168
+	/**
169
+	 * Ajax hooks for all routes in this page.
170
+	 */
171
+	protected function _ajax_hooks()
172
+	{
173
+		parent::_ajax_hooks();
174
+		add_action('wp_ajax_get_newsletter_form_content', array($this, 'get_newsletter_form_content'));
175
+	}
176 176
 
177 177
 
178
-    /**
179
-     * Global scripts for all routes in this page.
180
-     */
181
-    public function load_scripts_styles()
182
-    {
183
-        parent::load_scripts_styles();
184
-        // if newsletter message type is active then let's add filter and load js for it.
185
-        if (EEH_MSG_Template::is_mt_active('newsletter')) {
186
-            // enqueue newsletter js
187
-            wp_enqueue_script(
188
-                'ee-newsletter-trigger',
189
-                REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.js',
190
-                array('ee-dialog'),
191
-                EVENT_ESPRESSO_VERSION,
192
-                true
193
-            );
194
-            wp_enqueue_style(
195
-                'ee-newsletter-trigger-css',
196
-                REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.css',
197
-                array(),
198
-                EVENT_ESPRESSO_VERSION
199
-            );
200
-            // hook in buttons for newsletter message type trigger.
201
-            add_action(
202
-                'AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons',
203
-                array($this, 'add_newsletter_action_buttons'),
204
-                10
205
-            );
206
-        }
207
-    }
178
+	/**
179
+	 * Global scripts for all routes in this page.
180
+	 */
181
+	public function load_scripts_styles()
182
+	{
183
+		parent::load_scripts_styles();
184
+		// if newsletter message type is active then let's add filter and load js for it.
185
+		if (EEH_MSG_Template::is_mt_active('newsletter')) {
186
+			// enqueue newsletter js
187
+			wp_enqueue_script(
188
+				'ee-newsletter-trigger',
189
+				REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.js',
190
+				array('ee-dialog'),
191
+				EVENT_ESPRESSO_VERSION,
192
+				true
193
+			);
194
+			wp_enqueue_style(
195
+				'ee-newsletter-trigger-css',
196
+				REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.css',
197
+				array(),
198
+				EVENT_ESPRESSO_VERSION
199
+			);
200
+			// hook in buttons for newsletter message type trigger.
201
+			add_action(
202
+				'AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons',
203
+				array($this, 'add_newsletter_action_buttons'),
204
+				10
205
+			);
206
+		}
207
+	}
208 208
 
209 209
 
210
-    /**
211
-     * Scripts and styles for just the reports route.
212
-     */
213
-    public function load_scripts_styles_reports()
214
-    {
215
-        wp_register_script(
216
-            'ee-reg-reports-js',
217
-            REG_CAF_ASSETS_URL . 'ee-registration-admin-reports.js',
218
-            array('google-charts'),
219
-            EVENT_ESPRESSO_VERSION,
220
-            true
221
-        );
222
-        wp_enqueue_script('ee-reg-reports-js');
223
-        $this->_registration_reports_js_setup();
224
-    }
210
+	/**
211
+	 * Scripts and styles for just the reports route.
212
+	 */
213
+	public function load_scripts_styles_reports()
214
+	{
215
+		wp_register_script(
216
+			'ee-reg-reports-js',
217
+			REG_CAF_ASSETS_URL . 'ee-registration-admin-reports.js',
218
+			array('google-charts'),
219
+			EVENT_ESPRESSO_VERSION,
220
+			true
221
+		);
222
+		wp_enqueue_script('ee-reg-reports-js');
223
+		$this->_registration_reports_js_setup();
224
+	}
225 225
 
226 226
 
227
-    /**
228
-     * Register screen options for event_registrations route.
229
-     */
230
-    protected function _add_screen_options_event_registrations()
231
-    {
232
-        $this->_per_page_screen_option();
233
-    }
227
+	/**
228
+	 * Register screen options for event_registrations route.
229
+	 */
230
+	protected function _add_screen_options_event_registrations()
231
+	{
232
+		$this->_per_page_screen_option();
233
+	}
234 234
 
235 235
 
236
-    /**
237
-     * Register screen options for registration_checkins route
238
-     */
239
-    protected function _add_screen_options_registration_checkins()
240
-    {
241
-        $page_title = $this->_admin_page_title;
242
-        $this->_admin_page_title = esc_html__('Check-In Records', 'event_espresso');
243
-        $this->_per_page_screen_option();
244
-        $this->_admin_page_title = $page_title;
245
-    }
236
+	/**
237
+	 * Register screen options for registration_checkins route
238
+	 */
239
+	protected function _add_screen_options_registration_checkins()
240
+	{
241
+		$page_title = $this->_admin_page_title;
242
+		$this->_admin_page_title = esc_html__('Check-In Records', 'event_espresso');
243
+		$this->_per_page_screen_option();
244
+		$this->_admin_page_title = $page_title;
245
+	}
246 246
 
247 247
 
248
-    /**
249
-     * Set views property for event_registrations route.
250
-     */
251
-    protected function _set_list_table_views_event_registrations()
252
-    {
253
-        $this->_views = array(
254
-            'all' => array(
255
-                'slug'        => 'all',
256
-                'label'       => esc_html__('All', 'event_espresso'),
257
-                'count'       => 0,
258
-                'bulk_action' => ! isset($this->_req_data['event_id'])
259
-                    ? array()
260
-                    : array(
261
-                        'toggle_checkin_status_bulk' => esc_html__('Toggle Check-In', 'event_espresso'),
262
-                    ),
263
-            ),
264
-        );
265
-    }
248
+	/**
249
+	 * Set views property for event_registrations route.
250
+	 */
251
+	protected function _set_list_table_views_event_registrations()
252
+	{
253
+		$this->_views = array(
254
+			'all' => array(
255
+				'slug'        => 'all',
256
+				'label'       => esc_html__('All', 'event_espresso'),
257
+				'count'       => 0,
258
+				'bulk_action' => ! isset($this->_req_data['event_id'])
259
+					? array()
260
+					: array(
261
+						'toggle_checkin_status_bulk' => esc_html__('Toggle Check-In', 'event_espresso'),
262
+					),
263
+			),
264
+		);
265
+	}
266 266
 
267 267
 
268
-    /**
269
-     * Set views property for registration_checkins route.
270
-     */
271
-    protected function _set_list_table_views_registration_checkins()
272
-    {
273
-        $this->_views = array(
274
-            'all' => array(
275
-                'slug'        => 'all',
276
-                'label'       => esc_html__('All', 'event_espresso'),
277
-                'count'       => 0,
278
-                'bulk_action' => array('delete_checkin_rows' => esc_html__('Delete Check-In Rows', 'event_espresso')),
279
-            ),
280
-        );
281
-    }
268
+	/**
269
+	 * Set views property for registration_checkins route.
270
+	 */
271
+	protected function _set_list_table_views_registration_checkins()
272
+	{
273
+		$this->_views = array(
274
+			'all' => array(
275
+				'slug'        => 'all',
276
+				'label'       => esc_html__('All', 'event_espresso'),
277
+				'count'       => 0,
278
+				'bulk_action' => array('delete_checkin_rows' => esc_html__('Delete Check-In Rows', 'event_espresso')),
279
+			),
280
+		);
281
+	}
282 282
 
283 283
 
284
-    /**
285
-     * callback for ajax action.
286
-     *
287
-     * @since 4.3.0
288
-     * @return void (JSON)
289
-     * @throws EE_Error
290
-     * @throws InvalidArgumentException
291
-     * @throws InvalidDataTypeException
292
-     * @throws InvalidInterfaceException
293
-     */
294
-    public function get_newsletter_form_content()
295
-    {
296
-        // do a nonce check cause we're not coming in from an normal route here.
297
-        $nonce = isset($this->_req_data['get_newsletter_form_content_nonce']) ? sanitize_text_field(
298
-            $this->_req_data['get_newsletter_form_content_nonce']
299
-        ) : '';
300
-        $nonce_ref = 'get_newsletter_form_content_nonce';
301
-        $this->_verify_nonce($nonce, $nonce_ref);
302
-        // let's get the mtp for the incoming MTP_ ID
303
-        if (! isset($this->_req_data['GRP_ID'])) {
304
-            EE_Error::add_error(
305
-                esc_html__(
306
-                    'There must be something broken with the js or html structure because the required data for getting a message template group is not present (need an GRP_ID).',
307
-                    'event_espresso'
308
-                ),
309
-                __FILE__,
310
-                __FUNCTION__,
311
-                __LINE__
312
-            );
313
-            $this->_template_args['success'] = false;
314
-            $this->_template_args['error'] = true;
315
-            $this->_return_json();
316
-        }
317
-        $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID($this->_req_data['GRP_ID']);
318
-        if (! $MTPG instanceof EE_Message_Template_Group) {
319
-            EE_Error::add_error(
320
-                sprintf(
321
-                    esc_html__(
322
-                        'The GRP_ID given (%d) does not appear to have a corresponding row in the database.',
323
-                        'event_espresso'
324
-                    ),
325
-                    $this->_req_data['GRP_ID']
326
-                ),
327
-                __FILE__,
328
-                __FUNCTION__,
329
-                __LINE__
330
-            );
331
-            $this->_template_args['success'] = false;
332
-            $this->_template_args['error'] = true;
333
-            $this->_return_json();
334
-        }
335
-        $MTPs = $MTPG->context_templates();
336
-        $MTPs = $MTPs['attendee'];
337
-        $template_fields = array();
338
-        /** @var EE_Message_Template $MTP */
339
-        foreach ($MTPs as $MTP) {
340
-            $field = $MTP->get('MTP_template_field');
341
-            if ($field === 'content') {
342
-                $content = $MTP->get('MTP_content');
343
-                if (! empty($content['newsletter_content'])) {
344
-                    $template_fields['newsletter_content'] = $content['newsletter_content'];
345
-                }
346
-                continue;
347
-            }
348
-            $template_fields[ $MTP->get('MTP_template_field') ] = $MTP->get('MTP_content');
349
-        }
350
-        $this->_template_args['success'] = true;
351
-        $this->_template_args['error'] = false;
352
-        $this->_template_args['data'] = array(
353
-            'batch_message_from'    => isset($template_fields['from'])
354
-                ? $template_fields['from']
355
-                : '',
356
-            'batch_message_subject' => isset($template_fields['subject'])
357
-                ? $template_fields['subject']
358
-                : '',
359
-            'batch_message_content' => isset($template_fields['newsletter_content'])
360
-                ? $template_fields['newsletter_content']
361
-                : '',
362
-        );
363
-        $this->_return_json();
364
-    }
284
+	/**
285
+	 * callback for ajax action.
286
+	 *
287
+	 * @since 4.3.0
288
+	 * @return void (JSON)
289
+	 * @throws EE_Error
290
+	 * @throws InvalidArgumentException
291
+	 * @throws InvalidDataTypeException
292
+	 * @throws InvalidInterfaceException
293
+	 */
294
+	public function get_newsletter_form_content()
295
+	{
296
+		// do a nonce check cause we're not coming in from an normal route here.
297
+		$nonce = isset($this->_req_data['get_newsletter_form_content_nonce']) ? sanitize_text_field(
298
+			$this->_req_data['get_newsletter_form_content_nonce']
299
+		) : '';
300
+		$nonce_ref = 'get_newsletter_form_content_nonce';
301
+		$this->_verify_nonce($nonce, $nonce_ref);
302
+		// let's get the mtp for the incoming MTP_ ID
303
+		if (! isset($this->_req_data['GRP_ID'])) {
304
+			EE_Error::add_error(
305
+				esc_html__(
306
+					'There must be something broken with the js or html structure because the required data for getting a message template group is not present (need an GRP_ID).',
307
+					'event_espresso'
308
+				),
309
+				__FILE__,
310
+				__FUNCTION__,
311
+				__LINE__
312
+			);
313
+			$this->_template_args['success'] = false;
314
+			$this->_template_args['error'] = true;
315
+			$this->_return_json();
316
+		}
317
+		$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID($this->_req_data['GRP_ID']);
318
+		if (! $MTPG instanceof EE_Message_Template_Group) {
319
+			EE_Error::add_error(
320
+				sprintf(
321
+					esc_html__(
322
+						'The GRP_ID given (%d) does not appear to have a corresponding row in the database.',
323
+						'event_espresso'
324
+					),
325
+					$this->_req_data['GRP_ID']
326
+				),
327
+				__FILE__,
328
+				__FUNCTION__,
329
+				__LINE__
330
+			);
331
+			$this->_template_args['success'] = false;
332
+			$this->_template_args['error'] = true;
333
+			$this->_return_json();
334
+		}
335
+		$MTPs = $MTPG->context_templates();
336
+		$MTPs = $MTPs['attendee'];
337
+		$template_fields = array();
338
+		/** @var EE_Message_Template $MTP */
339
+		foreach ($MTPs as $MTP) {
340
+			$field = $MTP->get('MTP_template_field');
341
+			if ($field === 'content') {
342
+				$content = $MTP->get('MTP_content');
343
+				if (! empty($content['newsletter_content'])) {
344
+					$template_fields['newsletter_content'] = $content['newsletter_content'];
345
+				}
346
+				continue;
347
+			}
348
+			$template_fields[ $MTP->get('MTP_template_field') ] = $MTP->get('MTP_content');
349
+		}
350
+		$this->_template_args['success'] = true;
351
+		$this->_template_args['error'] = false;
352
+		$this->_template_args['data'] = array(
353
+			'batch_message_from'    => isset($template_fields['from'])
354
+				? $template_fields['from']
355
+				: '',
356
+			'batch_message_subject' => isset($template_fields['subject'])
357
+				? $template_fields['subject']
358
+				: '',
359
+			'batch_message_content' => isset($template_fields['newsletter_content'])
360
+				? $template_fields['newsletter_content']
361
+				: '',
362
+		);
363
+		$this->_return_json();
364
+	}
365 365
 
366 366
 
367
-    /**
368
-     * callback for AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons action
369
-     *
370
-     * @since 4.3.0
371
-     * @param EE_Admin_List_Table $list_table
372
-     * @return void
373
-     * @throws InvalidArgumentException
374
-     * @throws InvalidDataTypeException
375
-     * @throws InvalidInterfaceException
376
-     */
377
-    public function add_newsletter_action_buttons(EE_Admin_List_Table $list_table)
378
-    {
379
-        if (
380
-            ! EE_Registry::instance()->CAP->current_user_can(
381
-                'ee_send_message',
382
-                'espresso_registrations_newsletter_selected_send'
383
-            )
384
-        ) {
385
-            return;
386
-        }
387
-        $routes_to_add_to = array(
388
-            'contact_list',
389
-            'event_registrations',
390
-            'default',
391
-        );
392
-        if ($this->_current_page === 'espresso_registrations' && in_array($this->_req_action, $routes_to_add_to)) {
393
-            if (
394
-                ($this->_req_action === 'event_registrations' && empty($this->_req_data['event_id']))
395
-                || (isset($this->_req_data['status']) && $this->_req_data['status'] === 'trash')
396
-            ) {
397
-                echo '';
398
-            } else {
399
-                $button_text = sprintf(
400
-                    esc_html__('Send Batch Message (%s selected)', 'event_espresso'),
401
-                    '<span class="send-selected-newsletter-count">0</span>'
402
-                );
403
-                echo '<button id="selected-batch-send-trigger" class="button secondary-button">'
404
-                     . '<span class="dashicons dashicons-email "></span>'
405
-                     . $button_text
406
-                     . '</button>';
407
-                add_action('admin_footer', array($this, 'newsletter_send_form_skeleton'));
408
-            }
409
-        }
410
-    }
367
+	/**
368
+	 * callback for AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons action
369
+	 *
370
+	 * @since 4.3.0
371
+	 * @param EE_Admin_List_Table $list_table
372
+	 * @return void
373
+	 * @throws InvalidArgumentException
374
+	 * @throws InvalidDataTypeException
375
+	 * @throws InvalidInterfaceException
376
+	 */
377
+	public function add_newsletter_action_buttons(EE_Admin_List_Table $list_table)
378
+	{
379
+		if (
380
+			! EE_Registry::instance()->CAP->current_user_can(
381
+				'ee_send_message',
382
+				'espresso_registrations_newsletter_selected_send'
383
+			)
384
+		) {
385
+			return;
386
+		}
387
+		$routes_to_add_to = array(
388
+			'contact_list',
389
+			'event_registrations',
390
+			'default',
391
+		);
392
+		if ($this->_current_page === 'espresso_registrations' && in_array($this->_req_action, $routes_to_add_to)) {
393
+			if (
394
+				($this->_req_action === 'event_registrations' && empty($this->_req_data['event_id']))
395
+				|| (isset($this->_req_data['status']) && $this->_req_data['status'] === 'trash')
396
+			) {
397
+				echo '';
398
+			} else {
399
+				$button_text = sprintf(
400
+					esc_html__('Send Batch Message (%s selected)', 'event_espresso'),
401
+					'<span class="send-selected-newsletter-count">0</span>'
402
+				);
403
+				echo '<button id="selected-batch-send-trigger" class="button secondary-button">'
404
+					 . '<span class="dashicons dashicons-email "></span>'
405
+					 . $button_text
406
+					 . '</button>';
407
+				add_action('admin_footer', array($this, 'newsletter_send_form_skeleton'));
408
+			}
409
+		}
410
+	}
411 411
 
412 412
 
413
-    /**
414
-     * @throws DomainException
415
-     * @throws EE_Error
416
-     * @throws InvalidArgumentException
417
-     * @throws InvalidDataTypeException
418
-     * @throws InvalidInterfaceException
419
-     */
420
-    public function newsletter_send_form_skeleton()
421
-    {
422
-        $list_table = $this->_list_table_object;
423
-        $codes = array();
424
-        // need to templates for the newsletter message type for the template selector.
425
-        $values[] = array('text' => esc_html__('Select Template to Use', 'event_espresso'), 'id' => 0);
426
-        $mtps = EEM_Message_Template_Group::instance()->get_all(
427
-            array(array('MTP_message_type' => 'newsletter', 'MTP_messenger' => 'email'))
428
-        );
429
-        foreach ($mtps as $mtp) {
430
-            $name = $mtp->name();
431
-            $values[] = array(
432
-                'text' => empty($name) ? esc_html__('Global', 'event_espresso') : $name,
433
-                'id'   => $mtp->ID(),
434
-            );
435
-        }
436
-        // need to get a list of shortcodes that are available for the newsletter message type.
437
-        $shortcodes = EEH_MSG_Template::get_shortcodes(
438
-            'newsletter',
439
-            'email',
440
-            array(),
441
-            'attendee',
442
-            false
443
-        );
444
-        foreach ($shortcodes as $field => $shortcode_array) {
445
-            $available_shortcodes = array();
446
-            foreach ($shortcode_array as $shortcode => $shortcode_details) {
447
-                $field_id = $field === '[NEWSLETTER_CONTENT]'
448
-                    ? 'content'
449
-                    : $field;
450
-                $field_id = 'batch-message-' . strtolower($field_id);
451
-                $available_shortcodes[] = '<span class="js-shortcode-selection" data-value="'
452
-                                          . $shortcode
453
-                                          . '" data-linked-input-id="' . $field_id . '">'
454
-                                          . $shortcode
455
-                                          . '</span>';
456
-            }
457
-            $codes[ $field ] = implode(', ', $available_shortcodes);
458
-        }
459
-        $shortcodes = $codes;
460
-        $form_template = REG_CAF_TEMPLATE_PATH . 'newsletter-send-form.template.php';
461
-        $form_template_args = array(
462
-            'form_action'       => admin_url('admin.php?page=espresso_registrations'),
463
-            'form_route'        => 'newsletter_selected_send',
464
-            'form_nonce_name'   => 'newsletter_selected_send_nonce',
465
-            'form_nonce'        => wp_create_nonce('newsletter_selected_send_nonce'),
466
-            'redirect_back_to'  => $this->_req_action,
467
-            'ajax_nonce'        => wp_create_nonce('get_newsletter_form_content_nonce'),
468
-            'template_selector' => EEH_Form_Fields::select_input('newsletter_mtp_selected', $values),
469
-            'shortcodes'        => $shortcodes,
470
-            'id_type'           => $list_table instanceof EE_Attendee_Contact_List_Table ? 'contact' : 'registration',
471
-        );
472
-        EEH_Template::display_template($form_template, $form_template_args);
473
-    }
413
+	/**
414
+	 * @throws DomainException
415
+	 * @throws EE_Error
416
+	 * @throws InvalidArgumentException
417
+	 * @throws InvalidDataTypeException
418
+	 * @throws InvalidInterfaceException
419
+	 */
420
+	public function newsletter_send_form_skeleton()
421
+	{
422
+		$list_table = $this->_list_table_object;
423
+		$codes = array();
424
+		// need to templates for the newsletter message type for the template selector.
425
+		$values[] = array('text' => esc_html__('Select Template to Use', 'event_espresso'), 'id' => 0);
426
+		$mtps = EEM_Message_Template_Group::instance()->get_all(
427
+			array(array('MTP_message_type' => 'newsletter', 'MTP_messenger' => 'email'))
428
+		);
429
+		foreach ($mtps as $mtp) {
430
+			$name = $mtp->name();
431
+			$values[] = array(
432
+				'text' => empty($name) ? esc_html__('Global', 'event_espresso') : $name,
433
+				'id'   => $mtp->ID(),
434
+			);
435
+		}
436
+		// need to get a list of shortcodes that are available for the newsletter message type.
437
+		$shortcodes = EEH_MSG_Template::get_shortcodes(
438
+			'newsletter',
439
+			'email',
440
+			array(),
441
+			'attendee',
442
+			false
443
+		);
444
+		foreach ($shortcodes as $field => $shortcode_array) {
445
+			$available_shortcodes = array();
446
+			foreach ($shortcode_array as $shortcode => $shortcode_details) {
447
+				$field_id = $field === '[NEWSLETTER_CONTENT]'
448
+					? 'content'
449
+					: $field;
450
+				$field_id = 'batch-message-' . strtolower($field_id);
451
+				$available_shortcodes[] = '<span class="js-shortcode-selection" data-value="'
452
+										  . $shortcode
453
+										  . '" data-linked-input-id="' . $field_id . '">'
454
+										  . $shortcode
455
+										  . '</span>';
456
+			}
457
+			$codes[ $field ] = implode(', ', $available_shortcodes);
458
+		}
459
+		$shortcodes = $codes;
460
+		$form_template = REG_CAF_TEMPLATE_PATH . 'newsletter-send-form.template.php';
461
+		$form_template_args = array(
462
+			'form_action'       => admin_url('admin.php?page=espresso_registrations'),
463
+			'form_route'        => 'newsletter_selected_send',
464
+			'form_nonce_name'   => 'newsletter_selected_send_nonce',
465
+			'form_nonce'        => wp_create_nonce('newsletter_selected_send_nonce'),
466
+			'redirect_back_to'  => $this->_req_action,
467
+			'ajax_nonce'        => wp_create_nonce('get_newsletter_form_content_nonce'),
468
+			'template_selector' => EEH_Form_Fields::select_input('newsletter_mtp_selected', $values),
469
+			'shortcodes'        => $shortcodes,
470
+			'id_type'           => $list_table instanceof EE_Attendee_Contact_List_Table ? 'contact' : 'registration',
471
+		);
472
+		EEH_Template::display_template($form_template, $form_template_args);
473
+	}
474 474
 
475 475
 
476
-    /**
477
-     * Handles sending selected registrations/contacts a newsletter.
478
-     *
479
-     * @since  4.3.0
480
-     * @return void
481
-     * @throws EE_Error
482
-     * @throws InvalidArgumentException
483
-     * @throws InvalidDataTypeException
484
-     * @throws InvalidInterfaceException
485
-     */
486
-    protected function _newsletter_selected_send()
487
-    {
488
-        $success = true;
489
-        // first we need to make sure we have a GRP_ID so we know what template we're sending and updating!
490
-        if (empty($this->_req_data['newsletter_mtp_selected'])) {
491
-            EE_Error::add_error(
492
-                esc_html__(
493
-                    'In order to send a message, a Message Template GRP_ID is needed. It was not provided so messages were not sent.',
494
-                    'event_espresso'
495
-                ),
496
-                __FILE__,
497
-                __FUNCTION__,
498
-                __LINE__
499
-            );
500
-            $success = false;
501
-        }
502
-        if ($success) {
503
-            // update Message template in case there are any changes
504
-            $Message_Template_Group = EEM_Message_Template_Group::instance()->get_one_by_ID(
505
-                $this->_req_data['newsletter_mtp_selected']
506
-            );
507
-            $Message_Templates = $Message_Template_Group instanceof EE_Message_Template_Group
508
-                ? $Message_Template_Group->context_templates()
509
-                : array();
510
-            if (empty($Message_Templates)) {
511
-                EE_Error::add_error(
512
-                    esc_html__(
513
-                        'Unable to retrieve message template fields from the db. Messages not sent.',
514
-                        'event_espresso'
515
-                    ),
516
-                    __FILE__,
517
-                    __FUNCTION__,
518
-                    __LINE__
519
-                );
520
-            }
521
-            // let's just update the specific fields
522
-            foreach ($Message_Templates['attendee'] as $Message_Template) {
523
-                if ($Message_Template instanceof EE_Message_Template) {
524
-                    $field = $Message_Template->get('MTP_template_field');
525
-                    $content = $Message_Template->get('MTP_content');
526
-                    $new_content = $content;
527
-                    switch ($field) {
528
-                        case 'from':
529
-                            $new_content = ! empty($this->_req_data['batch_message']['from'])
530
-                                ? $this->_req_data['batch_message']['from']
531
-                                : $content;
532
-                            break;
533
-                        case 'subject':
534
-                            $new_content = ! empty($this->_req_data['batch_message']['subject'])
535
-                                ? $this->_req_data['batch_message']['subject']
536
-                                : $content;
537
-                            break;
538
-                        case 'content':
539
-                            $new_content = $content;
540
-                            $new_content['newsletter_content'] = ! empty($this->_req_data['batch_message']['content'])
541
-                                ? $this->_req_data['batch_message']['content']
542
-                                : $content['newsletter_content'];
543
-                            break;
544
-                        default:
545
-                            // continue the foreach loop, we don't want to set $new_content nor save.
546
-                            continue 2;
547
-                    }
548
-                    $Message_Template->set('MTP_content', $new_content);
549
-                    $Message_Template->save();
550
-                }
551
-            }
552
-            // great fields are updated!  now let's make sure we just have contact objects (EE_Attendee).
553
-            $id_type = ! empty($this->_req_data['batch_message']['id_type'])
554
-                ? $this->_req_data['batch_message']['id_type']
555
-                : 'registration';
556
-            // id_type will affect how we assemble the ids.
557
-            $ids = ! empty($this->_req_data['batch_message']['ids'])
558
-                ? json_decode(stripslashes($this->_req_data['batch_message']['ids']))
559
-                : array();
560
-            $registrations_used_for_contact_data = array();
561
-            // using switch because eventually we'll have other contexts that will be used for generating messages.
562
-            switch ($id_type) {
563
-                case 'registration':
564
-                    $registrations_used_for_contact_data = EEM_Registration::instance()->get_all(
565
-                        array(
566
-                            array(
567
-                                'REG_ID' => array('IN', $ids),
568
-                            ),
569
-                        )
570
-                    );
571
-                    break;
572
-                case 'contact':
573
-                    $registrations_used_for_contact_data = EEM_Registration::instance()
574
-                                                                           ->get_latest_registration_for_each_of_given_contacts(
575
-                                                                               $ids
576
-                                                                           );
577
-                    break;
578
-            }
579
-            do_action_ref_array(
580
-                'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
581
-                array(
582
-                    $registrations_used_for_contact_data,
583
-                    $Message_Template_Group->ID(),
584
-                )
585
-            );
586
-            // kept for backward compat, internally we no longer use this action.
587
-            // @deprecated 4.8.36.rc.002
588
-            $contacts = $id_type === 'registration'
589
-                ? EEM_Attendee::instance()->get_array_of_contacts_from_reg_ids($ids)
590
-                : EEM_Attendee::instance()->get_all(array(array('ATT_ID' => array('in', $ids))));
591
-            do_action_ref_array(
592
-                'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send',
593
-                array(
594
-                    $contacts,
595
-                    $Message_Template_Group->ID(),
596
-                )
597
-            );
598
-        }
599
-        $query_args = array(
600
-            'action' => ! empty($this->_req_data['redirect_back_to'])
601
-                ? $this->_req_data['redirect_back_to']
602
-                : 'default',
603
-        );
604
-        $this->_redirect_after_action(false, '', '', $query_args, true);
605
-    }
476
+	/**
477
+	 * Handles sending selected registrations/contacts a newsletter.
478
+	 *
479
+	 * @since  4.3.0
480
+	 * @return void
481
+	 * @throws EE_Error
482
+	 * @throws InvalidArgumentException
483
+	 * @throws InvalidDataTypeException
484
+	 * @throws InvalidInterfaceException
485
+	 */
486
+	protected function _newsletter_selected_send()
487
+	{
488
+		$success = true;
489
+		// first we need to make sure we have a GRP_ID so we know what template we're sending and updating!
490
+		if (empty($this->_req_data['newsletter_mtp_selected'])) {
491
+			EE_Error::add_error(
492
+				esc_html__(
493
+					'In order to send a message, a Message Template GRP_ID is needed. It was not provided so messages were not sent.',
494
+					'event_espresso'
495
+				),
496
+				__FILE__,
497
+				__FUNCTION__,
498
+				__LINE__
499
+			);
500
+			$success = false;
501
+		}
502
+		if ($success) {
503
+			// update Message template in case there are any changes
504
+			$Message_Template_Group = EEM_Message_Template_Group::instance()->get_one_by_ID(
505
+				$this->_req_data['newsletter_mtp_selected']
506
+			);
507
+			$Message_Templates = $Message_Template_Group instanceof EE_Message_Template_Group
508
+				? $Message_Template_Group->context_templates()
509
+				: array();
510
+			if (empty($Message_Templates)) {
511
+				EE_Error::add_error(
512
+					esc_html__(
513
+						'Unable to retrieve message template fields from the db. Messages not sent.',
514
+						'event_espresso'
515
+					),
516
+					__FILE__,
517
+					__FUNCTION__,
518
+					__LINE__
519
+				);
520
+			}
521
+			// let's just update the specific fields
522
+			foreach ($Message_Templates['attendee'] as $Message_Template) {
523
+				if ($Message_Template instanceof EE_Message_Template) {
524
+					$field = $Message_Template->get('MTP_template_field');
525
+					$content = $Message_Template->get('MTP_content');
526
+					$new_content = $content;
527
+					switch ($field) {
528
+						case 'from':
529
+							$new_content = ! empty($this->_req_data['batch_message']['from'])
530
+								? $this->_req_data['batch_message']['from']
531
+								: $content;
532
+							break;
533
+						case 'subject':
534
+							$new_content = ! empty($this->_req_data['batch_message']['subject'])
535
+								? $this->_req_data['batch_message']['subject']
536
+								: $content;
537
+							break;
538
+						case 'content':
539
+							$new_content = $content;
540
+							$new_content['newsletter_content'] = ! empty($this->_req_data['batch_message']['content'])
541
+								? $this->_req_data['batch_message']['content']
542
+								: $content['newsletter_content'];
543
+							break;
544
+						default:
545
+							// continue the foreach loop, we don't want to set $new_content nor save.
546
+							continue 2;
547
+					}
548
+					$Message_Template->set('MTP_content', $new_content);
549
+					$Message_Template->save();
550
+				}
551
+			}
552
+			// great fields are updated!  now let's make sure we just have contact objects (EE_Attendee).
553
+			$id_type = ! empty($this->_req_data['batch_message']['id_type'])
554
+				? $this->_req_data['batch_message']['id_type']
555
+				: 'registration';
556
+			// id_type will affect how we assemble the ids.
557
+			$ids = ! empty($this->_req_data['batch_message']['ids'])
558
+				? json_decode(stripslashes($this->_req_data['batch_message']['ids']))
559
+				: array();
560
+			$registrations_used_for_contact_data = array();
561
+			// using switch because eventually we'll have other contexts that will be used for generating messages.
562
+			switch ($id_type) {
563
+				case 'registration':
564
+					$registrations_used_for_contact_data = EEM_Registration::instance()->get_all(
565
+						array(
566
+							array(
567
+								'REG_ID' => array('IN', $ids),
568
+							),
569
+						)
570
+					);
571
+					break;
572
+				case 'contact':
573
+					$registrations_used_for_contact_data = EEM_Registration::instance()
574
+																		   ->get_latest_registration_for_each_of_given_contacts(
575
+																			   $ids
576
+																		   );
577
+					break;
578
+			}
579
+			do_action_ref_array(
580
+				'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
581
+				array(
582
+					$registrations_used_for_contact_data,
583
+					$Message_Template_Group->ID(),
584
+				)
585
+			);
586
+			// kept for backward compat, internally we no longer use this action.
587
+			// @deprecated 4.8.36.rc.002
588
+			$contacts = $id_type === 'registration'
589
+				? EEM_Attendee::instance()->get_array_of_contacts_from_reg_ids($ids)
590
+				: EEM_Attendee::instance()->get_all(array(array('ATT_ID' => array('in', $ids))));
591
+			do_action_ref_array(
592
+				'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send',
593
+				array(
594
+					$contacts,
595
+					$Message_Template_Group->ID(),
596
+				)
597
+			);
598
+		}
599
+		$query_args = array(
600
+			'action' => ! empty($this->_req_data['redirect_back_to'])
601
+				? $this->_req_data['redirect_back_to']
602
+				: 'default',
603
+		);
604
+		$this->_redirect_after_action(false, '', '', $query_args, true);
605
+	}
606 606
 
607 607
 
608
-    /**
609
-     * This is called when javascript is being enqueued to setup the various data needed for the reports js.
610
-     * Also $this->{$_reports_template_data} property is set for later usage by the _registration_reports method.
611
-     */
612
-    protected function _registration_reports_js_setup()
613
-    {
614
-        $this->_reports_template_data['admin_reports'][] = $this->_registrations_per_day_report();
615
-        $this->_reports_template_data['admin_reports'][] = $this->_registrations_per_event_report();
616
-    }
608
+	/**
609
+	 * This is called when javascript is being enqueued to setup the various data needed for the reports js.
610
+	 * Also $this->{$_reports_template_data} property is set for later usage by the _registration_reports method.
611
+	 */
612
+	protected function _registration_reports_js_setup()
613
+	{
614
+		$this->_reports_template_data['admin_reports'][] = $this->_registrations_per_day_report();
615
+		$this->_reports_template_data['admin_reports'][] = $this->_registrations_per_event_report();
616
+	}
617 617
 
618 618
 
619
-    /**
620
-     *        generates Business Reports regarding Registrations
621
-     *
622
-     * @access protected
623
-     * @return void
624
-     * @throws DomainException
625
-     */
626
-    protected function _registration_reports()
627
-    {
628
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_reports.template.php';
629
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
630
-            $template_path,
631
-            $this->_reports_template_data,
632
-            true
633
-        );
634
-        // the final template wrapper
635
-        $this->display_admin_page_with_no_sidebar();
636
-    }
619
+	/**
620
+	 *        generates Business Reports regarding Registrations
621
+	 *
622
+	 * @access protected
623
+	 * @return void
624
+	 * @throws DomainException
625
+	 */
626
+	protected function _registration_reports()
627
+	{
628
+		$template_path = EE_ADMIN_TEMPLATE . 'admin_reports.template.php';
629
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
630
+			$template_path,
631
+			$this->_reports_template_data,
632
+			true
633
+		);
634
+		// the final template wrapper
635
+		$this->display_admin_page_with_no_sidebar();
636
+	}
637 637
 
638 638
 
639
-    /**
640
-     * Generates Business Report showing total registrations per day.
641
-     *
642
-     * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
643
-     * @return string
644
-     * @throws EE_Error
645
-     * @throws InvalidArgumentException
646
-     * @throws InvalidDataTypeException
647
-     * @throws InvalidInterfaceException
648
-     */
649
-    private function _registrations_per_day_report($period = '-1 month')
650
-    {
651
-        $report_ID = 'reg-admin-registrations-per-day-report-dv';
652
-        $results = EEM_Registration::instance()->get_registrations_per_day_and_per_status_report($period);
653
-        $results = (array) $results;
654
-        $regs = array();
655
-        $subtitle = '';
656
-        if ($results) {
657
-            $column_titles = array();
658
-            $tracker = 0;
659
-            foreach ($results as $result) {
660
-                $report_column_values = array();
661
-                foreach ($result as $property_name => $property_value) {
662
-                    $property_value = $property_name === 'Registration_REG_date' ? $property_value
663
-                        : (int) $property_value;
664
-                    $report_column_values[] = $property_value;
665
-                    if ($tracker === 0) {
666
-                        if ($property_name === 'Registration_REG_date') {
667
-                            $column_titles[] = esc_html__(
668
-                                'Date (only days with registrations are shown)',
669
-                                'event_espresso'
670
-                            );
671
-                        } else {
672
-                            $column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
673
-                        }
674
-                    }
675
-                }
676
-                $tracker++;
677
-                $regs[] = $report_column_values;
678
-            }
679
-            // make sure the column_titles is pushed to the beginning of the array
680
-            array_unshift($regs, $column_titles);
681
-            // setup the date range.
682
-            $DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
683
-            $beginning_date = new DateTime("now " . $period, $DateTimeZone);
684
-            $ending_date = new DateTime("now", $DateTimeZone);
685
-            $subtitle = sprintf(
686
-                _x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
687
-                $beginning_date->format('Y-m-d'),
688
-                $ending_date->format('Y-m-d')
689
-            );
690
-        }
691
-        $report_title = esc_html__('Total Registrations per Day', 'event_espresso');
692
-        $report_params = array(
693
-            'title'     => $report_title,
694
-            'subtitle'  => $subtitle,
695
-            'id'        => $report_ID,
696
-            'regs'      => $regs,
697
-            'noResults' => empty($regs),
698
-            'noRegsMsg' => sprintf(
699
-                esc_html__(
700
-                    '%sThere are currently no registration records in the last month for this report.%s',
701
-                    'event_espresso'
702
-                ),
703
-                '<h2>' . $report_title . '</h2><p>',
704
-                '</p>'
705
-            ),
706
-        );
707
-        wp_localize_script('ee-reg-reports-js', 'regPerDay', $report_params);
708
-        return $report_ID;
709
-    }
639
+	/**
640
+	 * Generates Business Report showing total registrations per day.
641
+	 *
642
+	 * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
643
+	 * @return string
644
+	 * @throws EE_Error
645
+	 * @throws InvalidArgumentException
646
+	 * @throws InvalidDataTypeException
647
+	 * @throws InvalidInterfaceException
648
+	 */
649
+	private function _registrations_per_day_report($period = '-1 month')
650
+	{
651
+		$report_ID = 'reg-admin-registrations-per-day-report-dv';
652
+		$results = EEM_Registration::instance()->get_registrations_per_day_and_per_status_report($period);
653
+		$results = (array) $results;
654
+		$regs = array();
655
+		$subtitle = '';
656
+		if ($results) {
657
+			$column_titles = array();
658
+			$tracker = 0;
659
+			foreach ($results as $result) {
660
+				$report_column_values = array();
661
+				foreach ($result as $property_name => $property_value) {
662
+					$property_value = $property_name === 'Registration_REG_date' ? $property_value
663
+						: (int) $property_value;
664
+					$report_column_values[] = $property_value;
665
+					if ($tracker === 0) {
666
+						if ($property_name === 'Registration_REG_date') {
667
+							$column_titles[] = esc_html__(
668
+								'Date (only days with registrations are shown)',
669
+								'event_espresso'
670
+							);
671
+						} else {
672
+							$column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
673
+						}
674
+					}
675
+				}
676
+				$tracker++;
677
+				$regs[] = $report_column_values;
678
+			}
679
+			// make sure the column_titles is pushed to the beginning of the array
680
+			array_unshift($regs, $column_titles);
681
+			// setup the date range.
682
+			$DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
683
+			$beginning_date = new DateTime("now " . $period, $DateTimeZone);
684
+			$ending_date = new DateTime("now", $DateTimeZone);
685
+			$subtitle = sprintf(
686
+				_x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
687
+				$beginning_date->format('Y-m-d'),
688
+				$ending_date->format('Y-m-d')
689
+			);
690
+		}
691
+		$report_title = esc_html__('Total Registrations per Day', 'event_espresso');
692
+		$report_params = array(
693
+			'title'     => $report_title,
694
+			'subtitle'  => $subtitle,
695
+			'id'        => $report_ID,
696
+			'regs'      => $regs,
697
+			'noResults' => empty($regs),
698
+			'noRegsMsg' => sprintf(
699
+				esc_html__(
700
+					'%sThere are currently no registration records in the last month for this report.%s',
701
+					'event_espresso'
702
+				),
703
+				'<h2>' . $report_title . '</h2><p>',
704
+				'</p>'
705
+			),
706
+		);
707
+		wp_localize_script('ee-reg-reports-js', 'regPerDay', $report_params);
708
+		return $report_ID;
709
+	}
710 710
 
711 711
 
712
-    /**
713
-     * Generates Business Report showing total registrations per event.
714
-     *
715
-     * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
716
-     * @return string
717
-     * @throws EE_Error
718
-     * @throws InvalidArgumentException
719
-     * @throws InvalidDataTypeException
720
-     * @throws InvalidInterfaceException
721
-     */
722
-    private function _registrations_per_event_report($period = '-1 month')
723
-    {
724
-        $report_ID = 'reg-admin-registrations-per-event-report-dv';
725
-        $results = EEM_Registration::instance()->get_registrations_per_event_and_per_status_report($period);
726
-        $results = (array) $results;
727
-        $regs = array();
728
-        $subtitle = '';
729
-        if ($results) {
730
-            $column_titles = array();
731
-            $tracker = 0;
732
-            foreach ($results as $result) {
733
-                $report_column_values = array();
734
-                foreach ($result as $property_name => $property_value) {
735
-                    $property_value = $property_name === 'Registration_Event' ? wp_trim_words(
736
-                        $property_value,
737
-                        4,
738
-                        '...'
739
-                    ) : (int) $property_value;
740
-                    $report_column_values[] = $property_value;
741
-                    if ($tracker === 0) {
742
-                        if ($property_name === 'Registration_Event') {
743
-                            $column_titles[] = esc_html__('Event', 'event_espresso');
744
-                        } else {
745
-                            $column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
746
-                        }
747
-                    }
748
-                }
749
-                $tracker++;
750
-                $regs[] = $report_column_values;
751
-            }
752
-            // make sure the column_titles is pushed to the beginning of the array
753
-            array_unshift($regs, $column_titles);
754
-            // setup the date range.
755
-            $DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
756
-            $beginning_date = new DateTime("now " . $period, $DateTimeZone);
757
-            $ending_date = new DateTime("now", $DateTimeZone);
758
-            $subtitle = sprintf(
759
-                _x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
760
-                $beginning_date->format('Y-m-d'),
761
-                $ending_date->format('Y-m-d')
762
-            );
763
-        }
764
-        $report_title = esc_html__('Total Registrations per Event', 'event_espresso');
765
-        $report_params = array(
766
-            'title'     => $report_title,
767
-            'subtitle'  => $subtitle,
768
-            'id'        => $report_ID,
769
-            'regs'      => $regs,
770
-            'noResults' => empty($regs),
771
-            'noRegsMsg' => sprintf(
772
-                esc_html__(
773
-                    '%sThere are currently no registration records in the last month for this report.%s',
774
-                    'event_espresso'
775
-                ),
776
-                '<h2>' . $report_title . '</h2><p>',
777
-                '</p>'
778
-            ),
779
-        );
780
-        wp_localize_script('ee-reg-reports-js', 'regPerEvent', $report_params);
781
-        return $report_ID;
782
-    }
712
+	/**
713
+	 * Generates Business Report showing total registrations per event.
714
+	 *
715
+	 * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
716
+	 * @return string
717
+	 * @throws EE_Error
718
+	 * @throws InvalidArgumentException
719
+	 * @throws InvalidDataTypeException
720
+	 * @throws InvalidInterfaceException
721
+	 */
722
+	private function _registrations_per_event_report($period = '-1 month')
723
+	{
724
+		$report_ID = 'reg-admin-registrations-per-event-report-dv';
725
+		$results = EEM_Registration::instance()->get_registrations_per_event_and_per_status_report($period);
726
+		$results = (array) $results;
727
+		$regs = array();
728
+		$subtitle = '';
729
+		if ($results) {
730
+			$column_titles = array();
731
+			$tracker = 0;
732
+			foreach ($results as $result) {
733
+				$report_column_values = array();
734
+				foreach ($result as $property_name => $property_value) {
735
+					$property_value = $property_name === 'Registration_Event' ? wp_trim_words(
736
+						$property_value,
737
+						4,
738
+						'...'
739
+					) : (int) $property_value;
740
+					$report_column_values[] = $property_value;
741
+					if ($tracker === 0) {
742
+						if ($property_name === 'Registration_Event') {
743
+							$column_titles[] = esc_html__('Event', 'event_espresso');
744
+						} else {
745
+							$column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
746
+						}
747
+					}
748
+				}
749
+				$tracker++;
750
+				$regs[] = $report_column_values;
751
+			}
752
+			// make sure the column_titles is pushed to the beginning of the array
753
+			array_unshift($regs, $column_titles);
754
+			// setup the date range.
755
+			$DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
756
+			$beginning_date = new DateTime("now " . $period, $DateTimeZone);
757
+			$ending_date = new DateTime("now", $DateTimeZone);
758
+			$subtitle = sprintf(
759
+				_x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
760
+				$beginning_date->format('Y-m-d'),
761
+				$ending_date->format('Y-m-d')
762
+			);
763
+		}
764
+		$report_title = esc_html__('Total Registrations per Event', 'event_espresso');
765
+		$report_params = array(
766
+			'title'     => $report_title,
767
+			'subtitle'  => $subtitle,
768
+			'id'        => $report_ID,
769
+			'regs'      => $regs,
770
+			'noResults' => empty($regs),
771
+			'noRegsMsg' => sprintf(
772
+				esc_html__(
773
+					'%sThere are currently no registration records in the last month for this report.%s',
774
+					'event_espresso'
775
+				),
776
+				'<h2>' . $report_title . '</h2><p>',
777
+				'</p>'
778
+			),
779
+		);
780
+		wp_localize_script('ee-reg-reports-js', 'regPerEvent', $report_params);
781
+		return $report_ID;
782
+	}
783 783
 
784 784
 
785
-    /**
786
-     * generates HTML for the Registration Check-in list table (showing all Check-ins for a specific registration)
787
-     *
788
-     * @access protected
789
-     * @return void
790
-     * @throws EE_Error
791
-     * @throws InvalidArgumentException
792
-     * @throws InvalidDataTypeException
793
-     * @throws InvalidInterfaceException
794
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
795
-     */
796
-    protected function _registration_checkin_list_table()
797
-    {
798
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
799
-        $reg_id = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : null;
800
-        /** @var EE_Registration $registration */
801
-        $registration = EEM_Registration::instance()->get_one_by_ID($reg_id);
802
-        if (! $registration instanceof EE_Registration) {
803
-            throw new EE_Error(
804
-                sprintf(
805
-                    esc_html__('An error occurred. There is no registration with ID (%d)', 'event_espresso'),
806
-                    $reg_id
807
-                )
808
-            );
809
-        }
810
-        $attendee = $registration->attendee();
811
-        $this->_admin_page_title .= $this->get_action_link_or_button(
812
-            'new_registration',
813
-            'add-registrant',
814
-            array('event_id' => $registration->event_ID()),
815
-            'add-new-h2'
816
-        );
817
-        $checked_in = new CheckinStatusDashicon(EE_Checkin::status_checked_in);
818
-        $checked_out = new CheckinStatusDashicon(EE_Checkin::status_checked_out);
819
-        $legend_items = array(
820
-            'checkin'  => array(
821
-                'class' => $checked_in->cssClasses(),
822
-                'desc'  => $checked_in->legendLabel(),
823
-            ),
824
-            'checkout' => array(
825
-                'class' => $checked_out->cssClasses(),
826
-                'desc'  => $checked_out->legendLabel(),
827
-            ),
828
-        );
829
-        $this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
830
-        $dtt_id = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
831
-        /** @var EE_Datetime $datetime */
832
-        $datetime = EEM_Datetime::instance()->get_one_by_ID($dtt_id);
833
-        $datetime_label = '';
834
-        if ($datetime instanceof EE_Datetime) {
835
-            $datetime_label = $datetime->get_dtt_display_name(true);
836
-            $datetime_label .= ! empty($datetime_label)
837
-                ? ' (' . $datetime->get_dtt_display_name() . ')'
838
-                : $datetime->get_dtt_display_name();
839
-        }
840
-        $datetime_link = ! empty($dtt_id) && $registration instanceof EE_Registration
841
-            ? EE_Admin_Page::add_query_args_and_nonce(
842
-                array(
843
-                    'action'   => 'event_registrations',
844
-                    'event_id' => $registration->event_ID(),
845
-                    'DTT_ID'   => $dtt_id,
846
-                ),
847
-                $this->_admin_base_url
848
-            )
849
-            : '';
850
-        $datetime_link = ! empty($datetime_link)
851
-            ? '<a href="' . $datetime_link . '">'
852
-              . '<span id="checkin-dtt">'
853
-              . $datetime_label
854
-              . '</span></a>'
855
-            : $datetime_label;
856
-        $attendee_name = $attendee instanceof EE_Attendee
857
-            ? $attendee->full_name()
858
-            : '';
859
-        $attendee_link = $attendee instanceof EE_Attendee
860
-            ? $attendee->get_admin_details_link()
861
-            : '';
862
-        $attendee_link = ! empty($attendee_link)
863
-            ? '<a href="' . $attendee->get_admin_details_link() . '"'
864
-              . ' title="' . esc_html__('Click for attendee details', 'event_espresso') . '">'
865
-              . '<span id="checkin-attendee-name">'
866
-              . $attendee_name
867
-              . '</span></a>'
868
-            : '';
869
-        $event_link = $registration->event() instanceof EE_Event
870
-            ? $registration->event()->get_admin_details_link()
871
-            : '';
872
-        $event_link = ! empty($event_link)
873
-            ? '<a href="' . $event_link . '"'
874
-              . ' title="' . esc_html__('Click here to edit event.', 'event_espresso') . '">'
875
-              . '<span id="checkin-event-name">'
876
-              . $registration->event_name()
877
-              . '</span>'
878
-              . '</a>'
879
-            : '';
880
-        $this->_template_args['before_list_table'] = ! empty($reg_id) && ! empty($dtt_id)
881
-            ? '<h2>' . sprintf(
882
-                esc_html__('Displaying check in records for %1$s for %2$s at the event, %3$s', 'event_espresso'),
883
-                $attendee_link,
884
-                $datetime_link,
885
-                $event_link
886
-            ) . '</h2>'
887
-            : '';
888
-        $this->_template_args['list_table_hidden_fields'] = ! empty($reg_id)
889
-            ? '<input type="hidden" name="_REG_ID" value="' . $reg_id . '">' : '';
890
-        $this->_template_args['list_table_hidden_fields'] .= ! empty($dtt_id)
891
-            ? '<input type="hidden" name="DTT_ID" value="' . $dtt_id . '">' : '';
892
-        $this->display_admin_list_table_page_with_no_sidebar();
893
-    }
785
+	/**
786
+	 * generates HTML for the Registration Check-in list table (showing all Check-ins for a specific registration)
787
+	 *
788
+	 * @access protected
789
+	 * @return void
790
+	 * @throws EE_Error
791
+	 * @throws InvalidArgumentException
792
+	 * @throws InvalidDataTypeException
793
+	 * @throws InvalidInterfaceException
794
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
795
+	 */
796
+	protected function _registration_checkin_list_table()
797
+	{
798
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
799
+		$reg_id = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : null;
800
+		/** @var EE_Registration $registration */
801
+		$registration = EEM_Registration::instance()->get_one_by_ID($reg_id);
802
+		if (! $registration instanceof EE_Registration) {
803
+			throw new EE_Error(
804
+				sprintf(
805
+					esc_html__('An error occurred. There is no registration with ID (%d)', 'event_espresso'),
806
+					$reg_id
807
+				)
808
+			);
809
+		}
810
+		$attendee = $registration->attendee();
811
+		$this->_admin_page_title .= $this->get_action_link_or_button(
812
+			'new_registration',
813
+			'add-registrant',
814
+			array('event_id' => $registration->event_ID()),
815
+			'add-new-h2'
816
+		);
817
+		$checked_in = new CheckinStatusDashicon(EE_Checkin::status_checked_in);
818
+		$checked_out = new CheckinStatusDashicon(EE_Checkin::status_checked_out);
819
+		$legend_items = array(
820
+			'checkin'  => array(
821
+				'class' => $checked_in->cssClasses(),
822
+				'desc'  => $checked_in->legendLabel(),
823
+			),
824
+			'checkout' => array(
825
+				'class' => $checked_out->cssClasses(),
826
+				'desc'  => $checked_out->legendLabel(),
827
+			),
828
+		);
829
+		$this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
830
+		$dtt_id = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
831
+		/** @var EE_Datetime $datetime */
832
+		$datetime = EEM_Datetime::instance()->get_one_by_ID($dtt_id);
833
+		$datetime_label = '';
834
+		if ($datetime instanceof EE_Datetime) {
835
+			$datetime_label = $datetime->get_dtt_display_name(true);
836
+			$datetime_label .= ! empty($datetime_label)
837
+				? ' (' . $datetime->get_dtt_display_name() . ')'
838
+				: $datetime->get_dtt_display_name();
839
+		}
840
+		$datetime_link = ! empty($dtt_id) && $registration instanceof EE_Registration
841
+			? EE_Admin_Page::add_query_args_and_nonce(
842
+				array(
843
+					'action'   => 'event_registrations',
844
+					'event_id' => $registration->event_ID(),
845
+					'DTT_ID'   => $dtt_id,
846
+				),
847
+				$this->_admin_base_url
848
+			)
849
+			: '';
850
+		$datetime_link = ! empty($datetime_link)
851
+			? '<a href="' . $datetime_link . '">'
852
+			  . '<span id="checkin-dtt">'
853
+			  . $datetime_label
854
+			  . '</span></a>'
855
+			: $datetime_label;
856
+		$attendee_name = $attendee instanceof EE_Attendee
857
+			? $attendee->full_name()
858
+			: '';
859
+		$attendee_link = $attendee instanceof EE_Attendee
860
+			? $attendee->get_admin_details_link()
861
+			: '';
862
+		$attendee_link = ! empty($attendee_link)
863
+			? '<a href="' . $attendee->get_admin_details_link() . '"'
864
+			  . ' title="' . esc_html__('Click for attendee details', 'event_espresso') . '">'
865
+			  . '<span id="checkin-attendee-name">'
866
+			  . $attendee_name
867
+			  . '</span></a>'
868
+			: '';
869
+		$event_link = $registration->event() instanceof EE_Event
870
+			? $registration->event()->get_admin_details_link()
871
+			: '';
872
+		$event_link = ! empty($event_link)
873
+			? '<a href="' . $event_link . '"'
874
+			  . ' title="' . esc_html__('Click here to edit event.', 'event_espresso') . '">'
875
+			  . '<span id="checkin-event-name">'
876
+			  . $registration->event_name()
877
+			  . '</span>'
878
+			  . '</a>'
879
+			: '';
880
+		$this->_template_args['before_list_table'] = ! empty($reg_id) && ! empty($dtt_id)
881
+			? '<h2>' . sprintf(
882
+				esc_html__('Displaying check in records for %1$s for %2$s at the event, %3$s', 'event_espresso'),
883
+				$attendee_link,
884
+				$datetime_link,
885
+				$event_link
886
+			) . '</h2>'
887
+			: '';
888
+		$this->_template_args['list_table_hidden_fields'] = ! empty($reg_id)
889
+			? '<input type="hidden" name="_REG_ID" value="' . $reg_id . '">' : '';
890
+		$this->_template_args['list_table_hidden_fields'] .= ! empty($dtt_id)
891
+			? '<input type="hidden" name="DTT_ID" value="' . $dtt_id . '">' : '';
892
+		$this->display_admin_list_table_page_with_no_sidebar();
893
+	}
894 894
 
895 895
 
896
-    /**
897
-     * toggle the Check-in status for the given registration (coming from ajax)
898
-     *
899
-     * @return void (JSON)
900
-     * @throws EE_Error
901
-     * @throws InvalidArgumentException
902
-     * @throws InvalidDataTypeException
903
-     * @throws InvalidInterfaceException
904
-     */
905
-    public function toggle_checkin_status()
906
-    {
907
-        // first make sure we have the necessary data
908
-        if (! isset($this->_req_data['_regid'])) {
909
-            EE_Error::add_error(
910
-                esc_html__(
911
-                    'There must be something broken with the html structure because the required data for toggling the Check-in status is not being sent via ajax',
912
-                    'event_espresso'
913
-                ),
914
-                __FILE__,
915
-                __FUNCTION__,
916
-                __LINE__
917
-            );
918
-            $this->_template_args['success'] = false;
919
-            $this->_template_args['error'] = true;
920
-            $this->_return_json();
921
-        };
922
-        // do a nonce check cause we're not coming in from an normal route here.
923
-        $nonce = isset($this->_req_data['checkinnonce']) ? sanitize_text_field($this->_req_data['checkinnonce'])
924
-            : '';
925
-        $nonce_ref = 'checkin_nonce';
926
-        $this->_verify_nonce($nonce, $nonce_ref);
927
-        // beautiful! Made it this far so let's get the status.
928
-        $new_status = new CheckinStatusDashicon($this->_toggle_checkin_status());
929
-        // setup new class to return via ajax
930
-        $this->_template_args['admin_page_content'] = 'clickable trigger-checkin ' . $new_status->cssClasses();
931
-        $this->_template_args['success'] = true;
932
-        $this->_return_json();
933
-    }
896
+	/**
897
+	 * toggle the Check-in status for the given registration (coming from ajax)
898
+	 *
899
+	 * @return void (JSON)
900
+	 * @throws EE_Error
901
+	 * @throws InvalidArgumentException
902
+	 * @throws InvalidDataTypeException
903
+	 * @throws InvalidInterfaceException
904
+	 */
905
+	public function toggle_checkin_status()
906
+	{
907
+		// first make sure we have the necessary data
908
+		if (! isset($this->_req_data['_regid'])) {
909
+			EE_Error::add_error(
910
+				esc_html__(
911
+					'There must be something broken with the html structure because the required data for toggling the Check-in status is not being sent via ajax',
912
+					'event_espresso'
913
+				),
914
+				__FILE__,
915
+				__FUNCTION__,
916
+				__LINE__
917
+			);
918
+			$this->_template_args['success'] = false;
919
+			$this->_template_args['error'] = true;
920
+			$this->_return_json();
921
+		};
922
+		// do a nonce check cause we're not coming in from an normal route here.
923
+		$nonce = isset($this->_req_data['checkinnonce']) ? sanitize_text_field($this->_req_data['checkinnonce'])
924
+			: '';
925
+		$nonce_ref = 'checkin_nonce';
926
+		$this->_verify_nonce($nonce, $nonce_ref);
927
+		// beautiful! Made it this far so let's get the status.
928
+		$new_status = new CheckinStatusDashicon($this->_toggle_checkin_status());
929
+		// setup new class to return via ajax
930
+		$this->_template_args['admin_page_content'] = 'clickable trigger-checkin ' . $new_status->cssClasses();
931
+		$this->_template_args['success'] = true;
932
+		$this->_return_json();
933
+	}
934 934
 
935 935
 
936
-    /**
937
-     * handles toggling the checkin status for the registration,
938
-     *
939
-     * @access protected
940
-     * @return int|void
941
-     * @throws EE_Error
942
-     * @throws InvalidArgumentException
943
-     * @throws InvalidDataTypeException
944
-     * @throws InvalidInterfaceException
945
-     */
946
-    protected function _toggle_checkin_status()
947
-    {
948
-        // first let's get the query args out of the way for the redirect
949
-        $query_args = array(
950
-            'action'   => 'event_registrations',
951
-            'event_id' => isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null,
952
-            'DTT_ID'   => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null,
953
-        );
954
-        $new_status = false;
955
-        // bulk action check in toggle
956
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
957
-            // cycle thru checkboxes
958
-            while (list($REG_ID, $value) = each($this->_req_data['checkbox'])) {
959
-                $DTT_ID = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
960
-                $new_status = $this->_toggle_checkin($REG_ID, $DTT_ID);
961
-            }
962
-        } elseif (isset($this->_req_data['_regid'])) {
963
-            // coming from ajax request
964
-            $DTT_ID = isset($this->_req_data['dttid']) ? $this->_req_data['dttid'] : null;
965
-            $query_args['DTT_ID'] = $DTT_ID;
966
-            $new_status = $this->_toggle_checkin($this->_req_data['_regid'], $DTT_ID);
967
-        } else {
968
-            EE_Error::add_error(
969
-                esc_html__('Missing some required data to toggle the Check-in', 'event_espresso'),
970
-                __FILE__,
971
-                __FUNCTION__,
972
-                __LINE__
973
-            );
974
-        }
975
-        if (defined('DOING_AJAX')) {
976
-            return $new_status;
977
-        }
978
-        $this->_redirect_after_action(false, '', '', $query_args, true);
979
-    }
936
+	/**
937
+	 * handles toggling the checkin status for the registration,
938
+	 *
939
+	 * @access protected
940
+	 * @return int|void
941
+	 * @throws EE_Error
942
+	 * @throws InvalidArgumentException
943
+	 * @throws InvalidDataTypeException
944
+	 * @throws InvalidInterfaceException
945
+	 */
946
+	protected function _toggle_checkin_status()
947
+	{
948
+		// first let's get the query args out of the way for the redirect
949
+		$query_args = array(
950
+			'action'   => 'event_registrations',
951
+			'event_id' => isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null,
952
+			'DTT_ID'   => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null,
953
+		);
954
+		$new_status = false;
955
+		// bulk action check in toggle
956
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
957
+			// cycle thru checkboxes
958
+			while (list($REG_ID, $value) = each($this->_req_data['checkbox'])) {
959
+				$DTT_ID = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
960
+				$new_status = $this->_toggle_checkin($REG_ID, $DTT_ID);
961
+			}
962
+		} elseif (isset($this->_req_data['_regid'])) {
963
+			// coming from ajax request
964
+			$DTT_ID = isset($this->_req_data['dttid']) ? $this->_req_data['dttid'] : null;
965
+			$query_args['DTT_ID'] = $DTT_ID;
966
+			$new_status = $this->_toggle_checkin($this->_req_data['_regid'], $DTT_ID);
967
+		} else {
968
+			EE_Error::add_error(
969
+				esc_html__('Missing some required data to toggle the Check-in', 'event_espresso'),
970
+				__FILE__,
971
+				__FUNCTION__,
972
+				__LINE__
973
+			);
974
+		}
975
+		if (defined('DOING_AJAX')) {
976
+			return $new_status;
977
+		}
978
+		$this->_redirect_after_action(false, '', '', $query_args, true);
979
+	}
980 980
 
981 981
 
982
-    /**
983
-     * This is toggles a single Check-in for the given registration and datetime.
984
-     *
985
-     * @param  int $REG_ID The registration we're toggling
986
-     * @param  int $DTT_ID The datetime we're toggling
987
-     * @return int The new status toggled to.
988
-     * @throws EE_Error
989
-     * @throws InvalidArgumentException
990
-     * @throws InvalidDataTypeException
991
-     * @throws InvalidInterfaceException
992
-     */
993
-    private function _toggle_checkin($REG_ID, $DTT_ID)
994
-    {
995
-        /** @var EE_Registration $REG */
996
-        $REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
997
-        $new_status = $REG->toggle_checkin_status($DTT_ID);
998
-        if ($new_status !== false) {
999
-            EE_Error::add_success($REG->get_checkin_msg($DTT_ID));
1000
-        } else {
1001
-            EE_Error::add_error($REG->get_checkin_msg($DTT_ID, true), __FILE__, __FUNCTION__, __LINE__);
1002
-            $new_status = false;
1003
-        }
1004
-        return $new_status;
1005
-    }
982
+	/**
983
+	 * This is toggles a single Check-in for the given registration and datetime.
984
+	 *
985
+	 * @param  int $REG_ID The registration we're toggling
986
+	 * @param  int $DTT_ID The datetime we're toggling
987
+	 * @return int The new status toggled to.
988
+	 * @throws EE_Error
989
+	 * @throws InvalidArgumentException
990
+	 * @throws InvalidDataTypeException
991
+	 * @throws InvalidInterfaceException
992
+	 */
993
+	private function _toggle_checkin($REG_ID, $DTT_ID)
994
+	{
995
+		/** @var EE_Registration $REG */
996
+		$REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
997
+		$new_status = $REG->toggle_checkin_status($DTT_ID);
998
+		if ($new_status !== false) {
999
+			EE_Error::add_success($REG->get_checkin_msg($DTT_ID));
1000
+		} else {
1001
+			EE_Error::add_error($REG->get_checkin_msg($DTT_ID, true), __FILE__, __FUNCTION__, __LINE__);
1002
+			$new_status = false;
1003
+		}
1004
+		return $new_status;
1005
+	}
1006 1006
 
1007 1007
 
1008
-    /**
1009
-     * Takes care of deleting multiple EE_Checkin table rows
1010
-     *
1011
-     * @access protected
1012
-     * @return void
1013
-     * @throws EE_Error
1014
-     * @throws InvalidArgumentException
1015
-     * @throws InvalidDataTypeException
1016
-     * @throws InvalidInterfaceException
1017
-     */
1018
-    protected function _delete_checkin_rows()
1019
-    {
1020
-        $query_args = array(
1021
-            'action'  => 'registration_checkins',
1022
-            'DTT_ID'  => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
1023
-            '_REG_ID' => isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : 0,
1024
-        );
1025
-        $errors = 0;
1026
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1027
-            while (list($CHK_ID, $value) = each($this->_req_data['checkbox'])) {
1028
-                if (! EEM_Checkin::instance()->delete_by_ID($CHK_ID)) {
1029
-                    $errors++;
1030
-                }
1031
-            }
1032
-        } else {
1033
-            EE_Error::add_error(
1034
-                esc_html__(
1035
-                    'So, something went wrong with the bulk delete because there was no data received for instructions on WHAT to delete!',
1036
-                    'event_espresso'
1037
-                ),
1038
-                __FILE__,
1039
-                __FUNCTION__,
1040
-                __LINE__
1041
-            );
1042
-            $this->_redirect_after_action(false, '', '', $query_args, true);
1043
-        }
1044
-        if ($errors > 0) {
1045
-            EE_Error::add_error(
1046
-                sprintf(__('There were %d records that did not delete successfully', 'event_espresso'), $errors),
1047
-                __FILE__,
1048
-                __FUNCTION__,
1049
-                __LINE__
1050
-            );
1051
-        } else {
1052
-            EE_Error::add_success(__('Records were successfully deleted', 'event_espresso'));
1053
-        }
1054
-        $this->_redirect_after_action(false, '', '', $query_args, true);
1055
-    }
1008
+	/**
1009
+	 * Takes care of deleting multiple EE_Checkin table rows
1010
+	 *
1011
+	 * @access protected
1012
+	 * @return void
1013
+	 * @throws EE_Error
1014
+	 * @throws InvalidArgumentException
1015
+	 * @throws InvalidDataTypeException
1016
+	 * @throws InvalidInterfaceException
1017
+	 */
1018
+	protected function _delete_checkin_rows()
1019
+	{
1020
+		$query_args = array(
1021
+			'action'  => 'registration_checkins',
1022
+			'DTT_ID'  => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
1023
+			'_REG_ID' => isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : 0,
1024
+		);
1025
+		$errors = 0;
1026
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1027
+			while (list($CHK_ID, $value) = each($this->_req_data['checkbox'])) {
1028
+				if (! EEM_Checkin::instance()->delete_by_ID($CHK_ID)) {
1029
+					$errors++;
1030
+				}
1031
+			}
1032
+		} else {
1033
+			EE_Error::add_error(
1034
+				esc_html__(
1035
+					'So, something went wrong with the bulk delete because there was no data received for instructions on WHAT to delete!',
1036
+					'event_espresso'
1037
+				),
1038
+				__FILE__,
1039
+				__FUNCTION__,
1040
+				__LINE__
1041
+			);
1042
+			$this->_redirect_after_action(false, '', '', $query_args, true);
1043
+		}
1044
+		if ($errors > 0) {
1045
+			EE_Error::add_error(
1046
+				sprintf(__('There were %d records that did not delete successfully', 'event_espresso'), $errors),
1047
+				__FILE__,
1048
+				__FUNCTION__,
1049
+				__LINE__
1050
+			);
1051
+		} else {
1052
+			EE_Error::add_success(__('Records were successfully deleted', 'event_espresso'));
1053
+		}
1054
+		$this->_redirect_after_action(false, '', '', $query_args, true);
1055
+	}
1056 1056
 
1057 1057
 
1058
-    /**
1059
-     * Deletes a single EE_Checkin row
1060
-     *
1061
-     * @return void
1062
-     * @throws EE_Error
1063
-     * @throws InvalidArgumentException
1064
-     * @throws InvalidDataTypeException
1065
-     * @throws InvalidInterfaceException
1066
-     */
1067
-    protected function _delete_checkin_row()
1068
-    {
1069
-        $query_args = array(
1070
-            'action'  => 'registration_checkins',
1071
-            'DTT_ID'  => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
1072
-            '_REG_ID' => isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : 0,
1073
-        );
1074
-        if (! empty($this->_req_data['CHK_ID'])) {
1075
-            if (! EEM_Checkin::instance()->delete_by_ID($this->_req_data['CHK_ID'])) {
1076
-                EE_Error::add_error(
1077
-                    esc_html__('Something went wrong and this check-in record was not deleted', 'event_espresso'),
1078
-                    __FILE__,
1079
-                    __FUNCTION__,
1080
-                    __LINE__
1081
-                );
1082
-            } else {
1083
-                EE_Error::add_success(__('Check-In record successfully deleted', 'event_espresso'));
1084
-            }
1085
-        } else {
1086
-            EE_Error::add_error(
1087
-                esc_html__(
1088
-                    'In order to delete a Check-in record, there must be a Check-In ID available. There is not. It is not your fault, there is just a gremlin living in the code',
1089
-                    'event_espresso'
1090
-                ),
1091
-                __FILE__,
1092
-                __FUNCTION__,
1093
-                __LINE__
1094
-            );
1095
-        }
1096
-        $this->_redirect_after_action(false, '', '', $query_args, true);
1097
-    }
1058
+	/**
1059
+	 * Deletes a single EE_Checkin row
1060
+	 *
1061
+	 * @return void
1062
+	 * @throws EE_Error
1063
+	 * @throws InvalidArgumentException
1064
+	 * @throws InvalidDataTypeException
1065
+	 * @throws InvalidInterfaceException
1066
+	 */
1067
+	protected function _delete_checkin_row()
1068
+	{
1069
+		$query_args = array(
1070
+			'action'  => 'registration_checkins',
1071
+			'DTT_ID'  => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
1072
+			'_REG_ID' => isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : 0,
1073
+		);
1074
+		if (! empty($this->_req_data['CHK_ID'])) {
1075
+			if (! EEM_Checkin::instance()->delete_by_ID($this->_req_data['CHK_ID'])) {
1076
+				EE_Error::add_error(
1077
+					esc_html__('Something went wrong and this check-in record was not deleted', 'event_espresso'),
1078
+					__FILE__,
1079
+					__FUNCTION__,
1080
+					__LINE__
1081
+				);
1082
+			} else {
1083
+				EE_Error::add_success(__('Check-In record successfully deleted', 'event_espresso'));
1084
+			}
1085
+		} else {
1086
+			EE_Error::add_error(
1087
+				esc_html__(
1088
+					'In order to delete a Check-in record, there must be a Check-In ID available. There is not. It is not your fault, there is just a gremlin living in the code',
1089
+					'event_espresso'
1090
+				),
1091
+				__FILE__,
1092
+				__FUNCTION__,
1093
+				__LINE__
1094
+			);
1095
+		}
1096
+		$this->_redirect_after_action(false, '', '', $query_args, true);
1097
+	}
1098 1098
 
1099 1099
 
1100
-    /**
1101
-     *        generates HTML for the Event Registrations List Table
1102
-     *
1103
-     * @access protected
1104
-     * @return void
1105
-     * @throws EE_Error
1106
-     * @throws InvalidArgumentException
1107
-     * @throws InvalidDataTypeException
1108
-     * @throws InvalidInterfaceException
1109
-     */
1110
-    protected function _event_registrations_list_table()
1111
-    {
1112
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1113
-        $this->_admin_page_title .= isset($this->_req_data['event_id'])
1114
-            ? $this->get_action_link_or_button(
1115
-                'new_registration',
1116
-                'add-registrant',
1117
-                array('event_id' => $this->_req_data['event_id']),
1118
-                'add-new-h2',
1119
-                '',
1120
-                false
1121
-            )
1122
-            : '';
1123
-        $checked_in = new CheckinStatusDashicon(EE_Checkin::status_checked_in);
1124
-        $checked_out = new CheckinStatusDashicon(EE_Checkin::status_checked_out);
1125
-        $checked_never = new CheckinStatusDashicon(EE_Checkin::status_checked_never);
1126
-        $legend_items = array(
1127
-            'star-icon'        => array(
1128
-                'class' => 'dashicons dashicons-star-filled yellow-icon ee-icon-size-8',
1129
-                'desc'  => esc_html__('This Registrant is the Primary Registrant', 'event_espresso'),
1130
-            ),
1131
-            'checkin'          => array(
1132
-                'class' => $checked_in->cssClasses(),
1133
-                'desc'  => $checked_in->legendLabel(),
1134
-            ),
1135
-            'checkout'         => array(
1136
-                'class' => $checked_out->cssClasses(),
1137
-                'desc'  => $checked_out->legendLabel(),
1138
-            ),
1139
-            'nocheckinrecord'  => array(
1140
-                'class' => $checked_never->cssClasses(),
1141
-                'desc'  => $checked_never->legendLabel(),
1142
-            ),
1143
-            'approved_status'  => array(
1144
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
1145
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
1146
-            ),
1147
-            'cancelled_status' => array(
1148
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1149
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
1150
-            ),
1151
-            'declined_status'  => array(
1152
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
1153
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
1154
-            ),
1155
-            'not_approved'     => array(
1156
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
1157
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
1158
-            ),
1159
-            'pending_status'   => array(
1160
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
1161
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
1162
-            ),
1163
-            'wait_list'        => array(
1164
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
1165
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
1166
-            ),
1167
-        );
1168
-        $this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
1169
-        $event_id = isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null;
1170
-        /** @var EE_Event $event */
1171
-        $event = EEM_Event::instance()->get_one_by_ID($event_id);
1172
-        $this->_template_args['before_list_table'] = $event instanceof EE_Event
1173
-            ? '<h2>' . sprintf(
1174
-                esc_html__('Viewing Registrations for Event: %s', 'event_espresso'),
1175
-                EEM_Event::instance()->get_one_by_ID($event_id)->get('EVT_name')
1176
-            ) . '</h2>'
1177
-            : '';
1178
-        // need to get the number of datetimes on the event and set default datetime_id if there is only one datetime on
1179
-        // the event.
1180
-        $DTT_ID = ! empty($this->_req_data['DTT_ID']) ? absint($this->_req_data['DTT_ID']) : 0;
1181
-        $datetime = null;
1182
-        if ($event instanceof EE_Event) {
1183
-            $datetimes_on_event = $event->datetimes();
1184
-            if (count($datetimes_on_event) === 1) {
1185
-                $datetime = reset($datetimes_on_event);
1186
-            }
1187
-        }
1188
-        $datetime = $datetime instanceof EE_Datetime ? $datetime : EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1189
-        if ($datetime instanceof EE_Datetime && $this->_template_args['before_list_table'] !== '') {
1190
-            $this->_template_args['before_list_table'] = substr($this->_template_args['before_list_table'], 0, -5);
1191
-            $this->_template_args['before_list_table'] .= ' &nbsp;<span class="drk-grey-text">';
1192
-            $this->_template_args['before_list_table'] .= '<span class="dashicons dashicons-calendar"></span>';
1193
-            $this->_template_args['before_list_table'] .= $datetime->name();
1194
-            $this->_template_args['before_list_table'] .= ' ( ' . $datetime->date_and_time_range() . ' )';
1195
-            $this->_template_args['before_list_table'] .= '</span></h2>';
1196
-        }
1197
-        // if no datetime, then we're on the initial view, so let's give some helpful instructions on what the status
1198
-        // column represents
1199
-        if (! $datetime instanceof EE_Datetime) {
1200
-            $this->_template_args['before_list_table'] .= '<br><p class="description">'
1201
-                                                          . esc_html__(
1202
-                                                              'In this view, the check-in status represents the latest check-in record for the registration in that row.',
1203
-                                                              'event_espresso'
1204
-                                                          )
1205
-                                                          . '</p>';
1206
-        }
1207
-        $this->display_admin_list_table_page_with_no_sidebar();
1208
-    }
1100
+	/**
1101
+	 *        generates HTML for the Event Registrations List Table
1102
+	 *
1103
+	 * @access protected
1104
+	 * @return void
1105
+	 * @throws EE_Error
1106
+	 * @throws InvalidArgumentException
1107
+	 * @throws InvalidDataTypeException
1108
+	 * @throws InvalidInterfaceException
1109
+	 */
1110
+	protected function _event_registrations_list_table()
1111
+	{
1112
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1113
+		$this->_admin_page_title .= isset($this->_req_data['event_id'])
1114
+			? $this->get_action_link_or_button(
1115
+				'new_registration',
1116
+				'add-registrant',
1117
+				array('event_id' => $this->_req_data['event_id']),
1118
+				'add-new-h2',
1119
+				'',
1120
+				false
1121
+			)
1122
+			: '';
1123
+		$checked_in = new CheckinStatusDashicon(EE_Checkin::status_checked_in);
1124
+		$checked_out = new CheckinStatusDashicon(EE_Checkin::status_checked_out);
1125
+		$checked_never = new CheckinStatusDashicon(EE_Checkin::status_checked_never);
1126
+		$legend_items = array(
1127
+			'star-icon'        => array(
1128
+				'class' => 'dashicons dashicons-star-filled yellow-icon ee-icon-size-8',
1129
+				'desc'  => esc_html__('This Registrant is the Primary Registrant', 'event_espresso'),
1130
+			),
1131
+			'checkin'          => array(
1132
+				'class' => $checked_in->cssClasses(),
1133
+				'desc'  => $checked_in->legendLabel(),
1134
+			),
1135
+			'checkout'         => array(
1136
+				'class' => $checked_out->cssClasses(),
1137
+				'desc'  => $checked_out->legendLabel(),
1138
+			),
1139
+			'nocheckinrecord'  => array(
1140
+				'class' => $checked_never->cssClasses(),
1141
+				'desc'  => $checked_never->legendLabel(),
1142
+			),
1143
+			'approved_status'  => array(
1144
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
1145
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
1146
+			),
1147
+			'cancelled_status' => array(
1148
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1149
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
1150
+			),
1151
+			'declined_status'  => array(
1152
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
1153
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
1154
+			),
1155
+			'not_approved'     => array(
1156
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
1157
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
1158
+			),
1159
+			'pending_status'   => array(
1160
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
1161
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
1162
+			),
1163
+			'wait_list'        => array(
1164
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
1165
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
1166
+			),
1167
+		);
1168
+		$this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
1169
+		$event_id = isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null;
1170
+		/** @var EE_Event $event */
1171
+		$event = EEM_Event::instance()->get_one_by_ID($event_id);
1172
+		$this->_template_args['before_list_table'] = $event instanceof EE_Event
1173
+			? '<h2>' . sprintf(
1174
+				esc_html__('Viewing Registrations for Event: %s', 'event_espresso'),
1175
+				EEM_Event::instance()->get_one_by_ID($event_id)->get('EVT_name')
1176
+			) . '</h2>'
1177
+			: '';
1178
+		// need to get the number of datetimes on the event and set default datetime_id if there is only one datetime on
1179
+		// the event.
1180
+		$DTT_ID = ! empty($this->_req_data['DTT_ID']) ? absint($this->_req_data['DTT_ID']) : 0;
1181
+		$datetime = null;
1182
+		if ($event instanceof EE_Event) {
1183
+			$datetimes_on_event = $event->datetimes();
1184
+			if (count($datetimes_on_event) === 1) {
1185
+				$datetime = reset($datetimes_on_event);
1186
+			}
1187
+		}
1188
+		$datetime = $datetime instanceof EE_Datetime ? $datetime : EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1189
+		if ($datetime instanceof EE_Datetime && $this->_template_args['before_list_table'] !== '') {
1190
+			$this->_template_args['before_list_table'] = substr($this->_template_args['before_list_table'], 0, -5);
1191
+			$this->_template_args['before_list_table'] .= ' &nbsp;<span class="drk-grey-text">';
1192
+			$this->_template_args['before_list_table'] .= '<span class="dashicons dashicons-calendar"></span>';
1193
+			$this->_template_args['before_list_table'] .= $datetime->name();
1194
+			$this->_template_args['before_list_table'] .= ' ( ' . $datetime->date_and_time_range() . ' )';
1195
+			$this->_template_args['before_list_table'] .= '</span></h2>';
1196
+		}
1197
+		// if no datetime, then we're on the initial view, so let's give some helpful instructions on what the status
1198
+		// column represents
1199
+		if (! $datetime instanceof EE_Datetime) {
1200
+			$this->_template_args['before_list_table'] .= '<br><p class="description">'
1201
+														  . esc_html__(
1202
+															  'In this view, the check-in status represents the latest check-in record for the registration in that row.',
1203
+															  'event_espresso'
1204
+														  )
1205
+														  . '</p>';
1206
+		}
1207
+		$this->display_admin_list_table_page_with_no_sidebar();
1208
+	}
1209 1209
 
1210
-    /**
1211
-     * Download the registrations check-in report (same as the normal registration report, but with different where
1212
-     * conditions)
1213
-     *
1214
-     * @return void ends the request by a redirect or download
1215
-     */
1216
-    public function _registrations_checkin_report()
1217
-    {
1218
-        $this->_registrations_report_base('_get_checkin_query_params_from_request');
1219
-    }
1210
+	/**
1211
+	 * Download the registrations check-in report (same as the normal registration report, but with different where
1212
+	 * conditions)
1213
+	 *
1214
+	 * @return void ends the request by a redirect or download
1215
+	 */
1216
+	public function _registrations_checkin_report()
1217
+	{
1218
+		$this->_registrations_report_base('_get_checkin_query_params_from_request');
1219
+	}
1220 1220
 
1221
-    /**
1222
-     * Gets the query params from the request, plus adds a where condition for the registration status,
1223
-     * because on the checkin page we only ever want to see approved and pending-approval registrations
1224
-     *
1225
-     * @param array $request
1226
-     * @param int   $per_page
1227
-     * @param bool  $count
1228
-     * @return array
1229
-     * @throws EE_Error
1230
-     */
1231
-    protected function _get_checkin_query_params_from_request(
1232
-        $request,
1233
-        $per_page = 10,
1234
-        $count = false
1235
-    ) {
1236
-        $query_params = $this->_get_registration_query_parameters($request, $per_page, $count);
1237
-        // unlike the regular registrations list table,
1238
-        $status_ids_array = apply_filters(
1239
-            'FHEE__Extend_Registrations_Admin_Page__get_event_attendees__status_ids_array',
1240
-            array(EEM_Registration::status_id_pending_payment, EEM_Registration::status_id_approved)
1241
-        );
1242
-        $query_params[0]['STS_ID'] = array('IN', $status_ids_array);
1243
-        return $query_params;
1244
-    }
1221
+	/**
1222
+	 * Gets the query params from the request, plus adds a where condition for the registration status,
1223
+	 * because on the checkin page we only ever want to see approved and pending-approval registrations
1224
+	 *
1225
+	 * @param array $request
1226
+	 * @param int   $per_page
1227
+	 * @param bool  $count
1228
+	 * @return array
1229
+	 * @throws EE_Error
1230
+	 */
1231
+	protected function _get_checkin_query_params_from_request(
1232
+		$request,
1233
+		$per_page = 10,
1234
+		$count = false
1235
+	) {
1236
+		$query_params = $this->_get_registration_query_parameters($request, $per_page, $count);
1237
+		// unlike the regular registrations list table,
1238
+		$status_ids_array = apply_filters(
1239
+			'FHEE__Extend_Registrations_Admin_Page__get_event_attendees__status_ids_array',
1240
+			array(EEM_Registration::status_id_pending_payment, EEM_Registration::status_id_approved)
1241
+		);
1242
+		$query_params[0]['STS_ID'] = array('IN', $status_ids_array);
1243
+		return $query_params;
1244
+	}
1245 1245
 
1246 1246
 
1247
-    /**
1248
-     * Gets registrations for an event
1249
-     *
1250
-     * @param int    $per_page
1251
-     * @param bool   $count whether to return count or data.
1252
-     * @param bool   $trash
1253
-     * @param string $orderby
1254
-     * @return EE_Registration[]|int
1255
-     * @throws EE_Error
1256
-     * @throws InvalidArgumentException
1257
-     * @throws InvalidDataTypeException
1258
-     * @throws InvalidInterfaceException
1259
-     */
1260
-    public function get_event_attendees($per_page = 10, $count = false, $trash = false, $orderby = 'ATT_fname')
1261
-    {
1262
-        // normalize some request params that get setup by the parent `get_registrations` method.
1263
-        $request = $this->_req_data;
1264
-        $request['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : $orderby;
1265
-        $request['order'] = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'ASC';
1266
-        if ($trash) {
1267
-            $request['status'] = 'trash';
1268
-        }
1269
-        $query_params = $this->_get_checkin_query_params_from_request($request, $per_page, $count);
1270
-        /**
1271
-         * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1272
-         *
1273
-         * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1274
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1275
-         *                             or if you have the development copy of EE you can view this at the path:
1276
-         *                             /docs/G--Model-System/model-query-params.md
1277
-         */
1278
-        $query_params['group_by'] = '';
1247
+	/**
1248
+	 * Gets registrations for an event
1249
+	 *
1250
+	 * @param int    $per_page
1251
+	 * @param bool   $count whether to return count or data.
1252
+	 * @param bool   $trash
1253
+	 * @param string $orderby
1254
+	 * @return EE_Registration[]|int
1255
+	 * @throws EE_Error
1256
+	 * @throws InvalidArgumentException
1257
+	 * @throws InvalidDataTypeException
1258
+	 * @throws InvalidInterfaceException
1259
+	 */
1260
+	public function get_event_attendees($per_page = 10, $count = false, $trash = false, $orderby = 'ATT_fname')
1261
+	{
1262
+		// normalize some request params that get setup by the parent `get_registrations` method.
1263
+		$request = $this->_req_data;
1264
+		$request['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : $orderby;
1265
+		$request['order'] = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'ASC';
1266
+		if ($trash) {
1267
+			$request['status'] = 'trash';
1268
+		}
1269
+		$query_params = $this->_get_checkin_query_params_from_request($request, $per_page, $count);
1270
+		/**
1271
+		 * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1272
+		 *
1273
+		 * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1274
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1275
+		 *                             or if you have the development copy of EE you can view this at the path:
1276
+		 *                             /docs/G--Model-System/model-query-params.md
1277
+		 */
1278
+		$query_params['group_by'] = '';
1279 1279
 
1280
-        return $count
1281
-            ? EEM_Registration::instance()->count($query_params)
1282
-            /** @type EE_Registration[] */
1283
-            : EEM_Registration::instance()->get_all($query_params);
1284
-    }
1280
+		return $count
1281
+			? EEM_Registration::instance()->count($query_params)
1282
+			/** @type EE_Registration[] */
1283
+			: EEM_Registration::instance()->get_all($query_params);
1284
+	}
1285 1285
 }
Please login to merge, or discard this patch.
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -32,10 +32,10 @@  discard block
 block discarded – undo
32 32
     public function __construct($routing = true)
33 33
     {
34 34
         parent::__construct($routing);
35
-        if (! defined('REG_CAF_TEMPLATE_PATH')) {
36
-            define('REG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/templates/');
37
-            define('REG_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/assets/');
38
-            define('REG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registrations/assets/');
35
+        if ( ! defined('REG_CAF_TEMPLATE_PATH')) {
36
+            define('REG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND.'registrations/templates/');
37
+            define('REG_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND.'registrations/assets/');
38
+            define('REG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL.'registrations/assets/');
39 39
         }
40 40
     }
41 41
 
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
      */
46 46
     protected function _extend_page_config()
47 47
     {
48
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'registrations';
48
+        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND.'registrations';
49 49
         $reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
50 50
             ? $this->_req_data['_REG_ID']
51 51
             : 0;
@@ -186,14 +186,14 @@  discard block
 block discarded – undo
186 186
             // enqueue newsletter js
187 187
             wp_enqueue_script(
188 188
                 'ee-newsletter-trigger',
189
-                REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.js',
189
+                REG_CAF_ASSETS_URL.'ee-newsletter-trigger.js',
190 190
                 array('ee-dialog'),
191 191
                 EVENT_ESPRESSO_VERSION,
192 192
                 true
193 193
             );
194 194
             wp_enqueue_style(
195 195
                 'ee-newsletter-trigger-css',
196
-                REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.css',
196
+                REG_CAF_ASSETS_URL.'ee-newsletter-trigger.css',
197 197
                 array(),
198 198
                 EVENT_ESPRESSO_VERSION
199 199
             );
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
     {
215 215
         wp_register_script(
216 216
             'ee-reg-reports-js',
217
-            REG_CAF_ASSETS_URL . 'ee-registration-admin-reports.js',
217
+            REG_CAF_ASSETS_URL.'ee-registration-admin-reports.js',
218 218
             array('google-charts'),
219 219
             EVENT_ESPRESSO_VERSION,
220 220
             true
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
         $nonce_ref = 'get_newsletter_form_content_nonce';
301 301
         $this->_verify_nonce($nonce, $nonce_ref);
302 302
         // let's get the mtp for the incoming MTP_ ID
303
-        if (! isset($this->_req_data['GRP_ID'])) {
303
+        if ( ! isset($this->_req_data['GRP_ID'])) {
304 304
             EE_Error::add_error(
305 305
                 esc_html__(
306 306
                     'There must be something broken with the js or html structure because the required data for getting a message template group is not present (need an GRP_ID).',
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
             $this->_return_json();
316 316
         }
317 317
         $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID($this->_req_data['GRP_ID']);
318
-        if (! $MTPG instanceof EE_Message_Template_Group) {
318
+        if ( ! $MTPG instanceof EE_Message_Template_Group) {
319 319
             EE_Error::add_error(
320 320
                 sprintf(
321 321
                     esc_html__(
@@ -340,12 +340,12 @@  discard block
 block discarded – undo
340 340
             $field = $MTP->get('MTP_template_field');
341 341
             if ($field === 'content') {
342 342
                 $content = $MTP->get('MTP_content');
343
-                if (! empty($content['newsletter_content'])) {
343
+                if ( ! empty($content['newsletter_content'])) {
344 344
                     $template_fields['newsletter_content'] = $content['newsletter_content'];
345 345
                 }
346 346
                 continue;
347 347
             }
348
-            $template_fields[ $MTP->get('MTP_template_field') ] = $MTP->get('MTP_content');
348
+            $template_fields[$MTP->get('MTP_template_field')] = $MTP->get('MTP_content');
349 349
         }
350 350
         $this->_template_args['success'] = true;
351 351
         $this->_template_args['error'] = false;
@@ -447,17 +447,17 @@  discard block
 block discarded – undo
447 447
                 $field_id = $field === '[NEWSLETTER_CONTENT]'
448 448
                     ? 'content'
449 449
                     : $field;
450
-                $field_id = 'batch-message-' . strtolower($field_id);
450
+                $field_id = 'batch-message-'.strtolower($field_id);
451 451
                 $available_shortcodes[] = '<span class="js-shortcode-selection" data-value="'
452 452
                                           . $shortcode
453
-                                          . '" data-linked-input-id="' . $field_id . '">'
453
+                                          . '" data-linked-input-id="'.$field_id.'">'
454 454
                                           . $shortcode
455 455
                                           . '</span>';
456 456
             }
457
-            $codes[ $field ] = implode(', ', $available_shortcodes);
457
+            $codes[$field] = implode(', ', $available_shortcodes);
458 458
         }
459 459
         $shortcodes = $codes;
460
-        $form_template = REG_CAF_TEMPLATE_PATH . 'newsletter-send-form.template.php';
460
+        $form_template = REG_CAF_TEMPLATE_PATH.'newsletter-send-form.template.php';
461 461
         $form_template_args = array(
462 462
             'form_action'       => admin_url('admin.php?page=espresso_registrations'),
463 463
             'form_route'        => 'newsletter_selected_send',
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
      */
626 626
     protected function _registration_reports()
627 627
     {
628
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_reports.template.php';
628
+        $template_path = EE_ADMIN_TEMPLATE.'admin_reports.template.php';
629 629
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
630 630
             $template_path,
631 631
             $this->_reports_template_data,
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
             array_unshift($regs, $column_titles);
681 681
             // setup the date range.
682 682
             $DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
683
-            $beginning_date = new DateTime("now " . $period, $DateTimeZone);
683
+            $beginning_date = new DateTime("now ".$period, $DateTimeZone);
684 684
             $ending_date = new DateTime("now", $DateTimeZone);
685 685
             $subtitle = sprintf(
686 686
                 _x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
                     '%sThere are currently no registration records in the last month for this report.%s',
701 701
                     'event_espresso'
702 702
                 ),
703
-                '<h2>' . $report_title . '</h2><p>',
703
+                '<h2>'.$report_title.'</h2><p>',
704 704
                 '</p>'
705 705
             ),
706 706
         );
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
             array_unshift($regs, $column_titles);
754 754
             // setup the date range.
755 755
             $DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
756
-            $beginning_date = new DateTime("now " . $period, $DateTimeZone);
756
+            $beginning_date = new DateTime("now ".$period, $DateTimeZone);
757 757
             $ending_date = new DateTime("now", $DateTimeZone);
758 758
             $subtitle = sprintf(
759 759
                 _x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
@@ -773,7 +773,7 @@  discard block
 block discarded – undo
773 773
                     '%sThere are currently no registration records in the last month for this report.%s',
774 774
                     'event_espresso'
775 775
                 ),
776
-                '<h2>' . $report_title . '</h2><p>',
776
+                '<h2>'.$report_title.'</h2><p>',
777 777
                 '</p>'
778 778
             ),
779 779
         );
@@ -799,7 +799,7 @@  discard block
 block discarded – undo
799 799
         $reg_id = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : null;
800 800
         /** @var EE_Registration $registration */
801 801
         $registration = EEM_Registration::instance()->get_one_by_ID($reg_id);
802
-        if (! $registration instanceof EE_Registration) {
802
+        if ( ! $registration instanceof EE_Registration) {
803 803
             throw new EE_Error(
804 804
                 sprintf(
805 805
                     esc_html__('An error occurred. There is no registration with ID (%d)', 'event_espresso'),
@@ -834,7 +834,7 @@  discard block
 block discarded – undo
834 834
         if ($datetime instanceof EE_Datetime) {
835 835
             $datetime_label = $datetime->get_dtt_display_name(true);
836 836
             $datetime_label .= ! empty($datetime_label)
837
-                ? ' (' . $datetime->get_dtt_display_name() . ')'
837
+                ? ' ('.$datetime->get_dtt_display_name().')'
838 838
                 : $datetime->get_dtt_display_name();
839 839
         }
840 840
         $datetime_link = ! empty($dtt_id) && $registration instanceof EE_Registration
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
             )
849 849
             : '';
850 850
         $datetime_link = ! empty($datetime_link)
851
-            ? '<a href="' . $datetime_link . '">'
851
+            ? '<a href="'.$datetime_link.'">'
852 852
               . '<span id="checkin-dtt">'
853 853
               . $datetime_label
854 854
               . '</span></a>'
@@ -860,8 +860,8 @@  discard block
 block discarded – undo
860 860
             ? $attendee->get_admin_details_link()
861 861
             : '';
862 862
         $attendee_link = ! empty($attendee_link)
863
-            ? '<a href="' . $attendee->get_admin_details_link() . '"'
864
-              . ' title="' . esc_html__('Click for attendee details', 'event_espresso') . '">'
863
+            ? '<a href="'.$attendee->get_admin_details_link().'"'
864
+              . ' title="'.esc_html__('Click for attendee details', 'event_espresso').'">'
865 865
               . '<span id="checkin-attendee-name">'
866 866
               . $attendee_name
867 867
               . '</span></a>'
@@ -870,25 +870,25 @@  discard block
 block discarded – undo
870 870
             ? $registration->event()->get_admin_details_link()
871 871
             : '';
872 872
         $event_link = ! empty($event_link)
873
-            ? '<a href="' . $event_link . '"'
874
-              . ' title="' . esc_html__('Click here to edit event.', 'event_espresso') . '">'
873
+            ? '<a href="'.$event_link.'"'
874
+              . ' title="'.esc_html__('Click here to edit event.', 'event_espresso').'">'
875 875
               . '<span id="checkin-event-name">'
876 876
               . $registration->event_name()
877 877
               . '</span>'
878 878
               . '</a>'
879 879
             : '';
880 880
         $this->_template_args['before_list_table'] = ! empty($reg_id) && ! empty($dtt_id)
881
-            ? '<h2>' . sprintf(
881
+            ? '<h2>'.sprintf(
882 882
                 esc_html__('Displaying check in records for %1$s for %2$s at the event, %3$s', 'event_espresso'),
883 883
                 $attendee_link,
884 884
                 $datetime_link,
885 885
                 $event_link
886
-            ) . '</h2>'
886
+            ).'</h2>'
887 887
             : '';
888 888
         $this->_template_args['list_table_hidden_fields'] = ! empty($reg_id)
889
-            ? '<input type="hidden" name="_REG_ID" value="' . $reg_id . '">' : '';
889
+            ? '<input type="hidden" name="_REG_ID" value="'.$reg_id.'">' : '';
890 890
         $this->_template_args['list_table_hidden_fields'] .= ! empty($dtt_id)
891
-            ? '<input type="hidden" name="DTT_ID" value="' . $dtt_id . '">' : '';
891
+            ? '<input type="hidden" name="DTT_ID" value="'.$dtt_id.'">' : '';
892 892
         $this->display_admin_list_table_page_with_no_sidebar();
893 893
     }
894 894
 
@@ -905,7 +905,7 @@  discard block
 block discarded – undo
905 905
     public function toggle_checkin_status()
906 906
     {
907 907
         // first make sure we have the necessary data
908
-        if (! isset($this->_req_data['_regid'])) {
908
+        if ( ! isset($this->_req_data['_regid'])) {
909 909
             EE_Error::add_error(
910 910
                 esc_html__(
911 911
                     'There must be something broken with the html structure because the required data for toggling the Check-in status is not being sent via ajax',
@@ -927,7 +927,7 @@  discard block
 block discarded – undo
927 927
         // beautiful! Made it this far so let's get the status.
928 928
         $new_status = new CheckinStatusDashicon($this->_toggle_checkin_status());
929 929
         // setup new class to return via ajax
930
-        $this->_template_args['admin_page_content'] = 'clickable trigger-checkin ' . $new_status->cssClasses();
930
+        $this->_template_args['admin_page_content'] = 'clickable trigger-checkin '.$new_status->cssClasses();
931 931
         $this->_template_args['success'] = true;
932 932
         $this->_return_json();
933 933
     }
@@ -953,7 +953,7 @@  discard block
 block discarded – undo
953 953
         );
954 954
         $new_status = false;
955 955
         // bulk action check in toggle
956
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
956
+        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
957 957
             // cycle thru checkboxes
958 958
             while (list($REG_ID, $value) = each($this->_req_data['checkbox'])) {
959 959
                 $DTT_ID = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
@@ -1023,9 +1023,9 @@  discard block
 block discarded – undo
1023 1023
             '_REG_ID' => isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : 0,
1024 1024
         );
1025 1025
         $errors = 0;
1026
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1026
+        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1027 1027
             while (list($CHK_ID, $value) = each($this->_req_data['checkbox'])) {
1028
-                if (! EEM_Checkin::instance()->delete_by_ID($CHK_ID)) {
1028
+                if ( ! EEM_Checkin::instance()->delete_by_ID($CHK_ID)) {
1029 1029
                     $errors++;
1030 1030
                 }
1031 1031
             }
@@ -1071,8 +1071,8 @@  discard block
 block discarded – undo
1071 1071
             'DTT_ID'  => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
1072 1072
             '_REG_ID' => isset($this->_req_data['_REG_ID']) ? $this->_req_data['_REG_ID'] : 0,
1073 1073
         );
1074
-        if (! empty($this->_req_data['CHK_ID'])) {
1075
-            if (! EEM_Checkin::instance()->delete_by_ID($this->_req_data['CHK_ID'])) {
1074
+        if ( ! empty($this->_req_data['CHK_ID'])) {
1075
+            if ( ! EEM_Checkin::instance()->delete_by_ID($this->_req_data['CHK_ID'])) {
1076 1076
                 EE_Error::add_error(
1077 1077
                     esc_html__('Something went wrong and this check-in record was not deleted', 'event_espresso'),
1078 1078
                     __FILE__,
@@ -1141,27 +1141,27 @@  discard block
 block discarded – undo
1141 1141
                 'desc'  => $checked_never->legendLabel(),
1142 1142
             ),
1143 1143
             'approved_status'  => array(
1144
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
1144
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_approved,
1145 1145
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
1146 1146
             ),
1147 1147
             'cancelled_status' => array(
1148
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1148
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_cancelled,
1149 1149
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
1150 1150
             ),
1151 1151
             'declined_status'  => array(
1152
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
1152
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_declined,
1153 1153
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
1154 1154
             ),
1155 1155
             'not_approved'     => array(
1156
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
1156
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_not_approved,
1157 1157
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
1158 1158
             ),
1159 1159
             'pending_status'   => array(
1160
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
1160
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_pending_payment,
1161 1161
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
1162 1162
             ),
1163 1163
             'wait_list'        => array(
1164
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
1164
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_wait_list,
1165 1165
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
1166 1166
             ),
1167 1167
         );
@@ -1170,10 +1170,10 @@  discard block
 block discarded – undo
1170 1170
         /** @var EE_Event $event */
1171 1171
         $event = EEM_Event::instance()->get_one_by_ID($event_id);
1172 1172
         $this->_template_args['before_list_table'] = $event instanceof EE_Event
1173
-            ? '<h2>' . sprintf(
1173
+            ? '<h2>'.sprintf(
1174 1174
                 esc_html__('Viewing Registrations for Event: %s', 'event_espresso'),
1175 1175
                 EEM_Event::instance()->get_one_by_ID($event_id)->get('EVT_name')
1176
-            ) . '</h2>'
1176
+            ).'</h2>'
1177 1177
             : '';
1178 1178
         // need to get the number of datetimes on the event and set default datetime_id if there is only one datetime on
1179 1179
         // the event.
@@ -1191,12 +1191,12 @@  discard block
 block discarded – undo
1191 1191
             $this->_template_args['before_list_table'] .= ' &nbsp;<span class="drk-grey-text">';
1192 1192
             $this->_template_args['before_list_table'] .= '<span class="dashicons dashicons-calendar"></span>';
1193 1193
             $this->_template_args['before_list_table'] .= $datetime->name();
1194
-            $this->_template_args['before_list_table'] .= ' ( ' . $datetime->date_and_time_range() . ' )';
1194
+            $this->_template_args['before_list_table'] .= ' ( '.$datetime->date_and_time_range().' )';
1195 1195
             $this->_template_args['before_list_table'] .= '</span></h2>';
1196 1196
         }
1197 1197
         // if no datetime, then we're on the initial view, so let's give some helpful instructions on what the status
1198 1198
         // column represents
1199
-        if (! $datetime instanceof EE_Datetime) {
1199
+        if ( ! $datetime instanceof EE_Datetime) {
1200 1200
             $this->_template_args['before_list_table'] .= '<br><p class="description">'
1201 1201
                                                           . esc_html__(
1202 1202
                                                               'In this view, the check-in status represents the latest check-in record for the registration in that row.',
Please login to merge, or discard this patch.
caffeinated/admin/extend/events/Extend_Events_Admin_Page.core.php 1 patch
Indentation   +1413 added lines, -1413 removed lines patch added patch discarded remove patch
@@ -17,1417 +17,1417 @@
 block discarded – undo
17 17
 class Extend_Events_Admin_Page extends Events_Admin_Page
18 18
 {
19 19
 
20
-    /**
21
-     * @var EE_Admin_Config
22
-     */
23
-    protected $admin_config;
24
-
25
-    /**
26
-     * @var AdvancedEditorAdminFormSection
27
-     */
28
-    protected $advanced_editor_admin_form;
29
-
30
-
31
-    /**
32
-     * Extend_Events_Admin_Page constructor.
33
-     *
34
-     * @param bool $routing
35
-     * @throws ReflectionException
36
-     */
37
-    public function __construct($routing = true)
38
-    {
39
-        if (! defined('EVENTS_CAF_TEMPLATE_PATH')) {
40
-            define('EVENTS_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'events/templates/');
41
-            define('EVENTS_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'events/assets/');
42
-            define('EVENTS_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'events/assets/');
43
-        }
44
-        parent::__construct($routing);
45
-        $this->admin_config = $this->loader->getShared('EE_Admin_Config');
46
-    }
47
-
48
-
49
-    /**
50
-     * Sets routes.
51
-     *
52
-     * @throws EE_Error
53
-     * @throws InvalidArgumentException
54
-     * @throws InvalidDataTypeException
55
-     * @throws InvalidInterfaceException
56
-     * @throws Exception
57
-     */
58
-    protected function _extend_page_config()
59
-    {
60
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'events';
61
-        // is there a evt_id in the request?
62
-        $evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
63
-            ? $this->_req_data['EVT_ID']
64
-            : 0;
65
-        $evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
66
-        // tkt_id?
67
-        $tkt_id = ! empty($this->_req_data['TKT_ID']) && ! is_array($this->_req_data['TKT_ID'])
68
-            ? $this->_req_data['TKT_ID']
69
-            : 0;
70
-        $new_page_routes = [
71
-            'duplicate_event'          => [
72
-                'func'       => '_duplicate_event',
73
-                'capability' => 'ee_edit_event',
74
-                'obj_id'     => $evt_id,
75
-                'noheader'   => true,
76
-            ],
77
-            'import_page'              => [
78
-                'func'       => '_import_page',
79
-                'capability' => 'import',
80
-            ],
81
-            'import'                   => [
82
-                'func'       => '_import_events',
83
-                'capability' => 'import',
84
-                'noheader'   => true,
85
-            ],
86
-            'import_events'            => [
87
-                'func'       => '_import_events',
88
-                'capability' => 'import',
89
-                'noheader'   => true,
90
-            ],
91
-            'export_events'            => [
92
-                'func'       => '_events_export',
93
-                'capability' => 'export',
94
-                'noheader'   => true,
95
-            ],
96
-            'export_categories'        => [
97
-                'func'       => '_categories_export',
98
-                'capability' => 'export',
99
-                'noheader'   => true,
100
-            ],
101
-            'sample_export_file'       => [
102
-                'func'       => '_sample_export_file',
103
-                'capability' => 'export',
104
-                'noheader'   => true,
105
-            ],
106
-            'update_template_settings' => [
107
-                'func'       => '_update_template_settings',
108
-                'capability' => 'manage_options',
109
-                'noheader'   => true,
110
-            ],
111
-        ];        // don't load these meta boxes if using the advanced editor
112
-        $this->_page_config['create_new']['metaboxes'][] = '_premium_event_editor_meta_boxes';
113
-        $this->_page_config['edit']['metaboxes'][] = '_premium_event_editor_meta_boxes';
114
-        if (! $this->admin_config->useAdvancedEditor()) {
115
-            $this->_page_config['create_new']['qtips'][] = 'EE_Event_Editor_Tips';
116
-            $this->_page_config['edit']['qtips'][] = 'EE_Event_Editor_Tips';
117
-
118
-            $legacy_editor_page_routes = [
119
-                'ticket_list_table' => [
120
-                    'func'       => '_tickets_overview_list_table',
121
-                    'capability' => 'ee_read_default_tickets',
122
-                ],
123
-                'trash_ticket'      => [
124
-                    'func'       => '_trash_or_restore_ticket',
125
-                    'capability' => 'ee_delete_default_ticket',
126
-                    'obj_id'     => $tkt_id,
127
-                    'noheader'   => true,
128
-                    'args'       => ['trash' => true],
129
-                ],
130
-                'trash_tickets'     => [
131
-                    'func'       => '_trash_or_restore_ticket',
132
-                    'capability' => 'ee_delete_default_tickets',
133
-                    'noheader'   => true,
134
-                    'args'       => ['trash' => true],
135
-                ],
136
-                'restore_ticket'    => [
137
-                    'func'       => '_trash_or_restore_ticket',
138
-                    'capability' => 'ee_delete_default_ticket',
139
-                    'obj_id'     => $tkt_id,
140
-                    'noheader'   => true,
141
-                ],
142
-                'restore_tickets'   => [
143
-                    'func'       => '_trash_or_restore_ticket',
144
-                    'capability' => 'ee_delete_default_tickets',
145
-                    'noheader'   => true,
146
-                ],
147
-                'delete_ticket'     => [
148
-                    'func'       => '_delete_ticket',
149
-                    'capability' => 'ee_delete_default_ticket',
150
-                    'obj_id'     => $tkt_id,
151
-                    'noheader'   => true,
152
-                ],
153
-                'delete_tickets'    => [
154
-                    'func'       => '_delete_ticket',
155
-                    'capability' => 'ee_delete_default_tickets',
156
-                    'noheader'   => true,
157
-                ],
158
-            ];
159
-            $new_page_routes = array_merge($new_page_routes, $legacy_editor_page_routes);
160
-        }
161
-
162
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
163
-        // partial route/config override
164
-        $this->_page_config['import_events']['metaboxes'] = $this->_default_espresso_metaboxes;
165
-        $this->_page_config['default']['list_table'] = 'Extend_Events_Admin_List_Table';
166
-        // add tickets tab but only if there are more than one default ticket!
167
-        $tkt_count = EEM_Ticket::instance()->count_deleted_and_undeleted(
168
-            [['TKT_is_default' => 1]],
169
-            'TKT_ID',
170
-            true
171
-        );
172
-        if ($tkt_count > 1) {
173
-            $new_page_config = [
174
-                'ticket_list_table' => [
175
-                    'nav'           => [
176
-                        'label' => esc_html__('Default Tickets', 'event_espresso'),
177
-                        'order' => 60,
178
-                    ],
179
-                    'list_table'    => 'Tickets_List_Table',
180
-                    'require_nonce' => false,
181
-                ],
182
-            ];
183
-        }
184
-        // template settings
185
-        $new_page_config['template_settings'] = [
186
-            'nav'           => [
187
-                'label' => esc_html__('Templates', 'event_espresso'),
188
-                'order' => 30,
189
-            ],
190
-            'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
191
-            'help_tabs'     => [
192
-                'general_settings_templates_help_tab' => [
193
-                    'title'    => esc_html__('Templates', 'event_espresso'),
194
-                    'filename' => 'general_settings_templates',
195
-                ],
196
-            ],
197
-           // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
198
-            // 'help_tour'     => ['Templates_Help_Tour'],
199
-            'require_nonce' => false,
200
-        ];
201
-        $this->_page_config = array_merge($this->_page_config, $new_page_config);
202
-        // add filters and actions
203
-        // modifying _views
204
-        add_filter(
205
-            'FHEE_event_datetime_metabox_add_additional_date_time_template',
206
-            [$this, 'add_additional_datetime_button'],
207
-            10,
208
-            2
209
-        );
210
-        add_filter(
211
-            'FHEE_event_datetime_metabox_clone_button_template',
212
-            [$this, 'add_datetime_clone_button'],
213
-            10,
214
-            2
215
-        );
216
-        add_filter(
217
-            'FHEE_event_datetime_metabox_timezones_template',
218
-            [$this, 'datetime_timezones_template'],
219
-            10,
220
-            2
221
-        );
222
-        // filters for event list table
223
-        add_filter('FHEE__Extend_Events_Admin_List_Table__filters', [$this, 'list_table_filters'], 10, 2);
224
-        add_filter(
225
-            'FHEE__Events_Admin_List_Table__column_actions__action_links',
226
-            [$this, 'extra_list_table_actions'],
227
-            10,
228
-            2
229
-        );
230
-        // legend item
231
-        add_filter('FHEE__Events_Admin_Page___event_legend_items__items', [$this, 'additional_legend_items']);
232
-        add_action('admin_init', [$this, 'admin_init']);
233
-        // load additional handlers
234
-        $this->handleActionRequest();
235
-    }
236
-
237
-
238
-    private function getRequestAction()
239
-    {
240
-        return isset($this->_req_data['action']) ? sanitize_key($this->_req_data['action']) : null;
241
-    }
242
-
243
-
244
-    /**
245
-     * @throws Exception
246
-     */
247
-    private function handleActionRequest()
248
-    {
249
-        $action = $this->getRequestAction();
250
-        if ($action) {
251
-            // setup Advanced Editor ???
252
-            if ($action === 'default_event_settings' || $action === 'update_default_event_settings') {
253
-                $this->advanced_editor_admin_form = $this->loader->getShared(
254
-                    'EventEspresso\core\domain\services\admin\events\default_settings\AdvancedEditorAdminFormSection'
255
-                );
256
-            }
257
-        }
258
-    }
259
-
260
-
261
-    /**
262
-     * admin_init
263
-     */
264
-    public function admin_init()
265
-    {
266
-        EE_Registry::$i18n_js_strings = array_merge(
267
-            EE_Registry::$i18n_js_strings,
268
-            [
269
-                'image_confirm'          => esc_html__(
270
-                    'Do you really want to delete this image? Please remember to update your event to complete the removal.',
271
-                    'event_espresso'
272
-                ),
273
-                'event_starts_on'        => esc_html__('Event Starts on', 'event_espresso'),
274
-                'event_ends_on'          => esc_html__('Event Ends on', 'event_espresso'),
275
-                'event_datetime_actions' => esc_html__('Actions', 'event_espresso'),
276
-                'event_clone_dt_msg'     => esc_html__('Clone this Event Date and Time', 'event_espresso'),
277
-                'remove_event_dt_msg'    => esc_html__('Remove this Event Time', 'event_espresso'),
278
-            ]
279
-        );
280
-    }
281
-
282
-
283
-    /**
284
-     * Add per page screen options to the default ticket list table view.
285
-     *
286
-     * @throws InvalidArgumentException
287
-     * @throws InvalidDataTypeException
288
-     * @throws InvalidInterfaceException
289
-     */
290
-    protected function _add_screen_options_ticket_list_table()
291
-    {
292
-        $this->_per_page_screen_option();
293
-    }
294
-
295
-
296
-    /**
297
-     * @param string $return
298
-     * @param int    $id
299
-     * @param string $new_title
300
-     * @param string $new_slug
301
-     * @return string
302
-     */
303
-    public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
304
-    {
305
-        $return = parent::extra_permalink_field_buttons($return, $id, $new_title, $new_slug);
306
-        // make sure this is only when editing
307
-        if (! empty($id)) {
308
-            $href = EE_Admin_Page::add_query_args_and_nonce(
309
-                ['action' => 'duplicate_event', 'EVT_ID' => $id],
310
-                $this->_admin_base_url
311
-            );
312
-            $title = esc_attr__('Duplicate Event', 'event_espresso');
313
-            $return .= '<a href="'
314
-                       . $href
315
-                       . '" title="'
316
-                       . $title
317
-                       . '" id="ee-duplicate-event-button" class="button button-small"  value="duplicate_event">'
318
-                       . $title
319
-                       . '</a>';
320
-        }
321
-        return $return;
322
-    }
323
-
324
-
325
-    /**
326
-     * Set the list table views for the default ticket list table view.
327
-     */
328
-    public function _set_list_table_views_ticket_list_table()
329
-    {
330
-        $this->_views = [
331
-            'all'     => [
332
-                'slug'        => 'all',
333
-                'label'       => esc_html__('All', 'event_espresso'),
334
-                'count'       => 0,
335
-                'bulk_action' => [
336
-                    'trash_tickets' => esc_html__('Move to Trash', 'event_espresso'),
337
-                ],
338
-            ],
339
-            'trashed' => [
340
-                'slug'        => 'trashed',
341
-                'label'       => esc_html__('Trash', 'event_espresso'),
342
-                'count'       => 0,
343
-                'bulk_action' => [
344
-                    'restore_tickets' => esc_html__('Restore from Trash', 'event_espresso'),
345
-                    'delete_tickets'  => esc_html__('Delete Permanently', 'event_espresso'),
346
-                ],
347
-            ],
348
-        ];
349
-    }
350
-
351
-
352
-    /**
353
-     * Enqueue scripts and styles for the event editor.
354
-     */
355
-    public function load_scripts_styles_edit()
356
-    {
357
-        if (! $this->admin_config->useAdvancedEditor()) {
358
-            wp_register_script(
359
-                'ee-event-editor-heartbeat',
360
-                EVENTS_CAF_ASSETS_URL . 'event-editor-heartbeat.js',
361
-                ['ee_admin_js', 'heartbeat'],
362
-                EVENT_ESPRESSO_VERSION,
363
-                true
364
-            );
365
-            wp_enqueue_script('ee-accounting');
366
-            wp_enqueue_script('ee-event-editor-heartbeat');
367
-        }
368
-        wp_enqueue_script('event_editor_js');
369
-        // styles
370
-        wp_enqueue_style('espresso-ui-theme');
371
-    }
372
-
373
-
374
-    /**
375
-     * Returns template for the additional datetime.
376
-     *
377
-     * @param $template
378
-     * @param $template_args
379
-     * @return mixed
380
-     * @throws DomainException
381
-     */
382
-    public function add_additional_datetime_button($template, $template_args)
383
-    {
384
-        return EEH_Template::display_template(
385
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_add_additional_time.template.php',
386
-            $template_args,
387
-            true
388
-        );
389
-    }
390
-
391
-
392
-    /**
393
-     * Returns the template for cloning a datetime.
394
-     *
395
-     * @param $template
396
-     * @param $template_args
397
-     * @return mixed
398
-     * @throws DomainException
399
-     */
400
-    public function add_datetime_clone_button($template, $template_args)
401
-    {
402
-        return EEH_Template::display_template(
403
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_metabox_clone_button.template.php',
404
-            $template_args,
405
-            true
406
-        );
407
-    }
408
-
409
-
410
-    /**
411
-     * Returns the template for datetime timezones.
412
-     *
413
-     * @param $template
414
-     * @param $template_args
415
-     * @return mixed
416
-     * @throws DomainException
417
-     */
418
-    public function datetime_timezones_template($template, $template_args)
419
-    {
420
-        return EEH_Template::display_template(
421
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_timezones.template.php',
422
-            $template_args,
423
-            true
424
-        );
425
-    }
426
-
427
-
428
-    /**
429
-     * Sets the views for the default list table view.
430
-     *
431
-     * @throws EE_Error
432
-     */
433
-    protected function _set_list_table_views_default()
434
-    {
435
-        parent::_set_list_table_views_default();
436
-        $new_views = [
437
-            'today' => [
438
-                'slug'        => 'today',
439
-                'label'       => esc_html__('Today', 'event_espresso'),
440
-                'count'       => $this->total_events_today(),
441
-                'bulk_action' => [
442
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
443
-                ],
444
-            ],
445
-            'month' => [
446
-                'slug'        => 'month',
447
-                'label'       => esc_html__('This Month', 'event_espresso'),
448
-                'count'       => $this->total_events_this_month(),
449
-                'bulk_action' => [
450
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
451
-                ],
452
-            ],
453
-        ];
454
-        $this->_views = array_merge($this->_views, $new_views);
455
-    }
456
-
457
-
458
-    /**
459
-     * Returns the extra action links for the default list table view.
460
-     *
461
-     * @param array    $action_links
462
-     * @param EE_Event $event
463
-     * @return array
464
-     * @throws EE_Error
465
-     * @throws InvalidArgumentException
466
-     * @throws InvalidDataTypeException
467
-     * @throws InvalidInterfaceException
468
-     * @throws ReflectionException
469
-     */
470
-    public function extra_list_table_actions(array $action_links, EE_Event $event)
471
-    {
472
-        if (
473
-            EE_Registry::instance()->CAP->current_user_can(
474
-                'ee_read_registrations',
475
-                'espresso_registrations_reports',
476
-                $event->ID()
477
-            )
478
-        ) {
479
-            $reports_query_args = [
480
-                'action' => 'reports',
481
-                'EVT_ID' => $event->ID(),
482
-            ];
483
-            $reports_link = EE_Admin_Page::add_query_args_and_nonce($reports_query_args, REG_ADMIN_URL);
484
-            $action_links[] = '<a href="'
485
-                              . $reports_link
486
-                              . '" title="'
487
-                              . esc_attr__('View Report', 'event_espresso')
488
-                              . '"><div class="dashicons dashicons-chart-bar"></div></a>'
489
-                              . "\n\t";
490
-        }
491
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
492
-            EE_Registry::instance()->load_helper('MSG_Template');
493
-            $action_links[] = EEH_MSG_Template::get_message_action_link(
494
-                'see_notifications_for',
495
-                null,
496
-                ['EVT_ID' => $event->ID()]
497
-            );
498
-        }
499
-        return $action_links;
500
-    }
501
-
502
-
503
-    /**
504
-     * @param $items
505
-     * @return mixed
506
-     */
507
-    public function additional_legend_items($items)
508
-    {
509
-        if (
510
-            EE_Registry::instance()->CAP->current_user_can(
511
-                'ee_read_registrations',
512
-                'espresso_registrations_reports'
513
-            )
514
-        ) {
515
-            $items['reports'] = [
516
-                'class' => 'dashicons dashicons-chart-bar',
517
-                'desc'  => esc_html__('Event Reports', 'event_espresso'),
518
-            ];
519
-        }
520
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
521
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
522
-            // $related_for_icon can sometimes be a string so 'css_class' would be an illegal offset
523
-            // (can only use numeric offsets when treating strings as arrays)
524
-            if (is_array($related_for_icon) && isset($related_for_icon['css_class'], $related_for_icon['label'])) {
525
-                $items['view_related_messages'] = [
526
-                    'class' => $related_for_icon['css_class'],
527
-                    'desc'  => $related_for_icon['label'],
528
-                ];
529
-            }
530
-        }
531
-        return $items;
532
-    }
533
-
534
-
535
-    /**
536
-     * This is the callback method for the duplicate event route
537
-     * Method looks for 'EVT_ID' in the request and retrieves that event and its details and duplicates them
538
-     * into a new event.  We add a hook so that any plugins that add extra event details can hook into this
539
-     * action.  Note that the dupe will have **DUPLICATE** as its title and slug.
540
-     * After duplication the redirect is to the new event edit page.
541
-     *
542
-     * @return void
543
-     * @throws EE_Error If EE_Event is not available with given ID
544
-     * @throws InvalidArgumentException
545
-     * @throws InvalidDataTypeException
546
-     * @throws InvalidInterfaceException
547
-     * @throws ReflectionException
548
-     * @access protected
549
-     */
550
-    protected function _duplicate_event()
551
-    {
552
-        // first make sure the ID for the event is in the request.
553
-        //  If it isn't then we need to bail and redirect back to overview list table (cause how did we get here?)
554
-        if (! isset($this->_req_data['EVT_ID'])) {
555
-            EE_Error::add_error(
556
-                esc_html__(
557
-                    'In order to duplicate an event an Event ID is required.  None was given.',
558
-                    'event_espresso'
559
-                ),
560
-                __FILE__,
561
-                __FUNCTION__,
562
-                __LINE__
563
-            );
564
-            $this->_redirect_after_action(false, '', '', [], true);
565
-            return;
566
-        }
567
-        // k we've got EVT_ID so let's use that to get the event we'll duplicate
568
-        $orig_event = EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']);
569
-        if (! $orig_event instanceof EE_Event) {
570
-            throw new EE_Error(
571
-                sprintf(
572
-                    esc_html__('An EE_Event object could not be retrieved for the given ID (%s)', 'event_espresso'),
573
-                    $this->_req_data['EVT_ID']
574
-                )
575
-            );
576
-        }
577
-        // k now let's clone the $orig_event before getting relations
578
-        $new_event = clone $orig_event;
579
-        // original datetimes
580
-        $orig_datetimes = $orig_event->get_many_related('Datetime');
581
-        // other original relations
582
-        $orig_ven = $orig_event->get_many_related('Venue');
583
-        // reset the ID and modify other details to make it clear this is a dupe
584
-        $new_event->set('EVT_ID', 0);
585
-        $new_name = $new_event->name() . ' ' . esc_html__('**DUPLICATE**', 'event_espresso');
586
-        $new_event->set('EVT_name', $new_name);
587
-        $new_event->set(
588
-            'EVT_slug',
589
-            wp_unique_post_slug(
590
-                sanitize_title($orig_event->name()),
591
-                0,
592
-                'publish',
593
-                'espresso_events',
594
-                0
595
-            )
596
-        );
597
-        $new_event->set('status', 'draft');
598
-        // duplicate discussion settings
599
-        $new_event->set('comment_status', $orig_event->get('comment_status'));
600
-        $new_event->set('ping_status', $orig_event->get('ping_status'));
601
-        // save the new event
602
-        $new_event->save();
603
-        // venues
604
-        foreach ($orig_ven as $ven) {
605
-            $new_event->_add_relation_to($ven, 'Venue');
606
-        }
607
-        $new_event->save();
608
-        // now we need to get the question group relations and handle that
609
-        // first primary question groups
610
-        $orig_primary_qgs = $orig_event->get_many_related(
611
-            'Question_Group',
612
-            [['Event_Question_Group.EQG_primary' => true]]
613
-        );
614
-        if (! empty($orig_primary_qgs)) {
615
-            foreach ($orig_primary_qgs as $id => $obj) {
616
-                if ($obj instanceof EE_Question_Group) {
617
-                    $new_event->_add_relation_to($obj, 'Question_Group', ['EQG_primary' => true]);
618
-                }
619
-            }
620
-        }
621
-        // next additional attendee question groups
622
-        $orig_additional_qgs = $orig_event->get_many_related(
623
-            'Question_Group',
624
-            [['Event_Question_Group.EQG_additional' => true]]
625
-        );
626
-        if (! empty($orig_additional_qgs)) {
627
-            foreach ($orig_additional_qgs as $id => $obj) {
628
-                if ($obj instanceof EE_Question_Group) {
629
-                    $new_event->_add_relation_to($obj, 'Question_Group', ['EQG_additional' => true]);
630
-                }
631
-            }
632
-        }
633
-
634
-        $new_event->save();
635
-
636
-        // k now that we have the new event saved we can loop through the datetimes and start adding relations.
637
-        $cloned_tickets = [];
638
-        foreach ($orig_datetimes as $orig_dtt) {
639
-            if (! $orig_dtt instanceof EE_Datetime) {
640
-                continue;
641
-            }
642
-            $new_dtt = clone $orig_dtt;
643
-            $orig_tkts = $orig_dtt->tickets();
644
-            // save new dtt then add to event
645
-            $new_dtt->set('DTT_ID', 0);
646
-            $new_dtt->set('DTT_sold', 0);
647
-            $new_dtt->set_reserved(0);
648
-            $new_dtt->save();
649
-            $new_event->_add_relation_to($new_dtt, 'Datetime');
650
-            $new_event->save();
651
-            // now let's get the ticket relations setup.
652
-            foreach ((array) $orig_tkts as $orig_tkt) {
653
-                // it's possible a datetime will have no tickets so let's verify we HAVE a ticket first.
654
-                if (! $orig_tkt instanceof EE_Ticket) {
655
-                    continue;
656
-                }
657
-                // is this ticket archived?  If it is then let's skip
658
-                if ($orig_tkt->get('TKT_deleted')) {
659
-                    continue;
660
-                }
661
-                // does this original ticket already exist in the clone_tickets cache?
662
-                //  If so we'll just use the new ticket from it.
663
-                if (isset($cloned_tickets[ $orig_tkt->ID() ])) {
664
-                    $new_tkt = $cloned_tickets[ $orig_tkt->ID() ];
665
-                } else {
666
-                    $new_tkt = clone $orig_tkt;
667
-                    // get relations on the $orig_tkt that we need to setup.
668
-                    $orig_prices = $orig_tkt->prices();
669
-                    $new_tkt->set('TKT_ID', 0);
670
-                    $new_tkt->set('TKT_sold', 0);
671
-                    $new_tkt->set('TKT_reserved', 0);
672
-                    $new_tkt->save(); // make sure new ticket has ID.
673
-                    // price relations on new ticket need to be setup.
674
-                    foreach ($orig_prices as $orig_price) {
675
-                        $new_price = clone $orig_price;
676
-                        $new_price->set('PRC_ID', 0);
677
-                        $new_price->save();
678
-                        $new_tkt->_add_relation_to($new_price, 'Price');
679
-                        $new_tkt->save();
680
-                    }
681
-
682
-                    do_action(
683
-                        'AHEE__Extend_Events_Admin_Page___duplicate_event__duplicate_ticket__after',
684
-                        $orig_tkt,
685
-                        $new_tkt,
686
-                        $orig_prices,
687
-                        $orig_event,
688
-                        $orig_dtt,
689
-                        $new_dtt
690
-                    );
691
-                }
692
-                // k now we can add the new ticket as a relation to the new datetime
693
-                // and make sure its added to our cached $cloned_tickets array
694
-                // for use with later datetimes that have the same ticket.
695
-                $new_dtt->_add_relation_to($new_tkt, 'Ticket');
696
-                $new_dtt->save();
697
-                $cloned_tickets[ $orig_tkt->ID() ] = $new_tkt;
698
-            }
699
-        }
700
-        // clone taxonomy information
701
-        $taxonomies_to_clone_with = apply_filters(
702
-            'FHEE__Extend_Events_Admin_Page___duplicate_event__taxonomies_to_clone',
703
-            ['espresso_event_categories', 'espresso_event_type', 'post_tag']
704
-        );
705
-        // get terms for original event (notice)
706
-        $orig_terms = wp_get_object_terms($orig_event->ID(), $taxonomies_to_clone_with);
707
-        // loop through terms and add them to new event.
708
-        foreach ($orig_terms as $term) {
709
-            wp_set_object_terms($new_event->ID(), $term->term_id, $term->taxonomy, true);
710
-        }
711
-
712
-        // duplicate other core WP_Post items for this event.
713
-        // post thumbnail (feature image).
714
-        $feature_image_id = get_post_thumbnail_id($orig_event->ID());
715
-        if ($feature_image_id) {
716
-            update_post_meta($new_event->ID(), '_thumbnail_id', $feature_image_id);
717
-        }
718
-
719
-        // duplicate page_template setting
720
-        $page_template = get_post_meta($orig_event->ID(), '_wp_page_template', true);
721
-        if ($page_template) {
722
-            update_post_meta($new_event->ID(), '_wp_page_template', $page_template);
723
-        }
724
-
725
-        do_action('AHEE__Extend_Events_Admin_Page___duplicate_event__after', $new_event, $orig_event);
726
-        // now let's redirect to the edit page for this duplicated event if we have a new event id.
727
-        if ($new_event->ID()) {
728
-            $redirect_args = [
729
-                'post'   => $new_event->ID(),
730
-                'action' => 'edit',
731
-            ];
732
-            EE_Error::add_success(
733
-                esc_html__(
734
-                    'Event successfully duplicated.  Please review the details below and make any necessary edits',
735
-                    'event_espresso'
736
-                )
737
-            );
738
-        } else {
739
-            $redirect_args = [
740
-                'action' => 'default',
741
-            ];
742
-            EE_Error::add_error(
743
-                esc_html__('Not able to duplicate event.  Something went wrong.', 'event_espresso'),
744
-                __FILE__,
745
-                __FUNCTION__,
746
-                __LINE__
747
-            );
748
-        }
749
-        $this->_redirect_after_action(false, '', '', $redirect_args, true);
750
-    }
751
-
752
-
753
-    /**
754
-     * Generates output for the import page.
755
-     *
756
-     * @throws DomainException
757
-     * @throws EE_Error
758
-     * @throws InvalidArgumentException
759
-     * @throws InvalidDataTypeException
760
-     * @throws InvalidInterfaceException
761
-     */
762
-    protected function _import_page()
763
-    {
764
-        $title = esc_html__('Import', 'event_espresso');
765
-        $intro = esc_html__(
766
-            'If you have a previously exported Event Espresso 4 information in a Comma Separated Value (CSV) file format, you can upload the file here: ',
767
-            'event_espresso'
768
-        );
769
-        $form_url = EVENTS_ADMIN_URL;
770
-        $action = 'import_events';
771
-        $type = 'csv';
772
-        $this->_template_args['form'] = EE_Import::instance()->upload_form(
773
-            $title,
774
-            $intro,
775
-            $form_url,
776
-            $action,
777
-            $type
778
-        );
779
-        $this->_template_args['sample_file_link'] = EE_Admin_Page::add_query_args_and_nonce(
780
-            ['action' => 'sample_export_file'],
781
-            $this->_admin_base_url
782
-        );
783
-        $content = EEH_Template::display_template(
784
-            EVENTS_CAF_TEMPLATE_PATH . 'import_page.template.php',
785
-            $this->_template_args,
786
-            true
787
-        );
788
-        $this->_template_args['admin_page_content'] = $content;
789
-        $this->display_admin_page_with_sidebar();
790
-    }
791
-
792
-
793
-    /**
794
-     * _import_events
795
-     * This handles displaying the screen and running imports for importing events.
796
-     *
797
-     * @return void
798
-     * @throws EE_Error
799
-     * @throws InvalidArgumentException
800
-     * @throws InvalidDataTypeException
801
-     * @throws InvalidInterfaceException
802
-     */
803
-    protected function _import_events()
804
-    {
805
-        require_once(EE_CLASSES . 'EE_Import.class.php');
806
-        $success = EE_Import::instance()->import();
807
-        $this->_redirect_after_action($success, 'Import File', 'ran', ['action' => 'import_page'], true);
808
-    }
809
-
810
-
811
-    /**
812
-     * _events_export
813
-     * Will export all (or just the given event) to a Excel compatible file.
814
-     *
815
-     * @access protected
816
-     * @return void
817
-     */
818
-    protected function _events_export()
819
-    {
820
-        if (isset($this->_req_data['EVT_ID'])) {
821
-            $event_ids = $this->_req_data['EVT_ID'];
822
-        } elseif (isset($this->_req_data['EVT_IDs'])) {
823
-            $event_ids = $this->_req_data['EVT_IDs'];
824
-        } else {
825
-            $event_ids = null;
826
-        }
827
-        // todo: I don't like doing this but it'll do until we modify EE_Export Class.
828
-        $new_request_args = [
829
-            'export' => 'report',
830
-            'action' => 'all_event_data',
831
-            'EVT_ID' => $event_ids,
832
-        ];
833
-        $this->_req_data = array_merge($this->_req_data, $new_request_args);
834
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
835
-            require_once(EE_CLASSES . 'EE_Export.class.php');
836
-            $EE_Export = EE_Export::instance($this->_req_data);
837
-            if ($EE_Export instanceof EE_Export) {
838
-                $EE_Export->export();
839
-            }
840
-        }
841
-    }
842
-
843
-
844
-    /**
845
-     * handle category exports()
846
-     *
847
-     * @return void
848
-     */
849
-    protected function _categories_export()
850
-    {
851
-        // todo: I don't like doing this but it'll do until we modify EE_Export Class.
852
-        $new_request_args = [
853
-            'export'       => 'report',
854
-            'action'       => 'categories',
855
-            'category_ids' => $this->_req_data['EVT_CAT_ID'],
856
-        ];
857
-        $this->_req_data = array_merge($this->_req_data, $new_request_args);
858
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
859
-            require_once(EE_CLASSES . 'EE_Export.class.php');
860
-            $EE_Export = EE_Export::instance($this->_req_data);
861
-            if ($EE_Export instanceof EE_Export) {
862
-                $EE_Export->export();
863
-            }
864
-        }
865
-    }
866
-
867
-
868
-    /**
869
-     * Creates a sample CSV file for importing
870
-     */
871
-    protected function _sample_export_file()
872
-    {
873
-        $EE_Export = EE_Export::instance();
874
-        if ($EE_Export instanceof EE_Export) {
875
-            $EE_Export->export();
876
-        }
877
-    }
878
-
879
-
880
-    /*************        Template Settings        *************/
881
-    /**
882
-     * Generates template settings page output
883
-     *
884
-     * @throws DomainException
885
-     * @throws EE_Error
886
-     * @throws InvalidArgumentException
887
-     * @throws InvalidDataTypeException
888
-     * @throws InvalidInterfaceException
889
-     */
890
-    protected function _template_settings()
891
-    {
892
-        $this->_template_args['values'] = $this->_yes_no_values;
893
-        /**
894
-         * Note leaving this filter in for backward compatibility this was moved in 4.6.x
895
-         * from General_Settings_Admin_Page to here.
896
-         */
897
-        $this->_template_args = apply_filters(
898
-            'FHEE__General_Settings_Admin_Page__template_settings__template_args',
899
-            $this->_template_args
900
-        );
901
-        $this->_set_add_edit_form_tags('update_template_settings');
902
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
903
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
904
-            EVENTS_CAF_TEMPLATE_PATH . 'template_settings.template.php',
905
-            $this->_template_args,
906
-            true
907
-        );
908
-        $this->display_admin_page_with_sidebar();
909
-    }
910
-
911
-
912
-    /**
913
-     * Handler for updating template settings.
914
-     *
915
-     * @throws EE_Error
916
-     * @throws InvalidArgumentException
917
-     * @throws InvalidDataTypeException
918
-     * @throws InvalidInterfaceException
919
-     */
920
-    protected function _update_template_settings()
921
-    {
922
-        /**
923
-         * Note leaving this filter in for backward compatibility this was moved in 4.6.x
924
-         * from General_Settings_Admin_Page to here.
925
-         */
926
-        EE_Registry::instance()->CFG->template_settings = apply_filters(
927
-            'FHEE__General_Settings_Admin_Page__update_template_settings__data',
928
-            EE_Registry::instance()->CFG->template_settings,
929
-            $this->_req_data
930
-        );
931
-        // update custom post type slugs and detect if we need to flush rewrite rules
932
-        $old_slug = EE_Registry::instance()->CFG->core->event_cpt_slug;
933
-        EE_Registry::instance()->CFG->core->event_cpt_slug = empty($this->_req_data['event_cpt_slug'])
934
-            ? EE_Registry::instance()->CFG->core->event_cpt_slug
935
-            : EEH_URL::slugify($this->_req_data['event_cpt_slug'], 'events');
936
-        $what = 'Template Settings';
937
-        $success = $this->_update_espresso_configuration(
938
-            $what,
939
-            EE_Registry::instance()->CFG->template_settings,
940
-            __FILE__,
941
-            __FUNCTION__,
942
-            __LINE__
943
-        );
944
-        if (EE_Registry::instance()->CFG->core->event_cpt_slug !== $old_slug) {
945
-            /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
946
-            $rewrite_rules = LoaderFactory::getLoader()->getShared(
947
-                'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
948
-            );
949
-            $rewrite_rules->flush();
950
-        }
951
-        $this->_redirect_after_action($success, $what, 'updated', ['action' => 'template_settings']);
952
-    }
953
-
954
-
955
-    /**
956
-     * _premium_event_editor_meta_boxes
957
-     * add all metaboxes related to the event_editor
958
-     *
959
-     * @access protected
960
-     * @return void
961
-     * @throws EE_Error
962
-     * @throws InvalidArgumentException
963
-     * @throws InvalidDataTypeException
964
-     * @throws InvalidInterfaceException
965
-     * @throws ReflectionException
966
-     */
967
-    protected function _premium_event_editor_meta_boxes()
968
-    {
969
-        $this->verify_cpt_object();
970
-        /** @var FeatureFlags $flags */
971
-        $flags = $this->loader->getShared('EventEspresso\core\domain\services\capabilities\FeatureFlags');
972
-        // check if the new EDTR reg options meta box is being used, and if so, don't load the legacy version
973
-        if (! $this->admin_config->useAdvancedEditor() || ! $flags->featureAllowed('use_reg_options_meta_box')) {
974
-            add_meta_box(
975
-                'espresso_event_editor_event_options',
976
-                esc_html__('Event Registration Options', 'event_espresso'),
977
-                [$this, 'registration_options_meta_box'],
978
-                $this->page_slug,
979
-                'side',
980
-                'core'
981
-            );
982
-        }
983
-    }
984
-
985
-
986
-    /**
987
-     * override caf metabox
988
-     *
989
-     * @return void
990
-     * @throws DomainException
991
-     * @throws EE_Error
992
-     */
993
-    public function registration_options_meta_box()
994
-    {
995
-        $yes_no_values = [
996
-            ['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
997
-            ['id' => false, 'text' => esc_html__('No', 'event_espresso')],
998
-        ];
999
-        $default_reg_status_values = EEM_Registration::reg_status_array(
1000
-            [
1001
-                EEM_Registration::status_id_cancelled,
1002
-                EEM_Registration::status_id_declined,
1003
-                EEM_Registration::status_id_incomplete,
1004
-                EEM_Registration::status_id_wait_list,
1005
-            ],
1006
-            true
1007
-        );
1008
-        $template_args['active_status'] = $this->_cpt_model_obj->pretty_active_status(false);
1009
-        $template_args['_event'] = $this->_cpt_model_obj;
1010
-        $template_args['additional_limit'] = $this->_cpt_model_obj->additional_limit();
1011
-        $template_args['default_registration_status'] = EEH_Form_Fields::select_input(
1012
-            'default_reg_status',
1013
-            $default_reg_status_values,
1014
-            $this->_cpt_model_obj->default_registration_status()
1015
-        );
1016
-        $template_args['display_description'] = EEH_Form_Fields::select_input(
1017
-            'display_desc',
1018
-            $yes_no_values,
1019
-            $this->_cpt_model_obj->display_description()
1020
-        );
1021
-        $template_args['display_ticket_selector'] = EEH_Form_Fields::select_input(
1022
-            'display_ticket_selector',
1023
-            $yes_no_values,
1024
-            $this->_cpt_model_obj->display_ticket_selector(),
1025
-            '',
1026
-            '',
1027
-            false
1028
-        );
1029
-        $template_args['EVT_default_registration_status'] = EEH_Form_Fields::select_input(
1030
-            'EVT_default_registration_status',
1031
-            $default_reg_status_values,
1032
-            $this->_cpt_model_obj->default_registration_status()
1033
-        );
1034
-        $template_args['additional_registration_options'] = apply_filters(
1035
-            'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1036
-            '',
1037
-            $template_args,
1038
-            $yes_no_values,
1039
-            $default_reg_status_values
1040
-        );
1041
-        EEH_Template::display_template(
1042
-            EVENTS_CAF_TEMPLATE_PATH . 'event_registration_options.template.php',
1043
-            $template_args
1044
-        );
1045
-    }
1046
-
1047
-
1048
-
1049
-    /**
1050
-     * wp_list_table_mods for caf
1051
-     * ============================
1052
-     */
1053
-    /**
1054
-     * hook into list table filters and provide filters for caffeinated list table
1055
-     *
1056
-     * @param array $old_filters    any existing filters present
1057
-     * @param array $list_table_obj the list table object
1058
-     * @return array                  new filters
1059
-     * @throws EE_Error
1060
-     * @throws InvalidArgumentException
1061
-     * @throws InvalidDataTypeException
1062
-     * @throws InvalidInterfaceException
1063
-     * @throws ReflectionException
1064
-     */
1065
-    public function list_table_filters($old_filters, $list_table_obj)
1066
-    {
1067
-        $filters = [];
1068
-        // first month/year filters
1069
-        $filters[] = $this->espresso_event_months_dropdown();
1070
-        $status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1071
-        // active status dropdown
1072
-        if ($status !== 'draft') {
1073
-            $filters[] = $this->active_status_dropdown(
1074
-                isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : ''
1075
-            );
1076
-            $filters[] = $this->venuesDropdown(
1077
-                isset($this->_req_data['venue']) ? $this->_req_data['venue'] : ''
1078
-            );
1079
-        }
1080
-        // category filter
1081
-        $filters[] = $this->category_dropdown();
1082
-        return array_merge($old_filters, $filters);
1083
-    }
1084
-
1085
-
1086
-    /**
1087
-     * espresso_event_months_dropdown
1088
-     *
1089
-     * @access public
1090
-     * @return string                dropdown listing month/year selections for events.
1091
-     */
1092
-    public function espresso_event_months_dropdown()
1093
-    {
1094
-        // what we need to do is get all PRIMARY datetimes for all events to filter on.
1095
-        // Note we need to include any other filters that are set!
1096
-        $status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1097
-        // categories?
1098
-        $category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
1099
-            ? $this->_req_data['EVT_CAT']
1100
-            : null;
1101
-        // active status?
1102
-        $active_status = isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : null;
1103
-        $cur_date = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
1104
-        return EEH_Form_Fields::generate_event_months_dropdown($cur_date, $status, $category, $active_status);
1105
-    }
1106
-
1107
-
1108
-    /**
1109
-     * returns a list of "active" statuses on the event
1110
-     *
1111
-     * @param string $current_value whatever the current active status is
1112
-     * @return string
1113
-     */
1114
-    public function active_status_dropdown($current_value = '')
1115
-    {
1116
-        $select_name = 'active_status';
1117
-        $values = [
1118
-            'none'     => esc_html__('Show Active/Inactive', 'event_espresso'),
1119
-            'active'   => esc_html__('Active', 'event_espresso'),
1120
-            'upcoming' => esc_html__('Upcoming', 'event_espresso'),
1121
-            'expired'  => esc_html__('Expired', 'event_espresso'),
1122
-            'inactive' => esc_html__('Inactive', 'event_espresso'),
1123
-        ];
1124
-
1125
-        return EEH_Form_Fields::select_input($select_name, $values, $current_value, '', 'wide');
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * returns a list of "venues"
1131
-     *
1132
-     * @param string $current_value whatever the current active status is
1133
-     * @return string
1134
-     * @throws EE_Error
1135
-     * @throws InvalidArgumentException
1136
-     * @throws InvalidDataTypeException
1137
-     * @throws InvalidInterfaceException
1138
-     * @throws ReflectionException
1139
-     */
1140
-    protected function venuesDropdown($current_value = '')
1141
-    {
1142
-        $select_name = 'venue';
1143
-        $values = [
1144
-            '' => esc_html__('All Venues', 'event_espresso'),
1145
-        ];
1146
-        // populate the list of venues.
1147
-        $venue_model = EE_Registry::instance()->load_model('Venue');
1148
-        $venues = $venue_model->get_all(['order_by' => ['VNU_name' => 'ASC']]);
1149
-
1150
-        foreach ($venues as $venue) {
1151
-            $values[ $venue->ID() ] = $venue->name();
1152
-        }
1153
-
1154
-        return EEH_Form_Fields::select_input($select_name, $values, $current_value, '', 'wide');
1155
-    }
1156
-
1157
-
1158
-    /**
1159
-     * output a dropdown of the categories for the category filter on the event admin list table
1160
-     *
1161
-     * @access  public
1162
-     * @return string html
1163
-     */
1164
-    public function category_dropdown()
1165
-    {
1166
-        $cur_cat = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
1167
-        return EEH_Form_Fields::generate_event_category_dropdown($cur_cat);
1168
-    }
1169
-
1170
-
1171
-    /**
1172
-     * get total number of events today
1173
-     *
1174
-     * @access public
1175
-     * @return int
1176
-     * @throws EE_Error
1177
-     * @throws InvalidArgumentException
1178
-     * @throws InvalidDataTypeException
1179
-     * @throws InvalidInterfaceException
1180
-     */
1181
-    public function total_events_today()
1182
-    {
1183
-        $start = EEM_Datetime::instance()->convert_datetime_for_query(
1184
-            'DTT_EVT_start',
1185
-            date('Y-m-d') . ' 00:00:00',
1186
-            'Y-m-d H:i:s',
1187
-            'UTC'
1188
-        );
1189
-        $end = EEM_Datetime::instance()->convert_datetime_for_query(
1190
-            'DTT_EVT_start',
1191
-            date('Y-m-d') . ' 23:59:59',
1192
-            'Y-m-d H:i:s',
1193
-            'UTC'
1194
-        );
1195
-        $where = [
1196
-            'Datetime.DTT_EVT_start' => ['BETWEEN', [$start, $end]],
1197
-        ];
1198
-        return EEM_Event::instance()->count([$where, 'caps' => 'read_admin'], 'EVT_ID', true);
1199
-    }
1200
-
1201
-
1202
-    /**
1203
-     * get total number of events this month
1204
-     *
1205
-     * @access public
1206
-     * @return int
1207
-     * @throws EE_Error
1208
-     * @throws InvalidArgumentException
1209
-     * @throws InvalidDataTypeException
1210
-     * @throws InvalidInterfaceException
1211
-     */
1212
-    public function total_events_this_month()
1213
-    {
1214
-        // Dates
1215
-        $this_year_r = date('Y');
1216
-        $this_month_r = date('m');
1217
-        $days_this_month = date('t');
1218
-        $start = EEM_Datetime::instance()->convert_datetime_for_query(
1219
-            'DTT_EVT_start',
1220
-            $this_year_r . '-' . $this_month_r . '-01 00:00:00',
1221
-            'Y-m-d H:i:s',
1222
-            'UTC'
1223
-        );
1224
-        $end = EEM_Datetime::instance()->convert_datetime_for_query(
1225
-            'DTT_EVT_start',
1226
-            $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' 23:59:59',
1227
-            'Y-m-d H:i:s',
1228
-            'UTC'
1229
-        );
1230
-        $where = [
1231
-            'Datetime.DTT_EVT_start' => ['BETWEEN', [$start, $end]],
1232
-        ];
1233
-        return EEM_Event::instance()->count([$where, 'caps' => 'read_admin'], 'EVT_ID', true);
1234
-    }
1235
-
1236
-
1237
-    /** DEFAULT TICKETS STUFF **/
1238
-
1239
-    /**
1240
-     * Output default tickets list table view.
1241
-     *
1242
-     * @throws DomainException
1243
-     * @throws EE_Error
1244
-     * @throws InvalidArgumentException
1245
-     * @throws InvalidDataTypeException
1246
-     * @throws InvalidInterfaceException
1247
-     */
1248
-    public function _tickets_overview_list_table()
1249
-    {
1250
-        $this->_search_btn_label = esc_html__('Tickets', 'event_espresso');
1251
-        $this->display_admin_list_table_page_with_no_sidebar();
1252
-    }
1253
-
1254
-
1255
-    /**
1256
-     * @param int  $per_page
1257
-     * @param bool $count
1258
-     * @param bool $trashed
1259
-     * @return EE_Soft_Delete_Base_Class[]|int
1260
-     * @throws EE_Error
1261
-     * @throws InvalidArgumentException
1262
-     * @throws InvalidDataTypeException
1263
-     * @throws InvalidInterfaceException
1264
-     */
1265
-    public function get_default_tickets($per_page = 10, $count = false, $trashed = false)
1266
-    {
1267
-        $orderby = empty($this->_req_data['orderby']) ? 'TKT_name' : $this->_req_data['orderby'];
1268
-        $order = empty($this->_req_data['order']) ? 'ASC' : $this->_req_data['order'];
1269
-        switch ($orderby) {
1270
-            case 'TKT_name':
1271
-                $orderby = ['TKT_name' => $order];
1272
-                break;
1273
-            case 'TKT_price':
1274
-                $orderby = ['TKT_price' => $order];
1275
-                break;
1276
-            case 'TKT_uses':
1277
-                $orderby = ['TKT_uses' => $order];
1278
-                break;
1279
-            case 'TKT_min':
1280
-                $orderby = ['TKT_min' => $order];
1281
-                break;
1282
-            case 'TKT_max':
1283
-                $orderby = ['TKT_max' => $order];
1284
-                break;
1285
-            case 'TKT_qty':
1286
-                $orderby = ['TKT_qty' => $order];
1287
-                break;
1288
-        }
1289
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1290
-            ? $this->_req_data['paged']
1291
-            : 1;
1292
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1293
-            ? $this->_req_data['perpage']
1294
-            : $per_page;
1295
-        $_where = [
1296
-            'TKT_is_default' => 1,
1297
-            'TKT_deleted'    => $trashed,
1298
-        ];
1299
-        $offset = ($current_page - 1) * $per_page;
1300
-        $limit = [$offset, $per_page];
1301
-        if (isset($this->_req_data['s'])) {
1302
-            $sstr = '%' . $this->_req_data['s'] . '%';
1303
-            $_where['OR'] = [
1304
-                'TKT_name'        => ['LIKE', $sstr],
1305
-                'TKT_description' => ['LIKE', $sstr],
1306
-            ];
1307
-        }
1308
-        $query_params = [
1309
-            $_where,
1310
-            'order_by' => $orderby,
1311
-            'limit'    => $limit,
1312
-            'group_by' => 'TKT_ID',
1313
-        ];
1314
-        if ($count) {
1315
-            return EEM_Ticket::instance()->count_deleted_and_undeleted([$_where]);
1316
-        }
1317
-        return EEM_Ticket::instance()->get_all_deleted_and_undeleted($query_params);
1318
-    }
1319
-
1320
-
1321
-    /**
1322
-     * @param bool $trash
1323
-     * @throws EE_Error
1324
-     * @throws InvalidArgumentException
1325
-     * @throws InvalidDataTypeException
1326
-     * @throws InvalidInterfaceException
1327
-     */
1328
-    protected function _trash_or_restore_ticket($trash = false)
1329
-    {
1330
-        $success = 1;
1331
-        $TKT = EEM_Ticket::instance();
1332
-        // checkboxes?
1333
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1334
-            // if array has more than one element then success message should be plural
1335
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1336
-            // cycle thru the boxes
1337
-            foreach ($this->_req_data['checkbox'] as $TKT_ID) {
1338
-                if ($trash) {
1339
-                    if (! $TKT->delete_by_ID($TKT_ID)) {
1340
-                        $success = 0;
1341
-                    }
1342
-                } elseif (! $TKT->restore_by_ID($TKT_ID)) {
1343
-                    $success = 0;
1344
-                }
1345
-            }
1346
-        } else {
1347
-            // grab single id and trash
1348
-            $TKT_ID = absint($this->_req_data['TKT_ID']);
1349
-            if ($trash) {
1350
-                if (! $TKT->delete_by_ID($TKT_ID)) {
1351
-                    $success = 0;
1352
-                }
1353
-            } elseif (! $TKT->restore_by_ID($TKT_ID)) {
1354
-                $success = 0;
1355
-            }
1356
-        }
1357
-        $action_desc = $trash ? 'moved to the trash' : 'restored';
1358
-        $query_args = [
1359
-            'action' => 'ticket_list_table',
1360
-            'status' => $trash ? '' : 'trashed',
1361
-        ];
1362
-        $this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1363
-    }
1364
-
1365
-
1366
-    /**
1367
-     * Handles trashing default ticket.
1368
-     *
1369
-     * @throws EE_Error
1370
-     * @throws InvalidArgumentException
1371
-     * @throws InvalidDataTypeException
1372
-     * @throws InvalidInterfaceException
1373
-     * @throws ReflectionException
1374
-     */
1375
-    protected function _delete_ticket()
1376
-    {
1377
-        $success = 1;
1378
-        // checkboxes?
1379
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1380
-            // if array has more than one element then success message should be plural
1381
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1382
-            // cycle thru the boxes
1383
-            foreach ($this->_req_data['checkbox'] as $TKT_ID) {
1384
-                // delete
1385
-                if (! $this->_delete_the_ticket($TKT_ID)) {
1386
-                    $success = 0;
1387
-                }
1388
-            }
1389
-        } else {
1390
-            // grab single id and trash
1391
-            $TKT_ID = absint($this->_req_data['TKT_ID']);
1392
-            if (! $this->_delete_the_ticket($TKT_ID)) {
1393
-                $success = 0;
1394
-            }
1395
-        }
1396
-        $action_desc = 'deleted';
1397
-        // fail safe.  If the default ticket count === 1 then we need to redirect to event overview.
1398
-        $ticket_count = EEM_Ticket::instance()->count_deleted_and_undeleted(
1399
-            [['TKT_is_default' => 1]],
1400
-            'TKT_ID',
1401
-            true
1402
-        );
1403
-        $query_args = $ticket_count
1404
-            ? []
1405
-            : [
1406
-                'action' => 'ticket_list_table',
1407
-                'status' => 'trashed',
1408
-            ];
1409
-        $this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1410
-    }
1411
-
1412
-
1413
-    /**
1414
-     * @param int $TKT_ID
1415
-     * @return bool|int
1416
-     * @throws EE_Error
1417
-     * @throws InvalidArgumentException
1418
-     * @throws InvalidDataTypeException
1419
-     * @throws InvalidInterfaceException
1420
-     * @throws ReflectionException
1421
-     */
1422
-    protected function _delete_the_ticket($TKT_ID)
1423
-    {
1424
-        $ticket = EEM_Ticket::instance()->get_one_by_ID($TKT_ID);
1425
-        if (! $ticket instanceof EE_Ticket) {
1426
-            return false;
1427
-        }
1428
-        $ticket->_remove_relations('Datetime');
1429
-        // delete all related prices first
1430
-        $ticket->delete_related_permanently('Price');
1431
-        return $ticket->delete_permanently();
1432
-    }
20
+	/**
21
+	 * @var EE_Admin_Config
22
+	 */
23
+	protected $admin_config;
24
+
25
+	/**
26
+	 * @var AdvancedEditorAdminFormSection
27
+	 */
28
+	protected $advanced_editor_admin_form;
29
+
30
+
31
+	/**
32
+	 * Extend_Events_Admin_Page constructor.
33
+	 *
34
+	 * @param bool $routing
35
+	 * @throws ReflectionException
36
+	 */
37
+	public function __construct($routing = true)
38
+	{
39
+		if (! defined('EVENTS_CAF_TEMPLATE_PATH')) {
40
+			define('EVENTS_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'events/templates/');
41
+			define('EVENTS_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'events/assets/');
42
+			define('EVENTS_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'events/assets/');
43
+		}
44
+		parent::__construct($routing);
45
+		$this->admin_config = $this->loader->getShared('EE_Admin_Config');
46
+	}
47
+
48
+
49
+	/**
50
+	 * Sets routes.
51
+	 *
52
+	 * @throws EE_Error
53
+	 * @throws InvalidArgumentException
54
+	 * @throws InvalidDataTypeException
55
+	 * @throws InvalidInterfaceException
56
+	 * @throws Exception
57
+	 */
58
+	protected function _extend_page_config()
59
+	{
60
+		$this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'events';
61
+		// is there a evt_id in the request?
62
+		$evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
63
+			? $this->_req_data['EVT_ID']
64
+			: 0;
65
+		$evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
66
+		// tkt_id?
67
+		$tkt_id = ! empty($this->_req_data['TKT_ID']) && ! is_array($this->_req_data['TKT_ID'])
68
+			? $this->_req_data['TKT_ID']
69
+			: 0;
70
+		$new_page_routes = [
71
+			'duplicate_event'          => [
72
+				'func'       => '_duplicate_event',
73
+				'capability' => 'ee_edit_event',
74
+				'obj_id'     => $evt_id,
75
+				'noheader'   => true,
76
+			],
77
+			'import_page'              => [
78
+				'func'       => '_import_page',
79
+				'capability' => 'import',
80
+			],
81
+			'import'                   => [
82
+				'func'       => '_import_events',
83
+				'capability' => 'import',
84
+				'noheader'   => true,
85
+			],
86
+			'import_events'            => [
87
+				'func'       => '_import_events',
88
+				'capability' => 'import',
89
+				'noheader'   => true,
90
+			],
91
+			'export_events'            => [
92
+				'func'       => '_events_export',
93
+				'capability' => 'export',
94
+				'noheader'   => true,
95
+			],
96
+			'export_categories'        => [
97
+				'func'       => '_categories_export',
98
+				'capability' => 'export',
99
+				'noheader'   => true,
100
+			],
101
+			'sample_export_file'       => [
102
+				'func'       => '_sample_export_file',
103
+				'capability' => 'export',
104
+				'noheader'   => true,
105
+			],
106
+			'update_template_settings' => [
107
+				'func'       => '_update_template_settings',
108
+				'capability' => 'manage_options',
109
+				'noheader'   => true,
110
+			],
111
+		];        // don't load these meta boxes if using the advanced editor
112
+		$this->_page_config['create_new']['metaboxes'][] = '_premium_event_editor_meta_boxes';
113
+		$this->_page_config['edit']['metaboxes'][] = '_premium_event_editor_meta_boxes';
114
+		if (! $this->admin_config->useAdvancedEditor()) {
115
+			$this->_page_config['create_new']['qtips'][] = 'EE_Event_Editor_Tips';
116
+			$this->_page_config['edit']['qtips'][] = 'EE_Event_Editor_Tips';
117
+
118
+			$legacy_editor_page_routes = [
119
+				'ticket_list_table' => [
120
+					'func'       => '_tickets_overview_list_table',
121
+					'capability' => 'ee_read_default_tickets',
122
+				],
123
+				'trash_ticket'      => [
124
+					'func'       => '_trash_or_restore_ticket',
125
+					'capability' => 'ee_delete_default_ticket',
126
+					'obj_id'     => $tkt_id,
127
+					'noheader'   => true,
128
+					'args'       => ['trash' => true],
129
+				],
130
+				'trash_tickets'     => [
131
+					'func'       => '_trash_or_restore_ticket',
132
+					'capability' => 'ee_delete_default_tickets',
133
+					'noheader'   => true,
134
+					'args'       => ['trash' => true],
135
+				],
136
+				'restore_ticket'    => [
137
+					'func'       => '_trash_or_restore_ticket',
138
+					'capability' => 'ee_delete_default_ticket',
139
+					'obj_id'     => $tkt_id,
140
+					'noheader'   => true,
141
+				],
142
+				'restore_tickets'   => [
143
+					'func'       => '_trash_or_restore_ticket',
144
+					'capability' => 'ee_delete_default_tickets',
145
+					'noheader'   => true,
146
+				],
147
+				'delete_ticket'     => [
148
+					'func'       => '_delete_ticket',
149
+					'capability' => 'ee_delete_default_ticket',
150
+					'obj_id'     => $tkt_id,
151
+					'noheader'   => true,
152
+				],
153
+				'delete_tickets'    => [
154
+					'func'       => '_delete_ticket',
155
+					'capability' => 'ee_delete_default_tickets',
156
+					'noheader'   => true,
157
+				],
158
+			];
159
+			$new_page_routes = array_merge($new_page_routes, $legacy_editor_page_routes);
160
+		}
161
+
162
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
163
+		// partial route/config override
164
+		$this->_page_config['import_events']['metaboxes'] = $this->_default_espresso_metaboxes;
165
+		$this->_page_config['default']['list_table'] = 'Extend_Events_Admin_List_Table';
166
+		// add tickets tab but only if there are more than one default ticket!
167
+		$tkt_count = EEM_Ticket::instance()->count_deleted_and_undeleted(
168
+			[['TKT_is_default' => 1]],
169
+			'TKT_ID',
170
+			true
171
+		);
172
+		if ($tkt_count > 1) {
173
+			$new_page_config = [
174
+				'ticket_list_table' => [
175
+					'nav'           => [
176
+						'label' => esc_html__('Default Tickets', 'event_espresso'),
177
+						'order' => 60,
178
+					],
179
+					'list_table'    => 'Tickets_List_Table',
180
+					'require_nonce' => false,
181
+				],
182
+			];
183
+		}
184
+		// template settings
185
+		$new_page_config['template_settings'] = [
186
+			'nav'           => [
187
+				'label' => esc_html__('Templates', 'event_espresso'),
188
+				'order' => 30,
189
+			],
190
+			'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
191
+			'help_tabs'     => [
192
+				'general_settings_templates_help_tab' => [
193
+					'title'    => esc_html__('Templates', 'event_espresso'),
194
+					'filename' => 'general_settings_templates',
195
+				],
196
+			],
197
+		   // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
198
+			// 'help_tour'     => ['Templates_Help_Tour'],
199
+			'require_nonce' => false,
200
+		];
201
+		$this->_page_config = array_merge($this->_page_config, $new_page_config);
202
+		// add filters and actions
203
+		// modifying _views
204
+		add_filter(
205
+			'FHEE_event_datetime_metabox_add_additional_date_time_template',
206
+			[$this, 'add_additional_datetime_button'],
207
+			10,
208
+			2
209
+		);
210
+		add_filter(
211
+			'FHEE_event_datetime_metabox_clone_button_template',
212
+			[$this, 'add_datetime_clone_button'],
213
+			10,
214
+			2
215
+		);
216
+		add_filter(
217
+			'FHEE_event_datetime_metabox_timezones_template',
218
+			[$this, 'datetime_timezones_template'],
219
+			10,
220
+			2
221
+		);
222
+		// filters for event list table
223
+		add_filter('FHEE__Extend_Events_Admin_List_Table__filters', [$this, 'list_table_filters'], 10, 2);
224
+		add_filter(
225
+			'FHEE__Events_Admin_List_Table__column_actions__action_links',
226
+			[$this, 'extra_list_table_actions'],
227
+			10,
228
+			2
229
+		);
230
+		// legend item
231
+		add_filter('FHEE__Events_Admin_Page___event_legend_items__items', [$this, 'additional_legend_items']);
232
+		add_action('admin_init', [$this, 'admin_init']);
233
+		// load additional handlers
234
+		$this->handleActionRequest();
235
+	}
236
+
237
+
238
+	private function getRequestAction()
239
+	{
240
+		return isset($this->_req_data['action']) ? sanitize_key($this->_req_data['action']) : null;
241
+	}
242
+
243
+
244
+	/**
245
+	 * @throws Exception
246
+	 */
247
+	private function handleActionRequest()
248
+	{
249
+		$action = $this->getRequestAction();
250
+		if ($action) {
251
+			// setup Advanced Editor ???
252
+			if ($action === 'default_event_settings' || $action === 'update_default_event_settings') {
253
+				$this->advanced_editor_admin_form = $this->loader->getShared(
254
+					'EventEspresso\core\domain\services\admin\events\default_settings\AdvancedEditorAdminFormSection'
255
+				);
256
+			}
257
+		}
258
+	}
259
+
260
+
261
+	/**
262
+	 * admin_init
263
+	 */
264
+	public function admin_init()
265
+	{
266
+		EE_Registry::$i18n_js_strings = array_merge(
267
+			EE_Registry::$i18n_js_strings,
268
+			[
269
+				'image_confirm'          => esc_html__(
270
+					'Do you really want to delete this image? Please remember to update your event to complete the removal.',
271
+					'event_espresso'
272
+				),
273
+				'event_starts_on'        => esc_html__('Event Starts on', 'event_espresso'),
274
+				'event_ends_on'          => esc_html__('Event Ends on', 'event_espresso'),
275
+				'event_datetime_actions' => esc_html__('Actions', 'event_espresso'),
276
+				'event_clone_dt_msg'     => esc_html__('Clone this Event Date and Time', 'event_espresso'),
277
+				'remove_event_dt_msg'    => esc_html__('Remove this Event Time', 'event_espresso'),
278
+			]
279
+		);
280
+	}
281
+
282
+
283
+	/**
284
+	 * Add per page screen options to the default ticket list table view.
285
+	 *
286
+	 * @throws InvalidArgumentException
287
+	 * @throws InvalidDataTypeException
288
+	 * @throws InvalidInterfaceException
289
+	 */
290
+	protected function _add_screen_options_ticket_list_table()
291
+	{
292
+		$this->_per_page_screen_option();
293
+	}
294
+
295
+
296
+	/**
297
+	 * @param string $return
298
+	 * @param int    $id
299
+	 * @param string $new_title
300
+	 * @param string $new_slug
301
+	 * @return string
302
+	 */
303
+	public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
304
+	{
305
+		$return = parent::extra_permalink_field_buttons($return, $id, $new_title, $new_slug);
306
+		// make sure this is only when editing
307
+		if (! empty($id)) {
308
+			$href = EE_Admin_Page::add_query_args_and_nonce(
309
+				['action' => 'duplicate_event', 'EVT_ID' => $id],
310
+				$this->_admin_base_url
311
+			);
312
+			$title = esc_attr__('Duplicate Event', 'event_espresso');
313
+			$return .= '<a href="'
314
+					   . $href
315
+					   . '" title="'
316
+					   . $title
317
+					   . '" id="ee-duplicate-event-button" class="button button-small"  value="duplicate_event">'
318
+					   . $title
319
+					   . '</a>';
320
+		}
321
+		return $return;
322
+	}
323
+
324
+
325
+	/**
326
+	 * Set the list table views for the default ticket list table view.
327
+	 */
328
+	public function _set_list_table_views_ticket_list_table()
329
+	{
330
+		$this->_views = [
331
+			'all'     => [
332
+				'slug'        => 'all',
333
+				'label'       => esc_html__('All', 'event_espresso'),
334
+				'count'       => 0,
335
+				'bulk_action' => [
336
+					'trash_tickets' => esc_html__('Move to Trash', 'event_espresso'),
337
+				],
338
+			],
339
+			'trashed' => [
340
+				'slug'        => 'trashed',
341
+				'label'       => esc_html__('Trash', 'event_espresso'),
342
+				'count'       => 0,
343
+				'bulk_action' => [
344
+					'restore_tickets' => esc_html__('Restore from Trash', 'event_espresso'),
345
+					'delete_tickets'  => esc_html__('Delete Permanently', 'event_espresso'),
346
+				],
347
+			],
348
+		];
349
+	}
350
+
351
+
352
+	/**
353
+	 * Enqueue scripts and styles for the event editor.
354
+	 */
355
+	public function load_scripts_styles_edit()
356
+	{
357
+		if (! $this->admin_config->useAdvancedEditor()) {
358
+			wp_register_script(
359
+				'ee-event-editor-heartbeat',
360
+				EVENTS_CAF_ASSETS_URL . 'event-editor-heartbeat.js',
361
+				['ee_admin_js', 'heartbeat'],
362
+				EVENT_ESPRESSO_VERSION,
363
+				true
364
+			);
365
+			wp_enqueue_script('ee-accounting');
366
+			wp_enqueue_script('ee-event-editor-heartbeat');
367
+		}
368
+		wp_enqueue_script('event_editor_js');
369
+		// styles
370
+		wp_enqueue_style('espresso-ui-theme');
371
+	}
372
+
373
+
374
+	/**
375
+	 * Returns template for the additional datetime.
376
+	 *
377
+	 * @param $template
378
+	 * @param $template_args
379
+	 * @return mixed
380
+	 * @throws DomainException
381
+	 */
382
+	public function add_additional_datetime_button($template, $template_args)
383
+	{
384
+		return EEH_Template::display_template(
385
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_add_additional_time.template.php',
386
+			$template_args,
387
+			true
388
+		);
389
+	}
390
+
391
+
392
+	/**
393
+	 * Returns the template for cloning a datetime.
394
+	 *
395
+	 * @param $template
396
+	 * @param $template_args
397
+	 * @return mixed
398
+	 * @throws DomainException
399
+	 */
400
+	public function add_datetime_clone_button($template, $template_args)
401
+	{
402
+		return EEH_Template::display_template(
403
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_metabox_clone_button.template.php',
404
+			$template_args,
405
+			true
406
+		);
407
+	}
408
+
409
+
410
+	/**
411
+	 * Returns the template for datetime timezones.
412
+	 *
413
+	 * @param $template
414
+	 * @param $template_args
415
+	 * @return mixed
416
+	 * @throws DomainException
417
+	 */
418
+	public function datetime_timezones_template($template, $template_args)
419
+	{
420
+		return EEH_Template::display_template(
421
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_timezones.template.php',
422
+			$template_args,
423
+			true
424
+		);
425
+	}
426
+
427
+
428
+	/**
429
+	 * Sets the views for the default list table view.
430
+	 *
431
+	 * @throws EE_Error
432
+	 */
433
+	protected function _set_list_table_views_default()
434
+	{
435
+		parent::_set_list_table_views_default();
436
+		$new_views = [
437
+			'today' => [
438
+				'slug'        => 'today',
439
+				'label'       => esc_html__('Today', 'event_espresso'),
440
+				'count'       => $this->total_events_today(),
441
+				'bulk_action' => [
442
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
443
+				],
444
+			],
445
+			'month' => [
446
+				'slug'        => 'month',
447
+				'label'       => esc_html__('This Month', 'event_espresso'),
448
+				'count'       => $this->total_events_this_month(),
449
+				'bulk_action' => [
450
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
451
+				],
452
+			],
453
+		];
454
+		$this->_views = array_merge($this->_views, $new_views);
455
+	}
456
+
457
+
458
+	/**
459
+	 * Returns the extra action links for the default list table view.
460
+	 *
461
+	 * @param array    $action_links
462
+	 * @param EE_Event $event
463
+	 * @return array
464
+	 * @throws EE_Error
465
+	 * @throws InvalidArgumentException
466
+	 * @throws InvalidDataTypeException
467
+	 * @throws InvalidInterfaceException
468
+	 * @throws ReflectionException
469
+	 */
470
+	public function extra_list_table_actions(array $action_links, EE_Event $event)
471
+	{
472
+		if (
473
+			EE_Registry::instance()->CAP->current_user_can(
474
+				'ee_read_registrations',
475
+				'espresso_registrations_reports',
476
+				$event->ID()
477
+			)
478
+		) {
479
+			$reports_query_args = [
480
+				'action' => 'reports',
481
+				'EVT_ID' => $event->ID(),
482
+			];
483
+			$reports_link = EE_Admin_Page::add_query_args_and_nonce($reports_query_args, REG_ADMIN_URL);
484
+			$action_links[] = '<a href="'
485
+							  . $reports_link
486
+							  . '" title="'
487
+							  . esc_attr__('View Report', 'event_espresso')
488
+							  . '"><div class="dashicons dashicons-chart-bar"></div></a>'
489
+							  . "\n\t";
490
+		}
491
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
492
+			EE_Registry::instance()->load_helper('MSG_Template');
493
+			$action_links[] = EEH_MSG_Template::get_message_action_link(
494
+				'see_notifications_for',
495
+				null,
496
+				['EVT_ID' => $event->ID()]
497
+			);
498
+		}
499
+		return $action_links;
500
+	}
501
+
502
+
503
+	/**
504
+	 * @param $items
505
+	 * @return mixed
506
+	 */
507
+	public function additional_legend_items($items)
508
+	{
509
+		if (
510
+			EE_Registry::instance()->CAP->current_user_can(
511
+				'ee_read_registrations',
512
+				'espresso_registrations_reports'
513
+			)
514
+		) {
515
+			$items['reports'] = [
516
+				'class' => 'dashicons dashicons-chart-bar',
517
+				'desc'  => esc_html__('Event Reports', 'event_espresso'),
518
+			];
519
+		}
520
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
521
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
522
+			// $related_for_icon can sometimes be a string so 'css_class' would be an illegal offset
523
+			// (can only use numeric offsets when treating strings as arrays)
524
+			if (is_array($related_for_icon) && isset($related_for_icon['css_class'], $related_for_icon['label'])) {
525
+				$items['view_related_messages'] = [
526
+					'class' => $related_for_icon['css_class'],
527
+					'desc'  => $related_for_icon['label'],
528
+				];
529
+			}
530
+		}
531
+		return $items;
532
+	}
533
+
534
+
535
+	/**
536
+	 * This is the callback method for the duplicate event route
537
+	 * Method looks for 'EVT_ID' in the request and retrieves that event and its details and duplicates them
538
+	 * into a new event.  We add a hook so that any plugins that add extra event details can hook into this
539
+	 * action.  Note that the dupe will have **DUPLICATE** as its title and slug.
540
+	 * After duplication the redirect is to the new event edit page.
541
+	 *
542
+	 * @return void
543
+	 * @throws EE_Error If EE_Event is not available with given ID
544
+	 * @throws InvalidArgumentException
545
+	 * @throws InvalidDataTypeException
546
+	 * @throws InvalidInterfaceException
547
+	 * @throws ReflectionException
548
+	 * @access protected
549
+	 */
550
+	protected function _duplicate_event()
551
+	{
552
+		// first make sure the ID for the event is in the request.
553
+		//  If it isn't then we need to bail and redirect back to overview list table (cause how did we get here?)
554
+		if (! isset($this->_req_data['EVT_ID'])) {
555
+			EE_Error::add_error(
556
+				esc_html__(
557
+					'In order to duplicate an event an Event ID is required.  None was given.',
558
+					'event_espresso'
559
+				),
560
+				__FILE__,
561
+				__FUNCTION__,
562
+				__LINE__
563
+			);
564
+			$this->_redirect_after_action(false, '', '', [], true);
565
+			return;
566
+		}
567
+		// k we've got EVT_ID so let's use that to get the event we'll duplicate
568
+		$orig_event = EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']);
569
+		if (! $orig_event instanceof EE_Event) {
570
+			throw new EE_Error(
571
+				sprintf(
572
+					esc_html__('An EE_Event object could not be retrieved for the given ID (%s)', 'event_espresso'),
573
+					$this->_req_data['EVT_ID']
574
+				)
575
+			);
576
+		}
577
+		// k now let's clone the $orig_event before getting relations
578
+		$new_event = clone $orig_event;
579
+		// original datetimes
580
+		$orig_datetimes = $orig_event->get_many_related('Datetime');
581
+		// other original relations
582
+		$orig_ven = $orig_event->get_many_related('Venue');
583
+		// reset the ID and modify other details to make it clear this is a dupe
584
+		$new_event->set('EVT_ID', 0);
585
+		$new_name = $new_event->name() . ' ' . esc_html__('**DUPLICATE**', 'event_espresso');
586
+		$new_event->set('EVT_name', $new_name);
587
+		$new_event->set(
588
+			'EVT_slug',
589
+			wp_unique_post_slug(
590
+				sanitize_title($orig_event->name()),
591
+				0,
592
+				'publish',
593
+				'espresso_events',
594
+				0
595
+			)
596
+		);
597
+		$new_event->set('status', 'draft');
598
+		// duplicate discussion settings
599
+		$new_event->set('comment_status', $orig_event->get('comment_status'));
600
+		$new_event->set('ping_status', $orig_event->get('ping_status'));
601
+		// save the new event
602
+		$new_event->save();
603
+		// venues
604
+		foreach ($orig_ven as $ven) {
605
+			$new_event->_add_relation_to($ven, 'Venue');
606
+		}
607
+		$new_event->save();
608
+		// now we need to get the question group relations and handle that
609
+		// first primary question groups
610
+		$orig_primary_qgs = $orig_event->get_many_related(
611
+			'Question_Group',
612
+			[['Event_Question_Group.EQG_primary' => true]]
613
+		);
614
+		if (! empty($orig_primary_qgs)) {
615
+			foreach ($orig_primary_qgs as $id => $obj) {
616
+				if ($obj instanceof EE_Question_Group) {
617
+					$new_event->_add_relation_to($obj, 'Question_Group', ['EQG_primary' => true]);
618
+				}
619
+			}
620
+		}
621
+		// next additional attendee question groups
622
+		$orig_additional_qgs = $orig_event->get_many_related(
623
+			'Question_Group',
624
+			[['Event_Question_Group.EQG_additional' => true]]
625
+		);
626
+		if (! empty($orig_additional_qgs)) {
627
+			foreach ($orig_additional_qgs as $id => $obj) {
628
+				if ($obj instanceof EE_Question_Group) {
629
+					$new_event->_add_relation_to($obj, 'Question_Group', ['EQG_additional' => true]);
630
+				}
631
+			}
632
+		}
633
+
634
+		$new_event->save();
635
+
636
+		// k now that we have the new event saved we can loop through the datetimes and start adding relations.
637
+		$cloned_tickets = [];
638
+		foreach ($orig_datetimes as $orig_dtt) {
639
+			if (! $orig_dtt instanceof EE_Datetime) {
640
+				continue;
641
+			}
642
+			$new_dtt = clone $orig_dtt;
643
+			$orig_tkts = $orig_dtt->tickets();
644
+			// save new dtt then add to event
645
+			$new_dtt->set('DTT_ID', 0);
646
+			$new_dtt->set('DTT_sold', 0);
647
+			$new_dtt->set_reserved(0);
648
+			$new_dtt->save();
649
+			$new_event->_add_relation_to($new_dtt, 'Datetime');
650
+			$new_event->save();
651
+			// now let's get the ticket relations setup.
652
+			foreach ((array) $orig_tkts as $orig_tkt) {
653
+				// it's possible a datetime will have no tickets so let's verify we HAVE a ticket first.
654
+				if (! $orig_tkt instanceof EE_Ticket) {
655
+					continue;
656
+				}
657
+				// is this ticket archived?  If it is then let's skip
658
+				if ($orig_tkt->get('TKT_deleted')) {
659
+					continue;
660
+				}
661
+				// does this original ticket already exist in the clone_tickets cache?
662
+				//  If so we'll just use the new ticket from it.
663
+				if (isset($cloned_tickets[ $orig_tkt->ID() ])) {
664
+					$new_tkt = $cloned_tickets[ $orig_tkt->ID() ];
665
+				} else {
666
+					$new_tkt = clone $orig_tkt;
667
+					// get relations on the $orig_tkt that we need to setup.
668
+					$orig_prices = $orig_tkt->prices();
669
+					$new_tkt->set('TKT_ID', 0);
670
+					$new_tkt->set('TKT_sold', 0);
671
+					$new_tkt->set('TKT_reserved', 0);
672
+					$new_tkt->save(); // make sure new ticket has ID.
673
+					// price relations on new ticket need to be setup.
674
+					foreach ($orig_prices as $orig_price) {
675
+						$new_price = clone $orig_price;
676
+						$new_price->set('PRC_ID', 0);
677
+						$new_price->save();
678
+						$new_tkt->_add_relation_to($new_price, 'Price');
679
+						$new_tkt->save();
680
+					}
681
+
682
+					do_action(
683
+						'AHEE__Extend_Events_Admin_Page___duplicate_event__duplicate_ticket__after',
684
+						$orig_tkt,
685
+						$new_tkt,
686
+						$orig_prices,
687
+						$orig_event,
688
+						$orig_dtt,
689
+						$new_dtt
690
+					);
691
+				}
692
+				// k now we can add the new ticket as a relation to the new datetime
693
+				// and make sure its added to our cached $cloned_tickets array
694
+				// for use with later datetimes that have the same ticket.
695
+				$new_dtt->_add_relation_to($new_tkt, 'Ticket');
696
+				$new_dtt->save();
697
+				$cloned_tickets[ $orig_tkt->ID() ] = $new_tkt;
698
+			}
699
+		}
700
+		// clone taxonomy information
701
+		$taxonomies_to_clone_with = apply_filters(
702
+			'FHEE__Extend_Events_Admin_Page___duplicate_event__taxonomies_to_clone',
703
+			['espresso_event_categories', 'espresso_event_type', 'post_tag']
704
+		);
705
+		// get terms for original event (notice)
706
+		$orig_terms = wp_get_object_terms($orig_event->ID(), $taxonomies_to_clone_with);
707
+		// loop through terms and add them to new event.
708
+		foreach ($orig_terms as $term) {
709
+			wp_set_object_terms($new_event->ID(), $term->term_id, $term->taxonomy, true);
710
+		}
711
+
712
+		// duplicate other core WP_Post items for this event.
713
+		// post thumbnail (feature image).
714
+		$feature_image_id = get_post_thumbnail_id($orig_event->ID());
715
+		if ($feature_image_id) {
716
+			update_post_meta($new_event->ID(), '_thumbnail_id', $feature_image_id);
717
+		}
718
+
719
+		// duplicate page_template setting
720
+		$page_template = get_post_meta($orig_event->ID(), '_wp_page_template', true);
721
+		if ($page_template) {
722
+			update_post_meta($new_event->ID(), '_wp_page_template', $page_template);
723
+		}
724
+
725
+		do_action('AHEE__Extend_Events_Admin_Page___duplicate_event__after', $new_event, $orig_event);
726
+		// now let's redirect to the edit page for this duplicated event if we have a new event id.
727
+		if ($new_event->ID()) {
728
+			$redirect_args = [
729
+				'post'   => $new_event->ID(),
730
+				'action' => 'edit',
731
+			];
732
+			EE_Error::add_success(
733
+				esc_html__(
734
+					'Event successfully duplicated.  Please review the details below and make any necessary edits',
735
+					'event_espresso'
736
+				)
737
+			);
738
+		} else {
739
+			$redirect_args = [
740
+				'action' => 'default',
741
+			];
742
+			EE_Error::add_error(
743
+				esc_html__('Not able to duplicate event.  Something went wrong.', 'event_espresso'),
744
+				__FILE__,
745
+				__FUNCTION__,
746
+				__LINE__
747
+			);
748
+		}
749
+		$this->_redirect_after_action(false, '', '', $redirect_args, true);
750
+	}
751
+
752
+
753
+	/**
754
+	 * Generates output for the import page.
755
+	 *
756
+	 * @throws DomainException
757
+	 * @throws EE_Error
758
+	 * @throws InvalidArgumentException
759
+	 * @throws InvalidDataTypeException
760
+	 * @throws InvalidInterfaceException
761
+	 */
762
+	protected function _import_page()
763
+	{
764
+		$title = esc_html__('Import', 'event_espresso');
765
+		$intro = esc_html__(
766
+			'If you have a previously exported Event Espresso 4 information in a Comma Separated Value (CSV) file format, you can upload the file here: ',
767
+			'event_espresso'
768
+		);
769
+		$form_url = EVENTS_ADMIN_URL;
770
+		$action = 'import_events';
771
+		$type = 'csv';
772
+		$this->_template_args['form'] = EE_Import::instance()->upload_form(
773
+			$title,
774
+			$intro,
775
+			$form_url,
776
+			$action,
777
+			$type
778
+		);
779
+		$this->_template_args['sample_file_link'] = EE_Admin_Page::add_query_args_and_nonce(
780
+			['action' => 'sample_export_file'],
781
+			$this->_admin_base_url
782
+		);
783
+		$content = EEH_Template::display_template(
784
+			EVENTS_CAF_TEMPLATE_PATH . 'import_page.template.php',
785
+			$this->_template_args,
786
+			true
787
+		);
788
+		$this->_template_args['admin_page_content'] = $content;
789
+		$this->display_admin_page_with_sidebar();
790
+	}
791
+
792
+
793
+	/**
794
+	 * _import_events
795
+	 * This handles displaying the screen and running imports for importing events.
796
+	 *
797
+	 * @return void
798
+	 * @throws EE_Error
799
+	 * @throws InvalidArgumentException
800
+	 * @throws InvalidDataTypeException
801
+	 * @throws InvalidInterfaceException
802
+	 */
803
+	protected function _import_events()
804
+	{
805
+		require_once(EE_CLASSES . 'EE_Import.class.php');
806
+		$success = EE_Import::instance()->import();
807
+		$this->_redirect_after_action($success, 'Import File', 'ran', ['action' => 'import_page'], true);
808
+	}
809
+
810
+
811
+	/**
812
+	 * _events_export
813
+	 * Will export all (or just the given event) to a Excel compatible file.
814
+	 *
815
+	 * @access protected
816
+	 * @return void
817
+	 */
818
+	protected function _events_export()
819
+	{
820
+		if (isset($this->_req_data['EVT_ID'])) {
821
+			$event_ids = $this->_req_data['EVT_ID'];
822
+		} elseif (isset($this->_req_data['EVT_IDs'])) {
823
+			$event_ids = $this->_req_data['EVT_IDs'];
824
+		} else {
825
+			$event_ids = null;
826
+		}
827
+		// todo: I don't like doing this but it'll do until we modify EE_Export Class.
828
+		$new_request_args = [
829
+			'export' => 'report',
830
+			'action' => 'all_event_data',
831
+			'EVT_ID' => $event_ids,
832
+		];
833
+		$this->_req_data = array_merge($this->_req_data, $new_request_args);
834
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
835
+			require_once(EE_CLASSES . 'EE_Export.class.php');
836
+			$EE_Export = EE_Export::instance($this->_req_data);
837
+			if ($EE_Export instanceof EE_Export) {
838
+				$EE_Export->export();
839
+			}
840
+		}
841
+	}
842
+
843
+
844
+	/**
845
+	 * handle category exports()
846
+	 *
847
+	 * @return void
848
+	 */
849
+	protected function _categories_export()
850
+	{
851
+		// todo: I don't like doing this but it'll do until we modify EE_Export Class.
852
+		$new_request_args = [
853
+			'export'       => 'report',
854
+			'action'       => 'categories',
855
+			'category_ids' => $this->_req_data['EVT_CAT_ID'],
856
+		];
857
+		$this->_req_data = array_merge($this->_req_data, $new_request_args);
858
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
859
+			require_once(EE_CLASSES . 'EE_Export.class.php');
860
+			$EE_Export = EE_Export::instance($this->_req_data);
861
+			if ($EE_Export instanceof EE_Export) {
862
+				$EE_Export->export();
863
+			}
864
+		}
865
+	}
866
+
867
+
868
+	/**
869
+	 * Creates a sample CSV file for importing
870
+	 */
871
+	protected function _sample_export_file()
872
+	{
873
+		$EE_Export = EE_Export::instance();
874
+		if ($EE_Export instanceof EE_Export) {
875
+			$EE_Export->export();
876
+		}
877
+	}
878
+
879
+
880
+	/*************        Template Settings        *************/
881
+	/**
882
+	 * Generates template settings page output
883
+	 *
884
+	 * @throws DomainException
885
+	 * @throws EE_Error
886
+	 * @throws InvalidArgumentException
887
+	 * @throws InvalidDataTypeException
888
+	 * @throws InvalidInterfaceException
889
+	 */
890
+	protected function _template_settings()
891
+	{
892
+		$this->_template_args['values'] = $this->_yes_no_values;
893
+		/**
894
+		 * Note leaving this filter in for backward compatibility this was moved in 4.6.x
895
+		 * from General_Settings_Admin_Page to here.
896
+		 */
897
+		$this->_template_args = apply_filters(
898
+			'FHEE__General_Settings_Admin_Page__template_settings__template_args',
899
+			$this->_template_args
900
+		);
901
+		$this->_set_add_edit_form_tags('update_template_settings');
902
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
903
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
904
+			EVENTS_CAF_TEMPLATE_PATH . 'template_settings.template.php',
905
+			$this->_template_args,
906
+			true
907
+		);
908
+		$this->display_admin_page_with_sidebar();
909
+	}
910
+
911
+
912
+	/**
913
+	 * Handler for updating template settings.
914
+	 *
915
+	 * @throws EE_Error
916
+	 * @throws InvalidArgumentException
917
+	 * @throws InvalidDataTypeException
918
+	 * @throws InvalidInterfaceException
919
+	 */
920
+	protected function _update_template_settings()
921
+	{
922
+		/**
923
+		 * Note leaving this filter in for backward compatibility this was moved in 4.6.x
924
+		 * from General_Settings_Admin_Page to here.
925
+		 */
926
+		EE_Registry::instance()->CFG->template_settings = apply_filters(
927
+			'FHEE__General_Settings_Admin_Page__update_template_settings__data',
928
+			EE_Registry::instance()->CFG->template_settings,
929
+			$this->_req_data
930
+		);
931
+		// update custom post type slugs and detect if we need to flush rewrite rules
932
+		$old_slug = EE_Registry::instance()->CFG->core->event_cpt_slug;
933
+		EE_Registry::instance()->CFG->core->event_cpt_slug = empty($this->_req_data['event_cpt_slug'])
934
+			? EE_Registry::instance()->CFG->core->event_cpt_slug
935
+			: EEH_URL::slugify($this->_req_data['event_cpt_slug'], 'events');
936
+		$what = 'Template Settings';
937
+		$success = $this->_update_espresso_configuration(
938
+			$what,
939
+			EE_Registry::instance()->CFG->template_settings,
940
+			__FILE__,
941
+			__FUNCTION__,
942
+			__LINE__
943
+		);
944
+		if (EE_Registry::instance()->CFG->core->event_cpt_slug !== $old_slug) {
945
+			/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
946
+			$rewrite_rules = LoaderFactory::getLoader()->getShared(
947
+				'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
948
+			);
949
+			$rewrite_rules->flush();
950
+		}
951
+		$this->_redirect_after_action($success, $what, 'updated', ['action' => 'template_settings']);
952
+	}
953
+
954
+
955
+	/**
956
+	 * _premium_event_editor_meta_boxes
957
+	 * add all metaboxes related to the event_editor
958
+	 *
959
+	 * @access protected
960
+	 * @return void
961
+	 * @throws EE_Error
962
+	 * @throws InvalidArgumentException
963
+	 * @throws InvalidDataTypeException
964
+	 * @throws InvalidInterfaceException
965
+	 * @throws ReflectionException
966
+	 */
967
+	protected function _premium_event_editor_meta_boxes()
968
+	{
969
+		$this->verify_cpt_object();
970
+		/** @var FeatureFlags $flags */
971
+		$flags = $this->loader->getShared('EventEspresso\core\domain\services\capabilities\FeatureFlags');
972
+		// check if the new EDTR reg options meta box is being used, and if so, don't load the legacy version
973
+		if (! $this->admin_config->useAdvancedEditor() || ! $flags->featureAllowed('use_reg_options_meta_box')) {
974
+			add_meta_box(
975
+				'espresso_event_editor_event_options',
976
+				esc_html__('Event Registration Options', 'event_espresso'),
977
+				[$this, 'registration_options_meta_box'],
978
+				$this->page_slug,
979
+				'side',
980
+				'core'
981
+			);
982
+		}
983
+	}
984
+
985
+
986
+	/**
987
+	 * override caf metabox
988
+	 *
989
+	 * @return void
990
+	 * @throws DomainException
991
+	 * @throws EE_Error
992
+	 */
993
+	public function registration_options_meta_box()
994
+	{
995
+		$yes_no_values = [
996
+			['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
997
+			['id' => false, 'text' => esc_html__('No', 'event_espresso')],
998
+		];
999
+		$default_reg_status_values = EEM_Registration::reg_status_array(
1000
+			[
1001
+				EEM_Registration::status_id_cancelled,
1002
+				EEM_Registration::status_id_declined,
1003
+				EEM_Registration::status_id_incomplete,
1004
+				EEM_Registration::status_id_wait_list,
1005
+			],
1006
+			true
1007
+		);
1008
+		$template_args['active_status'] = $this->_cpt_model_obj->pretty_active_status(false);
1009
+		$template_args['_event'] = $this->_cpt_model_obj;
1010
+		$template_args['additional_limit'] = $this->_cpt_model_obj->additional_limit();
1011
+		$template_args['default_registration_status'] = EEH_Form_Fields::select_input(
1012
+			'default_reg_status',
1013
+			$default_reg_status_values,
1014
+			$this->_cpt_model_obj->default_registration_status()
1015
+		);
1016
+		$template_args['display_description'] = EEH_Form_Fields::select_input(
1017
+			'display_desc',
1018
+			$yes_no_values,
1019
+			$this->_cpt_model_obj->display_description()
1020
+		);
1021
+		$template_args['display_ticket_selector'] = EEH_Form_Fields::select_input(
1022
+			'display_ticket_selector',
1023
+			$yes_no_values,
1024
+			$this->_cpt_model_obj->display_ticket_selector(),
1025
+			'',
1026
+			'',
1027
+			false
1028
+		);
1029
+		$template_args['EVT_default_registration_status'] = EEH_Form_Fields::select_input(
1030
+			'EVT_default_registration_status',
1031
+			$default_reg_status_values,
1032
+			$this->_cpt_model_obj->default_registration_status()
1033
+		);
1034
+		$template_args['additional_registration_options'] = apply_filters(
1035
+			'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1036
+			'',
1037
+			$template_args,
1038
+			$yes_no_values,
1039
+			$default_reg_status_values
1040
+		);
1041
+		EEH_Template::display_template(
1042
+			EVENTS_CAF_TEMPLATE_PATH . 'event_registration_options.template.php',
1043
+			$template_args
1044
+		);
1045
+	}
1046
+
1047
+
1048
+
1049
+	/**
1050
+	 * wp_list_table_mods for caf
1051
+	 * ============================
1052
+	 */
1053
+	/**
1054
+	 * hook into list table filters and provide filters for caffeinated list table
1055
+	 *
1056
+	 * @param array $old_filters    any existing filters present
1057
+	 * @param array $list_table_obj the list table object
1058
+	 * @return array                  new filters
1059
+	 * @throws EE_Error
1060
+	 * @throws InvalidArgumentException
1061
+	 * @throws InvalidDataTypeException
1062
+	 * @throws InvalidInterfaceException
1063
+	 * @throws ReflectionException
1064
+	 */
1065
+	public function list_table_filters($old_filters, $list_table_obj)
1066
+	{
1067
+		$filters = [];
1068
+		// first month/year filters
1069
+		$filters[] = $this->espresso_event_months_dropdown();
1070
+		$status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1071
+		// active status dropdown
1072
+		if ($status !== 'draft') {
1073
+			$filters[] = $this->active_status_dropdown(
1074
+				isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : ''
1075
+			);
1076
+			$filters[] = $this->venuesDropdown(
1077
+				isset($this->_req_data['venue']) ? $this->_req_data['venue'] : ''
1078
+			);
1079
+		}
1080
+		// category filter
1081
+		$filters[] = $this->category_dropdown();
1082
+		return array_merge($old_filters, $filters);
1083
+	}
1084
+
1085
+
1086
+	/**
1087
+	 * espresso_event_months_dropdown
1088
+	 *
1089
+	 * @access public
1090
+	 * @return string                dropdown listing month/year selections for events.
1091
+	 */
1092
+	public function espresso_event_months_dropdown()
1093
+	{
1094
+		// what we need to do is get all PRIMARY datetimes for all events to filter on.
1095
+		// Note we need to include any other filters that are set!
1096
+		$status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1097
+		// categories?
1098
+		$category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
1099
+			? $this->_req_data['EVT_CAT']
1100
+			: null;
1101
+		// active status?
1102
+		$active_status = isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : null;
1103
+		$cur_date = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
1104
+		return EEH_Form_Fields::generate_event_months_dropdown($cur_date, $status, $category, $active_status);
1105
+	}
1106
+
1107
+
1108
+	/**
1109
+	 * returns a list of "active" statuses on the event
1110
+	 *
1111
+	 * @param string $current_value whatever the current active status is
1112
+	 * @return string
1113
+	 */
1114
+	public function active_status_dropdown($current_value = '')
1115
+	{
1116
+		$select_name = 'active_status';
1117
+		$values = [
1118
+			'none'     => esc_html__('Show Active/Inactive', 'event_espresso'),
1119
+			'active'   => esc_html__('Active', 'event_espresso'),
1120
+			'upcoming' => esc_html__('Upcoming', 'event_espresso'),
1121
+			'expired'  => esc_html__('Expired', 'event_espresso'),
1122
+			'inactive' => esc_html__('Inactive', 'event_espresso'),
1123
+		];
1124
+
1125
+		return EEH_Form_Fields::select_input($select_name, $values, $current_value, '', 'wide');
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * returns a list of "venues"
1131
+	 *
1132
+	 * @param string $current_value whatever the current active status is
1133
+	 * @return string
1134
+	 * @throws EE_Error
1135
+	 * @throws InvalidArgumentException
1136
+	 * @throws InvalidDataTypeException
1137
+	 * @throws InvalidInterfaceException
1138
+	 * @throws ReflectionException
1139
+	 */
1140
+	protected function venuesDropdown($current_value = '')
1141
+	{
1142
+		$select_name = 'venue';
1143
+		$values = [
1144
+			'' => esc_html__('All Venues', 'event_espresso'),
1145
+		];
1146
+		// populate the list of venues.
1147
+		$venue_model = EE_Registry::instance()->load_model('Venue');
1148
+		$venues = $venue_model->get_all(['order_by' => ['VNU_name' => 'ASC']]);
1149
+
1150
+		foreach ($venues as $venue) {
1151
+			$values[ $venue->ID() ] = $venue->name();
1152
+		}
1153
+
1154
+		return EEH_Form_Fields::select_input($select_name, $values, $current_value, '', 'wide');
1155
+	}
1156
+
1157
+
1158
+	/**
1159
+	 * output a dropdown of the categories for the category filter on the event admin list table
1160
+	 *
1161
+	 * @access  public
1162
+	 * @return string html
1163
+	 */
1164
+	public function category_dropdown()
1165
+	{
1166
+		$cur_cat = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
1167
+		return EEH_Form_Fields::generate_event_category_dropdown($cur_cat);
1168
+	}
1169
+
1170
+
1171
+	/**
1172
+	 * get total number of events today
1173
+	 *
1174
+	 * @access public
1175
+	 * @return int
1176
+	 * @throws EE_Error
1177
+	 * @throws InvalidArgumentException
1178
+	 * @throws InvalidDataTypeException
1179
+	 * @throws InvalidInterfaceException
1180
+	 */
1181
+	public function total_events_today()
1182
+	{
1183
+		$start = EEM_Datetime::instance()->convert_datetime_for_query(
1184
+			'DTT_EVT_start',
1185
+			date('Y-m-d') . ' 00:00:00',
1186
+			'Y-m-d H:i:s',
1187
+			'UTC'
1188
+		);
1189
+		$end = EEM_Datetime::instance()->convert_datetime_for_query(
1190
+			'DTT_EVT_start',
1191
+			date('Y-m-d') . ' 23:59:59',
1192
+			'Y-m-d H:i:s',
1193
+			'UTC'
1194
+		);
1195
+		$where = [
1196
+			'Datetime.DTT_EVT_start' => ['BETWEEN', [$start, $end]],
1197
+		];
1198
+		return EEM_Event::instance()->count([$where, 'caps' => 'read_admin'], 'EVT_ID', true);
1199
+	}
1200
+
1201
+
1202
+	/**
1203
+	 * get total number of events this month
1204
+	 *
1205
+	 * @access public
1206
+	 * @return int
1207
+	 * @throws EE_Error
1208
+	 * @throws InvalidArgumentException
1209
+	 * @throws InvalidDataTypeException
1210
+	 * @throws InvalidInterfaceException
1211
+	 */
1212
+	public function total_events_this_month()
1213
+	{
1214
+		// Dates
1215
+		$this_year_r = date('Y');
1216
+		$this_month_r = date('m');
1217
+		$days_this_month = date('t');
1218
+		$start = EEM_Datetime::instance()->convert_datetime_for_query(
1219
+			'DTT_EVT_start',
1220
+			$this_year_r . '-' . $this_month_r . '-01 00:00:00',
1221
+			'Y-m-d H:i:s',
1222
+			'UTC'
1223
+		);
1224
+		$end = EEM_Datetime::instance()->convert_datetime_for_query(
1225
+			'DTT_EVT_start',
1226
+			$this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' 23:59:59',
1227
+			'Y-m-d H:i:s',
1228
+			'UTC'
1229
+		);
1230
+		$where = [
1231
+			'Datetime.DTT_EVT_start' => ['BETWEEN', [$start, $end]],
1232
+		];
1233
+		return EEM_Event::instance()->count([$where, 'caps' => 'read_admin'], 'EVT_ID', true);
1234
+	}
1235
+
1236
+
1237
+	/** DEFAULT TICKETS STUFF **/
1238
+
1239
+	/**
1240
+	 * Output default tickets list table view.
1241
+	 *
1242
+	 * @throws DomainException
1243
+	 * @throws EE_Error
1244
+	 * @throws InvalidArgumentException
1245
+	 * @throws InvalidDataTypeException
1246
+	 * @throws InvalidInterfaceException
1247
+	 */
1248
+	public function _tickets_overview_list_table()
1249
+	{
1250
+		$this->_search_btn_label = esc_html__('Tickets', 'event_espresso');
1251
+		$this->display_admin_list_table_page_with_no_sidebar();
1252
+	}
1253
+
1254
+
1255
+	/**
1256
+	 * @param int  $per_page
1257
+	 * @param bool $count
1258
+	 * @param bool $trashed
1259
+	 * @return EE_Soft_Delete_Base_Class[]|int
1260
+	 * @throws EE_Error
1261
+	 * @throws InvalidArgumentException
1262
+	 * @throws InvalidDataTypeException
1263
+	 * @throws InvalidInterfaceException
1264
+	 */
1265
+	public function get_default_tickets($per_page = 10, $count = false, $trashed = false)
1266
+	{
1267
+		$orderby = empty($this->_req_data['orderby']) ? 'TKT_name' : $this->_req_data['orderby'];
1268
+		$order = empty($this->_req_data['order']) ? 'ASC' : $this->_req_data['order'];
1269
+		switch ($orderby) {
1270
+			case 'TKT_name':
1271
+				$orderby = ['TKT_name' => $order];
1272
+				break;
1273
+			case 'TKT_price':
1274
+				$orderby = ['TKT_price' => $order];
1275
+				break;
1276
+			case 'TKT_uses':
1277
+				$orderby = ['TKT_uses' => $order];
1278
+				break;
1279
+			case 'TKT_min':
1280
+				$orderby = ['TKT_min' => $order];
1281
+				break;
1282
+			case 'TKT_max':
1283
+				$orderby = ['TKT_max' => $order];
1284
+				break;
1285
+			case 'TKT_qty':
1286
+				$orderby = ['TKT_qty' => $order];
1287
+				break;
1288
+		}
1289
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1290
+			? $this->_req_data['paged']
1291
+			: 1;
1292
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1293
+			? $this->_req_data['perpage']
1294
+			: $per_page;
1295
+		$_where = [
1296
+			'TKT_is_default' => 1,
1297
+			'TKT_deleted'    => $trashed,
1298
+		];
1299
+		$offset = ($current_page - 1) * $per_page;
1300
+		$limit = [$offset, $per_page];
1301
+		if (isset($this->_req_data['s'])) {
1302
+			$sstr = '%' . $this->_req_data['s'] . '%';
1303
+			$_where['OR'] = [
1304
+				'TKT_name'        => ['LIKE', $sstr],
1305
+				'TKT_description' => ['LIKE', $sstr],
1306
+			];
1307
+		}
1308
+		$query_params = [
1309
+			$_where,
1310
+			'order_by' => $orderby,
1311
+			'limit'    => $limit,
1312
+			'group_by' => 'TKT_ID',
1313
+		];
1314
+		if ($count) {
1315
+			return EEM_Ticket::instance()->count_deleted_and_undeleted([$_where]);
1316
+		}
1317
+		return EEM_Ticket::instance()->get_all_deleted_and_undeleted($query_params);
1318
+	}
1319
+
1320
+
1321
+	/**
1322
+	 * @param bool $trash
1323
+	 * @throws EE_Error
1324
+	 * @throws InvalidArgumentException
1325
+	 * @throws InvalidDataTypeException
1326
+	 * @throws InvalidInterfaceException
1327
+	 */
1328
+	protected function _trash_or_restore_ticket($trash = false)
1329
+	{
1330
+		$success = 1;
1331
+		$TKT = EEM_Ticket::instance();
1332
+		// checkboxes?
1333
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1334
+			// if array has more than one element then success message should be plural
1335
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1336
+			// cycle thru the boxes
1337
+			foreach ($this->_req_data['checkbox'] as $TKT_ID) {
1338
+				if ($trash) {
1339
+					if (! $TKT->delete_by_ID($TKT_ID)) {
1340
+						$success = 0;
1341
+					}
1342
+				} elseif (! $TKT->restore_by_ID($TKT_ID)) {
1343
+					$success = 0;
1344
+				}
1345
+			}
1346
+		} else {
1347
+			// grab single id and trash
1348
+			$TKT_ID = absint($this->_req_data['TKT_ID']);
1349
+			if ($trash) {
1350
+				if (! $TKT->delete_by_ID($TKT_ID)) {
1351
+					$success = 0;
1352
+				}
1353
+			} elseif (! $TKT->restore_by_ID($TKT_ID)) {
1354
+				$success = 0;
1355
+			}
1356
+		}
1357
+		$action_desc = $trash ? 'moved to the trash' : 'restored';
1358
+		$query_args = [
1359
+			'action' => 'ticket_list_table',
1360
+			'status' => $trash ? '' : 'trashed',
1361
+		];
1362
+		$this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1363
+	}
1364
+
1365
+
1366
+	/**
1367
+	 * Handles trashing default ticket.
1368
+	 *
1369
+	 * @throws EE_Error
1370
+	 * @throws InvalidArgumentException
1371
+	 * @throws InvalidDataTypeException
1372
+	 * @throws InvalidInterfaceException
1373
+	 * @throws ReflectionException
1374
+	 */
1375
+	protected function _delete_ticket()
1376
+	{
1377
+		$success = 1;
1378
+		// checkboxes?
1379
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1380
+			// if array has more than one element then success message should be plural
1381
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1382
+			// cycle thru the boxes
1383
+			foreach ($this->_req_data['checkbox'] as $TKT_ID) {
1384
+				// delete
1385
+				if (! $this->_delete_the_ticket($TKT_ID)) {
1386
+					$success = 0;
1387
+				}
1388
+			}
1389
+		} else {
1390
+			// grab single id and trash
1391
+			$TKT_ID = absint($this->_req_data['TKT_ID']);
1392
+			if (! $this->_delete_the_ticket($TKT_ID)) {
1393
+				$success = 0;
1394
+			}
1395
+		}
1396
+		$action_desc = 'deleted';
1397
+		// fail safe.  If the default ticket count === 1 then we need to redirect to event overview.
1398
+		$ticket_count = EEM_Ticket::instance()->count_deleted_and_undeleted(
1399
+			[['TKT_is_default' => 1]],
1400
+			'TKT_ID',
1401
+			true
1402
+		);
1403
+		$query_args = $ticket_count
1404
+			? []
1405
+			: [
1406
+				'action' => 'ticket_list_table',
1407
+				'status' => 'trashed',
1408
+			];
1409
+		$this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1410
+	}
1411
+
1412
+
1413
+	/**
1414
+	 * @param int $TKT_ID
1415
+	 * @return bool|int
1416
+	 * @throws EE_Error
1417
+	 * @throws InvalidArgumentException
1418
+	 * @throws InvalidDataTypeException
1419
+	 * @throws InvalidInterfaceException
1420
+	 * @throws ReflectionException
1421
+	 */
1422
+	protected function _delete_the_ticket($TKT_ID)
1423
+	{
1424
+		$ticket = EEM_Ticket::instance()->get_one_by_ID($TKT_ID);
1425
+		if (! $ticket instanceof EE_Ticket) {
1426
+			return false;
1427
+		}
1428
+		$ticket->_remove_relations('Datetime');
1429
+		// delete all related prices first
1430
+		$ticket->delete_related_permanently('Price');
1431
+		return $ticket->delete_permanently();
1432
+	}
1433 1433
 }
Please login to merge, or discard this patch.
caffeinated/admin/new/pricing/espresso_events_Pricing_Hooks.class.php 1 patch
Indentation   +2155 added lines, -2155 removed lines patch added patch discarded remove patch
@@ -15,2217 +15,2217 @@
 block discarded – undo
15 15
 class espresso_events_Pricing_Hooks extends EE_Admin_Hooks
16 16
 {
17 17
 
18
-    /**
19
-     * This property is just used to hold the status of whether an event is currently being
20
-     * created (true) or edited (false)
21
-     *
22
-     * @access protected
23
-     * @var bool
24
-     */
25
-    protected $_is_creating_event;
18
+	/**
19
+	 * This property is just used to hold the status of whether an event is currently being
20
+	 * created (true) or edited (false)
21
+	 *
22
+	 * @access protected
23
+	 * @var bool
24
+	 */
25
+	protected $_is_creating_event;
26 26
 
27
-    /**
28
-     * Used to contain the format strings for date and time that will be used for php date and
29
-     * time.
30
-     * Is set in the _set_hooks_properties() method.
31
-     *
32
-     * @var array
33
-     */
34
-    protected $_date_format_strings;
27
+	/**
28
+	 * Used to contain the format strings for date and time that will be used for php date and
29
+	 * time.
30
+	 * Is set in the _set_hooks_properties() method.
31
+	 *
32
+	 * @var array
33
+	 */
34
+	protected $_date_format_strings;
35 35
 
36
-    /**
37
-     * @var string $_date_time_format
38
-     */
39
-    protected $_date_time_format;
36
+	/**
37
+	 * @var string $_date_time_format
38
+	 */
39
+	protected $_date_time_format;
40 40
 
41 41
 
42
-    /**
43
-     * @throws InvalidArgumentException
44
-     * @throws InvalidInterfaceException
45
-     * @throws InvalidDataTypeException
46
-     */
47
-    protected function _set_hooks_properties()
48
-    {
49
-        $this->_name = 'pricing';
50
-        // capability check
51
-        if (
52
-            EE_Registry::instance()->CFG->admin->useAdvancedEditor() ||
53
-            ! EE_Registry::instance()->CAP->current_user_can(
54
-                'ee_read_default_prices',
55
-                'advanced_ticket_datetime_metabox'
56
-            )
57
-        ) {
58
-            return;
59
-        }
60
-        $this->_setup_metaboxes();
61
-        $this->_set_date_time_formats();
62
-        $this->_validate_format_strings();
63
-        $this->_set_scripts_styles();
64
-        // commented out temporarily until logic is implemented in callback
65
-        // add_action(
66
-        //     'AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_Extend_Events_Admin_Page',
67
-        //     array($this, 'autosave_handling')
68
-        // );
69
-        add_filter(
70
-            'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
71
-            array($this, 'caf_updates')
72
-        );
73
-    }
42
+	/**
43
+	 * @throws InvalidArgumentException
44
+	 * @throws InvalidInterfaceException
45
+	 * @throws InvalidDataTypeException
46
+	 */
47
+	protected function _set_hooks_properties()
48
+	{
49
+		$this->_name = 'pricing';
50
+		// capability check
51
+		if (
52
+			EE_Registry::instance()->CFG->admin->useAdvancedEditor() ||
53
+			! EE_Registry::instance()->CAP->current_user_can(
54
+				'ee_read_default_prices',
55
+				'advanced_ticket_datetime_metabox'
56
+			)
57
+		) {
58
+			return;
59
+		}
60
+		$this->_setup_metaboxes();
61
+		$this->_set_date_time_formats();
62
+		$this->_validate_format_strings();
63
+		$this->_set_scripts_styles();
64
+		// commented out temporarily until logic is implemented in callback
65
+		// add_action(
66
+		//     'AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_Extend_Events_Admin_Page',
67
+		//     array($this, 'autosave_handling')
68
+		// );
69
+		add_filter(
70
+			'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
71
+			array($this, 'caf_updates')
72
+		);
73
+	}
74 74
 
75 75
 
76
-    /**
77
-     * @return void
78
-     */
79
-    protected function _setup_metaboxes()
80
-    {
81
-        // if we were going to add our own metaboxes we'd use the below.
82
-        $this->_metaboxes = array(
83
-            0 => array(
84
-                'page_route' => array('edit', 'create_new'),
85
-                'func'       => 'pricing_metabox',
86
-                'label'      => esc_html__('Event Tickets & Datetimes', 'event_espresso'),
87
-                'priority'   => 'high',
88
-                'context'    => 'normal',
89
-            ),
90
-        );
91
-        $this->_remove_metaboxes = array(
92
-            0 => array(
93
-                'page_route' => array('edit', 'create_new'),
94
-                'id'         => 'espresso_event_editor_tickets',
95
-                'context'    => 'normal',
96
-            ),
97
-        );
98
-    }
76
+	/**
77
+	 * @return void
78
+	 */
79
+	protected function _setup_metaboxes()
80
+	{
81
+		// if we were going to add our own metaboxes we'd use the below.
82
+		$this->_metaboxes = array(
83
+			0 => array(
84
+				'page_route' => array('edit', 'create_new'),
85
+				'func'       => 'pricing_metabox',
86
+				'label'      => esc_html__('Event Tickets & Datetimes', 'event_espresso'),
87
+				'priority'   => 'high',
88
+				'context'    => 'normal',
89
+			),
90
+		);
91
+		$this->_remove_metaboxes = array(
92
+			0 => array(
93
+				'page_route' => array('edit', 'create_new'),
94
+				'id'         => 'espresso_event_editor_tickets',
95
+				'context'    => 'normal',
96
+			),
97
+		);
98
+	}
99 99
 
100 100
 
101
-    /**
102
-     * @return void
103
-     */
104
-    protected function _set_date_time_formats()
105
-    {
106
-        /**
107
-         * Format strings for date and time.  Defaults are existing behaviour from 4.1.
108
-         * Note, that if you return null as the value for 'date', and 'time' in the array, then
109
-         * EE will automatically use the set wp_options, 'date_format', and 'time_format'.
110
-         *
111
-         * @since 4.6.7
112
-         * @var array  Expected an array returned with 'date' and 'time' keys.
113
-         */
114
-        $this->_date_format_strings = apply_filters(
115
-            'FHEE__espresso_events_Pricing_Hooks___set_hooks_properties__date_format_strings',
116
-            array(
117
-                'date' => 'Y-m-d',
118
-                'time' => 'h:i a',
119
-            )
120
-        );
121
-        // validate
122
-        $this->_date_format_strings['date'] = isset($this->_date_format_strings['date'])
123
-            ? $this->_date_format_strings['date']
124
-            : null;
125
-        $this->_date_format_strings['time'] = isset($this->_date_format_strings['time'])
126
-            ? $this->_date_format_strings['time']
127
-            : null;
128
-        $this->_date_time_format = $this->_date_format_strings['date']
129
-                                   . ' '
130
-                                   . $this->_date_format_strings['time'];
131
-    }
101
+	/**
102
+	 * @return void
103
+	 */
104
+	protected function _set_date_time_formats()
105
+	{
106
+		/**
107
+		 * Format strings for date and time.  Defaults are existing behaviour from 4.1.
108
+		 * Note, that if you return null as the value for 'date', and 'time' in the array, then
109
+		 * EE will automatically use the set wp_options, 'date_format', and 'time_format'.
110
+		 *
111
+		 * @since 4.6.7
112
+		 * @var array  Expected an array returned with 'date' and 'time' keys.
113
+		 */
114
+		$this->_date_format_strings = apply_filters(
115
+			'FHEE__espresso_events_Pricing_Hooks___set_hooks_properties__date_format_strings',
116
+			array(
117
+				'date' => 'Y-m-d',
118
+				'time' => 'h:i a',
119
+			)
120
+		);
121
+		// validate
122
+		$this->_date_format_strings['date'] = isset($this->_date_format_strings['date'])
123
+			? $this->_date_format_strings['date']
124
+			: null;
125
+		$this->_date_format_strings['time'] = isset($this->_date_format_strings['time'])
126
+			? $this->_date_format_strings['time']
127
+			: null;
128
+		$this->_date_time_format = $this->_date_format_strings['date']
129
+								   . ' '
130
+								   . $this->_date_format_strings['time'];
131
+	}
132 132
 
133 133
 
134
-    /**
135
-     * @return void
136
-     */
137
-    protected function _validate_format_strings()
138
-    {
139
-        // validate format strings
140
-        $format_validation = EEH_DTT_Helper::validate_format_string(
141
-            $this->_date_time_format
142
-        );
143
-        if (is_array($format_validation)) {
144
-            $msg = '<p>';
145
-            $msg .= sprintf(
146
-                esc_html__(
147
-                    'The format "%s" was likely added via a filter and is invalid for the following reasons:',
148
-                    'event_espresso'
149
-                ),
150
-                $this->_date_time_format
151
-            );
152
-            $msg .= '</p><ul>';
153
-            foreach ($format_validation as $error) {
154
-                $msg .= '<li>' . $error . '</li>';
155
-            }
156
-            $msg .= '</ul><p>';
157
-            $msg .= sprintf(
158
-                esc_html__(
159
-                    '%sPlease note that your date and time formats have been reset to "Y-m-d" and "h:i a" respectively.%s',
160
-                    'event_espresso'
161
-                ),
162
-                '<span style="color:#D54E21;">',
163
-                '</span>'
164
-            );
165
-            $msg .= '</p>';
166
-            EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
167
-            $this->_date_format_strings = array(
168
-                'date' => 'Y-m-d',
169
-                'time' => 'h:i a',
170
-            );
171
-        }
172
-    }
134
+	/**
135
+	 * @return void
136
+	 */
137
+	protected function _validate_format_strings()
138
+	{
139
+		// validate format strings
140
+		$format_validation = EEH_DTT_Helper::validate_format_string(
141
+			$this->_date_time_format
142
+		);
143
+		if (is_array($format_validation)) {
144
+			$msg = '<p>';
145
+			$msg .= sprintf(
146
+				esc_html__(
147
+					'The format "%s" was likely added via a filter and is invalid for the following reasons:',
148
+					'event_espresso'
149
+				),
150
+				$this->_date_time_format
151
+			);
152
+			$msg .= '</p><ul>';
153
+			foreach ($format_validation as $error) {
154
+				$msg .= '<li>' . $error . '</li>';
155
+			}
156
+			$msg .= '</ul><p>';
157
+			$msg .= sprintf(
158
+				esc_html__(
159
+					'%sPlease note that your date and time formats have been reset to "Y-m-d" and "h:i a" respectively.%s',
160
+					'event_espresso'
161
+				),
162
+				'<span style="color:#D54E21;">',
163
+				'</span>'
164
+			);
165
+			$msg .= '</p>';
166
+			EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
167
+			$this->_date_format_strings = array(
168
+				'date' => 'Y-m-d',
169
+				'time' => 'h:i a',
170
+			);
171
+		}
172
+	}
173 173
 
174 174
 
175
-    /**
176
-     * @return void
177
-     */
178
-    protected function _set_scripts_styles()
179
-    {
180
-        $this->_scripts_styles = array(
181
-            'registers'   => array(
182
-                'ee-tickets-datetimes-css' => array(
183
-                    'url'  => PRICING_ASSETS_URL . 'event-tickets-datetimes.css',
184
-                    'type' => 'css',
185
-                ),
186
-                'ee-dtt-ticket-metabox'    => array(
187
-                    'url'     => PRICING_ASSETS_URL . 'ee-datetime-ticket-metabox.js',
188
-                    'depends' => array('ee-datepicker', 'ee-dialog', 'underscore'),
189
-                ),
190
-            ),
191
-            'deregisters' => array(
192
-                'event-editor-css'       => array('type' => 'css'),
193
-                'event-datetime-metabox' => array('type' => 'js'),
194
-            ),
195
-            'enqueues'    => array(
196
-                'ee-tickets-datetimes-css' => array('edit', 'create_new'),
197
-                'ee-dtt-ticket-metabox'    => array('edit', 'create_new'),
198
-            ),
199
-            'localize'    => array(
200
-                'ee-dtt-ticket-metabox' => array(
201
-                    'DTT_TRASH_BLOCK'       => array(
202
-                        'main_warning'            => esc_html__(
203
-                            'The Datetime you are attempting to trash is the only datetime selected for the following ticket(s):',
204
-                            'event_espresso'
205
-                        ),
206
-                        'after_warning'           => esc_html__(
207
-                            'In order to trash this datetime you must first make sure the above ticket(s) are assigned to other datetimes.',
208
-                            'event_espresso'
209
-                        ),
210
-                        'cancel_button'           => '<button class="button-secondary ee-modal-cancel">'
211
-                                                     . esc_html__('Cancel', 'event_espresso') . '</button>',
212
-                        'close_button'            => '<button class="button-secondary ee-modal-cancel">'
213
-                                                     . esc_html__('Close', 'event_espresso') . '</button>',
214
-                        'single_warning_from_tkt' => esc_html__(
215
-                            'The Datetime you are attempting to unassign from this ticket is the only remaining datetime for this ticket. Tickets must always have at least one datetime assigned to them.',
216
-                            'event_espresso'
217
-                        ),
218
-                        'single_warning_from_dtt' => esc_html__(
219
-                            'The ticket you are attempting to unassign from this datetime cannot be unassigned because the datetime is the only remaining datetime for the ticket.  Tickets must always have at least one datetime assigned to them.',
220
-                            'event_espresso'
221
-                        ),
222
-                        'dismiss_button'          => '<button class="button-secondary ee-modal-cancel">'
223
-                                                     . esc_html__('Dismiss', 'event_espresso') . '</button>',
224
-                    ),
225
-                    'DTT_ERROR_MSG'         => array(
226
-                        'no_ticket_name' => esc_html__('General Admission', 'event_espresso'),
227
-                        'dismiss_button' => '<div class="save-cancel-button-container">'
228
-                                            . '<button class="button-secondary ee-modal-cancel">'
229
-                                            . esc_html__('Dismiss', 'event_espresso')
230
-                                            . '</button></div>',
231
-                    ),
232
-                    'DTT_OVERSELL_WARNING'  => array(
233
-                        'datetime_ticket' => esc_html__(
234
-                            'You cannot add this ticket to this datetime because it has a sold amount that is greater than the amount of spots remaining for this datetime.',
235
-                            'event_espresso'
236
-                        ),
237
-                        'ticket_datetime' => esc_html__(
238
-                            'You cannot add this datetime to this ticket because the ticket has a sold amount that is greater than the amount of spots remaining on the datetime.',
239
-                            'event_espresso'
240
-                        ),
241
-                    ),
242
-                    'DTT_CONVERTED_FORMATS' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats(
243
-                        $this->_date_format_strings['date'],
244
-                        $this->_date_format_strings['time']
245
-                    ),
246
-                    'DTT_START_OF_WEEK'     => array('dayValue' => (int) get_option('start_of_week')),
247
-                ),
248
-            ),
249
-        );
250
-    }
175
+	/**
176
+	 * @return void
177
+	 */
178
+	protected function _set_scripts_styles()
179
+	{
180
+		$this->_scripts_styles = array(
181
+			'registers'   => array(
182
+				'ee-tickets-datetimes-css' => array(
183
+					'url'  => PRICING_ASSETS_URL . 'event-tickets-datetimes.css',
184
+					'type' => 'css',
185
+				),
186
+				'ee-dtt-ticket-metabox'    => array(
187
+					'url'     => PRICING_ASSETS_URL . 'ee-datetime-ticket-metabox.js',
188
+					'depends' => array('ee-datepicker', 'ee-dialog', 'underscore'),
189
+				),
190
+			),
191
+			'deregisters' => array(
192
+				'event-editor-css'       => array('type' => 'css'),
193
+				'event-datetime-metabox' => array('type' => 'js'),
194
+			),
195
+			'enqueues'    => array(
196
+				'ee-tickets-datetimes-css' => array('edit', 'create_new'),
197
+				'ee-dtt-ticket-metabox'    => array('edit', 'create_new'),
198
+			),
199
+			'localize'    => array(
200
+				'ee-dtt-ticket-metabox' => array(
201
+					'DTT_TRASH_BLOCK'       => array(
202
+						'main_warning'            => esc_html__(
203
+							'The Datetime you are attempting to trash is the only datetime selected for the following ticket(s):',
204
+							'event_espresso'
205
+						),
206
+						'after_warning'           => esc_html__(
207
+							'In order to trash this datetime you must first make sure the above ticket(s) are assigned to other datetimes.',
208
+							'event_espresso'
209
+						),
210
+						'cancel_button'           => '<button class="button-secondary ee-modal-cancel">'
211
+													 . esc_html__('Cancel', 'event_espresso') . '</button>',
212
+						'close_button'            => '<button class="button-secondary ee-modal-cancel">'
213
+													 . esc_html__('Close', 'event_espresso') . '</button>',
214
+						'single_warning_from_tkt' => esc_html__(
215
+							'The Datetime you are attempting to unassign from this ticket is the only remaining datetime for this ticket. Tickets must always have at least one datetime assigned to them.',
216
+							'event_espresso'
217
+						),
218
+						'single_warning_from_dtt' => esc_html__(
219
+							'The ticket you are attempting to unassign from this datetime cannot be unassigned because the datetime is the only remaining datetime for the ticket.  Tickets must always have at least one datetime assigned to them.',
220
+							'event_espresso'
221
+						),
222
+						'dismiss_button'          => '<button class="button-secondary ee-modal-cancel">'
223
+													 . esc_html__('Dismiss', 'event_espresso') . '</button>',
224
+					),
225
+					'DTT_ERROR_MSG'         => array(
226
+						'no_ticket_name' => esc_html__('General Admission', 'event_espresso'),
227
+						'dismiss_button' => '<div class="save-cancel-button-container">'
228
+											. '<button class="button-secondary ee-modal-cancel">'
229
+											. esc_html__('Dismiss', 'event_espresso')
230
+											. '</button></div>',
231
+					),
232
+					'DTT_OVERSELL_WARNING'  => array(
233
+						'datetime_ticket' => esc_html__(
234
+							'You cannot add this ticket to this datetime because it has a sold amount that is greater than the amount of spots remaining for this datetime.',
235
+							'event_espresso'
236
+						),
237
+						'ticket_datetime' => esc_html__(
238
+							'You cannot add this datetime to this ticket because the ticket has a sold amount that is greater than the amount of spots remaining on the datetime.',
239
+							'event_espresso'
240
+						),
241
+					),
242
+					'DTT_CONVERTED_FORMATS' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats(
243
+						$this->_date_format_strings['date'],
244
+						$this->_date_format_strings['time']
245
+					),
246
+					'DTT_START_OF_WEEK'     => array('dayValue' => (int) get_option('start_of_week')),
247
+				),
248
+			),
249
+		);
250
+	}
251 251
 
252 252
 
253
-    /**
254
-     * @param array $update_callbacks
255
-     * @return array
256
-     */
257
-    public function caf_updates(array $update_callbacks)
258
-    {
259
-        foreach ($update_callbacks as $key => $callback) {
260
-            if ($callback[1] === '_default_tickets_update') {
261
-                unset($update_callbacks[ $key ]);
262
-            }
263
-        }
264
-        $update_callbacks[] = array($this, 'datetime_and_tickets_caf_update');
265
-        return $update_callbacks;
266
-    }
253
+	/**
254
+	 * @param array $update_callbacks
255
+	 * @return array
256
+	 */
257
+	public function caf_updates(array $update_callbacks)
258
+	{
259
+		foreach ($update_callbacks as $key => $callback) {
260
+			if ($callback[1] === '_default_tickets_update') {
261
+				unset($update_callbacks[ $key ]);
262
+			}
263
+		}
264
+		$update_callbacks[] = array($this, 'datetime_and_tickets_caf_update');
265
+		return $update_callbacks;
266
+	}
267 267
 
268 268
 
269
-    /**
270
-     * Handles saving everything related to Tickets (datetimes, tickets, prices)
271
-     *
272
-     * @param  EE_Event $event The Event object we're attaching data to
273
-     * @param  array    $data  The request data from the form
274
-     * @throws ReflectionException
275
-     * @throws Exception
276
-     * @throws InvalidInterfaceException
277
-     * @throws InvalidDataTypeException
278
-     * @throws EE_Error
279
-     * @throws InvalidArgumentException
280
-     */
281
-    public function datetime_and_tickets_caf_update($event, $data)
282
-    {
283
-        // first we need to start with datetimes cause they are the "root" items attached to events.
284
-        $saved_datetimes = $this->_update_datetimes($event, $data);
285
-        // next tackle the tickets (and prices?)
286
-        $this->_update_tickets($event, $saved_datetimes, $data);
287
-    }
269
+	/**
270
+	 * Handles saving everything related to Tickets (datetimes, tickets, prices)
271
+	 *
272
+	 * @param  EE_Event $event The Event object we're attaching data to
273
+	 * @param  array    $data  The request data from the form
274
+	 * @throws ReflectionException
275
+	 * @throws Exception
276
+	 * @throws InvalidInterfaceException
277
+	 * @throws InvalidDataTypeException
278
+	 * @throws EE_Error
279
+	 * @throws InvalidArgumentException
280
+	 */
281
+	public function datetime_and_tickets_caf_update($event, $data)
282
+	{
283
+		// first we need to start with datetimes cause they are the "root" items attached to events.
284
+		$saved_datetimes = $this->_update_datetimes($event, $data);
285
+		// next tackle the tickets (and prices?)
286
+		$this->_update_tickets($event, $saved_datetimes, $data);
287
+	}
288 288
 
289 289
 
290
-    /**
291
-     * update event_datetimes
292
-     *
293
-     * @param  EE_Event $event Event being updated
294
-     * @param  array    $data  the request data from the form
295
-     * @return EE_Datetime[]
296
-     * @throws Exception
297
-     * @throws ReflectionException
298
-     * @throws InvalidInterfaceException
299
-     * @throws InvalidDataTypeException
300
-     * @throws InvalidArgumentException
301
-     * @throws EE_Error
302
-     */
303
-    protected function _update_datetimes($event, $data)
304
-    {
305
-        $timezone = isset($data['timezone_string']) ? $data['timezone_string'] : null;
306
-        $saved_dtt_ids = array();
307
-        $saved_dtt_objs = array();
308
-        if (empty($data['edit_event_datetimes']) || ! is_array($data['edit_event_datetimes'])) {
309
-            throw new InvalidArgumentException(
310
-                esc_html__(
311
-                    'The "edit_event_datetimes" array is invalid therefore the event can not be updated.',
312
-                    'event_espresso'
313
-                )
314
-            );
315
-        }
316
-        foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
317
-            // trim all values to ensure any excess whitespace is removed.
318
-            $datetime_data = array_map(
319
-                function ($datetime_data) {
320
-                    return is_array($datetime_data) ? $datetime_data : trim($datetime_data);
321
-                },
322
-                $datetime_data
323
-            );
324
-            $datetime_data['DTT_EVT_end'] = isset($datetime_data['DTT_EVT_end'])
325
-                                            && ! empty($datetime_data['DTT_EVT_end'])
326
-                ? $datetime_data['DTT_EVT_end']
327
-                : $datetime_data['DTT_EVT_start'];
328
-            $datetime_values = array(
329
-                'DTT_ID'          => ! empty($datetime_data['DTT_ID'])
330
-                    ? $datetime_data['DTT_ID']
331
-                    : null,
332
-                'DTT_name'        => ! empty($datetime_data['DTT_name'])
333
-                    ? $datetime_data['DTT_name']
334
-                    : '',
335
-                'DTT_description' => ! empty($datetime_data['DTT_description'])
336
-                    ? $datetime_data['DTT_description']
337
-                    : '',
338
-                'DTT_EVT_start'   => $datetime_data['DTT_EVT_start'],
339
-                'DTT_EVT_end'     => $datetime_data['DTT_EVT_end'],
340
-                'DTT_reg_limit'   => empty($datetime_data['DTT_reg_limit'])
341
-                    ? EE_INF
342
-                    : $datetime_data['DTT_reg_limit'],
343
-                'DTT_order'       => ! isset($datetime_data['DTT_order'])
344
-                    ? $row
345
-                    : $datetime_data['DTT_order'],
346
-            );
347
-            // if we have an id then let's get existing object first and then set the new values.
348
-            // Otherwise we instantiate a new object for save.
349
-            if (! empty($datetime_data['DTT_ID'])) {
350
-                $datetime = EE_Registry::instance()
351
-                                       ->load_model('Datetime', array($timezone))
352
-                                       ->get_one_by_ID($datetime_data['DTT_ID']);
353
-                // set date and time format according to what is set in this class.
354
-                $datetime->set_date_format($this->_date_format_strings['date']);
355
-                $datetime->set_time_format($this->_date_format_strings['time']);
356
-                foreach ($datetime_values as $field => $value) {
357
-                    $datetime->set($field, $value);
358
-                }
359
-                // make sure the $dtt_id here is saved just in case
360
-                // after the add_relation_to() the autosave replaces it.
361
-                // We need to do this so we dont' TRASH the parent DTT.
362
-                // (save the ID for both key and value to avoid duplications)
363
-                $saved_dtt_ids[ $datetime->ID() ] = $datetime->ID();
364
-            } else {
365
-                $datetime = EE_Registry::instance()->load_class(
366
-                    'Datetime',
367
-                    array(
368
-                        $datetime_values,
369
-                        $timezone,
370
-                        array($this->_date_format_strings['date'], $this->_date_format_strings['time']),
371
-                    ),
372
-                    false,
373
-                    false
374
-                );
375
-                foreach ($datetime_values as $field => $value) {
376
-                    $datetime->set($field, $value);
377
-                }
378
-            }
379
-            $datetime->save();
380
-            do_action(
381
-                'AHEE__espresso_events_Pricing_Hooks___update_datetimes_after_save',
382
-                $datetime,
383
-                $row,
384
-                $datetime_data,
385
-                $data
386
-            );
387
-            $datetime = $event->_add_relation_to($datetime, 'Datetime');
388
-            // before going any further make sure our dates are setup correctly
389
-            // so that the end date is always equal or greater than the start date.
390
-            if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
391
-                $datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
392
-                $datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
393
-                $datetime->save();
394
-            }
395
-            // now we have to make sure we add the new DTT_ID to the $saved_dtt_ids array
396
-            // because it is possible there was a new one created for the autosave.
397
-            // (save the ID for both key and value to avoid duplications)
398
-            $DTT_ID = $datetime->ID();
399
-            $saved_dtt_ids[ $DTT_ID ] = $DTT_ID;
400
-            $saved_dtt_objs[ $row ] = $datetime;
401
-            // @todo if ANY of these updates fail then we want the appropriate global error message.
402
-        }
403
-        $event->save();
404
-        // now we need to REMOVE any datetimes that got deleted.
405
-        // Keep in mind that this process will only kick in for datetimes that don't have any DTT_sold on them.
406
-        // So its safe to permanently delete at this point.
407
-        $old_datetimes = explode(',', $data['datetime_IDs']);
408
-        $old_datetimes = $old_datetimes[0] === '' ? array() : $old_datetimes;
409
-        if (is_array($old_datetimes)) {
410
-            $datetimes_to_delete = array_diff($old_datetimes, $saved_dtt_ids);
411
-            foreach ($datetimes_to_delete as $id) {
412
-                $id = absint($id);
413
-                if (empty($id)) {
414
-                    continue;
415
-                }
416
-                $dtt_to_remove = EE_Registry::instance()->load_model('Datetime')->get_one_by_ID($id);
417
-                // remove tkt relationships.
418
-                $related_tickets = $dtt_to_remove->get_many_related('Ticket');
419
-                foreach ($related_tickets as $tkt) {
420
-                    $dtt_to_remove->_remove_relation_to($tkt, 'Ticket');
421
-                }
422
-                $event->_remove_relation_to($id, 'Datetime');
423
-                $dtt_to_remove->refresh_cache_of_related_objects();
424
-            }
425
-        }
426
-        return $saved_dtt_objs;
427
-    }
290
+	/**
291
+	 * update event_datetimes
292
+	 *
293
+	 * @param  EE_Event $event Event being updated
294
+	 * @param  array    $data  the request data from the form
295
+	 * @return EE_Datetime[]
296
+	 * @throws Exception
297
+	 * @throws ReflectionException
298
+	 * @throws InvalidInterfaceException
299
+	 * @throws InvalidDataTypeException
300
+	 * @throws InvalidArgumentException
301
+	 * @throws EE_Error
302
+	 */
303
+	protected function _update_datetimes($event, $data)
304
+	{
305
+		$timezone = isset($data['timezone_string']) ? $data['timezone_string'] : null;
306
+		$saved_dtt_ids = array();
307
+		$saved_dtt_objs = array();
308
+		if (empty($data['edit_event_datetimes']) || ! is_array($data['edit_event_datetimes'])) {
309
+			throw new InvalidArgumentException(
310
+				esc_html__(
311
+					'The "edit_event_datetimes" array is invalid therefore the event can not be updated.',
312
+					'event_espresso'
313
+				)
314
+			);
315
+		}
316
+		foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
317
+			// trim all values to ensure any excess whitespace is removed.
318
+			$datetime_data = array_map(
319
+				function ($datetime_data) {
320
+					return is_array($datetime_data) ? $datetime_data : trim($datetime_data);
321
+				},
322
+				$datetime_data
323
+			);
324
+			$datetime_data['DTT_EVT_end'] = isset($datetime_data['DTT_EVT_end'])
325
+											&& ! empty($datetime_data['DTT_EVT_end'])
326
+				? $datetime_data['DTT_EVT_end']
327
+				: $datetime_data['DTT_EVT_start'];
328
+			$datetime_values = array(
329
+				'DTT_ID'          => ! empty($datetime_data['DTT_ID'])
330
+					? $datetime_data['DTT_ID']
331
+					: null,
332
+				'DTT_name'        => ! empty($datetime_data['DTT_name'])
333
+					? $datetime_data['DTT_name']
334
+					: '',
335
+				'DTT_description' => ! empty($datetime_data['DTT_description'])
336
+					? $datetime_data['DTT_description']
337
+					: '',
338
+				'DTT_EVT_start'   => $datetime_data['DTT_EVT_start'],
339
+				'DTT_EVT_end'     => $datetime_data['DTT_EVT_end'],
340
+				'DTT_reg_limit'   => empty($datetime_data['DTT_reg_limit'])
341
+					? EE_INF
342
+					: $datetime_data['DTT_reg_limit'],
343
+				'DTT_order'       => ! isset($datetime_data['DTT_order'])
344
+					? $row
345
+					: $datetime_data['DTT_order'],
346
+			);
347
+			// if we have an id then let's get existing object first and then set the new values.
348
+			// Otherwise we instantiate a new object for save.
349
+			if (! empty($datetime_data['DTT_ID'])) {
350
+				$datetime = EE_Registry::instance()
351
+									   ->load_model('Datetime', array($timezone))
352
+									   ->get_one_by_ID($datetime_data['DTT_ID']);
353
+				// set date and time format according to what is set in this class.
354
+				$datetime->set_date_format($this->_date_format_strings['date']);
355
+				$datetime->set_time_format($this->_date_format_strings['time']);
356
+				foreach ($datetime_values as $field => $value) {
357
+					$datetime->set($field, $value);
358
+				}
359
+				// make sure the $dtt_id here is saved just in case
360
+				// after the add_relation_to() the autosave replaces it.
361
+				// We need to do this so we dont' TRASH the parent DTT.
362
+				// (save the ID for both key and value to avoid duplications)
363
+				$saved_dtt_ids[ $datetime->ID() ] = $datetime->ID();
364
+			} else {
365
+				$datetime = EE_Registry::instance()->load_class(
366
+					'Datetime',
367
+					array(
368
+						$datetime_values,
369
+						$timezone,
370
+						array($this->_date_format_strings['date'], $this->_date_format_strings['time']),
371
+					),
372
+					false,
373
+					false
374
+				);
375
+				foreach ($datetime_values as $field => $value) {
376
+					$datetime->set($field, $value);
377
+				}
378
+			}
379
+			$datetime->save();
380
+			do_action(
381
+				'AHEE__espresso_events_Pricing_Hooks___update_datetimes_after_save',
382
+				$datetime,
383
+				$row,
384
+				$datetime_data,
385
+				$data
386
+			);
387
+			$datetime = $event->_add_relation_to($datetime, 'Datetime');
388
+			// before going any further make sure our dates are setup correctly
389
+			// so that the end date is always equal or greater than the start date.
390
+			if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
391
+				$datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
392
+				$datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
393
+				$datetime->save();
394
+			}
395
+			// now we have to make sure we add the new DTT_ID to the $saved_dtt_ids array
396
+			// because it is possible there was a new one created for the autosave.
397
+			// (save the ID for both key and value to avoid duplications)
398
+			$DTT_ID = $datetime->ID();
399
+			$saved_dtt_ids[ $DTT_ID ] = $DTT_ID;
400
+			$saved_dtt_objs[ $row ] = $datetime;
401
+			// @todo if ANY of these updates fail then we want the appropriate global error message.
402
+		}
403
+		$event->save();
404
+		// now we need to REMOVE any datetimes that got deleted.
405
+		// Keep in mind that this process will only kick in for datetimes that don't have any DTT_sold on them.
406
+		// So its safe to permanently delete at this point.
407
+		$old_datetimes = explode(',', $data['datetime_IDs']);
408
+		$old_datetimes = $old_datetimes[0] === '' ? array() : $old_datetimes;
409
+		if (is_array($old_datetimes)) {
410
+			$datetimes_to_delete = array_diff($old_datetimes, $saved_dtt_ids);
411
+			foreach ($datetimes_to_delete as $id) {
412
+				$id = absint($id);
413
+				if (empty($id)) {
414
+					continue;
415
+				}
416
+				$dtt_to_remove = EE_Registry::instance()->load_model('Datetime')->get_one_by_ID($id);
417
+				// remove tkt relationships.
418
+				$related_tickets = $dtt_to_remove->get_many_related('Ticket');
419
+				foreach ($related_tickets as $tkt) {
420
+					$dtt_to_remove->_remove_relation_to($tkt, 'Ticket');
421
+				}
422
+				$event->_remove_relation_to($id, 'Datetime');
423
+				$dtt_to_remove->refresh_cache_of_related_objects();
424
+			}
425
+		}
426
+		return $saved_dtt_objs;
427
+	}
428 428
 
429 429
 
430
-    /**
431
-     * update tickets
432
-     *
433
-     * @param  EE_Event      $event           Event object being updated
434
-     * @param  EE_Datetime[] $saved_datetimes an array of datetime ids being updated
435
-     * @param  array         $data            incoming request data
436
-     * @return EE_Ticket[]
437
-     * @throws Exception
438
-     * @throws ReflectionException
439
-     * @throws InvalidInterfaceException
440
-     * @throws InvalidDataTypeException
441
-     * @throws InvalidArgumentException
442
-     * @throws EE_Error
443
-     */
444
-    protected function _update_tickets($event, $saved_datetimes, $data)
445
-    {
446
-        $new_tkt = null;
447
-        $new_default = null;
448
-        // stripslashes because WP filtered the $_POST ($data) array to add slashes
449
-        $data = stripslashes_deep($data);
450
-        $timezone = isset($data['timezone_string']) ? $data['timezone_string'] : null;
451
-        $saved_tickets = $datetimes_on_existing = array();
452
-        $old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
453
-        if (empty($data['edit_tickets']) || ! is_array($data['edit_tickets'])) {
454
-            throw new InvalidArgumentException(
455
-                esc_html__(
456
-                    'The "edit_tickets" array is invalid therefore the event can not be updated.',
457
-                    'event_espresso'
458
-                )
459
-            );
460
-        }
461
-        foreach ($data['edit_tickets'] as $row => $tkt) {
462
-            $update_prices = $create_new_TKT = false;
463
-            // figure out what datetimes were added to the ticket
464
-            // and what datetimes were removed from the ticket in the session.
465
-            $starting_tkt_dtt_rows = explode(',', $data['starting_ticket_datetime_rows'][ $row ]);
466
-            $tkt_dtt_rows = explode(',', $data['ticket_datetime_rows'][ $row ]);
467
-            $datetimes_added = array_diff($tkt_dtt_rows, $starting_tkt_dtt_rows);
468
-            $datetimes_removed = array_diff($starting_tkt_dtt_rows, $tkt_dtt_rows);
469
-            // trim inputs to ensure any excess whitespace is removed.
470
-            $tkt = array_map(
471
-                function ($ticket_data) {
472
-                    return is_array($ticket_data) ? $ticket_data : trim($ticket_data);
473
-                },
474
-                $tkt
475
-            );
476
-            // note we are doing conversions to floats here instead of allowing EE_Money_Field to handle
477
-            // because we're doing calculations prior to using the models.
478
-            // note incoming ['TKT_price'] value is already in standard notation (via js).
479
-            $ticket_price = isset($tkt['TKT_price'])
480
-                ? round((float) $tkt['TKT_price'], 3)
481
-                : 0;
482
-            // note incoming base price needs converted from localized value.
483
-            $base_price = isset($tkt['TKT_base_price'])
484
-                ? EEH_Money::convert_to_float_from_localized_money($tkt['TKT_base_price'])
485
-                : 0;
486
-            // if ticket price == 0 and $base_price != 0 then ticket price == base_price
487
-            $ticket_price = $ticket_price === 0 && $base_price !== 0
488
-                ? $base_price
489
-                : $ticket_price;
490
-            $base_price_id = isset($tkt['TKT_base_price_ID'])
491
-                ? $tkt['TKT_base_price_ID']
492
-                : 0;
493
-            $price_rows = is_array($data['edit_prices']) && isset($data['edit_prices'][ $row ])
494
-                ? $data['edit_prices'][ $row ]
495
-                : array();
496
-            $now = null;
497
-            if (empty($tkt['TKT_start_date'])) {
498
-                // lets' use now in the set timezone.
499
-                $now = new DateTime('now', new DateTimeZone($event->get_timezone()));
500
-                $tkt['TKT_start_date'] = $now->format($this->_date_time_format);
501
-            }
502
-            if (empty($tkt['TKT_end_date'])) {
503
-                /**
504
-                 * set the TKT_end_date to the first datetime attached to the ticket.
505
-                 */
506
-                $first_dtt = $saved_datetimes[ reset($tkt_dtt_rows) ];
507
-                $tkt['TKT_end_date'] = $first_dtt->start_date_and_time($this->_date_time_format);
508
-            }
509
-            $TKT_values = array(
510
-                'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
511
-                'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
512
-                'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
513
-                'TKT_description' => ! empty($tkt['TKT_description'])
514
-                                     && $tkt['TKT_description'] !== esc_html__(
515
-                                         'You can modify this description',
516
-                                         'event_espresso'
517
-                                     )
518
-                    ? $tkt['TKT_description']
519
-                    : '',
520
-                'TKT_start_date'  => $tkt['TKT_start_date'],
521
-                'TKT_end_date'    => $tkt['TKT_end_date'],
522
-                'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === ''
523
-                    ? EE_INF
524
-                    : $tkt['TKT_qty'],
525
-                'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === ''
526
-                    ? EE_INF
527
-                    : $tkt['TKT_uses'],
528
-                'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
529
-                'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
530
-                'TKT_row'         => $row,
531
-                'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : 0,
532
-                'TKT_taxable'     => ! empty($tkt['TKT_taxable']) ? 1 : 0,
533
-                'TKT_required'    => ! empty($tkt['TKT_required']) ? 1 : 0,
534
-                'TKT_price'       => $ticket_price,
535
-            );
536
-            // if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly,
537
-            // which means in turn that the prices will become new prices as well.
538
-            if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
539
-                $TKT_values['TKT_ID'] = 0;
540
-                $TKT_values['TKT_is_default'] = 0;
541
-                $update_prices = true;
542
-            }
543
-            // if we have a TKT_ID then we need to get that existing TKT_obj and update it
544
-            // we actually do our saves ahead of doing any add_relations to
545
-            // because its entirely possible that this ticket wasn't removed or added to any datetime in the session
546
-            // but DID have it's items modified.
547
-            // keep in mind that if the TKT has been sold (and we have changed pricing information),
548
-            // then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
549
-            if (absint($TKT_values['TKT_ID'])) {
550
-                $ticket = EE_Registry::instance()
551
-                                     ->load_model('Ticket', array($timezone))
552
-                                     ->get_one_by_ID($tkt['TKT_ID']);
553
-                if ($ticket instanceof EE_Ticket) {
554
-                    $ticket = $this->_update_ticket_datetimes(
555
-                        $ticket,
556
-                        $saved_datetimes,
557
-                        $datetimes_added,
558
-                        $datetimes_removed
559
-                    );
560
-                    // are there any registrations using this ticket ?
561
-                    $tickets_sold = $ticket->count_related(
562
-                        'Registration',
563
-                        array(
564
-                            array(
565
-                                'STS_ID' => array('NOT IN', array(EEM_Registration::status_id_incomplete)),
566
-                            ),
567
-                        )
568
-                    );
569
-                    // set ticket formats
570
-                    $ticket->set_date_format($this->_date_format_strings['date']);
571
-                    $ticket->set_time_format($this->_date_format_strings['time']);
572
-                    // let's just check the total price for the existing ticket
573
-                    // and determine if it matches the new total price.
574
-                    // if they are different then we create a new ticket (if tickets sold)
575
-                    // if they aren't different then we go ahead and modify existing ticket.
576
-                    $create_new_TKT = $tickets_sold > 0 && $ticket_price !== $ticket->price() && ! $ticket->deleted();
577
-                    // set new values
578
-                    foreach ($TKT_values as $field => $value) {
579
-                        if ($field === 'TKT_qty') {
580
-                            $ticket->set_qty($value);
581
-                        } else {
582
-                            $ticket->set($field, $value);
583
-                        }
584
-                    }
585
-                    // if $create_new_TKT is false then we can safely update the existing ticket.
586
-                    // Otherwise we have to create a new ticket.
587
-                    if ($create_new_TKT) {
588
-                        $new_tkt = $this->_duplicate_ticket(
589
-                            $ticket,
590
-                            $price_rows,
591
-                            $ticket_price,
592
-                            $base_price,
593
-                            $base_price_id
594
-                        );
595
-                    }
596
-                }
597
-            } else {
598
-                // no TKT_id so a new TKT
599
-                $ticket = EE_Ticket::new_instance(
600
-                    $TKT_values,
601
-                    $timezone,
602
-                    array($this->_date_format_strings['date'], $this->_date_format_strings['time'])
603
-                );
604
-                if ($ticket instanceof EE_Ticket) {
605
-                    // make sure ticket has an ID of setting relations won't work
606
-                    $ticket->save();
607
-                    $ticket = $this->_update_ticket_datetimes(
608
-                        $ticket,
609
-                        $saved_datetimes,
610
-                        $datetimes_added,
611
-                        $datetimes_removed
612
-                    );
613
-                    $update_prices = true;
614
-                }
615
-            }
616
-            // make sure any current values have been saved.
617
-            // $ticket->save();
618
-            // before going any further make sure our dates are setup correctly
619
-            // so that the end date is always equal or greater than the start date.
620
-            if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
621
-                $ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
622
-                $ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
623
-            }
624
-            // let's make sure the base price is handled
625
-            $ticket = ! $create_new_TKT
626
-                ? $this->_add_prices_to_ticket(
627
-                    array(),
628
-                    $ticket,
629
-                    $update_prices,
630
-                    $base_price,
631
-                    $base_price_id
632
-                )
633
-                : $ticket;
634
-            // add/update price_modifiers
635
-            $ticket = ! $create_new_TKT
636
-                ? $this->_add_prices_to_ticket($price_rows, $ticket, $update_prices)
637
-                : $ticket;
638
-            // need to make sue that the TKT_price is accurate after saving the prices.
639
-            $ticket->ensure_TKT_Price_correct();
640
-            // handle CREATING a default tkt from the incoming tkt but ONLY if this isn't an autosave.
641
-            if (! defined('DOING_AUTOSAVE') && ! empty($tkt['TKT_is_default_selector'])) {
642
-                $update_prices = true;
643
-                $new_default = clone $ticket;
644
-                $new_default->set('TKT_ID', 0);
645
-                $new_default->set('TKT_is_default', 1);
646
-                $new_default->set('TKT_row', 1);
647
-                $new_default->set('TKT_price', $ticket_price);
648
-                // remove any dtt relations cause we DON'T want dtt relations attached
649
-                // (note this is just removing the cached relations in the object)
650
-                $new_default->_remove_relations('Datetime');
651
-                // @todo we need to add the current attached prices as new prices to the new default ticket.
652
-                $new_default = $this->_add_prices_to_ticket(
653
-                    $price_rows,
654
-                    $new_default,
655
-                    $update_prices
656
-                );
657
-                // don't forget the base price!
658
-                $new_default = $this->_add_prices_to_ticket(
659
-                    array(),
660
-                    $new_default,
661
-                    $update_prices,
662
-                    $base_price,
663
-                    $base_price_id
664
-                );
665
-                $new_default->save();
666
-                do_action(
667
-                    'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_default_ticket',
668
-                    $new_default,
669
-                    $row,
670
-                    $ticket,
671
-                    $data
672
-                );
673
-            }
674
-            // DO ALL dtt relationships for both current tickets and any archived tickets
675
-            // for the given dtt that are related to the current ticket.
676
-            // TODO... not sure exactly how we're going to do this considering we don't know
677
-            // what current ticket the archived tickets are related to
678
-            // (and TKT_parent is used for autosaves so that's not a field we can reliably use).
679
-            // let's assign any tickets that have been setup to the saved_tickets tracker
680
-            // save existing TKT
681
-            $ticket->save();
682
-            if ($create_new_TKT && $new_tkt instanceof EE_Ticket) {
683
-                // save new TKT
684
-                $new_tkt->save();
685
-                // add new ticket to array
686
-                $saved_tickets[ $new_tkt->ID() ] = $new_tkt;
687
-                do_action(
688
-                    'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_ticket',
689
-                    $new_tkt,
690
-                    $row,
691
-                    $tkt,
692
-                    $data
693
-                );
694
-            } else {
695
-                // add tkt to saved tkts
696
-                $saved_tickets[ $ticket->ID() ] = $ticket;
697
-                do_action(
698
-                    'AHEE__espresso_events_Pricing_Hooks___update_tkts_update_ticket',
699
-                    $ticket,
700
-                    $row,
701
-                    $tkt,
702
-                    $data
703
-                );
704
-            }
705
-        }
706
-        // now we need to handle tickets actually "deleted permanently".
707
-        // There are cases where we'd want this to happen
708
-        // (i.e. autosaves are happening and then in between autosaves the user trashes a ticket).
709
-        // Or a draft event was saved and in the process of editing a ticket is trashed.
710
-        // No sense in keeping all the related data in the db!
711
-        $old_tickets = isset($old_tickets[0]) && $old_tickets[0] === '' ? array() : $old_tickets;
712
-        $tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
713
-        foreach ($tickets_removed as $id) {
714
-            $id = absint($id);
715
-            // get the ticket for this id
716
-            $tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
717
-            // if this tkt is a default tkt we leave it alone cause it won't be attached to the datetime
718
-            if ($tkt_to_remove->get('TKT_is_default')) {
719
-                continue;
720
-            }
721
-            // if this tkt has any registrations attached so then we just ARCHIVE
722
-            // because we don't actually permanently delete these tickets.
723
-            if ($tkt_to_remove->count_related('Registration') > 0) {
724
-                $tkt_to_remove->delete();
725
-                continue;
726
-            }
727
-            // need to get all the related datetimes on this ticket and remove from every single one of them
728
-            // (remember this process can ONLY kick off if there are NO tkts_sold)
729
-            $datetimes = $tkt_to_remove->get_many_related('Datetime');
730
-            foreach ($datetimes as $datetime) {
731
-                $tkt_to_remove->_remove_relation_to($datetime, 'Datetime');
732
-            }
733
-            // need to do the same for prices (except these prices can also be deleted because again,
734
-            // tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
735
-            $tkt_to_remove->delete_related_permanently('Price');
736
-            do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_delete_ticket', $tkt_to_remove);
737
-            // finally let's delete this ticket
738
-            // (which should not be blocked at this point b/c we've removed all our relationships)
739
-            $tkt_to_remove->delete_permanently();
740
-        }
741
-        return $saved_tickets;
742
-    }
430
+	/**
431
+	 * update tickets
432
+	 *
433
+	 * @param  EE_Event      $event           Event object being updated
434
+	 * @param  EE_Datetime[] $saved_datetimes an array of datetime ids being updated
435
+	 * @param  array         $data            incoming request data
436
+	 * @return EE_Ticket[]
437
+	 * @throws Exception
438
+	 * @throws ReflectionException
439
+	 * @throws InvalidInterfaceException
440
+	 * @throws InvalidDataTypeException
441
+	 * @throws InvalidArgumentException
442
+	 * @throws EE_Error
443
+	 */
444
+	protected function _update_tickets($event, $saved_datetimes, $data)
445
+	{
446
+		$new_tkt = null;
447
+		$new_default = null;
448
+		// stripslashes because WP filtered the $_POST ($data) array to add slashes
449
+		$data = stripslashes_deep($data);
450
+		$timezone = isset($data['timezone_string']) ? $data['timezone_string'] : null;
451
+		$saved_tickets = $datetimes_on_existing = array();
452
+		$old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
453
+		if (empty($data['edit_tickets']) || ! is_array($data['edit_tickets'])) {
454
+			throw new InvalidArgumentException(
455
+				esc_html__(
456
+					'The "edit_tickets" array is invalid therefore the event can not be updated.',
457
+					'event_espresso'
458
+				)
459
+			);
460
+		}
461
+		foreach ($data['edit_tickets'] as $row => $tkt) {
462
+			$update_prices = $create_new_TKT = false;
463
+			// figure out what datetimes were added to the ticket
464
+			// and what datetimes were removed from the ticket in the session.
465
+			$starting_tkt_dtt_rows = explode(',', $data['starting_ticket_datetime_rows'][ $row ]);
466
+			$tkt_dtt_rows = explode(',', $data['ticket_datetime_rows'][ $row ]);
467
+			$datetimes_added = array_diff($tkt_dtt_rows, $starting_tkt_dtt_rows);
468
+			$datetimes_removed = array_diff($starting_tkt_dtt_rows, $tkt_dtt_rows);
469
+			// trim inputs to ensure any excess whitespace is removed.
470
+			$tkt = array_map(
471
+				function ($ticket_data) {
472
+					return is_array($ticket_data) ? $ticket_data : trim($ticket_data);
473
+				},
474
+				$tkt
475
+			);
476
+			// note we are doing conversions to floats here instead of allowing EE_Money_Field to handle
477
+			// because we're doing calculations prior to using the models.
478
+			// note incoming ['TKT_price'] value is already in standard notation (via js).
479
+			$ticket_price = isset($tkt['TKT_price'])
480
+				? round((float) $tkt['TKT_price'], 3)
481
+				: 0;
482
+			// note incoming base price needs converted from localized value.
483
+			$base_price = isset($tkt['TKT_base_price'])
484
+				? EEH_Money::convert_to_float_from_localized_money($tkt['TKT_base_price'])
485
+				: 0;
486
+			// if ticket price == 0 and $base_price != 0 then ticket price == base_price
487
+			$ticket_price = $ticket_price === 0 && $base_price !== 0
488
+				? $base_price
489
+				: $ticket_price;
490
+			$base_price_id = isset($tkt['TKT_base_price_ID'])
491
+				? $tkt['TKT_base_price_ID']
492
+				: 0;
493
+			$price_rows = is_array($data['edit_prices']) && isset($data['edit_prices'][ $row ])
494
+				? $data['edit_prices'][ $row ]
495
+				: array();
496
+			$now = null;
497
+			if (empty($tkt['TKT_start_date'])) {
498
+				// lets' use now in the set timezone.
499
+				$now = new DateTime('now', new DateTimeZone($event->get_timezone()));
500
+				$tkt['TKT_start_date'] = $now->format($this->_date_time_format);
501
+			}
502
+			if (empty($tkt['TKT_end_date'])) {
503
+				/**
504
+				 * set the TKT_end_date to the first datetime attached to the ticket.
505
+				 */
506
+				$first_dtt = $saved_datetimes[ reset($tkt_dtt_rows) ];
507
+				$tkt['TKT_end_date'] = $first_dtt->start_date_and_time($this->_date_time_format);
508
+			}
509
+			$TKT_values = array(
510
+				'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
511
+				'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
512
+				'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
513
+				'TKT_description' => ! empty($tkt['TKT_description'])
514
+									 && $tkt['TKT_description'] !== esc_html__(
515
+										 'You can modify this description',
516
+										 'event_espresso'
517
+									 )
518
+					? $tkt['TKT_description']
519
+					: '',
520
+				'TKT_start_date'  => $tkt['TKT_start_date'],
521
+				'TKT_end_date'    => $tkt['TKT_end_date'],
522
+				'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === ''
523
+					? EE_INF
524
+					: $tkt['TKT_qty'],
525
+				'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === ''
526
+					? EE_INF
527
+					: $tkt['TKT_uses'],
528
+				'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
529
+				'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
530
+				'TKT_row'         => $row,
531
+				'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : 0,
532
+				'TKT_taxable'     => ! empty($tkt['TKT_taxable']) ? 1 : 0,
533
+				'TKT_required'    => ! empty($tkt['TKT_required']) ? 1 : 0,
534
+				'TKT_price'       => $ticket_price,
535
+			);
536
+			// if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly,
537
+			// which means in turn that the prices will become new prices as well.
538
+			if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
539
+				$TKT_values['TKT_ID'] = 0;
540
+				$TKT_values['TKT_is_default'] = 0;
541
+				$update_prices = true;
542
+			}
543
+			// if we have a TKT_ID then we need to get that existing TKT_obj and update it
544
+			// we actually do our saves ahead of doing any add_relations to
545
+			// because its entirely possible that this ticket wasn't removed or added to any datetime in the session
546
+			// but DID have it's items modified.
547
+			// keep in mind that if the TKT has been sold (and we have changed pricing information),
548
+			// then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
549
+			if (absint($TKT_values['TKT_ID'])) {
550
+				$ticket = EE_Registry::instance()
551
+									 ->load_model('Ticket', array($timezone))
552
+									 ->get_one_by_ID($tkt['TKT_ID']);
553
+				if ($ticket instanceof EE_Ticket) {
554
+					$ticket = $this->_update_ticket_datetimes(
555
+						$ticket,
556
+						$saved_datetimes,
557
+						$datetimes_added,
558
+						$datetimes_removed
559
+					);
560
+					// are there any registrations using this ticket ?
561
+					$tickets_sold = $ticket->count_related(
562
+						'Registration',
563
+						array(
564
+							array(
565
+								'STS_ID' => array('NOT IN', array(EEM_Registration::status_id_incomplete)),
566
+							),
567
+						)
568
+					);
569
+					// set ticket formats
570
+					$ticket->set_date_format($this->_date_format_strings['date']);
571
+					$ticket->set_time_format($this->_date_format_strings['time']);
572
+					// let's just check the total price for the existing ticket
573
+					// and determine if it matches the new total price.
574
+					// if they are different then we create a new ticket (if tickets sold)
575
+					// if they aren't different then we go ahead and modify existing ticket.
576
+					$create_new_TKT = $tickets_sold > 0 && $ticket_price !== $ticket->price() && ! $ticket->deleted();
577
+					// set new values
578
+					foreach ($TKT_values as $field => $value) {
579
+						if ($field === 'TKT_qty') {
580
+							$ticket->set_qty($value);
581
+						} else {
582
+							$ticket->set($field, $value);
583
+						}
584
+					}
585
+					// if $create_new_TKT is false then we can safely update the existing ticket.
586
+					// Otherwise we have to create a new ticket.
587
+					if ($create_new_TKT) {
588
+						$new_tkt = $this->_duplicate_ticket(
589
+							$ticket,
590
+							$price_rows,
591
+							$ticket_price,
592
+							$base_price,
593
+							$base_price_id
594
+						);
595
+					}
596
+				}
597
+			} else {
598
+				// no TKT_id so a new TKT
599
+				$ticket = EE_Ticket::new_instance(
600
+					$TKT_values,
601
+					$timezone,
602
+					array($this->_date_format_strings['date'], $this->_date_format_strings['time'])
603
+				);
604
+				if ($ticket instanceof EE_Ticket) {
605
+					// make sure ticket has an ID of setting relations won't work
606
+					$ticket->save();
607
+					$ticket = $this->_update_ticket_datetimes(
608
+						$ticket,
609
+						$saved_datetimes,
610
+						$datetimes_added,
611
+						$datetimes_removed
612
+					);
613
+					$update_prices = true;
614
+				}
615
+			}
616
+			// make sure any current values have been saved.
617
+			// $ticket->save();
618
+			// before going any further make sure our dates are setup correctly
619
+			// so that the end date is always equal or greater than the start date.
620
+			if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
621
+				$ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
622
+				$ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
623
+			}
624
+			// let's make sure the base price is handled
625
+			$ticket = ! $create_new_TKT
626
+				? $this->_add_prices_to_ticket(
627
+					array(),
628
+					$ticket,
629
+					$update_prices,
630
+					$base_price,
631
+					$base_price_id
632
+				)
633
+				: $ticket;
634
+			// add/update price_modifiers
635
+			$ticket = ! $create_new_TKT
636
+				? $this->_add_prices_to_ticket($price_rows, $ticket, $update_prices)
637
+				: $ticket;
638
+			// need to make sue that the TKT_price is accurate after saving the prices.
639
+			$ticket->ensure_TKT_Price_correct();
640
+			// handle CREATING a default tkt from the incoming tkt but ONLY if this isn't an autosave.
641
+			if (! defined('DOING_AUTOSAVE') && ! empty($tkt['TKT_is_default_selector'])) {
642
+				$update_prices = true;
643
+				$new_default = clone $ticket;
644
+				$new_default->set('TKT_ID', 0);
645
+				$new_default->set('TKT_is_default', 1);
646
+				$new_default->set('TKT_row', 1);
647
+				$new_default->set('TKT_price', $ticket_price);
648
+				// remove any dtt relations cause we DON'T want dtt relations attached
649
+				// (note this is just removing the cached relations in the object)
650
+				$new_default->_remove_relations('Datetime');
651
+				// @todo we need to add the current attached prices as new prices to the new default ticket.
652
+				$new_default = $this->_add_prices_to_ticket(
653
+					$price_rows,
654
+					$new_default,
655
+					$update_prices
656
+				);
657
+				// don't forget the base price!
658
+				$new_default = $this->_add_prices_to_ticket(
659
+					array(),
660
+					$new_default,
661
+					$update_prices,
662
+					$base_price,
663
+					$base_price_id
664
+				);
665
+				$new_default->save();
666
+				do_action(
667
+					'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_default_ticket',
668
+					$new_default,
669
+					$row,
670
+					$ticket,
671
+					$data
672
+				);
673
+			}
674
+			// DO ALL dtt relationships for both current tickets and any archived tickets
675
+			// for the given dtt that are related to the current ticket.
676
+			// TODO... not sure exactly how we're going to do this considering we don't know
677
+			// what current ticket the archived tickets are related to
678
+			// (and TKT_parent is used for autosaves so that's not a field we can reliably use).
679
+			// let's assign any tickets that have been setup to the saved_tickets tracker
680
+			// save existing TKT
681
+			$ticket->save();
682
+			if ($create_new_TKT && $new_tkt instanceof EE_Ticket) {
683
+				// save new TKT
684
+				$new_tkt->save();
685
+				// add new ticket to array
686
+				$saved_tickets[ $new_tkt->ID() ] = $new_tkt;
687
+				do_action(
688
+					'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_ticket',
689
+					$new_tkt,
690
+					$row,
691
+					$tkt,
692
+					$data
693
+				);
694
+			} else {
695
+				// add tkt to saved tkts
696
+				$saved_tickets[ $ticket->ID() ] = $ticket;
697
+				do_action(
698
+					'AHEE__espresso_events_Pricing_Hooks___update_tkts_update_ticket',
699
+					$ticket,
700
+					$row,
701
+					$tkt,
702
+					$data
703
+				);
704
+			}
705
+		}
706
+		// now we need to handle tickets actually "deleted permanently".
707
+		// There are cases where we'd want this to happen
708
+		// (i.e. autosaves are happening and then in between autosaves the user trashes a ticket).
709
+		// Or a draft event was saved and in the process of editing a ticket is trashed.
710
+		// No sense in keeping all the related data in the db!
711
+		$old_tickets = isset($old_tickets[0]) && $old_tickets[0] === '' ? array() : $old_tickets;
712
+		$tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
713
+		foreach ($tickets_removed as $id) {
714
+			$id = absint($id);
715
+			// get the ticket for this id
716
+			$tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
717
+			// if this tkt is a default tkt we leave it alone cause it won't be attached to the datetime
718
+			if ($tkt_to_remove->get('TKT_is_default')) {
719
+				continue;
720
+			}
721
+			// if this tkt has any registrations attached so then we just ARCHIVE
722
+			// because we don't actually permanently delete these tickets.
723
+			if ($tkt_to_remove->count_related('Registration') > 0) {
724
+				$tkt_to_remove->delete();
725
+				continue;
726
+			}
727
+			// need to get all the related datetimes on this ticket and remove from every single one of them
728
+			// (remember this process can ONLY kick off if there are NO tkts_sold)
729
+			$datetimes = $tkt_to_remove->get_many_related('Datetime');
730
+			foreach ($datetimes as $datetime) {
731
+				$tkt_to_remove->_remove_relation_to($datetime, 'Datetime');
732
+			}
733
+			// need to do the same for prices (except these prices can also be deleted because again,
734
+			// tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
735
+			$tkt_to_remove->delete_related_permanently('Price');
736
+			do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_delete_ticket', $tkt_to_remove);
737
+			// finally let's delete this ticket
738
+			// (which should not be blocked at this point b/c we've removed all our relationships)
739
+			$tkt_to_remove->delete_permanently();
740
+		}
741
+		return $saved_tickets;
742
+	}
743 743
 
744 744
 
745
-    /**
746
-     * @access  protected
747
-     * @param EE_Ticket      $ticket
748
-     * @param \EE_Datetime[] $saved_datetimes
749
-     * @param \EE_Datetime[] $added_datetimes
750
-     * @param \EE_Datetime[] $removed_datetimes
751
-     * @return EE_Ticket
752
-     * @throws EE_Error
753
-     */
754
-    protected function _update_ticket_datetimes(
755
-        EE_Ticket $ticket,
756
-        $saved_datetimes = array(),
757
-        $added_datetimes = array(),
758
-        $removed_datetimes = array()
759
-    ) {
760
-        // to start we have to add the ticket to all the datetimes its supposed to be with,
761
-        // and removing the ticket from datetimes it got removed from.
762
-        // first let's add datetimes
763
-        if (! empty($added_datetimes) && is_array($added_datetimes)) {
764
-            foreach ($added_datetimes as $row_id) {
765
-                $row_id = (int) $row_id;
766
-                if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
767
-                    $ticket->_add_relation_to($saved_datetimes[ $row_id ], 'Datetime');
768
-                    // Is this an existing ticket (has an ID) and does it have any sold?
769
-                    // If so, then we need to add that to the DTT sold because this DTT is getting added.
770
-                    if ($ticket->ID() && $ticket->sold() > 0) {
771
-                        $saved_datetimes[ $row_id ]->increaseSold($ticket->sold(), false);
772
-                    }
773
-                }
774
-            }
775
-        }
776
-        // then remove datetimes
777
-        if (! empty($removed_datetimes) && is_array($removed_datetimes)) {
778
-            foreach ($removed_datetimes as $row_id) {
779
-                $row_id = (int) $row_id;
780
-                // its entirely possible that a datetime got deleted (instead of just removed from relationship.
781
-                // So make sure we skip over this if the dtt isn't in the $saved_datetimes array)
782
-                if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
783
-                    $ticket->_remove_relation_to($saved_datetimes[ $row_id ], 'Datetime');
784
-                    // Is this an existing ticket (has an ID) and does it have any sold?
785
-                    // If so, then we need to remove it's sold from the DTT_sold.
786
-                    if ($ticket->ID() && $ticket->sold() > 0) {
787
-                        $saved_datetimes[ $row_id ]->decreaseSold($ticket->sold());
788
-                    }
789
-                }
790
-            }
791
-        }
792
-        // cap ticket qty by datetime reg limits
793
-        $ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
794
-        return $ticket;
795
-    }
745
+	/**
746
+	 * @access  protected
747
+	 * @param EE_Ticket      $ticket
748
+	 * @param \EE_Datetime[] $saved_datetimes
749
+	 * @param \EE_Datetime[] $added_datetimes
750
+	 * @param \EE_Datetime[] $removed_datetimes
751
+	 * @return EE_Ticket
752
+	 * @throws EE_Error
753
+	 */
754
+	protected function _update_ticket_datetimes(
755
+		EE_Ticket $ticket,
756
+		$saved_datetimes = array(),
757
+		$added_datetimes = array(),
758
+		$removed_datetimes = array()
759
+	) {
760
+		// to start we have to add the ticket to all the datetimes its supposed to be with,
761
+		// and removing the ticket from datetimes it got removed from.
762
+		// first let's add datetimes
763
+		if (! empty($added_datetimes) && is_array($added_datetimes)) {
764
+			foreach ($added_datetimes as $row_id) {
765
+				$row_id = (int) $row_id;
766
+				if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
767
+					$ticket->_add_relation_to($saved_datetimes[ $row_id ], 'Datetime');
768
+					// Is this an existing ticket (has an ID) and does it have any sold?
769
+					// If so, then we need to add that to the DTT sold because this DTT is getting added.
770
+					if ($ticket->ID() && $ticket->sold() > 0) {
771
+						$saved_datetimes[ $row_id ]->increaseSold($ticket->sold(), false);
772
+					}
773
+				}
774
+			}
775
+		}
776
+		// then remove datetimes
777
+		if (! empty($removed_datetimes) && is_array($removed_datetimes)) {
778
+			foreach ($removed_datetimes as $row_id) {
779
+				$row_id = (int) $row_id;
780
+				// its entirely possible that a datetime got deleted (instead of just removed from relationship.
781
+				// So make sure we skip over this if the dtt isn't in the $saved_datetimes array)
782
+				if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
783
+					$ticket->_remove_relation_to($saved_datetimes[ $row_id ], 'Datetime');
784
+					// Is this an existing ticket (has an ID) and does it have any sold?
785
+					// If so, then we need to remove it's sold from the DTT_sold.
786
+					if ($ticket->ID() && $ticket->sold() > 0) {
787
+						$saved_datetimes[ $row_id ]->decreaseSold($ticket->sold());
788
+					}
789
+				}
790
+			}
791
+		}
792
+		// cap ticket qty by datetime reg limits
793
+		$ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
794
+		return $ticket;
795
+	}
796 796
 
797 797
 
798
-    /**
799
-     * @access  protected
800
-     * @param EE_Ticket $ticket
801
-     * @param array     $price_rows
802
-     * @param int       $ticket_price
803
-     * @param int       $base_price
804
-     * @param int       $base_price_id
805
-     * @return EE_Ticket
806
-     * @throws ReflectionException
807
-     * @throws InvalidArgumentException
808
-     * @throws InvalidInterfaceException
809
-     * @throws InvalidDataTypeException
810
-     * @throws EE_Error
811
-     */
812
-    protected function _duplicate_ticket(
813
-        EE_Ticket $ticket,
814
-        $price_rows = array(),
815
-        $ticket_price = 0,
816
-        $base_price = 0,
817
-        $base_price_id = 0
818
-    ) {
819
-        // create new ticket that's a copy of the existing
820
-        // except a new id of course (and not archived)
821
-        // AND has the new TKT_price associated with it.
822
-        $new_ticket = clone $ticket;
823
-        $new_ticket->set('TKT_ID', 0);
824
-        $new_ticket->set_deleted(0);
825
-        $new_ticket->set_price($ticket_price);
826
-        $new_ticket->set_sold(0);
827
-        // let's get a new ID for this ticket
828
-        $new_ticket->save();
829
-        // we also need to make sure this new ticket gets the same datetime attachments as the archived ticket
830
-        $datetimes_on_existing = $ticket->datetimes();
831
-        $new_ticket = $this->_update_ticket_datetimes(
832
-            $new_ticket,
833
-            $datetimes_on_existing,
834
-            array_keys($datetimes_on_existing)
835
-        );
836
-        // $ticket will get archived later b/c we are NOT adding it to the saved_tickets array.
837
-        // if existing $ticket has sold amount, then we need to adjust the qty for the new TKT to = the remaining
838
-        // available.
839
-        if ($ticket->sold() > 0) {
840
-            $new_qty = $ticket->qty() - $ticket->sold();
841
-            $new_ticket->set_qty($new_qty);
842
-        }
843
-        // now we update the prices just for this ticket
844
-        $new_ticket = $this->_add_prices_to_ticket($price_rows, $new_ticket, true);
845
-        // and we update the base price
846
-        $new_ticket = $this->_add_prices_to_ticket(
847
-            array(),
848
-            $new_ticket,
849
-            true,
850
-            $base_price,
851
-            $base_price_id
852
-        );
853
-        return $new_ticket;
854
-    }
798
+	/**
799
+	 * @access  protected
800
+	 * @param EE_Ticket $ticket
801
+	 * @param array     $price_rows
802
+	 * @param int       $ticket_price
803
+	 * @param int       $base_price
804
+	 * @param int       $base_price_id
805
+	 * @return EE_Ticket
806
+	 * @throws ReflectionException
807
+	 * @throws InvalidArgumentException
808
+	 * @throws InvalidInterfaceException
809
+	 * @throws InvalidDataTypeException
810
+	 * @throws EE_Error
811
+	 */
812
+	protected function _duplicate_ticket(
813
+		EE_Ticket $ticket,
814
+		$price_rows = array(),
815
+		$ticket_price = 0,
816
+		$base_price = 0,
817
+		$base_price_id = 0
818
+	) {
819
+		// create new ticket that's a copy of the existing
820
+		// except a new id of course (and not archived)
821
+		// AND has the new TKT_price associated with it.
822
+		$new_ticket = clone $ticket;
823
+		$new_ticket->set('TKT_ID', 0);
824
+		$new_ticket->set_deleted(0);
825
+		$new_ticket->set_price($ticket_price);
826
+		$new_ticket->set_sold(0);
827
+		// let's get a new ID for this ticket
828
+		$new_ticket->save();
829
+		// we also need to make sure this new ticket gets the same datetime attachments as the archived ticket
830
+		$datetimes_on_existing = $ticket->datetimes();
831
+		$new_ticket = $this->_update_ticket_datetimes(
832
+			$new_ticket,
833
+			$datetimes_on_existing,
834
+			array_keys($datetimes_on_existing)
835
+		);
836
+		// $ticket will get archived later b/c we are NOT adding it to the saved_tickets array.
837
+		// if existing $ticket has sold amount, then we need to adjust the qty for the new TKT to = the remaining
838
+		// available.
839
+		if ($ticket->sold() > 0) {
840
+			$new_qty = $ticket->qty() - $ticket->sold();
841
+			$new_ticket->set_qty($new_qty);
842
+		}
843
+		// now we update the prices just for this ticket
844
+		$new_ticket = $this->_add_prices_to_ticket($price_rows, $new_ticket, true);
845
+		// and we update the base price
846
+		$new_ticket = $this->_add_prices_to_ticket(
847
+			array(),
848
+			$new_ticket,
849
+			true,
850
+			$base_price,
851
+			$base_price_id
852
+		);
853
+		return $new_ticket;
854
+	}
855 855
 
856 856
 
857
-    /**
858
-     * This attaches a list of given prices to a ticket.
859
-     * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
860
-     * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
861
-     * price info and prices are automatically "archived" via the ticket.
862
-     *
863
-     * @access  private
864
-     * @param array     $prices        Array of prices from the form.
865
-     * @param EE_Ticket $ticket        EE_Ticket object that prices are being attached to.
866
-     * @param bool      $new_prices    Whether attach existing incoming prices or create new ones.
867
-     * @param int|bool  $base_price    if FALSE then NOT doing a base price add.
868
-     * @param int|bool  $base_price_id if present then this is the base_price_id being updated.
869
-     * @return EE_Ticket
870
-     * @throws ReflectionException
871
-     * @throws InvalidArgumentException
872
-     * @throws InvalidInterfaceException
873
-     * @throws InvalidDataTypeException
874
-     * @throws EE_Error
875
-     */
876
-    protected function _add_prices_to_ticket(
877
-        $prices = array(),
878
-        EE_Ticket $ticket,
879
-        $new_prices = false,
880
-        $base_price = false,
881
-        $base_price_id = false
882
-    ) {
883
-        // let's just get any current prices that may exist on the given ticket
884
-        // so we can remove any prices that got trashed in this session.
885
-        $current_prices_on_ticket = $base_price !== false
886
-            ? $ticket->base_price(true)
887
-            : $ticket->price_modifiers();
888
-        $updated_prices = array();
889
-        // if $base_price ! FALSE then updating a base price.
890
-        if ($base_price !== false) {
891
-            $prices[1] = array(
892
-                'PRC_ID'     => $new_prices || $base_price_id === 1 ? null : $base_price_id,
893
-                'PRT_ID'     => 1,
894
-                'PRC_amount' => $base_price,
895
-                'PRC_name'   => $ticket->get('TKT_name'),
896
-                'PRC_desc'   => $ticket->get('TKT_description'),
897
-            );
898
-        }
899
-        // possibly need to save tkt
900
-        if (! $ticket->ID()) {
901
-            $ticket->save();
902
-        }
903
-        foreach ($prices as $row => $prc) {
904
-            $prt_id = ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null;
905
-            if (empty($prt_id)) {
906
-                continue;
907
-            } //prices MUST have a price type id.
908
-            $PRC_values = array(
909
-                'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
910
-                'PRT_ID'         => $prt_id,
911
-                'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
912
-                'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
913
-                'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
914
-                'PRC_is_default' => false,
915
-                // make sure we set PRC_is_default to false for all ticket saves from event_editor
916
-                'PRC_order'      => $row,
917
-            );
918
-            if ($new_prices || empty($PRC_values['PRC_ID'])) {
919
-                $PRC_values['PRC_ID'] = 0;
920
-                $price = EE_Registry::instance()->load_class(
921
-                    'Price',
922
-                    array($PRC_values),
923
-                    false,
924
-                    false
925
-                );
926
-            } else {
927
-                $price = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
928
-                // update this price with new values
929
-                foreach ($PRC_values as $field => $value) {
930
-                    $price->set($field, $value);
931
-                }
932
-            }
933
-            $price->save();
934
-            $updated_prices[ $price->ID() ] = $price;
935
-            $ticket->_add_relation_to($price, 'Price');
936
-        }
937
-        // now let's remove any prices that got removed from the ticket
938
-        if (! empty($current_prices_on_ticket)) {
939
-            $current = array_keys($current_prices_on_ticket);
940
-            $updated = array_keys($updated_prices);
941
-            $prices_to_remove = array_diff($current, $updated);
942
-            if (! empty($prices_to_remove)) {
943
-                foreach ($prices_to_remove as $prc_id) {
944
-                    $p = $current_prices_on_ticket[ $prc_id ];
945
-                    $ticket->_remove_relation_to($p, 'Price');
946
-                    // delete permanently the price
947
-                    $p->delete_permanently();
948
-                }
949
-            }
950
-        }
951
-        return $ticket;
952
-    }
857
+	/**
858
+	 * This attaches a list of given prices to a ticket.
859
+	 * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
860
+	 * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
861
+	 * price info and prices are automatically "archived" via the ticket.
862
+	 *
863
+	 * @access  private
864
+	 * @param array     $prices        Array of prices from the form.
865
+	 * @param EE_Ticket $ticket        EE_Ticket object that prices are being attached to.
866
+	 * @param bool      $new_prices    Whether attach existing incoming prices or create new ones.
867
+	 * @param int|bool  $base_price    if FALSE then NOT doing a base price add.
868
+	 * @param int|bool  $base_price_id if present then this is the base_price_id being updated.
869
+	 * @return EE_Ticket
870
+	 * @throws ReflectionException
871
+	 * @throws InvalidArgumentException
872
+	 * @throws InvalidInterfaceException
873
+	 * @throws InvalidDataTypeException
874
+	 * @throws EE_Error
875
+	 */
876
+	protected function _add_prices_to_ticket(
877
+		$prices = array(),
878
+		EE_Ticket $ticket,
879
+		$new_prices = false,
880
+		$base_price = false,
881
+		$base_price_id = false
882
+	) {
883
+		// let's just get any current prices that may exist on the given ticket
884
+		// so we can remove any prices that got trashed in this session.
885
+		$current_prices_on_ticket = $base_price !== false
886
+			? $ticket->base_price(true)
887
+			: $ticket->price_modifiers();
888
+		$updated_prices = array();
889
+		// if $base_price ! FALSE then updating a base price.
890
+		if ($base_price !== false) {
891
+			$prices[1] = array(
892
+				'PRC_ID'     => $new_prices || $base_price_id === 1 ? null : $base_price_id,
893
+				'PRT_ID'     => 1,
894
+				'PRC_amount' => $base_price,
895
+				'PRC_name'   => $ticket->get('TKT_name'),
896
+				'PRC_desc'   => $ticket->get('TKT_description'),
897
+			);
898
+		}
899
+		// possibly need to save tkt
900
+		if (! $ticket->ID()) {
901
+			$ticket->save();
902
+		}
903
+		foreach ($prices as $row => $prc) {
904
+			$prt_id = ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null;
905
+			if (empty($prt_id)) {
906
+				continue;
907
+			} //prices MUST have a price type id.
908
+			$PRC_values = array(
909
+				'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
910
+				'PRT_ID'         => $prt_id,
911
+				'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
912
+				'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
913
+				'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
914
+				'PRC_is_default' => false,
915
+				// make sure we set PRC_is_default to false for all ticket saves from event_editor
916
+				'PRC_order'      => $row,
917
+			);
918
+			if ($new_prices || empty($PRC_values['PRC_ID'])) {
919
+				$PRC_values['PRC_ID'] = 0;
920
+				$price = EE_Registry::instance()->load_class(
921
+					'Price',
922
+					array($PRC_values),
923
+					false,
924
+					false
925
+				);
926
+			} else {
927
+				$price = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
928
+				// update this price with new values
929
+				foreach ($PRC_values as $field => $value) {
930
+					$price->set($field, $value);
931
+				}
932
+			}
933
+			$price->save();
934
+			$updated_prices[ $price->ID() ] = $price;
935
+			$ticket->_add_relation_to($price, 'Price');
936
+		}
937
+		// now let's remove any prices that got removed from the ticket
938
+		if (! empty($current_prices_on_ticket)) {
939
+			$current = array_keys($current_prices_on_ticket);
940
+			$updated = array_keys($updated_prices);
941
+			$prices_to_remove = array_diff($current, $updated);
942
+			if (! empty($prices_to_remove)) {
943
+				foreach ($prices_to_remove as $prc_id) {
944
+					$p = $current_prices_on_ticket[ $prc_id ];
945
+					$ticket->_remove_relation_to($p, 'Price');
946
+					// delete permanently the price
947
+					$p->delete_permanently();
948
+				}
949
+			}
950
+		}
951
+		return $ticket;
952
+	}
953 953
 
954 954
 
955
-    /**
956
-     * @param Events_Admin_Page $event_admin_obj
957
-     * @return Events_Admin_Page
958
-     */
959
-    public function autosave_handling(Events_Admin_Page $event_admin_obj)
960
-    {
961
-        return $event_admin_obj;
962
-        // doing nothing for the moment.
963
-        // todo when I get to this remember that I need to set the template args on the $event_admin_obj
964
-        // (use the set_template_args() method)
965
-        /**
966
-         * need to remember to handle TICKET DEFAULT saves correctly:  I've got two input fields in the dom:
967
-         * 1. TKT_is_default_selector (visible)
968
-         * 2. TKT_is_default (hidden)
969
-         * I think we'll use the TKT_is_default for recording whether the ticket displayed IS a default ticket
970
-         * (on new event creations). Whereas the TKT_is_default_selector is for the user to indicate they want
971
-         * this ticket to be saved as a default.
972
-         * The tricky part is, on an initial display on create or edit (or after manually updating),
973
-         * the TKT_is_default_selector will always be unselected and the TKT_is_default will only be true
974
-         * if this is a create.  However, after an autosave, users will want some sort of indicator that
975
-         * the TKT HAS been saved as a default..
976
-         * in other words we don't want to remove the check on TKT_is_default_selector. So here's what I'm thinking.
977
-         * On Autosave:
978
-         * 1. If TKT_is_default is true: we create a new TKT, send back the new id and add id to related elements,
979
-         * then set the TKT_is_default to false.
980
-         * 2. If TKT_is_default_selector is true: we create/edit existing ticket (following conditions above as well).
981
-         *  We do NOT create a new default ticket.  The checkbox stays selected after autosave.
982
-         * 3. only on MANUAL update do we check for the selection and if selected create the new default ticket.
983
-         */
984
-    }
955
+	/**
956
+	 * @param Events_Admin_Page $event_admin_obj
957
+	 * @return Events_Admin_Page
958
+	 */
959
+	public function autosave_handling(Events_Admin_Page $event_admin_obj)
960
+	{
961
+		return $event_admin_obj;
962
+		// doing nothing for the moment.
963
+		// todo when I get to this remember that I need to set the template args on the $event_admin_obj
964
+		// (use the set_template_args() method)
965
+		/**
966
+		 * need to remember to handle TICKET DEFAULT saves correctly:  I've got two input fields in the dom:
967
+		 * 1. TKT_is_default_selector (visible)
968
+		 * 2. TKT_is_default (hidden)
969
+		 * I think we'll use the TKT_is_default for recording whether the ticket displayed IS a default ticket
970
+		 * (on new event creations). Whereas the TKT_is_default_selector is for the user to indicate they want
971
+		 * this ticket to be saved as a default.
972
+		 * The tricky part is, on an initial display on create or edit (or after manually updating),
973
+		 * the TKT_is_default_selector will always be unselected and the TKT_is_default will only be true
974
+		 * if this is a create.  However, after an autosave, users will want some sort of indicator that
975
+		 * the TKT HAS been saved as a default..
976
+		 * in other words we don't want to remove the check on TKT_is_default_selector. So here's what I'm thinking.
977
+		 * On Autosave:
978
+		 * 1. If TKT_is_default is true: we create a new TKT, send back the new id and add id to related elements,
979
+		 * then set the TKT_is_default to false.
980
+		 * 2. If TKT_is_default_selector is true: we create/edit existing ticket (following conditions above as well).
981
+		 *  We do NOT create a new default ticket.  The checkbox stays selected after autosave.
982
+		 * 3. only on MANUAL update do we check for the selection and if selected create the new default ticket.
983
+		 */
984
+	}
985 985
 
986 986
 
987
-    /**
988
-     * @throws ReflectionException
989
-     * @throws InvalidArgumentException
990
-     * @throws InvalidInterfaceException
991
-     * @throws InvalidDataTypeException
992
-     * @throws DomainException
993
-     * @throws EE_Error
994
-     */
995
-    public function pricing_metabox()
996
-    {
997
-        $existing_datetime_ids = $existing_ticket_ids = $datetime_tickets = $ticket_datetimes = array();
998
-        $event = $this->_adminpage_obj->get_cpt_model_obj();
999
-        // set is_creating_event property.
1000
-        $EVT_ID = $event->ID();
1001
-        $this->_is_creating_event = empty($this->_req_data['post']);
1002
-        // default main template args
1003
-        $main_template_args = array(
1004
-            'event_datetime_help_link' => EEH_Template::get_help_tab_link(
1005
-                'event_editor_event_datetimes_help_tab',
1006
-                $this->_adminpage_obj->page_slug,
1007
-                $this->_adminpage_obj->get_req_action(),
1008
-                false,
1009
-                false
1010
-            ),
1011
-            // todo need to add a filter to the template for the help text
1012
-            // in the Events_Admin_Page core file so we can add further help
1013
-            'existing_datetime_ids'    => '',
1014
-            'total_dtt_rows'           => 1,
1015
-            'add_new_dtt_help_link'    => EEH_Template::get_help_tab_link(
1016
-                'add_new_dtt_info',
1017
-                $this->_adminpage_obj->page_slug,
1018
-                $this->_adminpage_obj->get_req_action(),
1019
-                false,
1020
-                false
1021
-            ),
1022
-            // todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1023
-            'datetime_rows'            => '',
1024
-            'show_tickets_container'   => '',
1025
-            // $this->_adminpage_obj->get_cpt_model_obj()->ID() > 1 ? ' style="display:none;"' : '',
1026
-            'ticket_rows'              => '',
1027
-            'existing_ticket_ids'      => '',
1028
-            'total_ticket_rows'        => 1,
1029
-            'ticket_js_structure'      => '',
1030
-            'ee_collapsible_status'    => ' ee-collapsible-open'
1031
-            // $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? ' ee-collapsible-closed' : ' ee-collapsible-open'
1032
-        );
1033
-        $timezone = $event instanceof EE_Event ? $event->timezone_string() : null;
1034
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1035
-        /**
1036
-         * 1. Start with retrieving Datetimes
1037
-         * 2. For each datetime get related tickets
1038
-         * 3. For each ticket get related prices
1039
-         */
1040
-        /** @var EEM_Datetime $datetime_model */
1041
-        $datetime_model = EE_Registry::instance()->load_model('Datetime', array($timezone));
1042
-        $datetimes = $datetime_model->get_all_event_dates($EVT_ID);
1043
-        $main_template_args['total_dtt_rows'] = count($datetimes);
1044
-        /**
1045
-         * @see https://events.codebasehq.com/projects/event-espresso/tickets/9486
1046
-         * for why we are counting $datetime_row and then setting that on the Datetime object
1047
-         */
1048
-        $datetime_row = 1;
1049
-        foreach ($datetimes as $datetime) {
1050
-            $DTT_ID = $datetime->get('DTT_ID');
1051
-            $datetime->set('DTT_order', $datetime_row);
1052
-            $existing_datetime_ids[] = $DTT_ID;
1053
-            // tickets attached
1054
-            $related_tickets = $datetime->ID() > 0
1055
-                ? $datetime->get_many_related(
1056
-                    'Ticket',
1057
-                    array(
1058
-                        array(
1059
-                            'OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0),
1060
-                        ),
1061
-                        'default_where_conditions' => 'none',
1062
-                        'order_by'                 => array('TKT_order' => 'ASC'),
1063
-                    )
1064
-                )
1065
-                : array();
1066
-            // if there are no related tickets this is likely a new event OR autodraft
1067
-            // event so we need to generate the default tickets because datetimes
1068
-            // ALWAYS have at least one related ticket!!.  EXCEPT, we dont' do this if there is already more than one
1069
-            // datetime on the event.
1070
-            if (empty($related_tickets) && count($datetimes) < 2) {
1071
-                /** @var EEM_Ticket $ticket_model */
1072
-                $ticket_model = EE_Registry::instance()->load_model('Ticket');
1073
-                $related_tickets = $ticket_model->get_all_default_tickets();
1074
-                // this should be ordered by TKT_ID, so let's grab the first default ticket
1075
-                // (which will be the main default) and ensure it has any default prices added to it (but do NOT save).
1076
-                $default_prices = EEM_Price::instance()->get_all_default_prices();
1077
-                $main_default_ticket = reset($related_tickets);
1078
-                if ($main_default_ticket instanceof EE_Ticket) {
1079
-                    foreach ($default_prices as $default_price) {
1080
-                        if ($default_price instanceof EE_Price && $default_price->is_base_price()) {
1081
-                            continue;
1082
-                        }
1083
-                        $main_default_ticket->cache('Price', $default_price);
1084
-                    }
1085
-                }
1086
-            }
1087
-            // we can't actually setup rows in this loop yet cause we don't know all
1088
-            // the unique tickets for this event yet (tickets are linked through all datetimes).
1089
-            // So we're going to temporarily cache some of that information.
1090
-            // loop through and setup the ticket rows and make sure the order is set.
1091
-            foreach ($related_tickets as $ticket) {
1092
-                $TKT_ID = $ticket->get('TKT_ID');
1093
-                $ticket_row = $ticket->get('TKT_row');
1094
-                // we only want unique tickets in our final display!!
1095
-                if (! in_array($TKT_ID, $existing_ticket_ids, true)) {
1096
-                    $existing_ticket_ids[] = $TKT_ID;
1097
-                    $all_tickets[] = $ticket;
1098
-                }
1099
-                // temporary cache of this ticket info for this datetime for later processing of datetime rows.
1100
-                $datetime_tickets[ $DTT_ID ][] = $ticket_row;
1101
-                // temporary cache of this datetime info for this ticket for later processing of ticket rows.
1102
-                if (
1103
-                    ! isset($ticket_datetimes[ $TKT_ID ])
1104
-                    || ! in_array($datetime_row, $ticket_datetimes[ $TKT_ID ], true)
1105
-                ) {
1106
-                    $ticket_datetimes[ $TKT_ID ][] = $datetime_row;
1107
-                }
1108
-            }
1109
-            $datetime_row++;
1110
-        }
1111
-        $main_template_args['total_ticket_rows'] = count($existing_ticket_ids);
1112
-        $main_template_args['existing_ticket_ids'] = implode(',', $existing_ticket_ids);
1113
-        $main_template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
1114
-        // sort $all_tickets by order
1115
-        usort(
1116
-            $all_tickets,
1117
-            function (EE_Ticket $a, EE_Ticket $b) {
1118
-                $a_order = (int) $a->get('TKT_order');
1119
-                $b_order = (int) $b->get('TKT_order');
1120
-                if ($a_order === $b_order) {
1121
-                    return 0;
1122
-                }
1123
-                return ($a_order < $b_order) ? -1 : 1;
1124
-            }
1125
-        );
1126
-        // k NOW we have all the data we need for setting up the dtt rows
1127
-        // and ticket rows so we start our dtt loop again.
1128
-        $datetime_row = 1;
1129
-        foreach ($datetimes as $datetime) {
1130
-            $main_template_args['datetime_rows'] .= $this->_get_datetime_row(
1131
-                $datetime_row,
1132
-                $datetime,
1133
-                $datetime_tickets,
1134
-                $all_tickets,
1135
-                false,
1136
-                $datetimes
1137
-            );
1138
-            $datetime_row++;
1139
-        }
1140
-        // then loop through all tickets for the ticket rows.
1141
-        $ticket_row = 1;
1142
-        foreach ($all_tickets as $ticket) {
1143
-            $main_template_args['ticket_rows'] .= $this->_get_ticket_row(
1144
-                $ticket_row,
1145
-                $ticket,
1146
-                $ticket_datetimes,
1147
-                $datetimes,
1148
-                false,
1149
-                $all_tickets
1150
-            );
1151
-            $ticket_row++;
1152
-        }
1153
-        $main_template_args['ticket_js_structure'] = $this->_get_ticket_js_structure($datetimes, $all_tickets);
987
+	/**
988
+	 * @throws ReflectionException
989
+	 * @throws InvalidArgumentException
990
+	 * @throws InvalidInterfaceException
991
+	 * @throws InvalidDataTypeException
992
+	 * @throws DomainException
993
+	 * @throws EE_Error
994
+	 */
995
+	public function pricing_metabox()
996
+	{
997
+		$existing_datetime_ids = $existing_ticket_ids = $datetime_tickets = $ticket_datetimes = array();
998
+		$event = $this->_adminpage_obj->get_cpt_model_obj();
999
+		// set is_creating_event property.
1000
+		$EVT_ID = $event->ID();
1001
+		$this->_is_creating_event = empty($this->_req_data['post']);
1002
+		// default main template args
1003
+		$main_template_args = array(
1004
+			'event_datetime_help_link' => EEH_Template::get_help_tab_link(
1005
+				'event_editor_event_datetimes_help_tab',
1006
+				$this->_adminpage_obj->page_slug,
1007
+				$this->_adminpage_obj->get_req_action(),
1008
+				false,
1009
+				false
1010
+			),
1011
+			// todo need to add a filter to the template for the help text
1012
+			// in the Events_Admin_Page core file so we can add further help
1013
+			'existing_datetime_ids'    => '',
1014
+			'total_dtt_rows'           => 1,
1015
+			'add_new_dtt_help_link'    => EEH_Template::get_help_tab_link(
1016
+				'add_new_dtt_info',
1017
+				$this->_adminpage_obj->page_slug,
1018
+				$this->_adminpage_obj->get_req_action(),
1019
+				false,
1020
+				false
1021
+			),
1022
+			// todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1023
+			'datetime_rows'            => '',
1024
+			'show_tickets_container'   => '',
1025
+			// $this->_adminpage_obj->get_cpt_model_obj()->ID() > 1 ? ' style="display:none;"' : '',
1026
+			'ticket_rows'              => '',
1027
+			'existing_ticket_ids'      => '',
1028
+			'total_ticket_rows'        => 1,
1029
+			'ticket_js_structure'      => '',
1030
+			'ee_collapsible_status'    => ' ee-collapsible-open'
1031
+			// $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? ' ee-collapsible-closed' : ' ee-collapsible-open'
1032
+		);
1033
+		$timezone = $event instanceof EE_Event ? $event->timezone_string() : null;
1034
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1035
+		/**
1036
+		 * 1. Start with retrieving Datetimes
1037
+		 * 2. For each datetime get related tickets
1038
+		 * 3. For each ticket get related prices
1039
+		 */
1040
+		/** @var EEM_Datetime $datetime_model */
1041
+		$datetime_model = EE_Registry::instance()->load_model('Datetime', array($timezone));
1042
+		$datetimes = $datetime_model->get_all_event_dates($EVT_ID);
1043
+		$main_template_args['total_dtt_rows'] = count($datetimes);
1044
+		/**
1045
+		 * @see https://events.codebasehq.com/projects/event-espresso/tickets/9486
1046
+		 * for why we are counting $datetime_row and then setting that on the Datetime object
1047
+		 */
1048
+		$datetime_row = 1;
1049
+		foreach ($datetimes as $datetime) {
1050
+			$DTT_ID = $datetime->get('DTT_ID');
1051
+			$datetime->set('DTT_order', $datetime_row);
1052
+			$existing_datetime_ids[] = $DTT_ID;
1053
+			// tickets attached
1054
+			$related_tickets = $datetime->ID() > 0
1055
+				? $datetime->get_many_related(
1056
+					'Ticket',
1057
+					array(
1058
+						array(
1059
+							'OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0),
1060
+						),
1061
+						'default_where_conditions' => 'none',
1062
+						'order_by'                 => array('TKT_order' => 'ASC'),
1063
+					)
1064
+				)
1065
+				: array();
1066
+			// if there are no related tickets this is likely a new event OR autodraft
1067
+			// event so we need to generate the default tickets because datetimes
1068
+			// ALWAYS have at least one related ticket!!.  EXCEPT, we dont' do this if there is already more than one
1069
+			// datetime on the event.
1070
+			if (empty($related_tickets) && count($datetimes) < 2) {
1071
+				/** @var EEM_Ticket $ticket_model */
1072
+				$ticket_model = EE_Registry::instance()->load_model('Ticket');
1073
+				$related_tickets = $ticket_model->get_all_default_tickets();
1074
+				// this should be ordered by TKT_ID, so let's grab the first default ticket
1075
+				// (which will be the main default) and ensure it has any default prices added to it (but do NOT save).
1076
+				$default_prices = EEM_Price::instance()->get_all_default_prices();
1077
+				$main_default_ticket = reset($related_tickets);
1078
+				if ($main_default_ticket instanceof EE_Ticket) {
1079
+					foreach ($default_prices as $default_price) {
1080
+						if ($default_price instanceof EE_Price && $default_price->is_base_price()) {
1081
+							continue;
1082
+						}
1083
+						$main_default_ticket->cache('Price', $default_price);
1084
+					}
1085
+				}
1086
+			}
1087
+			// we can't actually setup rows in this loop yet cause we don't know all
1088
+			// the unique tickets for this event yet (tickets are linked through all datetimes).
1089
+			// So we're going to temporarily cache some of that information.
1090
+			// loop through and setup the ticket rows and make sure the order is set.
1091
+			foreach ($related_tickets as $ticket) {
1092
+				$TKT_ID = $ticket->get('TKT_ID');
1093
+				$ticket_row = $ticket->get('TKT_row');
1094
+				// we only want unique tickets in our final display!!
1095
+				if (! in_array($TKT_ID, $existing_ticket_ids, true)) {
1096
+					$existing_ticket_ids[] = $TKT_ID;
1097
+					$all_tickets[] = $ticket;
1098
+				}
1099
+				// temporary cache of this ticket info for this datetime for later processing of datetime rows.
1100
+				$datetime_tickets[ $DTT_ID ][] = $ticket_row;
1101
+				// temporary cache of this datetime info for this ticket for later processing of ticket rows.
1102
+				if (
1103
+					! isset($ticket_datetimes[ $TKT_ID ])
1104
+					|| ! in_array($datetime_row, $ticket_datetimes[ $TKT_ID ], true)
1105
+				) {
1106
+					$ticket_datetimes[ $TKT_ID ][] = $datetime_row;
1107
+				}
1108
+			}
1109
+			$datetime_row++;
1110
+		}
1111
+		$main_template_args['total_ticket_rows'] = count($existing_ticket_ids);
1112
+		$main_template_args['existing_ticket_ids'] = implode(',', $existing_ticket_ids);
1113
+		$main_template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
1114
+		// sort $all_tickets by order
1115
+		usort(
1116
+			$all_tickets,
1117
+			function (EE_Ticket $a, EE_Ticket $b) {
1118
+				$a_order = (int) $a->get('TKT_order');
1119
+				$b_order = (int) $b->get('TKT_order');
1120
+				if ($a_order === $b_order) {
1121
+					return 0;
1122
+				}
1123
+				return ($a_order < $b_order) ? -1 : 1;
1124
+			}
1125
+		);
1126
+		// k NOW we have all the data we need for setting up the dtt rows
1127
+		// and ticket rows so we start our dtt loop again.
1128
+		$datetime_row = 1;
1129
+		foreach ($datetimes as $datetime) {
1130
+			$main_template_args['datetime_rows'] .= $this->_get_datetime_row(
1131
+				$datetime_row,
1132
+				$datetime,
1133
+				$datetime_tickets,
1134
+				$all_tickets,
1135
+				false,
1136
+				$datetimes
1137
+			);
1138
+			$datetime_row++;
1139
+		}
1140
+		// then loop through all tickets for the ticket rows.
1141
+		$ticket_row = 1;
1142
+		foreach ($all_tickets as $ticket) {
1143
+			$main_template_args['ticket_rows'] .= $this->_get_ticket_row(
1144
+				$ticket_row,
1145
+				$ticket,
1146
+				$ticket_datetimes,
1147
+				$datetimes,
1148
+				false,
1149
+				$all_tickets
1150
+			);
1151
+			$ticket_row++;
1152
+		}
1153
+		$main_template_args['ticket_js_structure'] = $this->_get_ticket_js_structure($datetimes, $all_tickets);
1154 1154
 
1155
-        $status_change_notice = EventEspresso\core\services\loaders\LoaderFactory::getLoader()->getShared(
1156
-            'EventEspresso\core\admin\StatusChangeNotice'
1157
-        );
1158
-        if (! $status_change_notice->isDismissed()) {
1159
-            $main_template_args['status_change_notice'] = EEH_Template::display_template(
1160
-                EE_ADMIN_TEMPLATE . 'status_change_notice.template.php',
1161
-                ['context' => '__event-editor', 'page_slug' => 'espresso-events'],
1162
-                true
1163
-            );
1164
-        }
1155
+		$status_change_notice = EventEspresso\core\services\loaders\LoaderFactory::getLoader()->getShared(
1156
+			'EventEspresso\core\admin\StatusChangeNotice'
1157
+		);
1158
+		if (! $status_change_notice->isDismissed()) {
1159
+			$main_template_args['status_change_notice'] = EEH_Template::display_template(
1160
+				EE_ADMIN_TEMPLATE . 'status_change_notice.template.php',
1161
+				['context' => '__event-editor', 'page_slug' => 'espresso-events'],
1162
+				true
1163
+			);
1164
+		}
1165 1165
 
1166
-        EEH_Template::display_template(
1167
-            PRICING_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php',
1168
-            $main_template_args
1169
-        );
1170
-    }
1166
+		EEH_Template::display_template(
1167
+			PRICING_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php',
1168
+			$main_template_args
1169
+		);
1170
+	}
1171 1171
 
1172 1172
 
1173
-    /**
1174
-     * @param int         $datetime_row
1175
-     * @param EE_Datetime $datetime
1176
-     * @param array       $datetime_tickets
1177
-     * @param array       $all_tickets
1178
-     * @param bool        $default
1179
-     * @param array       $all_datetimes
1180
-     * @return mixed
1181
-     * @throws DomainException
1182
-     * @throws EE_Error
1183
-     */
1184
-    protected function _get_datetime_row(
1185
-        $datetime_row,
1186
-        EE_Datetime $datetime,
1187
-        $datetime_tickets = array(),
1188
-        $all_tickets = array(),
1189
-        $default = false,
1190
-        $all_datetimes = array()
1191
-    ) {
1192
-        $dtt_display_template_args = array(
1193
-            'dtt_edit_row'             => $this->_get_dtt_edit_row(
1194
-                $datetime_row,
1195
-                $datetime,
1196
-                $default,
1197
-                $all_datetimes
1198
-            ),
1199
-            'dtt_attached_tickets_row' => $this->_get_dtt_attached_tickets_row(
1200
-                $datetime_row,
1201
-                $datetime,
1202
-                $datetime_tickets,
1203
-                $all_tickets,
1204
-                $default
1205
-            ),
1206
-            'dtt_row'                  => $default ? 'DTTNUM' : $datetime_row,
1207
-        );
1208
-        return EEH_Template::display_template(
1209
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_row_wrapper.template.php',
1210
-            $dtt_display_template_args,
1211
-            true
1212
-        );
1213
-    }
1173
+	/**
1174
+	 * @param int         $datetime_row
1175
+	 * @param EE_Datetime $datetime
1176
+	 * @param array       $datetime_tickets
1177
+	 * @param array       $all_tickets
1178
+	 * @param bool        $default
1179
+	 * @param array       $all_datetimes
1180
+	 * @return mixed
1181
+	 * @throws DomainException
1182
+	 * @throws EE_Error
1183
+	 */
1184
+	protected function _get_datetime_row(
1185
+		$datetime_row,
1186
+		EE_Datetime $datetime,
1187
+		$datetime_tickets = array(),
1188
+		$all_tickets = array(),
1189
+		$default = false,
1190
+		$all_datetimes = array()
1191
+	) {
1192
+		$dtt_display_template_args = array(
1193
+			'dtt_edit_row'             => $this->_get_dtt_edit_row(
1194
+				$datetime_row,
1195
+				$datetime,
1196
+				$default,
1197
+				$all_datetimes
1198
+			),
1199
+			'dtt_attached_tickets_row' => $this->_get_dtt_attached_tickets_row(
1200
+				$datetime_row,
1201
+				$datetime,
1202
+				$datetime_tickets,
1203
+				$all_tickets,
1204
+				$default
1205
+			),
1206
+			'dtt_row'                  => $default ? 'DTTNUM' : $datetime_row,
1207
+		);
1208
+		return EEH_Template::display_template(
1209
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_row_wrapper.template.php',
1210
+			$dtt_display_template_args,
1211
+			true
1212
+		);
1213
+	}
1214 1214
 
1215 1215
 
1216
-    /**
1217
-     * This method is used to generate a dtt fields  edit row.
1218
-     * The same row is used to generate a row with valid DTT objects
1219
-     * and the default row that is used as the skeleton by the js.
1220
-     *
1221
-     * @param int           $datetime_row  The row number for the row being generated.
1222
-     * @param EE_Datetime   $datetime
1223
-     * @param bool          $default       Whether a default row is being generated or not.
1224
-     * @param EE_Datetime[] $all_datetimes This is the array of all datetimes used in the editor.
1225
-     * @return string
1226
-     * @throws DomainException
1227
-     * @throws EE_Error
1228
-     */
1229
-    protected function _get_dtt_edit_row($datetime_row, $datetime, $default, $all_datetimes)
1230
-    {
1231
-        // if the incoming $datetime object is NOT an instance of EE_Datetime then force default to true.
1232
-        $default = ! $datetime instanceof EE_Datetime ? true : $default;
1233
-        $template_args = array(
1234
-            'dtt_row'              => $default ? 'DTTNUM' : $datetime_row,
1235
-            'event_datetimes_name' => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1236
-            'edit_dtt_expanded'    => '',
1237
-            'DTT_ID'               => $default ? '' : $datetime->ID(),
1238
-            'DTT_name'             => $default ? '' : $datetime->get_f('DTT_name'),
1239
-            'DTT_description'      => $default ? '' : $datetime->get_f('DTT_description'),
1240
-            'DTT_EVT_start'        => $default ? '' : $datetime->start_date($this->_date_time_format),
1241
-            'DTT_EVT_end'          => $default ? '' : $datetime->end_date($this->_date_time_format),
1242
-            'DTT_reg_limit'        => $default
1243
-                ? ''
1244
-                : $datetime->get_pretty(
1245
-                    'DTT_reg_limit',
1246
-                    'input'
1247
-                ),
1248
-            'DTT_order'            => $default ? 'DTTNUM' : $datetime_row,
1249
-            'dtt_sold'             => $default ? '0' : $datetime->get('DTT_sold'),
1250
-            'dtt_reserved'         => $default ? '0' : $datetime->reserved(),
1251
-            'clone_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1252
-                ? ''
1253
-                : 'clone-icon ee-icon ee-icon-clone clickable',
1254
-            'trash_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1255
-                ? 'ee-lock-icon'
1256
-                : 'trash-icon dashicons dashicons-post-trash clickable',
1257
-            'reg_list_url'         => $default || ! $datetime->event() instanceof \EE_Event
1258
-                ? ''
1259
-                : EE_Admin_Page::add_query_args_and_nonce(
1260
-                    array('event_id' => $datetime->event()->ID(), 'datetime_id' => $datetime->ID()),
1261
-                    REG_ADMIN_URL
1262
-                ),
1263
-        );
1264
-        $template_args['show_trash'] = count($all_datetimes) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1265
-            ? ' style="display:none"'
1266
-            : '';
1267
-        // allow filtering of template args at this point.
1268
-        $template_args = apply_filters(
1269
-            'FHEE__espresso_events_Pricing_Hooks___get_dtt_edit_row__template_args',
1270
-            $template_args,
1271
-            $datetime_row,
1272
-            $datetime,
1273
-            $default,
1274
-            $all_datetimes,
1275
-            $this->_is_creating_event
1276
-        );
1277
-        return EEH_Template::display_template(
1278
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_edit_row.template.php',
1279
-            $template_args,
1280
-            true
1281
-        );
1282
-    }
1216
+	/**
1217
+	 * This method is used to generate a dtt fields  edit row.
1218
+	 * The same row is used to generate a row with valid DTT objects
1219
+	 * and the default row that is used as the skeleton by the js.
1220
+	 *
1221
+	 * @param int           $datetime_row  The row number for the row being generated.
1222
+	 * @param EE_Datetime   $datetime
1223
+	 * @param bool          $default       Whether a default row is being generated or not.
1224
+	 * @param EE_Datetime[] $all_datetimes This is the array of all datetimes used in the editor.
1225
+	 * @return string
1226
+	 * @throws DomainException
1227
+	 * @throws EE_Error
1228
+	 */
1229
+	protected function _get_dtt_edit_row($datetime_row, $datetime, $default, $all_datetimes)
1230
+	{
1231
+		// if the incoming $datetime object is NOT an instance of EE_Datetime then force default to true.
1232
+		$default = ! $datetime instanceof EE_Datetime ? true : $default;
1233
+		$template_args = array(
1234
+			'dtt_row'              => $default ? 'DTTNUM' : $datetime_row,
1235
+			'event_datetimes_name' => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1236
+			'edit_dtt_expanded'    => '',
1237
+			'DTT_ID'               => $default ? '' : $datetime->ID(),
1238
+			'DTT_name'             => $default ? '' : $datetime->get_f('DTT_name'),
1239
+			'DTT_description'      => $default ? '' : $datetime->get_f('DTT_description'),
1240
+			'DTT_EVT_start'        => $default ? '' : $datetime->start_date($this->_date_time_format),
1241
+			'DTT_EVT_end'          => $default ? '' : $datetime->end_date($this->_date_time_format),
1242
+			'DTT_reg_limit'        => $default
1243
+				? ''
1244
+				: $datetime->get_pretty(
1245
+					'DTT_reg_limit',
1246
+					'input'
1247
+				),
1248
+			'DTT_order'            => $default ? 'DTTNUM' : $datetime_row,
1249
+			'dtt_sold'             => $default ? '0' : $datetime->get('DTT_sold'),
1250
+			'dtt_reserved'         => $default ? '0' : $datetime->reserved(),
1251
+			'clone_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1252
+				? ''
1253
+				: 'clone-icon ee-icon ee-icon-clone clickable',
1254
+			'trash_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1255
+				? 'ee-lock-icon'
1256
+				: 'trash-icon dashicons dashicons-post-trash clickable',
1257
+			'reg_list_url'         => $default || ! $datetime->event() instanceof \EE_Event
1258
+				? ''
1259
+				: EE_Admin_Page::add_query_args_and_nonce(
1260
+					array('event_id' => $datetime->event()->ID(), 'datetime_id' => $datetime->ID()),
1261
+					REG_ADMIN_URL
1262
+				),
1263
+		);
1264
+		$template_args['show_trash'] = count($all_datetimes) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1265
+			? ' style="display:none"'
1266
+			: '';
1267
+		// allow filtering of template args at this point.
1268
+		$template_args = apply_filters(
1269
+			'FHEE__espresso_events_Pricing_Hooks___get_dtt_edit_row__template_args',
1270
+			$template_args,
1271
+			$datetime_row,
1272
+			$datetime,
1273
+			$default,
1274
+			$all_datetimes,
1275
+			$this->_is_creating_event
1276
+		);
1277
+		return EEH_Template::display_template(
1278
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_edit_row.template.php',
1279
+			$template_args,
1280
+			true
1281
+		);
1282
+	}
1283 1283
 
1284 1284
 
1285
-    /**
1286
-     * @param int         $datetime_row
1287
-     * @param EE_Datetime $datetime
1288
-     * @param array       $datetime_tickets
1289
-     * @param array       $all_tickets
1290
-     * @param bool        $default
1291
-     * @return mixed
1292
-     * @throws DomainException
1293
-     * @throws EE_Error
1294
-     */
1295
-    protected function _get_dtt_attached_tickets_row(
1296
-        $datetime_row,
1297
-        $datetime,
1298
-        $datetime_tickets = array(),
1299
-        $all_tickets = array(),
1300
-        $default
1301
-    ) {
1302
-        $template_args = array(
1303
-            'dtt_row'                           => $default ? 'DTTNUM' : $datetime_row,
1304
-            'event_datetimes_name'              => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1305
-            'DTT_description'                   => $default ? '' : $datetime->get_f('DTT_description'),
1306
-            'datetime_tickets_list'             => $default ? '<li class="hidden"></li>' : '',
1307
-            'show_tickets_row'                  => ' style="display:none;"',
1308
-            'add_new_datetime_ticket_help_link' => EEH_Template::get_help_tab_link(
1309
-                'add_new_ticket_via_datetime',
1310
-                $this->_adminpage_obj->page_slug,
1311
-                $this->_adminpage_obj->get_req_action(),
1312
-                false,
1313
-                false
1314
-            ),
1315
-            // todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1316
-            'DTT_ID'                            => $default ? '' : $datetime->ID(),
1317
-        );
1318
-        // need to setup the list items (but only if this isn't a default skeleton setup)
1319
-        if (! $default) {
1320
-            $ticket_row = 1;
1321
-            foreach ($all_tickets as $ticket) {
1322
-                $template_args['datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
1323
-                    $datetime_row,
1324
-                    $ticket_row,
1325
-                    $datetime,
1326
-                    $ticket,
1327
-                    $datetime_tickets,
1328
-                    $default
1329
-                );
1330
-                $ticket_row++;
1331
-            }
1332
-        }
1333
-        // filter template args at this point
1334
-        $template_args = apply_filters(
1335
-            'FHEE__espresso_events_Pricing_Hooks___get_dtt_attached_ticket_row__template_args',
1336
-            $template_args,
1337
-            $datetime_row,
1338
-            $datetime,
1339
-            $datetime_tickets,
1340
-            $all_tickets,
1341
-            $default,
1342
-            $this->_is_creating_event
1343
-        );
1344
-        return EEH_Template::display_template(
1345
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_attached_tickets_row.template.php',
1346
-            $template_args,
1347
-            true
1348
-        );
1349
-    }
1285
+	/**
1286
+	 * @param int         $datetime_row
1287
+	 * @param EE_Datetime $datetime
1288
+	 * @param array       $datetime_tickets
1289
+	 * @param array       $all_tickets
1290
+	 * @param bool        $default
1291
+	 * @return mixed
1292
+	 * @throws DomainException
1293
+	 * @throws EE_Error
1294
+	 */
1295
+	protected function _get_dtt_attached_tickets_row(
1296
+		$datetime_row,
1297
+		$datetime,
1298
+		$datetime_tickets = array(),
1299
+		$all_tickets = array(),
1300
+		$default
1301
+	) {
1302
+		$template_args = array(
1303
+			'dtt_row'                           => $default ? 'DTTNUM' : $datetime_row,
1304
+			'event_datetimes_name'              => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1305
+			'DTT_description'                   => $default ? '' : $datetime->get_f('DTT_description'),
1306
+			'datetime_tickets_list'             => $default ? '<li class="hidden"></li>' : '',
1307
+			'show_tickets_row'                  => ' style="display:none;"',
1308
+			'add_new_datetime_ticket_help_link' => EEH_Template::get_help_tab_link(
1309
+				'add_new_ticket_via_datetime',
1310
+				$this->_adminpage_obj->page_slug,
1311
+				$this->_adminpage_obj->get_req_action(),
1312
+				false,
1313
+				false
1314
+			),
1315
+			// todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1316
+			'DTT_ID'                            => $default ? '' : $datetime->ID(),
1317
+		);
1318
+		// need to setup the list items (but only if this isn't a default skeleton setup)
1319
+		if (! $default) {
1320
+			$ticket_row = 1;
1321
+			foreach ($all_tickets as $ticket) {
1322
+				$template_args['datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
1323
+					$datetime_row,
1324
+					$ticket_row,
1325
+					$datetime,
1326
+					$ticket,
1327
+					$datetime_tickets,
1328
+					$default
1329
+				);
1330
+				$ticket_row++;
1331
+			}
1332
+		}
1333
+		// filter template args at this point
1334
+		$template_args = apply_filters(
1335
+			'FHEE__espresso_events_Pricing_Hooks___get_dtt_attached_ticket_row__template_args',
1336
+			$template_args,
1337
+			$datetime_row,
1338
+			$datetime,
1339
+			$datetime_tickets,
1340
+			$all_tickets,
1341
+			$default,
1342
+			$this->_is_creating_event
1343
+		);
1344
+		return EEH_Template::display_template(
1345
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_attached_tickets_row.template.php',
1346
+			$template_args,
1347
+			true
1348
+		);
1349
+	}
1350 1350
 
1351 1351
 
1352
-    /**
1353
-     * @param int         $datetime_row
1354
-     * @param int         $ticket_row
1355
-     * @param EE_Datetime $datetime
1356
-     * @param EE_Ticket   $ticket
1357
-     * @param array       $datetime_tickets
1358
-     * @param bool        $default
1359
-     * @return mixed
1360
-     * @throws DomainException
1361
-     * @throws EE_Error
1362
-     */
1363
-    protected function _get_datetime_tickets_list_item(
1364
-        $datetime_row,
1365
-        $ticket_row,
1366
-        $datetime,
1367
-        $ticket,
1368
-        $datetime_tickets = array(),
1369
-        $default
1370
-    ) {
1371
-        $dtt_tkts = $datetime instanceof EE_Datetime && isset($datetime_tickets[ $datetime->ID() ])
1372
-            ? $datetime_tickets[ $datetime->ID() ]
1373
-            : array();
1374
-        $display_row = $ticket instanceof EE_Ticket ? $ticket->get('TKT_row') : 0;
1375
-        $no_ticket = $default && empty($ticket);
1376
-        $template_args = array(
1377
-            'dtt_row'                 => $default
1378
-                ? 'DTTNUM'
1379
-                : $datetime_row,
1380
-            'tkt_row'                 => $no_ticket
1381
-                ? 'TICKETNUM'
1382
-                : $ticket_row,
1383
-            'datetime_ticket_checked' => in_array($display_row, $dtt_tkts, true)
1384
-                ? ' checked="checked"'
1385
-                : '',
1386
-            'ticket_selected'         => in_array($display_row, $dtt_tkts, true)
1387
-                ? ' ticket-selected'
1388
-                : '',
1389
-            'TKT_name'                => $no_ticket
1390
-                ? 'TKTNAME'
1391
-                : $ticket->get('TKT_name'),
1392
-            'tkt_status_class'        => $no_ticket || $this->_is_creating_event
1393
-                ? ' tkt-status-' . EE_Ticket::onsale
1394
-                : ' tkt-status-' . $ticket->ticket_status(),
1395
-        );
1396
-        // filter template args
1397
-        $template_args = apply_filters(
1398
-            'FHEE__espresso_events_Pricing_Hooks___get_datetime_tickets_list_item__template_args',
1399
-            $template_args,
1400
-            $datetime_row,
1401
-            $ticket_row,
1402
-            $datetime,
1403
-            $ticket,
1404
-            $datetime_tickets,
1405
-            $default,
1406
-            $this->_is_creating_event
1407
-        );
1408
-        return EEH_Template::display_template(
1409
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_dtt_tickets_list.template.php',
1410
-            $template_args,
1411
-            true
1412
-        );
1413
-    }
1352
+	/**
1353
+	 * @param int         $datetime_row
1354
+	 * @param int         $ticket_row
1355
+	 * @param EE_Datetime $datetime
1356
+	 * @param EE_Ticket   $ticket
1357
+	 * @param array       $datetime_tickets
1358
+	 * @param bool        $default
1359
+	 * @return mixed
1360
+	 * @throws DomainException
1361
+	 * @throws EE_Error
1362
+	 */
1363
+	protected function _get_datetime_tickets_list_item(
1364
+		$datetime_row,
1365
+		$ticket_row,
1366
+		$datetime,
1367
+		$ticket,
1368
+		$datetime_tickets = array(),
1369
+		$default
1370
+	) {
1371
+		$dtt_tkts = $datetime instanceof EE_Datetime && isset($datetime_tickets[ $datetime->ID() ])
1372
+			? $datetime_tickets[ $datetime->ID() ]
1373
+			: array();
1374
+		$display_row = $ticket instanceof EE_Ticket ? $ticket->get('TKT_row') : 0;
1375
+		$no_ticket = $default && empty($ticket);
1376
+		$template_args = array(
1377
+			'dtt_row'                 => $default
1378
+				? 'DTTNUM'
1379
+				: $datetime_row,
1380
+			'tkt_row'                 => $no_ticket
1381
+				? 'TICKETNUM'
1382
+				: $ticket_row,
1383
+			'datetime_ticket_checked' => in_array($display_row, $dtt_tkts, true)
1384
+				? ' checked="checked"'
1385
+				: '',
1386
+			'ticket_selected'         => in_array($display_row, $dtt_tkts, true)
1387
+				? ' ticket-selected'
1388
+				: '',
1389
+			'TKT_name'                => $no_ticket
1390
+				? 'TKTNAME'
1391
+				: $ticket->get('TKT_name'),
1392
+			'tkt_status_class'        => $no_ticket || $this->_is_creating_event
1393
+				? ' tkt-status-' . EE_Ticket::onsale
1394
+				: ' tkt-status-' . $ticket->ticket_status(),
1395
+		);
1396
+		// filter template args
1397
+		$template_args = apply_filters(
1398
+			'FHEE__espresso_events_Pricing_Hooks___get_datetime_tickets_list_item__template_args',
1399
+			$template_args,
1400
+			$datetime_row,
1401
+			$ticket_row,
1402
+			$datetime,
1403
+			$ticket,
1404
+			$datetime_tickets,
1405
+			$default,
1406
+			$this->_is_creating_event
1407
+		);
1408
+		return EEH_Template::display_template(
1409
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_dtt_tickets_list.template.php',
1410
+			$template_args,
1411
+			true
1412
+		);
1413
+	}
1414 1414
 
1415 1415
 
1416
-    /**
1417
-     * This generates the ticket row for tickets.
1418
-     * This same method is used to generate both the actual rows and the js skeleton row
1419
-     * (when default === true)
1420
-     *
1421
-     * @param int           $ticket_row       Represents the row number being generated.
1422
-     * @param               $ticket
1423
-     * @param EE_Datetime[] $ticket_datetimes Either an array of all datetimes on all tickets indexed by each ticket
1424
-     *                                        or empty for default
1425
-     * @param EE_Datetime[] $all_datetimes    All Datetimes on the event or empty for default.
1426
-     * @param bool          $default          Whether default row being generated or not.
1427
-     * @param EE_Ticket[]   $all_tickets      This is an array of all tickets attached to the event
1428
-     *                                        (or empty in the case of defaults)
1429
-     * @return mixed
1430
-     * @throws InvalidArgumentException
1431
-     * @throws InvalidInterfaceException
1432
-     * @throws InvalidDataTypeException
1433
-     * @throws DomainException
1434
-     * @throws EE_Error
1435
-     * @throws ReflectionException
1436
-     */
1437
-    protected function _get_ticket_row(
1438
-        $ticket_row,
1439
-        $ticket,
1440
-        $ticket_datetimes,
1441
-        $all_datetimes,
1442
-        $default = false,
1443
-        $all_tickets = array()
1444
-    ) {
1445
-        // if $ticket is not an instance of EE_Ticket then force default to true.
1446
-        $default = ! $ticket instanceof EE_Ticket ? true : $default;
1447
-        $prices = ! empty($ticket) && ! $default
1448
-            ? $ticket->get_many_related(
1449
-                'Price',
1450
-                array('default_where_conditions' => 'none', 'order_by' => array('PRC_order' => 'ASC'))
1451
-            )
1452
-            : array();
1453
-        // if there is only one price (which would be the base price)
1454
-        // or NO prices and this ticket is a default ticket,
1455
-        // let's just make sure there are no cached default prices on the object.
1456
-        // This is done by not including any query_params.
1457
-        if ($ticket instanceof EE_Ticket && $ticket->is_default() && (count($prices) === 1 || empty($prices))) {
1458
-            $prices = $ticket->prices();
1459
-        }
1460
-        // check if we're dealing with a default ticket in which case
1461
-        // we don't want any starting_ticket_datetime_row values set
1462
-        // (otherwise there won't be any new relationships created for tickets based off of the default ticket).
1463
-        // This will future proof in case there is ever any behaviour change between what the primary_key defaults to.
1464
-        $default_dtt = $default || ($ticket instanceof EE_Ticket && $ticket->is_default());
1465
-        $tkt_datetimes = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
1466
-            ? $ticket_datetimes[ $ticket->ID() ]
1467
-            : array();
1468
-        $ticket_subtotal = $default ? 0 : $ticket->get_ticket_subtotal();
1469
-        $base_price = $default ? null : $ticket->base_price();
1470
-        $count_price_mods = EEM_Price::instance()->get_all_default_prices(true);
1471
-        // breaking out complicated condition for ticket_status
1472
-        if ($default) {
1473
-            $ticket_status_class = ' tkt-status-' . EE_Ticket::onsale;
1474
-        } else {
1475
-            $ticket_status_class = $ticket->is_default()
1476
-                ? ' tkt-status-' . EE_Ticket::onsale
1477
-                : ' tkt-status-' . $ticket->ticket_status();
1478
-        }
1479
-        // breaking out complicated condition for TKT_taxable
1480
-        if ($default) {
1481
-            $TKT_taxable = '';
1482
-        } else {
1483
-            $TKT_taxable = $ticket->taxable()
1484
-                ? ' checked="checked"'
1485
-                : '';
1486
-        }
1487
-        if ($default) {
1488
-            $TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1489
-        } elseif ($ticket->is_default()) {
1490
-            $TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1491
-        } else {
1492
-            $TKT_status = $ticket->ticket_status(true);
1493
-        }
1494
-        if ($default) {
1495
-            $TKT_min = '';
1496
-        } else {
1497
-            $TKT_min = $ticket->min();
1498
-            if ($TKT_min === -1 || $TKT_min === 0) {
1499
-                $TKT_min = '';
1500
-            }
1501
-        }
1502
-        $template_args = array(
1503
-            'tkt_row'                       => $default ? 'TICKETNUM' : $ticket_row,
1504
-            'TKT_order'                     => $default ? 'TICKETNUM' : $ticket_row,
1505
-            // on initial page load this will always be the correct order.
1506
-            'tkt_status_class'              => $ticket_status_class,
1507
-            'display_edit_tkt_row'          => ' style="display:none;"',
1508
-            'edit_tkt_expanded'             => '',
1509
-            'edit_tickets_name'             => $default ? 'TICKETNAMEATTR' : 'edit_tickets',
1510
-            'TKT_name'                      => $default ? '' : $ticket->get_f('TKT_name'),
1511
-            'TKT_start_date'                => $default
1512
-                ? ''
1513
-                : $ticket->get_date('TKT_start_date', $this->_date_time_format),
1514
-            'TKT_end_date'                  => $default
1515
-                ? ''
1516
-                : $ticket->get_date('TKT_end_date', $this->_date_time_format),
1517
-            'TKT_status'                    => $TKT_status,
1518
-            'TKT_price'                     => $default
1519
-                ? ''
1520
-                : EEH_Template::format_currency(
1521
-                    $ticket->get_ticket_total_with_taxes(),
1522
-                    false,
1523
-                    false
1524
-                ),
1525
-            'TKT_price_code'                => EE_Registry::instance()->CFG->currency->code,
1526
-            'TKT_price_amount'              => $default ? 0 : $ticket_subtotal,
1527
-            'TKT_qty'                       => $default
1528
-                ? ''
1529
-                : $ticket->get_pretty('TKT_qty', 'symbol'),
1530
-            'TKT_qty_for_input'             => $default
1531
-                ? ''
1532
-                : $ticket->get_pretty('TKT_qty', 'input'),
1533
-            'TKT_uses'                      => $default
1534
-                ? ''
1535
-                : $ticket->get_pretty('TKT_uses', 'input'),
1536
-            'TKT_min'                       => $TKT_min,
1537
-            'TKT_max'                       => $default
1538
-                ? ''
1539
-                : $ticket->get_pretty('TKT_max', 'input'),
1540
-            'TKT_sold'                      => $default ? 0 : $ticket->tickets_sold('ticket'),
1541
-            'TKT_reserved'                  => $default ? 0 : $ticket->reserved(),
1542
-            'TKT_registrations'             => $default
1543
-                ? 0
1544
-                : $ticket->count_registrations(
1545
-                    array(
1546
-                        array(
1547
-                            'STS_ID' => array(
1548
-                                '!=',
1549
-                                EEM_Registration::status_id_incomplete,
1550
-                            ),
1551
-                        ),
1552
-                    )
1553
-                ),
1554
-            'TKT_ID'                        => $default ? 0 : $ticket->ID(),
1555
-            'TKT_description'               => $default ? '' : $ticket->get_f('TKT_description'),
1556
-            'TKT_is_default'                => $default ? 0 : $ticket->is_default(),
1557
-            'TKT_required'                  => $default ? 0 : $ticket->required(),
1558
-            'TKT_is_default_selector'       => '',
1559
-            'ticket_price_rows'             => '',
1560
-            'TKT_base_price'                => $default || ! $base_price instanceof EE_Price
1561
-                ? ''
1562
-                : $base_price->get_pretty('PRC_amount', 'localized_float'),
1563
-            'TKT_base_price_ID'             => $default || ! $base_price instanceof EE_Price ? 0 : $base_price->ID(),
1564
-            'show_price_modifier'           => count($prices) > 1 || ($default && $count_price_mods > 0)
1565
-                ? ''
1566
-                : ' style="display:none;"',
1567
-            'show_price_mod_button'         => count($prices) > 1
1568
-                                               || ($default && $count_price_mods > 0)
1569
-                                               || (! $default && $ticket->deleted())
1570
-                ? ' style="display:none;"'
1571
-                : '',
1572
-            'total_price_rows'              => count($prices) > 1 ? count($prices) : 1,
1573
-            'ticket_datetimes_list'         => $default ? '<li class="hidden"></li>' : '',
1574
-            'starting_ticket_datetime_rows' => $default || $default_dtt ? '' : implode(',', $tkt_datetimes),
1575
-            'ticket_datetime_rows'          => $default ? '' : implode(',', $tkt_datetimes),
1576
-            'existing_ticket_price_ids'     => $default ? '' : implode(',', array_keys($prices)),
1577
-            'ticket_template_id'            => $default ? 0 : $ticket->get('TTM_ID'),
1578
-            'TKT_taxable'                   => $TKT_taxable,
1579
-            'display_subtotal'              => $ticket instanceof EE_Ticket && $ticket->taxable()
1580
-                ? ''
1581
-                : ' style="display:none"',
1582
-            'price_currency_symbol'         => EE_Registry::instance()->CFG->currency->sign,
1583
-            'TKT_subtotal_amount_display'   => EEH_Template::format_currency(
1584
-                $ticket_subtotal,
1585
-                false,
1586
-                false
1587
-            ),
1588
-            'TKT_subtotal_amount'           => $ticket_subtotal,
1589
-            'tax_rows'                      => $this->_get_tax_rows($ticket_row, $ticket),
1590
-            'disabled'                      => $ticket instanceof EE_Ticket && $ticket->deleted(),
1591
-            'ticket_archive_class'          => $ticket instanceof EE_Ticket && $ticket->deleted()
1592
-                ? ' ticket-archived'
1593
-                : '',
1594
-            'trash_icon'                    => $ticket instanceof EE_Ticket
1595
-                                               && $ticket->deleted()
1596
-                                               && ! $ticket->is_permanently_deleteable()
1597
-                ? 'ee-lock-icon '
1598
-                : 'trash-icon dashicons dashicons-post-trash clickable',
1599
-            'clone_icon'                    => $ticket instanceof EE_Ticket && $ticket->deleted()
1600
-                ? ''
1601
-                : 'clone-icon ee-icon ee-icon-clone clickable',
1602
-        );
1603
-        $template_args['trash_hidden'] = count($all_tickets) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1604
-            ? ' style="display:none"'
1605
-            : '';
1606
-        // handle rows that should NOT be empty
1607
-        if (empty($template_args['TKT_start_date'])) {
1608
-            // if empty then the start date will be now.
1609
-            $template_args['TKT_start_date'] = date(
1610
-                $this->_date_time_format,
1611
-                current_time('timestamp')
1612
-            );
1613
-            $template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1614
-        }
1615
-        if (empty($template_args['TKT_end_date'])) {
1616
-            // get the earliest datetime (if present);
1617
-            $earliest_dtt = $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0
1618
-                ? $this->_adminpage_obj->get_cpt_model_obj()->get_first_related(
1619
-                    'Datetime',
1620
-                    array('order_by' => array('DTT_EVT_start' => 'ASC'))
1621
-                )
1622
-                : null;
1623
-            if (! empty($earliest_dtt)) {
1624
-                $template_args['TKT_end_date'] = $earliest_dtt->get_datetime(
1625
-                    'DTT_EVT_start',
1626
-                    $this->_date_time_format
1627
-                );
1628
-            } else {
1629
-                // default so let's just use what's been set for the default date-time which is 30 days from now.
1630
-                $template_args['TKT_end_date'] = date(
1631
-                    $this->_date_time_format,
1632
-                    mktime(
1633
-                        24,
1634
-                        0,
1635
-                        0,
1636
-                        date('m'),
1637
-                        date('d') + 29,
1638
-                        date('Y')
1639
-                    )
1640
-                );
1641
-            }
1642
-            $template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1643
-        }
1644
-        // generate ticket_datetime items
1645
-        if (! $default) {
1646
-            $datetime_row = 1;
1647
-            foreach ($all_datetimes as $datetime) {
1648
-                $template_args['ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
1649
-                    $datetime_row,
1650
-                    $ticket_row,
1651
-                    $datetime,
1652
-                    $ticket,
1653
-                    $ticket_datetimes,
1654
-                    $default
1655
-                );
1656
-                $datetime_row++;
1657
-            }
1658
-        }
1659
-        $price_row = 1;
1660
-        foreach ($prices as $price) {
1661
-            if (! $price instanceof EE_Price) {
1662
-                continue;
1663
-            }
1664
-            if ($price->is_base_price()) {
1665
-                $price_row++;
1666
-                continue;
1667
-            }
1668
-            $show_trash = ! ((count($prices) > 1 && $price_row === 1) || count($prices) === 1);
1669
-            $show_create = ! (count($prices) > 1 && count($prices) !== $price_row);
1670
-            $template_args['ticket_price_rows'] .= $this->_get_ticket_price_row(
1671
-                $ticket_row,
1672
-                $price_row,
1673
-                $price,
1674
-                $default,
1675
-                $ticket,
1676
-                $show_trash,
1677
-                $show_create
1678
-            );
1679
-            $price_row++;
1680
-        }
1681
-        // filter $template_args
1682
-        $template_args = apply_filters(
1683
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_row__template_args',
1684
-            $template_args,
1685
-            $ticket_row,
1686
-            $ticket,
1687
-            $ticket_datetimes,
1688
-            $all_datetimes,
1689
-            $default,
1690
-            $all_tickets,
1691
-            $this->_is_creating_event
1692
-        );
1693
-        return EEH_Template::display_template(
1694
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_row.template.php',
1695
-            $template_args,
1696
-            true
1697
-        );
1698
-    }
1416
+	/**
1417
+	 * This generates the ticket row for tickets.
1418
+	 * This same method is used to generate both the actual rows and the js skeleton row
1419
+	 * (when default === true)
1420
+	 *
1421
+	 * @param int           $ticket_row       Represents the row number being generated.
1422
+	 * @param               $ticket
1423
+	 * @param EE_Datetime[] $ticket_datetimes Either an array of all datetimes on all tickets indexed by each ticket
1424
+	 *                                        or empty for default
1425
+	 * @param EE_Datetime[] $all_datetimes    All Datetimes on the event or empty for default.
1426
+	 * @param bool          $default          Whether default row being generated or not.
1427
+	 * @param EE_Ticket[]   $all_tickets      This is an array of all tickets attached to the event
1428
+	 *                                        (or empty in the case of defaults)
1429
+	 * @return mixed
1430
+	 * @throws InvalidArgumentException
1431
+	 * @throws InvalidInterfaceException
1432
+	 * @throws InvalidDataTypeException
1433
+	 * @throws DomainException
1434
+	 * @throws EE_Error
1435
+	 * @throws ReflectionException
1436
+	 */
1437
+	protected function _get_ticket_row(
1438
+		$ticket_row,
1439
+		$ticket,
1440
+		$ticket_datetimes,
1441
+		$all_datetimes,
1442
+		$default = false,
1443
+		$all_tickets = array()
1444
+	) {
1445
+		// if $ticket is not an instance of EE_Ticket then force default to true.
1446
+		$default = ! $ticket instanceof EE_Ticket ? true : $default;
1447
+		$prices = ! empty($ticket) && ! $default
1448
+			? $ticket->get_many_related(
1449
+				'Price',
1450
+				array('default_where_conditions' => 'none', 'order_by' => array('PRC_order' => 'ASC'))
1451
+			)
1452
+			: array();
1453
+		// if there is only one price (which would be the base price)
1454
+		// or NO prices and this ticket is a default ticket,
1455
+		// let's just make sure there are no cached default prices on the object.
1456
+		// This is done by not including any query_params.
1457
+		if ($ticket instanceof EE_Ticket && $ticket->is_default() && (count($prices) === 1 || empty($prices))) {
1458
+			$prices = $ticket->prices();
1459
+		}
1460
+		// check if we're dealing with a default ticket in which case
1461
+		// we don't want any starting_ticket_datetime_row values set
1462
+		// (otherwise there won't be any new relationships created for tickets based off of the default ticket).
1463
+		// This will future proof in case there is ever any behaviour change between what the primary_key defaults to.
1464
+		$default_dtt = $default || ($ticket instanceof EE_Ticket && $ticket->is_default());
1465
+		$tkt_datetimes = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
1466
+			? $ticket_datetimes[ $ticket->ID() ]
1467
+			: array();
1468
+		$ticket_subtotal = $default ? 0 : $ticket->get_ticket_subtotal();
1469
+		$base_price = $default ? null : $ticket->base_price();
1470
+		$count_price_mods = EEM_Price::instance()->get_all_default_prices(true);
1471
+		// breaking out complicated condition for ticket_status
1472
+		if ($default) {
1473
+			$ticket_status_class = ' tkt-status-' . EE_Ticket::onsale;
1474
+		} else {
1475
+			$ticket_status_class = $ticket->is_default()
1476
+				? ' tkt-status-' . EE_Ticket::onsale
1477
+				: ' tkt-status-' . $ticket->ticket_status();
1478
+		}
1479
+		// breaking out complicated condition for TKT_taxable
1480
+		if ($default) {
1481
+			$TKT_taxable = '';
1482
+		} else {
1483
+			$TKT_taxable = $ticket->taxable()
1484
+				? ' checked="checked"'
1485
+				: '';
1486
+		}
1487
+		if ($default) {
1488
+			$TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1489
+		} elseif ($ticket->is_default()) {
1490
+			$TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1491
+		} else {
1492
+			$TKT_status = $ticket->ticket_status(true);
1493
+		}
1494
+		if ($default) {
1495
+			$TKT_min = '';
1496
+		} else {
1497
+			$TKT_min = $ticket->min();
1498
+			if ($TKT_min === -1 || $TKT_min === 0) {
1499
+				$TKT_min = '';
1500
+			}
1501
+		}
1502
+		$template_args = array(
1503
+			'tkt_row'                       => $default ? 'TICKETNUM' : $ticket_row,
1504
+			'TKT_order'                     => $default ? 'TICKETNUM' : $ticket_row,
1505
+			// on initial page load this will always be the correct order.
1506
+			'tkt_status_class'              => $ticket_status_class,
1507
+			'display_edit_tkt_row'          => ' style="display:none;"',
1508
+			'edit_tkt_expanded'             => '',
1509
+			'edit_tickets_name'             => $default ? 'TICKETNAMEATTR' : 'edit_tickets',
1510
+			'TKT_name'                      => $default ? '' : $ticket->get_f('TKT_name'),
1511
+			'TKT_start_date'                => $default
1512
+				? ''
1513
+				: $ticket->get_date('TKT_start_date', $this->_date_time_format),
1514
+			'TKT_end_date'                  => $default
1515
+				? ''
1516
+				: $ticket->get_date('TKT_end_date', $this->_date_time_format),
1517
+			'TKT_status'                    => $TKT_status,
1518
+			'TKT_price'                     => $default
1519
+				? ''
1520
+				: EEH_Template::format_currency(
1521
+					$ticket->get_ticket_total_with_taxes(),
1522
+					false,
1523
+					false
1524
+				),
1525
+			'TKT_price_code'                => EE_Registry::instance()->CFG->currency->code,
1526
+			'TKT_price_amount'              => $default ? 0 : $ticket_subtotal,
1527
+			'TKT_qty'                       => $default
1528
+				? ''
1529
+				: $ticket->get_pretty('TKT_qty', 'symbol'),
1530
+			'TKT_qty_for_input'             => $default
1531
+				? ''
1532
+				: $ticket->get_pretty('TKT_qty', 'input'),
1533
+			'TKT_uses'                      => $default
1534
+				? ''
1535
+				: $ticket->get_pretty('TKT_uses', 'input'),
1536
+			'TKT_min'                       => $TKT_min,
1537
+			'TKT_max'                       => $default
1538
+				? ''
1539
+				: $ticket->get_pretty('TKT_max', 'input'),
1540
+			'TKT_sold'                      => $default ? 0 : $ticket->tickets_sold('ticket'),
1541
+			'TKT_reserved'                  => $default ? 0 : $ticket->reserved(),
1542
+			'TKT_registrations'             => $default
1543
+				? 0
1544
+				: $ticket->count_registrations(
1545
+					array(
1546
+						array(
1547
+							'STS_ID' => array(
1548
+								'!=',
1549
+								EEM_Registration::status_id_incomplete,
1550
+							),
1551
+						),
1552
+					)
1553
+				),
1554
+			'TKT_ID'                        => $default ? 0 : $ticket->ID(),
1555
+			'TKT_description'               => $default ? '' : $ticket->get_f('TKT_description'),
1556
+			'TKT_is_default'                => $default ? 0 : $ticket->is_default(),
1557
+			'TKT_required'                  => $default ? 0 : $ticket->required(),
1558
+			'TKT_is_default_selector'       => '',
1559
+			'ticket_price_rows'             => '',
1560
+			'TKT_base_price'                => $default || ! $base_price instanceof EE_Price
1561
+				? ''
1562
+				: $base_price->get_pretty('PRC_amount', 'localized_float'),
1563
+			'TKT_base_price_ID'             => $default || ! $base_price instanceof EE_Price ? 0 : $base_price->ID(),
1564
+			'show_price_modifier'           => count($prices) > 1 || ($default && $count_price_mods > 0)
1565
+				? ''
1566
+				: ' style="display:none;"',
1567
+			'show_price_mod_button'         => count($prices) > 1
1568
+											   || ($default && $count_price_mods > 0)
1569
+											   || (! $default && $ticket->deleted())
1570
+				? ' style="display:none;"'
1571
+				: '',
1572
+			'total_price_rows'              => count($prices) > 1 ? count($prices) : 1,
1573
+			'ticket_datetimes_list'         => $default ? '<li class="hidden"></li>' : '',
1574
+			'starting_ticket_datetime_rows' => $default || $default_dtt ? '' : implode(',', $tkt_datetimes),
1575
+			'ticket_datetime_rows'          => $default ? '' : implode(',', $tkt_datetimes),
1576
+			'existing_ticket_price_ids'     => $default ? '' : implode(',', array_keys($prices)),
1577
+			'ticket_template_id'            => $default ? 0 : $ticket->get('TTM_ID'),
1578
+			'TKT_taxable'                   => $TKT_taxable,
1579
+			'display_subtotal'              => $ticket instanceof EE_Ticket && $ticket->taxable()
1580
+				? ''
1581
+				: ' style="display:none"',
1582
+			'price_currency_symbol'         => EE_Registry::instance()->CFG->currency->sign,
1583
+			'TKT_subtotal_amount_display'   => EEH_Template::format_currency(
1584
+				$ticket_subtotal,
1585
+				false,
1586
+				false
1587
+			),
1588
+			'TKT_subtotal_amount'           => $ticket_subtotal,
1589
+			'tax_rows'                      => $this->_get_tax_rows($ticket_row, $ticket),
1590
+			'disabled'                      => $ticket instanceof EE_Ticket && $ticket->deleted(),
1591
+			'ticket_archive_class'          => $ticket instanceof EE_Ticket && $ticket->deleted()
1592
+				? ' ticket-archived'
1593
+				: '',
1594
+			'trash_icon'                    => $ticket instanceof EE_Ticket
1595
+											   && $ticket->deleted()
1596
+											   && ! $ticket->is_permanently_deleteable()
1597
+				? 'ee-lock-icon '
1598
+				: 'trash-icon dashicons dashicons-post-trash clickable',
1599
+			'clone_icon'                    => $ticket instanceof EE_Ticket && $ticket->deleted()
1600
+				? ''
1601
+				: 'clone-icon ee-icon ee-icon-clone clickable',
1602
+		);
1603
+		$template_args['trash_hidden'] = count($all_tickets) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1604
+			? ' style="display:none"'
1605
+			: '';
1606
+		// handle rows that should NOT be empty
1607
+		if (empty($template_args['TKT_start_date'])) {
1608
+			// if empty then the start date will be now.
1609
+			$template_args['TKT_start_date'] = date(
1610
+				$this->_date_time_format,
1611
+				current_time('timestamp')
1612
+			);
1613
+			$template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1614
+		}
1615
+		if (empty($template_args['TKT_end_date'])) {
1616
+			// get the earliest datetime (if present);
1617
+			$earliest_dtt = $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0
1618
+				? $this->_adminpage_obj->get_cpt_model_obj()->get_first_related(
1619
+					'Datetime',
1620
+					array('order_by' => array('DTT_EVT_start' => 'ASC'))
1621
+				)
1622
+				: null;
1623
+			if (! empty($earliest_dtt)) {
1624
+				$template_args['TKT_end_date'] = $earliest_dtt->get_datetime(
1625
+					'DTT_EVT_start',
1626
+					$this->_date_time_format
1627
+				);
1628
+			} else {
1629
+				// default so let's just use what's been set for the default date-time which is 30 days from now.
1630
+				$template_args['TKT_end_date'] = date(
1631
+					$this->_date_time_format,
1632
+					mktime(
1633
+						24,
1634
+						0,
1635
+						0,
1636
+						date('m'),
1637
+						date('d') + 29,
1638
+						date('Y')
1639
+					)
1640
+				);
1641
+			}
1642
+			$template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1643
+		}
1644
+		// generate ticket_datetime items
1645
+		if (! $default) {
1646
+			$datetime_row = 1;
1647
+			foreach ($all_datetimes as $datetime) {
1648
+				$template_args['ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
1649
+					$datetime_row,
1650
+					$ticket_row,
1651
+					$datetime,
1652
+					$ticket,
1653
+					$ticket_datetimes,
1654
+					$default
1655
+				);
1656
+				$datetime_row++;
1657
+			}
1658
+		}
1659
+		$price_row = 1;
1660
+		foreach ($prices as $price) {
1661
+			if (! $price instanceof EE_Price) {
1662
+				continue;
1663
+			}
1664
+			if ($price->is_base_price()) {
1665
+				$price_row++;
1666
+				continue;
1667
+			}
1668
+			$show_trash = ! ((count($prices) > 1 && $price_row === 1) || count($prices) === 1);
1669
+			$show_create = ! (count($prices) > 1 && count($prices) !== $price_row);
1670
+			$template_args['ticket_price_rows'] .= $this->_get_ticket_price_row(
1671
+				$ticket_row,
1672
+				$price_row,
1673
+				$price,
1674
+				$default,
1675
+				$ticket,
1676
+				$show_trash,
1677
+				$show_create
1678
+			);
1679
+			$price_row++;
1680
+		}
1681
+		// filter $template_args
1682
+		$template_args = apply_filters(
1683
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_row__template_args',
1684
+			$template_args,
1685
+			$ticket_row,
1686
+			$ticket,
1687
+			$ticket_datetimes,
1688
+			$all_datetimes,
1689
+			$default,
1690
+			$all_tickets,
1691
+			$this->_is_creating_event
1692
+		);
1693
+		return EEH_Template::display_template(
1694
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_row.template.php',
1695
+			$template_args,
1696
+			true
1697
+		);
1698
+	}
1699 1699
 
1700 1700
 
1701
-    /**
1702
-     * @param int            $ticket_row
1703
-     * @param EE_Ticket|null $ticket
1704
-     * @return string
1705
-     * @throws DomainException
1706
-     * @throws EE_Error
1707
-     */
1708
-    protected function _get_tax_rows($ticket_row, $ticket)
1709
-    {
1710
-        $tax_rows = '';
1711
-        /** @var EE_Price[] $taxes */
1712
-        $taxes = empty($ticket) ? EE_Taxes::get_taxes_for_admin() : $ticket->get_ticket_taxes_for_admin();
1713
-        foreach ($taxes as $tax) {
1714
-            $tax_added = $this->_get_tax_added($tax, $ticket);
1715
-            $template_args = array(
1716
-                'display_tax'       => ! empty($ticket) && $ticket->get('TKT_taxable')
1717
-                    ? ''
1718
-                    : ' style="display:none;"',
1719
-                'tax_id'            => $tax->ID(),
1720
-                'tkt_row'           => $ticket_row,
1721
-                'tax_label'         => $tax->get('PRC_name'),
1722
-                'tax_added'         => $tax_added,
1723
-                'tax_added_display' => EEH_Template::format_currency($tax_added, false, false),
1724
-                'tax_amount'        => $tax->get('PRC_amount'),
1725
-            );
1726
-            $template_args = apply_filters(
1727
-                'FHEE__espresso_events_Pricing_Hooks___get_tax_rows__template_args',
1728
-                $template_args,
1729
-                $ticket_row,
1730
-                $ticket,
1731
-                $this->_is_creating_event
1732
-            );
1733
-            $tax_rows .= EEH_Template::display_template(
1734
-                PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_tax_row.template.php',
1735
-                $template_args,
1736
-                true
1737
-            );
1738
-        }
1739
-        return $tax_rows;
1740
-    }
1701
+	/**
1702
+	 * @param int            $ticket_row
1703
+	 * @param EE_Ticket|null $ticket
1704
+	 * @return string
1705
+	 * @throws DomainException
1706
+	 * @throws EE_Error
1707
+	 */
1708
+	protected function _get_tax_rows($ticket_row, $ticket)
1709
+	{
1710
+		$tax_rows = '';
1711
+		/** @var EE_Price[] $taxes */
1712
+		$taxes = empty($ticket) ? EE_Taxes::get_taxes_for_admin() : $ticket->get_ticket_taxes_for_admin();
1713
+		foreach ($taxes as $tax) {
1714
+			$tax_added = $this->_get_tax_added($tax, $ticket);
1715
+			$template_args = array(
1716
+				'display_tax'       => ! empty($ticket) && $ticket->get('TKT_taxable')
1717
+					? ''
1718
+					: ' style="display:none;"',
1719
+				'tax_id'            => $tax->ID(),
1720
+				'tkt_row'           => $ticket_row,
1721
+				'tax_label'         => $tax->get('PRC_name'),
1722
+				'tax_added'         => $tax_added,
1723
+				'tax_added_display' => EEH_Template::format_currency($tax_added, false, false),
1724
+				'tax_amount'        => $tax->get('PRC_amount'),
1725
+			);
1726
+			$template_args = apply_filters(
1727
+				'FHEE__espresso_events_Pricing_Hooks___get_tax_rows__template_args',
1728
+				$template_args,
1729
+				$ticket_row,
1730
+				$ticket,
1731
+				$this->_is_creating_event
1732
+			);
1733
+			$tax_rows .= EEH_Template::display_template(
1734
+				PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_tax_row.template.php',
1735
+				$template_args,
1736
+				true
1737
+			);
1738
+		}
1739
+		return $tax_rows;
1740
+	}
1741 1741
 
1742 1742
 
1743
-    /**
1744
-     * @param EE_Price       $tax
1745
-     * @param EE_Ticket|null $ticket
1746
-     * @return float|int
1747
-     * @throws EE_Error
1748
-     */
1749
-    protected function _get_tax_added(EE_Price $tax, $ticket)
1750
-    {
1751
-        $subtotal = empty($ticket) ? 0 : $ticket->get_ticket_subtotal();
1752
-        return $subtotal * $tax->get('PRC_amount') / 100;
1753
-    }
1743
+	/**
1744
+	 * @param EE_Price       $tax
1745
+	 * @param EE_Ticket|null $ticket
1746
+	 * @return float|int
1747
+	 * @throws EE_Error
1748
+	 */
1749
+	protected function _get_tax_added(EE_Price $tax, $ticket)
1750
+	{
1751
+		$subtotal = empty($ticket) ? 0 : $ticket->get_ticket_subtotal();
1752
+		return $subtotal * $tax->get('PRC_amount') / 100;
1753
+	}
1754 1754
 
1755 1755
 
1756
-    /**
1757
-     * @param int            $ticket_row
1758
-     * @param int            $price_row
1759
-     * @param EE_Price|null  $price
1760
-     * @param bool           $default
1761
-     * @param EE_Ticket|null $ticket
1762
-     * @param bool           $show_trash
1763
-     * @param bool           $show_create
1764
-     * @return mixed
1765
-     * @throws InvalidArgumentException
1766
-     * @throws InvalidInterfaceException
1767
-     * @throws InvalidDataTypeException
1768
-     * @throws DomainException
1769
-     * @throws EE_Error
1770
-     * @throws ReflectionException
1771
-     */
1772
-    protected function _get_ticket_price_row(
1773
-        $ticket_row,
1774
-        $price_row,
1775
-        $price,
1776
-        $default,
1777
-        $ticket,
1778
-        $show_trash = true,
1779
-        $show_create = true
1780
-    ) {
1781
-        $send_disabled = ! empty($ticket) && $ticket->get('TKT_deleted');
1782
-        $template_args = array(
1783
-            'tkt_row'               => $default && empty($ticket)
1784
-                ? 'TICKETNUM'
1785
-                : $ticket_row,
1786
-            'PRC_order'             => $default && empty($price)
1787
-                ? 'PRICENUM'
1788
-                : $price_row,
1789
-            'edit_prices_name'      => $default && empty($price)
1790
-                ? 'PRICENAMEATTR'
1791
-                : 'edit_prices',
1792
-            'price_type_selector'   => $default && empty($price)
1793
-                ? $this->_get_base_price_template($ticket_row, $price_row, $price, $default)
1794
-                : $this->_get_price_type_selector(
1795
-                    $ticket_row,
1796
-                    $price_row,
1797
-                    $price,
1798
-                    $default,
1799
-                    $send_disabled
1800
-                ),
1801
-            'PRC_ID'                => $default && empty($price)
1802
-                ? 0
1803
-                : $price->ID(),
1804
-            'PRC_is_default'        => $default && empty($price)
1805
-                ? 0
1806
-                : $price->get('PRC_is_default'),
1807
-            'PRC_name'              => $default && empty($price)
1808
-                ? ''
1809
-                : $price->get('PRC_name'),
1810
-            'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1811
-            'show_plus_or_minus'    => $default && empty($price)
1812
-                ? ''
1813
-                : ' style="display:none;"',
1814
-            'show_plus'             => ($default && empty($price)) || ($price->is_discount() || $price->is_base_price())
1815
-                ? ' style="display:none;"'
1816
-                : '',
1817
-            'show_minus'            => ($default && empty($price)) || ! $price->is_discount()
1818
-                ? ' style="display:none;"'
1819
-                : '',
1820
-            'show_currency_symbol'  => ($default && empty($price)) || $price->is_percent()
1821
-                ? ' style="display:none"'
1822
-                : '',
1823
-            'PRC_amount'            => $default && empty($price)
1824
-                ? 0
1825
-                : $price->get_pretty('PRC_amount', 'localized_float'),
1826
-            'show_percentage'       => ($default && empty($price)) || ! $price->is_percent()
1827
-                ? ' style="display:none;"'
1828
-                : '',
1829
-            'show_trash_icon'       => $show_trash
1830
-                ? ''
1831
-                : ' style="display:none;"',
1832
-            'show_create_button'    => $show_create
1833
-                ? ''
1834
-                : ' style="display:none;"',
1835
-            'PRC_desc'              => $default && empty($price)
1836
-                ? ''
1837
-                : $price->get('PRC_desc'),
1838
-            'disabled'              => ! empty($ticket) && $ticket->get('TKT_deleted'),
1839
-        );
1840
-        $template_args = apply_filters(
1841
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_price_row__template_args',
1842
-            $template_args,
1843
-            $ticket_row,
1844
-            $price_row,
1845
-            $price,
1846
-            $default,
1847
-            $ticket,
1848
-            $show_trash,
1849
-            $show_create,
1850
-            $this->_is_creating_event
1851
-        );
1852
-        return EEH_Template::display_template(
1853
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_price_row.template.php',
1854
-            $template_args,
1855
-            true
1856
-        );
1857
-    }
1756
+	/**
1757
+	 * @param int            $ticket_row
1758
+	 * @param int            $price_row
1759
+	 * @param EE_Price|null  $price
1760
+	 * @param bool           $default
1761
+	 * @param EE_Ticket|null $ticket
1762
+	 * @param bool           $show_trash
1763
+	 * @param bool           $show_create
1764
+	 * @return mixed
1765
+	 * @throws InvalidArgumentException
1766
+	 * @throws InvalidInterfaceException
1767
+	 * @throws InvalidDataTypeException
1768
+	 * @throws DomainException
1769
+	 * @throws EE_Error
1770
+	 * @throws ReflectionException
1771
+	 */
1772
+	protected function _get_ticket_price_row(
1773
+		$ticket_row,
1774
+		$price_row,
1775
+		$price,
1776
+		$default,
1777
+		$ticket,
1778
+		$show_trash = true,
1779
+		$show_create = true
1780
+	) {
1781
+		$send_disabled = ! empty($ticket) && $ticket->get('TKT_deleted');
1782
+		$template_args = array(
1783
+			'tkt_row'               => $default && empty($ticket)
1784
+				? 'TICKETNUM'
1785
+				: $ticket_row,
1786
+			'PRC_order'             => $default && empty($price)
1787
+				? 'PRICENUM'
1788
+				: $price_row,
1789
+			'edit_prices_name'      => $default && empty($price)
1790
+				? 'PRICENAMEATTR'
1791
+				: 'edit_prices',
1792
+			'price_type_selector'   => $default && empty($price)
1793
+				? $this->_get_base_price_template($ticket_row, $price_row, $price, $default)
1794
+				: $this->_get_price_type_selector(
1795
+					$ticket_row,
1796
+					$price_row,
1797
+					$price,
1798
+					$default,
1799
+					$send_disabled
1800
+				),
1801
+			'PRC_ID'                => $default && empty($price)
1802
+				? 0
1803
+				: $price->ID(),
1804
+			'PRC_is_default'        => $default && empty($price)
1805
+				? 0
1806
+				: $price->get('PRC_is_default'),
1807
+			'PRC_name'              => $default && empty($price)
1808
+				? ''
1809
+				: $price->get('PRC_name'),
1810
+			'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1811
+			'show_plus_or_minus'    => $default && empty($price)
1812
+				? ''
1813
+				: ' style="display:none;"',
1814
+			'show_plus'             => ($default && empty($price)) || ($price->is_discount() || $price->is_base_price())
1815
+				? ' style="display:none;"'
1816
+				: '',
1817
+			'show_minus'            => ($default && empty($price)) || ! $price->is_discount()
1818
+				? ' style="display:none;"'
1819
+				: '',
1820
+			'show_currency_symbol'  => ($default && empty($price)) || $price->is_percent()
1821
+				? ' style="display:none"'
1822
+				: '',
1823
+			'PRC_amount'            => $default && empty($price)
1824
+				? 0
1825
+				: $price->get_pretty('PRC_amount', 'localized_float'),
1826
+			'show_percentage'       => ($default && empty($price)) || ! $price->is_percent()
1827
+				? ' style="display:none;"'
1828
+				: '',
1829
+			'show_trash_icon'       => $show_trash
1830
+				? ''
1831
+				: ' style="display:none;"',
1832
+			'show_create_button'    => $show_create
1833
+				? ''
1834
+				: ' style="display:none;"',
1835
+			'PRC_desc'              => $default && empty($price)
1836
+				? ''
1837
+				: $price->get('PRC_desc'),
1838
+			'disabled'              => ! empty($ticket) && $ticket->get('TKT_deleted'),
1839
+		);
1840
+		$template_args = apply_filters(
1841
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_price_row__template_args',
1842
+			$template_args,
1843
+			$ticket_row,
1844
+			$price_row,
1845
+			$price,
1846
+			$default,
1847
+			$ticket,
1848
+			$show_trash,
1849
+			$show_create,
1850
+			$this->_is_creating_event
1851
+		);
1852
+		return EEH_Template::display_template(
1853
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_price_row.template.php',
1854
+			$template_args,
1855
+			true
1856
+		);
1857
+	}
1858 1858
 
1859 1859
 
1860
-    /**
1861
-     * @param int      $ticket_row
1862
-     * @param int      $price_row
1863
-     * @param EE_Price $price
1864
-     * @param bool     $default
1865
-     * @param bool     $disabled
1866
-     * @return mixed
1867
-     * @throws ReflectionException
1868
-     * @throws InvalidArgumentException
1869
-     * @throws InvalidInterfaceException
1870
-     * @throws InvalidDataTypeException
1871
-     * @throws DomainException
1872
-     * @throws EE_Error
1873
-     */
1874
-    protected function _get_price_type_selector($ticket_row, $price_row, $price, $default, $disabled = false)
1875
-    {
1876
-        if ($price->is_base_price()) {
1877
-            return $this->_get_base_price_template(
1878
-                $ticket_row,
1879
-                $price_row,
1880
-                $price,
1881
-                $default
1882
-            );
1883
-        }
1884
-        return $this->_get_price_modifier_template(
1885
-            $ticket_row,
1886
-            $price_row,
1887
-            $price,
1888
-            $default,
1889
-            $disabled
1890
-        );
1891
-    }
1860
+	/**
1861
+	 * @param int      $ticket_row
1862
+	 * @param int      $price_row
1863
+	 * @param EE_Price $price
1864
+	 * @param bool     $default
1865
+	 * @param bool     $disabled
1866
+	 * @return mixed
1867
+	 * @throws ReflectionException
1868
+	 * @throws InvalidArgumentException
1869
+	 * @throws InvalidInterfaceException
1870
+	 * @throws InvalidDataTypeException
1871
+	 * @throws DomainException
1872
+	 * @throws EE_Error
1873
+	 */
1874
+	protected function _get_price_type_selector($ticket_row, $price_row, $price, $default, $disabled = false)
1875
+	{
1876
+		if ($price->is_base_price()) {
1877
+			return $this->_get_base_price_template(
1878
+				$ticket_row,
1879
+				$price_row,
1880
+				$price,
1881
+				$default
1882
+			);
1883
+		}
1884
+		return $this->_get_price_modifier_template(
1885
+			$ticket_row,
1886
+			$price_row,
1887
+			$price,
1888
+			$default,
1889
+			$disabled
1890
+		);
1891
+	}
1892 1892
 
1893 1893
 
1894
-    /**
1895
-     * @param int      $ticket_row
1896
-     * @param int      $price_row
1897
-     * @param EE_Price $price
1898
-     * @param bool     $default
1899
-     * @return mixed
1900
-     * @throws DomainException
1901
-     * @throws EE_Error
1902
-     */
1903
-    protected function _get_base_price_template($ticket_row, $price_row, $price, $default)
1904
-    {
1905
-        $template_args = array(
1906
-            'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
1907
-            'PRC_order'                 => $default && empty($price) ? 'PRICENUM' : $price_row,
1908
-            'PRT_ID'                    => $default && empty($price) ? 1 : $price->get('PRT_ID'),
1909
-            'PRT_name'                  => esc_html__('Price', 'event_espresso'),
1910
-            'price_selected_operator'   => '+',
1911
-            'price_selected_is_percent' => 0,
1912
-        );
1913
-        $template_args = apply_filters(
1914
-            'FHEE__espresso_events_Pricing_Hooks___get_base_price_template__template_args',
1915
-            $template_args,
1916
-            $ticket_row,
1917
-            $price_row,
1918
-            $price,
1919
-            $default,
1920
-            $this->_is_creating_event
1921
-        );
1922
-        return EEH_Template::display_template(
1923
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_type_base.template.php',
1924
-            $template_args,
1925
-            true
1926
-        );
1927
-    }
1894
+	/**
1895
+	 * @param int      $ticket_row
1896
+	 * @param int      $price_row
1897
+	 * @param EE_Price $price
1898
+	 * @param bool     $default
1899
+	 * @return mixed
1900
+	 * @throws DomainException
1901
+	 * @throws EE_Error
1902
+	 */
1903
+	protected function _get_base_price_template($ticket_row, $price_row, $price, $default)
1904
+	{
1905
+		$template_args = array(
1906
+			'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
1907
+			'PRC_order'                 => $default && empty($price) ? 'PRICENUM' : $price_row,
1908
+			'PRT_ID'                    => $default && empty($price) ? 1 : $price->get('PRT_ID'),
1909
+			'PRT_name'                  => esc_html__('Price', 'event_espresso'),
1910
+			'price_selected_operator'   => '+',
1911
+			'price_selected_is_percent' => 0,
1912
+		);
1913
+		$template_args = apply_filters(
1914
+			'FHEE__espresso_events_Pricing_Hooks___get_base_price_template__template_args',
1915
+			$template_args,
1916
+			$ticket_row,
1917
+			$price_row,
1918
+			$price,
1919
+			$default,
1920
+			$this->_is_creating_event
1921
+		);
1922
+		return EEH_Template::display_template(
1923
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_type_base.template.php',
1924
+			$template_args,
1925
+			true
1926
+		);
1927
+	}
1928 1928
 
1929 1929
 
1930
-    /**
1931
-     * @param int      $ticket_row
1932
-     * @param int      $price_row
1933
-     * @param EE_Price $price
1934
-     * @param bool     $default
1935
-     * @param bool     $disabled
1936
-     * @return mixed
1937
-     * @throws ReflectionException
1938
-     * @throws InvalidArgumentException
1939
-     * @throws InvalidInterfaceException
1940
-     * @throws InvalidDataTypeException
1941
-     * @throws DomainException
1942
-     * @throws EE_Error
1943
-     */
1944
-    protected function _get_price_modifier_template(
1945
-        $ticket_row,
1946
-        $price_row,
1947
-        $price,
1948
-        $default,
1949
-        $disabled = false
1950
-    ) {
1951
-        $select_name = $default && ! $price instanceof EE_Price
1952
-            ? 'edit_prices[TICKETNUM][PRICENUM][PRT_ID]'
1953
-            : 'edit_prices[' . $ticket_row . '][' . $price_row . '][PRT_ID]';
1954
-        /** @var EEM_Price_Type $price_type_model */
1955
-        $price_type_model = EE_Registry::instance()->load_model('Price_Type');
1956
-        $price_types = $price_type_model->get_all(array(
1957
-            array(
1958
-                'OR' => array(
1959
-                    'PBT_ID'  => '2',
1960
-                    'PBT_ID*' => '3',
1961
-                ),
1962
-            ),
1963
-        ));
1964
-        $all_price_types = $default && ! $price instanceof EE_Price
1965
-            ? array(esc_html__('Select Modifier', 'event_espresso'))
1966
-            : array();
1967
-        $selected_price_type_id = $default && ! $price instanceof EE_Price ? 0 : $price->type();
1968
-        $price_option_spans = '';
1969
-        // setup price types for selector
1970
-        foreach ($price_types as $price_type) {
1971
-            if (! $price_type instanceof EE_Price_Type) {
1972
-                continue;
1973
-            }
1974
-            $all_price_types[ $price_type->ID() ] = $price_type->get('PRT_name');
1975
-            // while we're in the loop let's setup the option spans used by js
1976
-            $span_args = array(
1977
-                'PRT_ID'         => $price_type->ID(),
1978
-                'PRT_operator'   => $price_type->is_discount() ? '-' : '+',
1979
-                'PRT_is_percent' => $price_type->get('PRT_is_percent') ? 1 : 0,
1980
-            );
1981
-            $price_option_spans .= EEH_Template::display_template(
1982
-                PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_option_span.template.php',
1983
-                $span_args,
1984
-                true
1985
-            );
1986
-        }
1987
-        $select_name = $disabled ? 'archive_price[' . $ticket_row . '][' . $price_row . '][PRT_ID]'
1988
-            : $select_name;
1989
-        $select_input = new EE_Select_Input(
1990
-            $all_price_types,
1991
-            array(
1992
-                'default'               => $selected_price_type_id,
1993
-                'html_name'             => $select_name,
1994
-                'html_class'            => 'edit-price-PRT_ID',
1995
-                'other_html_attributes' => $disabled ? 'style="width:auto;" disabled' : 'style="width:auto;"',
1996
-            )
1997
-        );
1998
-        $price_selected_operator = $price instanceof EE_Price && $price->is_discount() ? '-' : '+';
1999
-        $price_selected_operator = $default && ! $price instanceof EE_Price ? '' : $price_selected_operator;
2000
-        $price_selected_is_percent = $price instanceof EE_Price && $price->is_percent() ? 1 : 0;
2001
-        $price_selected_is_percent = $default && ! $price instanceof EE_Price ? '' : $price_selected_is_percent;
2002
-        $template_args = array(
2003
-            'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
2004
-            'PRC_order'                 => $default && ! $price instanceof EE_Price ? 'PRICENUM' : $price_row,
2005
-            'price_modifier_selector'   => $select_input->get_html_for_input(),
2006
-            'main_name'                 => $select_name,
2007
-            'selected_price_type_id'    => $selected_price_type_id,
2008
-            'price_option_spans'        => $price_option_spans,
2009
-            'price_selected_operator'   => $price_selected_operator,
2010
-            'price_selected_is_percent' => $price_selected_is_percent,
2011
-            'disabled'                  => $disabled,
2012
-        );
2013
-        $template_args = apply_filters(
2014
-            'FHEE__espresso_events_Pricing_Hooks___get_price_modifier_template__template_args',
2015
-            $template_args,
2016
-            $ticket_row,
2017
-            $price_row,
2018
-            $price,
2019
-            $default,
2020
-            $disabled,
2021
-            $this->_is_creating_event
2022
-        );
2023
-        return EEH_Template::display_template(
2024
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_modifier_selector.template.php',
2025
-            $template_args,
2026
-            true
2027
-        );
2028
-    }
1930
+	/**
1931
+	 * @param int      $ticket_row
1932
+	 * @param int      $price_row
1933
+	 * @param EE_Price $price
1934
+	 * @param bool     $default
1935
+	 * @param bool     $disabled
1936
+	 * @return mixed
1937
+	 * @throws ReflectionException
1938
+	 * @throws InvalidArgumentException
1939
+	 * @throws InvalidInterfaceException
1940
+	 * @throws InvalidDataTypeException
1941
+	 * @throws DomainException
1942
+	 * @throws EE_Error
1943
+	 */
1944
+	protected function _get_price_modifier_template(
1945
+		$ticket_row,
1946
+		$price_row,
1947
+		$price,
1948
+		$default,
1949
+		$disabled = false
1950
+	) {
1951
+		$select_name = $default && ! $price instanceof EE_Price
1952
+			? 'edit_prices[TICKETNUM][PRICENUM][PRT_ID]'
1953
+			: 'edit_prices[' . $ticket_row . '][' . $price_row . '][PRT_ID]';
1954
+		/** @var EEM_Price_Type $price_type_model */
1955
+		$price_type_model = EE_Registry::instance()->load_model('Price_Type');
1956
+		$price_types = $price_type_model->get_all(array(
1957
+			array(
1958
+				'OR' => array(
1959
+					'PBT_ID'  => '2',
1960
+					'PBT_ID*' => '3',
1961
+				),
1962
+			),
1963
+		));
1964
+		$all_price_types = $default && ! $price instanceof EE_Price
1965
+			? array(esc_html__('Select Modifier', 'event_espresso'))
1966
+			: array();
1967
+		$selected_price_type_id = $default && ! $price instanceof EE_Price ? 0 : $price->type();
1968
+		$price_option_spans = '';
1969
+		// setup price types for selector
1970
+		foreach ($price_types as $price_type) {
1971
+			if (! $price_type instanceof EE_Price_Type) {
1972
+				continue;
1973
+			}
1974
+			$all_price_types[ $price_type->ID() ] = $price_type->get('PRT_name');
1975
+			// while we're in the loop let's setup the option spans used by js
1976
+			$span_args = array(
1977
+				'PRT_ID'         => $price_type->ID(),
1978
+				'PRT_operator'   => $price_type->is_discount() ? '-' : '+',
1979
+				'PRT_is_percent' => $price_type->get('PRT_is_percent') ? 1 : 0,
1980
+			);
1981
+			$price_option_spans .= EEH_Template::display_template(
1982
+				PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_option_span.template.php',
1983
+				$span_args,
1984
+				true
1985
+			);
1986
+		}
1987
+		$select_name = $disabled ? 'archive_price[' . $ticket_row . '][' . $price_row . '][PRT_ID]'
1988
+			: $select_name;
1989
+		$select_input = new EE_Select_Input(
1990
+			$all_price_types,
1991
+			array(
1992
+				'default'               => $selected_price_type_id,
1993
+				'html_name'             => $select_name,
1994
+				'html_class'            => 'edit-price-PRT_ID',
1995
+				'other_html_attributes' => $disabled ? 'style="width:auto;" disabled' : 'style="width:auto;"',
1996
+			)
1997
+		);
1998
+		$price_selected_operator = $price instanceof EE_Price && $price->is_discount() ? '-' : '+';
1999
+		$price_selected_operator = $default && ! $price instanceof EE_Price ? '' : $price_selected_operator;
2000
+		$price_selected_is_percent = $price instanceof EE_Price && $price->is_percent() ? 1 : 0;
2001
+		$price_selected_is_percent = $default && ! $price instanceof EE_Price ? '' : $price_selected_is_percent;
2002
+		$template_args = array(
2003
+			'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
2004
+			'PRC_order'                 => $default && ! $price instanceof EE_Price ? 'PRICENUM' : $price_row,
2005
+			'price_modifier_selector'   => $select_input->get_html_for_input(),
2006
+			'main_name'                 => $select_name,
2007
+			'selected_price_type_id'    => $selected_price_type_id,
2008
+			'price_option_spans'        => $price_option_spans,
2009
+			'price_selected_operator'   => $price_selected_operator,
2010
+			'price_selected_is_percent' => $price_selected_is_percent,
2011
+			'disabled'                  => $disabled,
2012
+		);
2013
+		$template_args = apply_filters(
2014
+			'FHEE__espresso_events_Pricing_Hooks___get_price_modifier_template__template_args',
2015
+			$template_args,
2016
+			$ticket_row,
2017
+			$price_row,
2018
+			$price,
2019
+			$default,
2020
+			$disabled,
2021
+			$this->_is_creating_event
2022
+		);
2023
+		return EEH_Template::display_template(
2024
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_modifier_selector.template.php',
2025
+			$template_args,
2026
+			true
2027
+		);
2028
+	}
2029 2029
 
2030 2030
 
2031
-    /**
2032
-     * @param int              $datetime_row
2033
-     * @param int              $ticket_row
2034
-     * @param EE_Datetime|null $datetime
2035
-     * @param EE_Ticket|null   $ticket
2036
-     * @param array            $ticket_datetimes
2037
-     * @param bool             $default
2038
-     * @return mixed
2039
-     * @throws DomainException
2040
-     * @throws EE_Error
2041
-     */
2042
-    protected function _get_ticket_datetime_list_item(
2043
-        $datetime_row,
2044
-        $ticket_row,
2045
-        $datetime,
2046
-        $ticket,
2047
-        $ticket_datetimes = array(),
2048
-        $default
2049
-    ) {
2050
-        $tkt_datetimes = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
2051
-            ? $ticket_datetimes[ $ticket->ID() ]
2052
-            : array();
2053
-        $template_args = array(
2054
-            'dtt_row'                  => $default && ! $datetime instanceof EE_Datetime
2055
-                ? 'DTTNUM'
2056
-                : $datetime_row,
2057
-            'tkt_row'                  => $default
2058
-                ? 'TICKETNUM'
2059
-                : $ticket_row,
2060
-            'ticket_datetime_selected' => in_array($datetime_row, $tkt_datetimes, true)
2061
-                ? ' ticket-selected'
2062
-                : '',
2063
-            'ticket_datetime_checked'  => in_array($datetime_row, $tkt_datetimes, true)
2064
-                ? ' checked="checked"'
2065
-                : '',
2066
-            'DTT_name'                 => $default && empty($datetime)
2067
-                ? 'DTTNAME'
2068
-                : $datetime->get_dtt_display_name(true),
2069
-            'tkt_status_class'         => '',
2070
-        );
2071
-        $template_args = apply_filters(
2072
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_datetime_list_item__template_args',
2073
-            $template_args,
2074
-            $datetime_row,
2075
-            $ticket_row,
2076
-            $datetime,
2077
-            $ticket,
2078
-            $ticket_datetimes,
2079
-            $default,
2080
-            $this->_is_creating_event
2081
-        );
2082
-        return EEH_Template::display_template(
2083
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_datetimes_list_item.template.php',
2084
-            $template_args,
2085
-            true
2086
-        );
2087
-    }
2031
+	/**
2032
+	 * @param int              $datetime_row
2033
+	 * @param int              $ticket_row
2034
+	 * @param EE_Datetime|null $datetime
2035
+	 * @param EE_Ticket|null   $ticket
2036
+	 * @param array            $ticket_datetimes
2037
+	 * @param bool             $default
2038
+	 * @return mixed
2039
+	 * @throws DomainException
2040
+	 * @throws EE_Error
2041
+	 */
2042
+	protected function _get_ticket_datetime_list_item(
2043
+		$datetime_row,
2044
+		$ticket_row,
2045
+		$datetime,
2046
+		$ticket,
2047
+		$ticket_datetimes = array(),
2048
+		$default
2049
+	) {
2050
+		$tkt_datetimes = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
2051
+			? $ticket_datetimes[ $ticket->ID() ]
2052
+			: array();
2053
+		$template_args = array(
2054
+			'dtt_row'                  => $default && ! $datetime instanceof EE_Datetime
2055
+				? 'DTTNUM'
2056
+				: $datetime_row,
2057
+			'tkt_row'                  => $default
2058
+				? 'TICKETNUM'
2059
+				: $ticket_row,
2060
+			'ticket_datetime_selected' => in_array($datetime_row, $tkt_datetimes, true)
2061
+				? ' ticket-selected'
2062
+				: '',
2063
+			'ticket_datetime_checked'  => in_array($datetime_row, $tkt_datetimes, true)
2064
+				? ' checked="checked"'
2065
+				: '',
2066
+			'DTT_name'                 => $default && empty($datetime)
2067
+				? 'DTTNAME'
2068
+				: $datetime->get_dtt_display_name(true),
2069
+			'tkt_status_class'         => '',
2070
+		);
2071
+		$template_args = apply_filters(
2072
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_datetime_list_item__template_args',
2073
+			$template_args,
2074
+			$datetime_row,
2075
+			$ticket_row,
2076
+			$datetime,
2077
+			$ticket,
2078
+			$ticket_datetimes,
2079
+			$default,
2080
+			$this->_is_creating_event
2081
+		);
2082
+		return EEH_Template::display_template(
2083
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_datetimes_list_item.template.php',
2084
+			$template_args,
2085
+			true
2086
+		);
2087
+	}
2088 2088
 
2089 2089
 
2090
-    /**
2091
-     * @param array $all_datetimes
2092
-     * @param array $all_tickets
2093
-     * @return mixed
2094
-     * @throws ReflectionException
2095
-     * @throws InvalidArgumentException
2096
-     * @throws InvalidInterfaceException
2097
-     * @throws InvalidDataTypeException
2098
-     * @throws DomainException
2099
-     * @throws EE_Error
2100
-     */
2101
-    protected function _get_ticket_js_structure($all_datetimes = array(), $all_tickets = array())
2102
-    {
2103
-        $template_args = array(
2104
-            'default_datetime_edit_row'                => $this->_get_dtt_edit_row(
2105
-                'DTTNUM',
2106
-                null,
2107
-                true,
2108
-                $all_datetimes
2109
-            ),
2110
-            'default_ticket_row'                       => $this->_get_ticket_row(
2111
-                'TICKETNUM',
2112
-                null,
2113
-                array(),
2114
-                array(),
2115
-                true
2116
-            ),
2117
-            'default_price_row'                        => $this->_get_ticket_price_row(
2118
-                'TICKETNUM',
2119
-                'PRICENUM',
2120
-                null,
2121
-                true,
2122
-                null
2123
-            ),
2124
-            'default_price_rows'                       => '',
2125
-            'default_base_price_amount'                => 0,
2126
-            'default_base_price_name'                  => '',
2127
-            'default_base_price_description'           => '',
2128
-            'default_price_modifier_selector_row'      => $this->_get_price_modifier_template(
2129
-                'TICKETNUM',
2130
-                'PRICENUM',
2131
-                null,
2132
-                true
2133
-            ),
2134
-            'default_available_tickets_for_datetime'   => $this->_get_dtt_attached_tickets_row(
2135
-                'DTTNUM',
2136
-                null,
2137
-                array(),
2138
-                array(),
2139
-                true
2140
-            ),
2141
-            'existing_available_datetime_tickets_list' => '',
2142
-            'existing_available_ticket_datetimes_list' => '',
2143
-            'new_available_datetime_ticket_list_item'  => $this->_get_datetime_tickets_list_item(
2144
-                'DTTNUM',
2145
-                'TICKETNUM',
2146
-                null,
2147
-                null,
2148
-                array(),
2149
-                true
2150
-            ),
2151
-            'new_available_ticket_datetime_list_item'  => $this->_get_ticket_datetime_list_item(
2152
-                'DTTNUM',
2153
-                'TICKETNUM',
2154
-                null,
2155
-                null,
2156
-                array(),
2157
-                true
2158
-            ),
2159
-        );
2160
-        $ticket_row = 1;
2161
-        foreach ($all_tickets as $ticket) {
2162
-            $template_args['existing_available_datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
2163
-                'DTTNUM',
2164
-                $ticket_row,
2165
-                null,
2166
-                $ticket,
2167
-                array(),
2168
-                true
2169
-            );
2170
-            $ticket_row++;
2171
-        }
2172
-        $datetime_row = 1;
2173
-        foreach ($all_datetimes as $datetime) {
2174
-            $template_args['existing_available_ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
2175
-                $datetime_row,
2176
-                'TICKETNUM',
2177
-                $datetime,
2178
-                null,
2179
-                array(),
2180
-                true
2181
-            );
2182
-            $datetime_row++;
2183
-        }
2184
-        /** @var EEM_Price $price_model */
2185
-        $price_model = EE_Registry::instance()->load_model('Price');
2186
-        $default_prices = $price_model->get_all_default_prices();
2187
-        $price_row = 1;
2188
-        foreach ($default_prices as $price) {
2189
-            if (! $price instanceof EE_Price) {
2190
-                continue;
2191
-            }
2192
-            if ($price->is_base_price()) {
2193
-                $template_args['default_base_price_amount'] = $price->get_pretty(
2194
-                    'PRC_amount',
2195
-                    'localized_float'
2196
-                );
2197
-                $template_args['default_base_price_name'] = $price->get('PRC_name');
2198
-                $template_args['default_base_price_description'] = $price->get('PRC_desc');
2199
-                $price_row++;
2200
-                continue;
2201
-            }
2202
-            $show_trash = ! ((count($default_prices) > 1 && $price_row === 1)
2203
-                             || count($default_prices) === 1);
2204
-            $show_create = ! (count($default_prices) > 1
2205
-                              && count($default_prices)
2206
-                                 !== $price_row);
2207
-            $template_args['default_price_rows'] .= $this->_get_ticket_price_row(
2208
-                'TICKETNUM',
2209
-                $price_row,
2210
-                $price,
2211
-                true,
2212
-                null,
2213
-                $show_trash,
2214
-                $show_create
2215
-            );
2216
-            $price_row++;
2217
-        }
2218
-        $template_args = apply_filters(
2219
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_js_structure__template_args',
2220
-            $template_args,
2221
-            $all_datetimes,
2222
-            $all_tickets,
2223
-            $this->_is_creating_event
2224
-        );
2225
-        return EEH_Template::display_template(
2226
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_js_structure.template.php',
2227
-            $template_args,
2228
-            true
2229
-        );
2230
-    }
2090
+	/**
2091
+	 * @param array $all_datetimes
2092
+	 * @param array $all_tickets
2093
+	 * @return mixed
2094
+	 * @throws ReflectionException
2095
+	 * @throws InvalidArgumentException
2096
+	 * @throws InvalidInterfaceException
2097
+	 * @throws InvalidDataTypeException
2098
+	 * @throws DomainException
2099
+	 * @throws EE_Error
2100
+	 */
2101
+	protected function _get_ticket_js_structure($all_datetimes = array(), $all_tickets = array())
2102
+	{
2103
+		$template_args = array(
2104
+			'default_datetime_edit_row'                => $this->_get_dtt_edit_row(
2105
+				'DTTNUM',
2106
+				null,
2107
+				true,
2108
+				$all_datetimes
2109
+			),
2110
+			'default_ticket_row'                       => $this->_get_ticket_row(
2111
+				'TICKETNUM',
2112
+				null,
2113
+				array(),
2114
+				array(),
2115
+				true
2116
+			),
2117
+			'default_price_row'                        => $this->_get_ticket_price_row(
2118
+				'TICKETNUM',
2119
+				'PRICENUM',
2120
+				null,
2121
+				true,
2122
+				null
2123
+			),
2124
+			'default_price_rows'                       => '',
2125
+			'default_base_price_amount'                => 0,
2126
+			'default_base_price_name'                  => '',
2127
+			'default_base_price_description'           => '',
2128
+			'default_price_modifier_selector_row'      => $this->_get_price_modifier_template(
2129
+				'TICKETNUM',
2130
+				'PRICENUM',
2131
+				null,
2132
+				true
2133
+			),
2134
+			'default_available_tickets_for_datetime'   => $this->_get_dtt_attached_tickets_row(
2135
+				'DTTNUM',
2136
+				null,
2137
+				array(),
2138
+				array(),
2139
+				true
2140
+			),
2141
+			'existing_available_datetime_tickets_list' => '',
2142
+			'existing_available_ticket_datetimes_list' => '',
2143
+			'new_available_datetime_ticket_list_item'  => $this->_get_datetime_tickets_list_item(
2144
+				'DTTNUM',
2145
+				'TICKETNUM',
2146
+				null,
2147
+				null,
2148
+				array(),
2149
+				true
2150
+			),
2151
+			'new_available_ticket_datetime_list_item'  => $this->_get_ticket_datetime_list_item(
2152
+				'DTTNUM',
2153
+				'TICKETNUM',
2154
+				null,
2155
+				null,
2156
+				array(),
2157
+				true
2158
+			),
2159
+		);
2160
+		$ticket_row = 1;
2161
+		foreach ($all_tickets as $ticket) {
2162
+			$template_args['existing_available_datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
2163
+				'DTTNUM',
2164
+				$ticket_row,
2165
+				null,
2166
+				$ticket,
2167
+				array(),
2168
+				true
2169
+			);
2170
+			$ticket_row++;
2171
+		}
2172
+		$datetime_row = 1;
2173
+		foreach ($all_datetimes as $datetime) {
2174
+			$template_args['existing_available_ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
2175
+				$datetime_row,
2176
+				'TICKETNUM',
2177
+				$datetime,
2178
+				null,
2179
+				array(),
2180
+				true
2181
+			);
2182
+			$datetime_row++;
2183
+		}
2184
+		/** @var EEM_Price $price_model */
2185
+		$price_model = EE_Registry::instance()->load_model('Price');
2186
+		$default_prices = $price_model->get_all_default_prices();
2187
+		$price_row = 1;
2188
+		foreach ($default_prices as $price) {
2189
+			if (! $price instanceof EE_Price) {
2190
+				continue;
2191
+			}
2192
+			if ($price->is_base_price()) {
2193
+				$template_args['default_base_price_amount'] = $price->get_pretty(
2194
+					'PRC_amount',
2195
+					'localized_float'
2196
+				);
2197
+				$template_args['default_base_price_name'] = $price->get('PRC_name');
2198
+				$template_args['default_base_price_description'] = $price->get('PRC_desc');
2199
+				$price_row++;
2200
+				continue;
2201
+			}
2202
+			$show_trash = ! ((count($default_prices) > 1 && $price_row === 1)
2203
+							 || count($default_prices) === 1);
2204
+			$show_create = ! (count($default_prices) > 1
2205
+							  && count($default_prices)
2206
+								 !== $price_row);
2207
+			$template_args['default_price_rows'] .= $this->_get_ticket_price_row(
2208
+				'TICKETNUM',
2209
+				$price_row,
2210
+				$price,
2211
+				true,
2212
+				null,
2213
+				$show_trash,
2214
+				$show_create
2215
+			);
2216
+			$price_row++;
2217
+		}
2218
+		$template_args = apply_filters(
2219
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_js_structure__template_args',
2220
+			$template_args,
2221
+			$all_datetimes,
2222
+			$all_tickets,
2223
+			$this->_is_creating_event
2224
+		);
2225
+		return EEH_Template::display_template(
2226
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_js_structure.template.php',
2227
+			$template_args,
2228
+			true
2229
+		);
2230
+	}
2231 2231
 }
Please login to merge, or discard this patch.
caffeinated/admin/new/pricing/Pricing_Admin_Page.core.php 1 patch
Indentation   +1422 added lines, -1422 removed lines patch added patch discarded remove patch
@@ -12,1430 +12,1430 @@
 block discarded – undo
12 12
 class Pricing_Admin_Page extends EE_Admin_Page
13 13
 {
14 14
 
15
-    /**
16
-     *    constructor
17
-     *
18
-     * @Constructor
19
-     * @access public
20
-     * @param bool $routing
21
-     * @return Pricing_Admin_Page
22
-     */
23
-    public function __construct($routing = true)
24
-    {
25
-        parent::__construct($routing);
26
-    }
27
-
28
-
29
-    protected function _init_page_props()
30
-    {
31
-        $this->page_slug = PRICING_PG_SLUG;
32
-        $this->page_label = PRICING_LABEL;
33
-        $this->_admin_base_url = PRICING_ADMIN_URL;
34
-        $this->_admin_base_path = PRICING_ADMIN;
35
-    }
36
-
37
-
38
-    protected function _ajax_hooks()
39
-    {
40
-        add_action('wp_ajax_espresso_update_prices_order', array($this, 'update_price_order'));
41
-    }
42
-
43
-
44
-    protected function _define_page_props()
45
-    {
46
-        $this->_admin_page_title = PRICING_LABEL;
47
-        $this->_labels = array(
48
-            'buttons' => array(
49
-                'add'         => __('Add New Default Price', 'event_espresso'),
50
-                'edit'        => __('Edit Default Price', 'event_espresso'),
51
-                'delete'      => __('Delete Default Price', 'event_espresso'),
52
-                'add_type'    => __('Add New Default Price Type', 'event_espresso'),
53
-                'edit_type'   => __('Edit Price Type', 'event_espresso'),
54
-                'delete_type' => __('Delete Price Type', 'event_espresso'),
55
-            ),
56
-        );
57
-    }
58
-
59
-
60
-    /**
61
-     *        an array for storing request actions and their corresponding methods
62
-     *
63
-     * @access private
64
-     * @return void
65
-     */
66
-    protected function _set_page_routes()
67
-    {
68
-        $prc_id = ! empty($this->_req_data['PRC_ID']) && ! is_array($this->_req_data['PRC_ID'])
69
-            ? $this->_req_data['PRC_ID'] : 0;
70
-        $prt_id = ! empty($this->_req_data['PRT_ID']) && ! is_array($this->_req_data['PRT_ID'])
71
-            ? $this->_req_data['PRT_ID'] : 0;
72
-        $this->_page_routes = array(
73
-            'default'                     => array(
74
-                'func'       => '_price_overview_list_table',
75
-                'capability' => 'ee_read_default_prices',
76
-            ),
77
-            'add_new_price'               => array(
78
-                'func'       => '_edit_price_details',
79
-                'args'       => array('new_price' => true),
80
-                'capability' => 'ee_edit_default_prices',
81
-            ),
82
-            'edit_price'                  => array(
83
-                'func'       => '_edit_price_details',
84
-                'args'       => array('new_price' => false),
85
-                'capability' => 'ee_edit_default_price',
86
-                'obj_id'     => $prc_id,
87
-            ),
88
-            'insert_price'                => array(
89
-                'func'       => '_insert_or_update_price',
90
-                'args'       => array('new_price' => true),
91
-                'noheader'   => true,
92
-                'capability' => 'ee_edit_default_prices',
93
-            ),
94
-            'update_price'                => array(
95
-                'func'       => '_insert_or_update_price',
96
-                'args'       => array('new_price' => false),
97
-                'noheader'   => true,
98
-                'capability' => 'ee_edit_default_price',
99
-                'obj_id'     => $prc_id,
100
-            ),
101
-            'trash_price'                 => array(
102
-                'func'       => '_trash_or_restore_price',
103
-                'args'       => array('trash' => true),
104
-                'noheader'   => true,
105
-                'capability' => 'ee_delete_default_price',
106
-                'obj_id'     => $prc_id,
107
-            ),
108
-            'restore_price'               => array(
109
-                'func'       => '_trash_or_restore_price',
110
-                'args'       => array('trash' => false),
111
-                'noheader'   => true,
112
-                'capability' => 'ee_delete_default_price',
113
-                'obj_id'     => $prc_id,
114
-            ),
115
-            'delete_price'                => array(
116
-                'func'       => '_delete_price',
117
-                'noheader'   => true,
118
-                'capability' => 'ee_delete_default_price',
119
-                'obj_id'     => $prc_id,
120
-            ),
121
-            'espresso_update_price_order' => array(
122
-                'func'       => 'update_price_order',
123
-                'noheader'   => true,
124
-                'capability' => 'ee_edit_default_prices',
125
-            ),
126
-            // price types
127
-            'price_types'                 => array(
128
-                'func'       => '_price_types_overview_list_table',
129
-                'capability' => 'ee_read_default_price_types',
130
-            ),
131
-            'add_new_price_type'          => array(
132
-                'func'       => '_edit_price_type_details',
133
-                'capability' => 'ee_edit_default_price_types',
134
-            ),
135
-            'edit_price_type'             => array(
136
-                'func'       => '_edit_price_type_details',
137
-                'capability' => 'ee_edit_default_price_type',
138
-                'obj_id'     => $prt_id,
139
-            ),
140
-            'insert_price_type'           => array(
141
-                'func'       => '_insert_or_update_price_type',
142
-                'args'       => array('new_price_type' => true),
143
-                'noheader'   => true,
144
-                'capability' => 'ee_edit_default_price_types',
145
-            ),
146
-            'update_price_type'           => array(
147
-                'func'       => '_insert_or_update_price_type',
148
-                'args'       => array('new_price_type' => false),
149
-                'noheader'   => true,
150
-                'capability' => 'ee_edit_default_price_type',
151
-                'obj_id'     => $prt_id,
152
-            ),
153
-            'trash_price_type'            => array(
154
-                'func'       => '_trash_or_restore_price_type',
155
-                'args'       => array('trash' => true),
156
-                'noheader'   => true,
157
-                'capability' => 'ee_delete_default_price_type',
158
-                'obj_id'     => $prt_id,
159
-            ),
160
-            'restore_price_type'          => array(
161
-                'func'       => '_trash_or_restore_price_type',
162
-                'args'       => array('trash' => false),
163
-                'noheader'   => true,
164
-                'capability' => 'ee_delete_default_price_type',
165
-                'obj_id'     => $prt_id,
166
-            ),
167
-            'delete_price_type'           => array(
168
-                'func'       => '_delete_price_type',
169
-                'noheader'   => true,
170
-                'capability' => 'ee_delete_default_price_type',
171
-                'obj_id'     => $prt_id,
172
-            ),
173
-            'tax_settings'                => array(
174
-                'func'       => '_tax_settings',
175
-                'capability' => 'manage_options',
176
-            ),
177
-            'update_tax_settings'         => array(
178
-                'func'       => '_update_tax_settings',
179
-                'capability' => 'manage_options',
180
-                'noheader'   => true,
181
-            ),
182
-        );
183
-    }
184
-
185
-
186
-    protected function _set_page_config()
187
-    {
188
-
189
-        $this->_page_config = array(
190
-            'default'            => array(
191
-                'nav'           => array(
192
-                    'label' => __('Default Pricing', 'event_espresso'),
193
-                    'order' => 10,
194
-                ),
195
-                'list_table'    => 'Prices_List_Table',
196
-                'help_tabs'     => array(
197
-                    'pricing_default_pricing_help_tab'                           => array(
198
-                        'title'    => __('Default Pricing', 'event_espresso'),
199
-                        'filename' => 'pricing_default_pricing',
200
-                    ),
201
-                    'pricing_default_pricing_table_column_headings_help_tab'     => array(
202
-                        'title'    => __('Default Pricing Table Column Headings', 'event_espresso'),
203
-                        'filename' => 'pricing_default_pricing_table_column_headings',
204
-                    ),
205
-                    'pricing_default_pricing_views_bulk_actions_search_help_tab' => array(
206
-                        'title'    => __('Default Pricing Views & Bulk Actions & Search', 'event_espresso'),
207
-                        'filename' => 'pricing_default_pricing_views_bulk_actions_search',
208
-                    ),
209
-                ),
210
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
211
-                // 'help_tour'     => array('Pricing_Default_Prices_Help_Tour'),
212
-                'require_nonce' => false,
213
-            ),
214
-            'add_new_price'      => array(
215
-                'nav'           => array(
216
-                    'label'      => __('Add New Default Price', 'event_espresso'),
217
-                    'order'      => 20,
218
-                    'persistent' => false,
219
-                ),
220
-                'help_tabs'     => array(
221
-                    'add_new_default_price_help_tab' => array(
222
-                        'title'    => __('Add New Default Price', 'event_espresso'),
223
-                        'filename' => 'pricing_add_new_default_price',
224
-                    ),
225
-                ),
226
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
227
-                // 'help_tour'     => array('Pricing_Add_New_Default_Price_Help_Tour'),
228
-                'metaboxes'     => array('_publish_post_box', '_espresso_news_post_box', '_price_details_meta_boxes'),
229
-                'require_nonce' => false,
230
-            ),
231
-            'edit_price'         => array(
232
-                'nav'           => array(
233
-                    'label'      => __('Edit Default Price', 'event_espresso'),
234
-                    'order'      => 20,
235
-                    'url'        => isset($this->_req_data['id']) ? add_query_arg(
236
-                        array('id' => $this->_req_data['id']),
237
-                        $this->_current_page_view_url
238
-                    ) : $this->_admin_base_url,
239
-                    'persistent' => false,
240
-                ),
241
-                'metaboxes'     => array('_publish_post_box', '_espresso_news_post_box', '_price_details_meta_boxes'),
242
-                'help_tabs'     => array(
243
-                    'edit_default_price_help_tab' => array(
244
-                        'title'    => __('Edit Default Price', 'event_espresso'),
245
-                        'filename' => 'pricing_edit_default_price',
246
-                    ),
247
-                ),
248
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
249
-                // 'help_tour'     => array('Pricing_Edit_Default_Price_Help_Tour'),
250
-                'require_nonce' => false,
251
-            ),
252
-            'price_types'        => array(
253
-                'nav'           => array(
254
-                    'label' => __('Price Types', 'event_espresso'),
255
-                    'order' => 30,
256
-                ),
257
-                'list_table'    => 'Price_Types_List_Table',
258
-                'help_tabs'     => array(
259
-                    'pricing_price_types_help_tab'                           => array(
260
-                        'title'    => __('Price Types', 'event_espresso'),
261
-                        'filename' => 'pricing_price_types',
262
-                    ),
263
-                    'pricing_price_types_table_column_headings_help_tab'     => array(
264
-                        'title'    => __('Price Types Table Column Headings', 'event_espresso'),
265
-                        'filename' => 'pricing_price_types_table_column_headings',
266
-                    ),
267
-                    'pricing_price_types_views_bulk_actions_search_help_tab' => array(
268
-                        'title'    => __('Price Types Views & Bulk Actions & Search', 'event_espresso'),
269
-                        'filename' => 'pricing_price_types_views_bulk_actions_search',
270
-                    ),
271
-                ),
272
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
273
-                // 'help_tour'     => array('Pricing_Price_Types_Default_Help_Tour'),
274
-                'metaboxes'     => array('_espresso_news_post_box', '_espresso_links_post_box'),
275
-                'require_nonce' => false,
276
-            ),
277
-            'add_new_price_type' => array(
278
-                'nav'           => array(
279
-                    'label'      => __('Add New Price Type', 'event_espresso'),
280
-                    'order'      => 40,
281
-                    'persistent' => false,
282
-                ),
283
-                'help_tabs'     => array(
284
-                    'add_new_price_type_help_tab' => array(
285
-                        'title'    => __('Add New Price Type', 'event_espresso'),
286
-                        'filename' => 'pricing_add_new_price_type',
287
-                    ),
288
-                ),
289
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
290
-                // 'help_tour'     => array('Pricing_Add_New_Price_Type_Help_Tour'),
291
-                'metaboxes'     => array(
292
-                    '_publish_post_box',
293
-                    '_espresso_news_post_box',
294
-                    '_price_type_details_meta_boxes',
295
-                ),
296
-                'require_nonce' => false,
297
-            ),
298
-            'edit_price_type'    => array(
299
-                'nav'       => array(
300
-                    'label'      => __('Edit Price Type', 'event_espresso'),
301
-                    'order'      => 40,
302
-                    'persistent' => false,
303
-                ),
304
-                'help_tabs' => array(
305
-                    'edit_price_type_help_tab' => array(
306
-                        'title'    => __('Edit Price Type', 'event_espresso'),
307
-                        'filename' => 'pricing_edit_price_type',
308
-                    ),
309
-                ),
310
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
311
-                // 'help_tour' => array('Pricing_Edit_Price_Type_Help_Tour'),
312
-                'metaboxes' => array('_publish_post_box', '_espresso_news_post_box', '_price_type_details_meta_boxes'),
313
-
314
-                'require_nonce' => false,
315
-            ),
316
-            'tax_settings'       => array(
317
-                'nav'           => array(
318
-                    'label' => esc_html__('Tax Settings', 'event_espresso'),
319
-                    'order' => 40,
320
-                ),
321
-                'labels'        => array(
322
-                    'publishbox' => esc_html__('Update Tax Settings', 'event_espresso'),
323
-                ),
324
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
325
-                // 'help_tabs'     => array(
326
-                //     'registration_form_reg_form_settings_help_tab' => array(
327
-                //         'title'    => esc_html__('Registration Form Settings', 'event_espresso'),
328
-                //         'filename' => 'registration_form_reg_form_settings'
329
-                //     ),
330
-                // ),
331
-                // 'help_tour'     => array('Registration_Form_Settings_Help_Tour'),
332
-                'require_nonce' => true,
333
-            ),
334
-        );
335
-    }
336
-
337
-
338
-    protected function _add_screen_options()
339
-    {
340
-        // todo
341
-    }
342
-
343
-
344
-    protected function _add_screen_options_default()
345
-    {
346
-        $this->_per_page_screen_option();
347
-    }
348
-
349
-
350
-    protected function _add_screen_options_price_types()
351
-    {
352
-        $page_title = $this->_admin_page_title;
353
-        $this->_admin_page_title = __('Price Types', 'event_espresso');
354
-        $this->_per_page_screen_option();
355
-        $this->_admin_page_title = $page_title;
356
-    }
357
-
358
-
359
-    protected function _add_feature_pointers()
360
-    {
361
-    }
362
-
363
-
364
-    public function load_scripts_styles()
365
-    {
366
-        // styles
367
-        wp_enqueue_style('espresso-ui-theme');
368
-        wp_register_style(
369
-            'espresso_PRICING',
370
-            PRICING_ASSETS_URL . 'espresso_pricing_admin.css',
371
-            array(),
372
-            EVENT_ESPRESSO_VERSION
373
-        );
374
-        wp_enqueue_style('espresso_PRICING');
375
-
376
-        // scripts
377
-        wp_enqueue_script('ee_admin_js');
378
-        wp_enqueue_script('jquery-ui-position');
379
-        wp_enqueue_script('jquery-ui-widget');
380
-        // wp_enqueue_script('jquery-ui-dialog');
381
-        // wp_enqueue_script('jquery-ui-draggable');
382
-        // wp_enqueue_script('jquery-ui-datepicker');
383
-        wp_register_script(
384
-            'espresso_PRICING',
385
-            PRICING_ASSETS_URL . 'espresso_pricing_admin.js',
386
-            array('jquery'),
387
-            EVENT_ESPRESSO_VERSION,
388
-            true
389
-        );
390
-        wp_enqueue_script('espresso_PRICING');
391
-    }
392
-
393
-
394
-    public function load_scripts_styles_default()
395
-    {
396
-        wp_enqueue_script('espresso_ajax_table_sorting');
397
-    }
398
-
399
-
400
-    public function admin_footer_scripts()
401
-    {
402
-    }
403
-
404
-    public function admin_init()
405
-    {
406
-    }
407
-
408
-    public function admin_notices()
409
-    {
410
-    }
411
-
412
-
413
-    protected function _set_list_table_views_default()
414
-    {
415
-        $this->_views = array(
416
-            'all' => array(
417
-                'slug'        => 'all',
418
-                'label'       => __('View All Default Pricing', 'event_espresso'),
419
-                'count'       => 0,
420
-                'bulk_action' => array(
421
-                    'trash_price' => __('Move to Trash', 'event_espresso'),
422
-                ),
423
-            ),
424
-        );
425
-
426
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_default_prices', 'pricing_trash_price')) {
427
-            $this->_views['trashed'] = array(
428
-                'slug'        => 'trashed',
429
-                'label'       => __('Trash', 'event_espresso'),
430
-                'count'       => 0,
431
-                'bulk_action' => array(
432
-                    'restore_price' => __('Restore from Trash', 'event_espresso'),
433
-                    'delete_price'  => __('Delete Permanently', 'event_espresso'),
434
-                ),
435
-            );
436
-        }
437
-    }
438
-
439
-
440
-    protected function _set_list_table_views_price_types()
441
-    {
442
-        $this->_views = array(
443
-            'all' => array(
444
-                'slug'        => 'all',
445
-                'label'       => __('All', 'event_espresso'),
446
-                'count'       => 0,
447
-                'bulk_action' => array(
448
-                    'trash_price_type' => __('Move to Trash', 'event_espresso'),
449
-                ),
450
-            ),
451
-        );
452
-
453
-        if (
454
-            EE_Registry::instance()->CAP->current_user_can(
455
-                'ee_delete_default_price_types',
456
-                'pricing_trash_price_type'
457
-            )
458
-        ) {
459
-            $this->_views['trashed'] = array(
460
-                'slug'        => 'trashed',
461
-                'label'       => __('Trash', 'event_espresso'),
462
-                'count'       => 0,
463
-                'bulk_action' => array(
464
-                    'restore_price_type' => __('Restore from Trash', 'event_espresso'),
465
-                    'delete_price_type'  => __('Delete Permanently', 'event_espresso'),
466
-                ),
467
-            );
468
-        }
469
-    }
470
-
471
-
472
-    /**
473
-     *        generates HTML for main Prices Admin page
474
-     *
475
-     * @access protected
476
-     * @return void
477
-     */
478
-    protected function _price_overview_list_table()
479
-    {
480
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
481
-            'add_new_price',
482
-            'add',
483
-            array(),
484
-            'add-new-h2'
485
-        );
486
-        $this->admin_page_title .= $this->_learn_more_about_pricing_link();
487
-        $this->_search_btn_label = __('Default Prices', 'event_espresso');
488
-        $this->display_admin_list_table_page_with_no_sidebar();
489
-    }
490
-
491
-
492
-    /**
493
-     *    retrieve data for Prices List table
494
-     *
495
-     * @access public
496
-     * @param  int     $per_page how many prices displayed per page
497
-     * @param  boolean $count    return the count or objects
498
-     * @param  boolean $trashed  whether the current view is of the trash can - eww yuck!
499
-     * @return mixed (int|array)  int = count || array of price objects
500
-     */
501
-    public function get_prices_overview_data($per_page = 10, $count = false, $trashed = false)
502
-    {
503
-
504
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
505
-        // start with an empty array
506
-        $event_pricing = array();
507
-
508
-        require_once(PRICING_ADMIN . 'Prices_List_Table.class.php');
509
-        require_once(EE_MODELS . 'EEM_Price.model.php');
510
-        // $PRC = EEM_Price::instance();
511
-
512
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? '' : $this->_req_data['orderby'];
513
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
514
-            : 'ASC';
515
-
516
-        switch ($this->_req_data['orderby']) {
517
-            case 'name':
518
-                $orderby = array('PRC_name' => $order);
519
-                break;
520
-            case 'type':
521
-                $orderby = array('Price_Type.PRT_name' => $order);
522
-                break;
523
-            case 'amount':
524
-                $orderby = array('PRC_amount' => $order);
525
-                break;
526
-            default:
527
-                $orderby = array('PRC_order' => $order, 'Price_Type.PRT_order' => $order, 'PRC_ID' => $order);
528
-        }
529
-
530
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
531
-            ? $this->_req_data['paged'] : 1;
532
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
533
-            ? $this->_req_data['perpage'] : $per_page;
534
-
535
-        $_where = array(
536
-            'PRC_is_default' => 1,
537
-            'PRC_deleted'    => $trashed,
538
-        );
539
-
540
-        $offset = ($current_page - 1) * $per_page;
541
-        $limit = array($offset, $per_page);
542
-
543
-        if (isset($this->_req_data['s'])) {
544
-            $sstr = '%' . $this->_req_data['s'] . '%';
545
-            $_where['OR'] = array(
546
-                'PRC_name'            => array('LIKE', $sstr),
547
-                'PRC_desc'            => array('LIKE', $sstr),
548
-                'PRC_amount'          => array('LIKE', $sstr),
549
-                'Price_Type.PRT_name' => array('LIKE', $sstr),
550
-            );
551
-        }
552
-
553
-        $query_params = array(
554
-            $_where,
555
-            'order_by' => $orderby,
556
-            'limit'    => $limit,
557
-            'group_by' => 'PRC_ID',
558
-        );
559
-
560
-        if ($count) {
561
-            return $trashed ? EEM_Price::instance()->count(array($_where))
562
-                : EEM_Price::instance()->count_deleted_and_undeleted(array($_where));
563
-        } else {
564
-            return EEM_Price::instance()->get_all_deleted_and_undeleted($query_params);
565
-        }
566
-    }
567
-
568
-
569
-    /**
570
-     *        _price_details
571
-     *
572
-     * @access protected
573
-     * @return void
574
-     */
575
-    protected function _edit_price_details()
576
-    {
577
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
578
-        // grab price ID
579
-        $PRC_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id'])
580
-            : false;
581
-        // change page title based on request action
582
-        switch ($this->_req_action) {
583
-            case 'add_new_price':
584
-                $this->_admin_page_title = esc_html__('Add New Price', 'event_espresso');
585
-                break;
586
-            case 'edit_price':
587
-                $this->_admin_page_title = esc_html__('Edit Price', 'event_espresso');
588
-                break;
589
-            default:
590
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
591
-        }
592
-        // add PRC_ID to title if editing
593
-        $this->_admin_page_title = $PRC_ID ? $this->_admin_page_title . ' # ' . $PRC_ID : $this->_admin_page_title;
594
-
595
-        // get prices
596
-        require_once(EE_MODELS . 'EEM_Price.model.php');
597
-        $PRC = EEM_Price::instance();
598
-
599
-        if ($PRC_ID) {
600
-            $price = $PRC->get_one_by_ID($PRC_ID);
601
-            $additional_hidden_fields = array(
602
-                'PRC_ID' => array('type' => 'hidden', 'value' => $PRC_ID),
603
-            );
604
-            $this->_set_add_edit_form_tags('update_price', $additional_hidden_fields);
605
-        } else {
606
-            $price = $PRC->get_new_price();
607
-            $this->_set_add_edit_form_tags('insert_price');
608
-        }
609
-
610
-        $this->_template_args['PRC_ID'] = $PRC_ID;
611
-        $this->_template_args['price'] = $price;
612
-
613
-        // get price types
614
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
615
-        $PRT = EEM_Price_Type::instance();
616
-        $price_types = $PRT->get_all(array(array('PBT_ID' => array('!=', 1))));
617
-        $price_type_names = array();
618
-        if (empty($price_types)) {
619
-            $msg = __(
620
-                'You have no price types defined. Please add a price type before adding a price.',
621
-                'event_espresso'
622
-            );
623
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
624
-            exit();
625
-        } else {
626
-            foreach ($price_types as $type) {
627
-                // if ($type->is_global()) {
628
-                $price_type_names[] = array('id' => $type->ID(), 'text' => $type->name());
629
-            // }
630
-            }
631
-        }
632
-
633
-        $this->_template_args['price_types'] = $price_type_names;
634
-        $this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
635
-
636
-        $this->_set_publish_post_box_vars('id', $PRC_ID);
637
-        // the details template wrapper
638
-        $this->display_admin_page_with_sidebar();
639
-    }
640
-
641
-
642
-    /**
643
-     *        declare price details page metaboxes
644
-     *
645
-     * @access protected
646
-     * @return void
647
-     */
648
-    protected function _price_details_meta_boxes()
649
-    {
650
-        add_meta_box(
651
-            'edit-price-details-mbox',
652
-            __('Default Price Details', 'event_espresso'),
653
-            array($this, '_edit_price_details_meta_box'),
654
-            $this->wp_page_slug,
655
-            'normal',
656
-            'high'
657
-        );
658
-    }
659
-
660
-
661
-    /**
662
-     *        _edit_price_details_meta_box
663
-     *
664
-     * @access public
665
-     * @return void
666
-     */
667
-    public function _edit_price_details_meta_box()
668
-    {
669
-        echo EEH_Template::display_template(
670
-            PRICING_TEMPLATE_PATH . 'pricing_details_main_meta_box.template.php',
671
-            $this->_template_args,
672
-            true
673
-        );
674
-    }
675
-
676
-
677
-    /**
678
-     * @return array
679
-     * @throws EE_Error
680
-     * @throws ReflectionException
681
-     */
682
-    protected function set_price_column_values()
683
-    {
684
-        $PRC_order = 0;
685
-        $PRT_ID = absint($this->_req_data['PRT_ID']);
686
-        if ($PRT_ID) {
687
-            /** @var EE_Price_Type $price_type */
688
-            $price_type = EEM_Price_Type::instance()->get_one_by_ID($PRT_ID);
689
-            if ($price_type instanceof EE_Price_Type) {
690
-                $PRC_order = $price_type->order();
691
-            }
692
-        }
693
-        return array(
694
-            'PRT_ID'         => $PRT_ID,
695
-            'PRC_amount'     => $this->_req_data['PRC_amount'],
696
-            'PRC_name'       => $this->_req_data['PRC_name'],
697
-            'PRC_desc'       => $this->_req_data['PRC_desc'],
698
-            'PRC_is_default' => 1,
699
-            'PRC_overrides'  => null,
700
-            'PRC_order'      => $PRC_order,
701
-            'PRC_deleted'    => 0,
702
-            'PRC_parent'     => 0,
703
-        );
704
-    }
705
-
706
-
707
-    /**
708
-     * @param boolean $insert - whether to insert or update
709
-     * @return void
710
-     * @throws EE_Error
711
-     * @throws ReflectionException
712
-     */
713
-    protected function _insert_or_update_price($insert = false)
714
-    {
715
-        require_once(EE_MODELS . 'EEM_Price.model.php');
716
-        $PRC = EEM_Price::instance();
717
-
718
-        // why be so pessimistic ???  : (
719
-        $success = 0;
720
-
721
-        $set_column_values = $this->set_price_column_values();
722
-        // is this a new Price ?
723
-        if ($insert) {
724
-            // run the insert
725
-            if ($PRC_ID = $PRC->insert($set_column_values)) {
726
-                // make sure this new price modifier is attached to the ticket but ONLY if it is not a tax type
727
-                $PR = EEM_price::instance()->get_one_by_ID($PRC_ID);
728
-                if ($PR instanceof EE_Price && $PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
729
-                    $ticket = EEM_Ticket::instance()->get_one_by_ID(1);
730
-                    $ticket->_add_relation_to($PR, 'Price');
731
-                    $ticket->save();
732
-                }
733
-                $success = 1;
734
-            } else {
735
-                $PRC_ID = false;
736
-                $success = 0;
737
-            }
738
-            $action_desc = 'created';
739
-        } else {
740
-            $PRC_ID = absint($this->_req_data['PRC_ID']);
741
-            // run the update
742
-            $where_cols_n_values = array('PRC_ID' => $PRC_ID);
743
-            if ($PRC->update($set_column_values, array($where_cols_n_values))) {
744
-                $success = 1;
745
-            }
746
-
747
-            $PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
748
-            if ($PR instanceof EE_Price && $PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
749
-                // if this is $PRC_ID == 1,
750
-                // then we need to update the default ticket attached to this price so the TKT_price value is updated.
751
-                if ($PRC_ID === 1) {
752
-                    $ticket = $PR->get_first_related('Ticket');
753
-                    if ($ticket) {
754
-                        $ticket->set('TKT_price', $PR->get('PRC_amount'));
755
-                        $ticket->set('TKT_name', $PR->get('PRC_name'));
756
-                        $ticket->set('TKT_description', $PR->get('PRC_desc'));
757
-                        $ticket->save();
758
-                    }
759
-                } else {
760
-                    // we make sure this price is attached to base ticket. but ONLY if its not a tax ticket type.
761
-                    $ticket = EEM_Ticket::instance()->get_one_by_ID(1);
762
-                    $ticket->_add_relation_to($PRC_ID, 'Price');
763
-                    $ticket->save();
764
-                }
765
-            }
766
-
767
-            $action_desc = 'updated';
768
-        }
769
-
770
-        $query_args = array('action' => 'edit_price', 'id' => $PRC_ID);
771
-
772
-        $this->_redirect_after_action($success, 'Prices', $action_desc, $query_args);
773
-    }
774
-
775
-
776
-    /**
777
-     *        _trash_or_restore_price
778
-     *
779
-     * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
780
-     * @access protected
781
-     * @return void
782
-     */
783
-    protected function _trash_or_restore_price($trash = true)
784
-    {
785
-
786
-        // echo '<h3>'. __CLASS__ . '->' . __FUNCTION__ . ' <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h3>';
787
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
788
-
789
-        require_once(EE_MODELS . 'EEM_Price.model.php');
790
-        $PRC = EEM_Price::instance();
791
-
792
-        $success = 1;
793
-        $PRC_deleted = $trash ? true : false;
794
-
795
-        // get base ticket for updating
796
-        $ticket = EEM_Ticket::instance()->get_one_by_ID(1);
797
-        // Checkboxes
798
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
799
-            // if array has more than one element than success message should be plural
800
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
801
-            // cycle thru checkboxes
802
-            while (list($PRC_ID, $value) = each($this->_req_data['checkbox'])) {
803
-                if (! $PRC->update_by_ID(array('PRC_deleted' => $PRC_deleted), absint($PRC_ID))) {
804
-                    $success = 0;
805
-                } else {
806
-                    $PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
807
-                    if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
808
-                        // if trashing then remove relations to base default ticket.  If restoring then add back to base default ticket
809
-                        if ($PRC_deleted) {
810
-                            $ticket->_remove_relation_to($PRC_ID, 'Price');
811
-                        } else {
812
-                            $ticket->_add_relation_to($PRC_ID, 'Price');
813
-                        }
814
-                        $ticket->save();
815
-                    }
816
-                }
817
-            }
818
-        } else {
819
-            // grab single id and delete
820
-            $PRC_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
821
-            if (empty($PRC_ID) || ! $PRC->update_by_ID(array('PRC_deleted' => $PRC_deleted), $PRC_ID)) {
822
-                $success = 0;
823
-            } else {
824
-                $PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
825
-                if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
826
-                    // if trashing then remove relations to base default ticket.  If restoring then add back to base default ticket
827
-                    if ($PRC_deleted) {
828
-                        $ticket->_remove_relation_to($PRC_ID, 'Price');
829
-                    } else {
830
-                        $ticket->_add_relation_to($PRC_ID, 'Price');
831
-                    }
832
-                    $ticket->save();
833
-                }
834
-            }
835
-        }
836
-        $query_args = array(
837
-            'action' => 'default',
838
-        );
839
-
840
-        if ($success) {
841
-            if ($trash) {
842
-                $msg = $success == 2
843
-                    ? __('The Prices have been trashed.', 'event_espresso')
844
-                    : __(
845
-                        'The Price has been trashed.',
846
-                        'event_espresso'
847
-                    );
848
-            } else {
849
-                $msg = $success == 2
850
-                    ? __('The Prices have been restored.', 'event_espresso')
851
-                    : __(
852
-                        'The Price has been restored.',
853
-                        'event_espresso'
854
-                    );
855
-            }
856
-
857
-            EE_Error::add_success($msg);
858
-        }
859
-
860
-        $this->_redirect_after_action(false, '', '', $query_args, true);
861
-    }
862
-
863
-
864
-    /**
865
-     *        _delete_price
866
-     *
867
-     * @access protected
868
-     * @return void
869
-     */
870
-    protected function _delete_price()
871
-    {
872
-
873
-        // echo '<h3>'. __CLASS__ . '->' . __FUNCTION__ . ' <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h3>';
874
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
875
-
876
-        require_once(EE_MODELS . 'EEM_Price.model.php');
877
-        $PRC = EEM_Price::instance();
878
-
879
-        $success = 1;
880
-        // Checkboxes
881
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
882
-            // if array has more than one element than success message should be plural
883
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
884
-            // cycle thru bulk action checkboxes
885
-            while (list($PRC_ID, $value) = each($this->_req_data['checkbox'])) {
886
-                if (! $PRC->delete_permanently_by_ID(absint($PRC_ID))) {
887
-                    $success = 0;
888
-                }
889
-            }
890
-        } else {
891
-            // grab single id and delete
892
-            $PRC_ID = absint($this->_req_data['id']);
893
-            if (! $PRC->delete_permanently_by_ID($PRC_ID)) {
894
-                $success = 0;
895
-            }
896
-        }
897
-
898
-        $this->_redirect_after_action($success, 'Prices', 'deleted', array());
899
-    }
900
-
901
-
902
-    public function update_price_order()
903
-    {
904
-        $success = __('Price order was updated successfully.', 'event_espresso');
905
-
906
-        // grab our row IDs
907
-        $row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids']) ? explode(
908
-            ',',
909
-            rtrim(
910
-                $this->_req_data['row_ids'],
911
-                ','
912
-            )
913
-        ) : false;
914
-
915
-        if (is_array($row_ids)) {
916
-            for ($i = 0; $i < count($row_ids); $i++) {
917
-                // Update the prices when re-ordering
918
-                $id = absint($row_ids[ $i ]);
919
-                if (
920
-                    EEM_Price::instance()->update(
921
-                        array('PRC_order' => $i + 1),
922
-                        array(array('PRC_ID' => $id))
923
-                    ) === false
924
-                ) {
925
-                    $success = false;
926
-                }
927
-            }
928
-        } else {
929
-            $success = false;
930
-        }
931
-
932
-        $errors = ! $success ? __('An error occurred. The price order was not updated.', 'event_espresso') : false;
933
-
934
-        echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
935
-        die();
936
-    }
937
-
938
-
939
-
940
-
941
-
942
-
943
-    /**************************************************************************************************************************************************************
15
+	/**
16
+	 *    constructor
17
+	 *
18
+	 * @Constructor
19
+	 * @access public
20
+	 * @param bool $routing
21
+	 * @return Pricing_Admin_Page
22
+	 */
23
+	public function __construct($routing = true)
24
+	{
25
+		parent::__construct($routing);
26
+	}
27
+
28
+
29
+	protected function _init_page_props()
30
+	{
31
+		$this->page_slug = PRICING_PG_SLUG;
32
+		$this->page_label = PRICING_LABEL;
33
+		$this->_admin_base_url = PRICING_ADMIN_URL;
34
+		$this->_admin_base_path = PRICING_ADMIN;
35
+	}
36
+
37
+
38
+	protected function _ajax_hooks()
39
+	{
40
+		add_action('wp_ajax_espresso_update_prices_order', array($this, 'update_price_order'));
41
+	}
42
+
43
+
44
+	protected function _define_page_props()
45
+	{
46
+		$this->_admin_page_title = PRICING_LABEL;
47
+		$this->_labels = array(
48
+			'buttons' => array(
49
+				'add'         => __('Add New Default Price', 'event_espresso'),
50
+				'edit'        => __('Edit Default Price', 'event_espresso'),
51
+				'delete'      => __('Delete Default Price', 'event_espresso'),
52
+				'add_type'    => __('Add New Default Price Type', 'event_espresso'),
53
+				'edit_type'   => __('Edit Price Type', 'event_espresso'),
54
+				'delete_type' => __('Delete Price Type', 'event_espresso'),
55
+			),
56
+		);
57
+	}
58
+
59
+
60
+	/**
61
+	 *        an array for storing request actions and their corresponding methods
62
+	 *
63
+	 * @access private
64
+	 * @return void
65
+	 */
66
+	protected function _set_page_routes()
67
+	{
68
+		$prc_id = ! empty($this->_req_data['PRC_ID']) && ! is_array($this->_req_data['PRC_ID'])
69
+			? $this->_req_data['PRC_ID'] : 0;
70
+		$prt_id = ! empty($this->_req_data['PRT_ID']) && ! is_array($this->_req_data['PRT_ID'])
71
+			? $this->_req_data['PRT_ID'] : 0;
72
+		$this->_page_routes = array(
73
+			'default'                     => array(
74
+				'func'       => '_price_overview_list_table',
75
+				'capability' => 'ee_read_default_prices',
76
+			),
77
+			'add_new_price'               => array(
78
+				'func'       => '_edit_price_details',
79
+				'args'       => array('new_price' => true),
80
+				'capability' => 'ee_edit_default_prices',
81
+			),
82
+			'edit_price'                  => array(
83
+				'func'       => '_edit_price_details',
84
+				'args'       => array('new_price' => false),
85
+				'capability' => 'ee_edit_default_price',
86
+				'obj_id'     => $prc_id,
87
+			),
88
+			'insert_price'                => array(
89
+				'func'       => '_insert_or_update_price',
90
+				'args'       => array('new_price' => true),
91
+				'noheader'   => true,
92
+				'capability' => 'ee_edit_default_prices',
93
+			),
94
+			'update_price'                => array(
95
+				'func'       => '_insert_or_update_price',
96
+				'args'       => array('new_price' => false),
97
+				'noheader'   => true,
98
+				'capability' => 'ee_edit_default_price',
99
+				'obj_id'     => $prc_id,
100
+			),
101
+			'trash_price'                 => array(
102
+				'func'       => '_trash_or_restore_price',
103
+				'args'       => array('trash' => true),
104
+				'noheader'   => true,
105
+				'capability' => 'ee_delete_default_price',
106
+				'obj_id'     => $prc_id,
107
+			),
108
+			'restore_price'               => array(
109
+				'func'       => '_trash_or_restore_price',
110
+				'args'       => array('trash' => false),
111
+				'noheader'   => true,
112
+				'capability' => 'ee_delete_default_price',
113
+				'obj_id'     => $prc_id,
114
+			),
115
+			'delete_price'                => array(
116
+				'func'       => '_delete_price',
117
+				'noheader'   => true,
118
+				'capability' => 'ee_delete_default_price',
119
+				'obj_id'     => $prc_id,
120
+			),
121
+			'espresso_update_price_order' => array(
122
+				'func'       => 'update_price_order',
123
+				'noheader'   => true,
124
+				'capability' => 'ee_edit_default_prices',
125
+			),
126
+			// price types
127
+			'price_types'                 => array(
128
+				'func'       => '_price_types_overview_list_table',
129
+				'capability' => 'ee_read_default_price_types',
130
+			),
131
+			'add_new_price_type'          => array(
132
+				'func'       => '_edit_price_type_details',
133
+				'capability' => 'ee_edit_default_price_types',
134
+			),
135
+			'edit_price_type'             => array(
136
+				'func'       => '_edit_price_type_details',
137
+				'capability' => 'ee_edit_default_price_type',
138
+				'obj_id'     => $prt_id,
139
+			),
140
+			'insert_price_type'           => array(
141
+				'func'       => '_insert_or_update_price_type',
142
+				'args'       => array('new_price_type' => true),
143
+				'noheader'   => true,
144
+				'capability' => 'ee_edit_default_price_types',
145
+			),
146
+			'update_price_type'           => array(
147
+				'func'       => '_insert_or_update_price_type',
148
+				'args'       => array('new_price_type' => false),
149
+				'noheader'   => true,
150
+				'capability' => 'ee_edit_default_price_type',
151
+				'obj_id'     => $prt_id,
152
+			),
153
+			'trash_price_type'            => array(
154
+				'func'       => '_trash_or_restore_price_type',
155
+				'args'       => array('trash' => true),
156
+				'noheader'   => true,
157
+				'capability' => 'ee_delete_default_price_type',
158
+				'obj_id'     => $prt_id,
159
+			),
160
+			'restore_price_type'          => array(
161
+				'func'       => '_trash_or_restore_price_type',
162
+				'args'       => array('trash' => false),
163
+				'noheader'   => true,
164
+				'capability' => 'ee_delete_default_price_type',
165
+				'obj_id'     => $prt_id,
166
+			),
167
+			'delete_price_type'           => array(
168
+				'func'       => '_delete_price_type',
169
+				'noheader'   => true,
170
+				'capability' => 'ee_delete_default_price_type',
171
+				'obj_id'     => $prt_id,
172
+			),
173
+			'tax_settings'                => array(
174
+				'func'       => '_tax_settings',
175
+				'capability' => 'manage_options',
176
+			),
177
+			'update_tax_settings'         => array(
178
+				'func'       => '_update_tax_settings',
179
+				'capability' => 'manage_options',
180
+				'noheader'   => true,
181
+			),
182
+		);
183
+	}
184
+
185
+
186
+	protected function _set_page_config()
187
+	{
188
+
189
+		$this->_page_config = array(
190
+			'default'            => array(
191
+				'nav'           => array(
192
+					'label' => __('Default Pricing', 'event_espresso'),
193
+					'order' => 10,
194
+				),
195
+				'list_table'    => 'Prices_List_Table',
196
+				'help_tabs'     => array(
197
+					'pricing_default_pricing_help_tab'                           => array(
198
+						'title'    => __('Default Pricing', 'event_espresso'),
199
+						'filename' => 'pricing_default_pricing',
200
+					),
201
+					'pricing_default_pricing_table_column_headings_help_tab'     => array(
202
+						'title'    => __('Default Pricing Table Column Headings', 'event_espresso'),
203
+						'filename' => 'pricing_default_pricing_table_column_headings',
204
+					),
205
+					'pricing_default_pricing_views_bulk_actions_search_help_tab' => array(
206
+						'title'    => __('Default Pricing Views & Bulk Actions & Search', 'event_espresso'),
207
+						'filename' => 'pricing_default_pricing_views_bulk_actions_search',
208
+					),
209
+				),
210
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
211
+				// 'help_tour'     => array('Pricing_Default_Prices_Help_Tour'),
212
+				'require_nonce' => false,
213
+			),
214
+			'add_new_price'      => array(
215
+				'nav'           => array(
216
+					'label'      => __('Add New Default Price', 'event_espresso'),
217
+					'order'      => 20,
218
+					'persistent' => false,
219
+				),
220
+				'help_tabs'     => array(
221
+					'add_new_default_price_help_tab' => array(
222
+						'title'    => __('Add New Default Price', 'event_espresso'),
223
+						'filename' => 'pricing_add_new_default_price',
224
+					),
225
+				),
226
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
227
+				// 'help_tour'     => array('Pricing_Add_New_Default_Price_Help_Tour'),
228
+				'metaboxes'     => array('_publish_post_box', '_espresso_news_post_box', '_price_details_meta_boxes'),
229
+				'require_nonce' => false,
230
+			),
231
+			'edit_price'         => array(
232
+				'nav'           => array(
233
+					'label'      => __('Edit Default Price', 'event_espresso'),
234
+					'order'      => 20,
235
+					'url'        => isset($this->_req_data['id']) ? add_query_arg(
236
+						array('id' => $this->_req_data['id']),
237
+						$this->_current_page_view_url
238
+					) : $this->_admin_base_url,
239
+					'persistent' => false,
240
+				),
241
+				'metaboxes'     => array('_publish_post_box', '_espresso_news_post_box', '_price_details_meta_boxes'),
242
+				'help_tabs'     => array(
243
+					'edit_default_price_help_tab' => array(
244
+						'title'    => __('Edit Default Price', 'event_espresso'),
245
+						'filename' => 'pricing_edit_default_price',
246
+					),
247
+				),
248
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
249
+				// 'help_tour'     => array('Pricing_Edit_Default_Price_Help_Tour'),
250
+				'require_nonce' => false,
251
+			),
252
+			'price_types'        => array(
253
+				'nav'           => array(
254
+					'label' => __('Price Types', 'event_espresso'),
255
+					'order' => 30,
256
+				),
257
+				'list_table'    => 'Price_Types_List_Table',
258
+				'help_tabs'     => array(
259
+					'pricing_price_types_help_tab'                           => array(
260
+						'title'    => __('Price Types', 'event_espresso'),
261
+						'filename' => 'pricing_price_types',
262
+					),
263
+					'pricing_price_types_table_column_headings_help_tab'     => array(
264
+						'title'    => __('Price Types Table Column Headings', 'event_espresso'),
265
+						'filename' => 'pricing_price_types_table_column_headings',
266
+					),
267
+					'pricing_price_types_views_bulk_actions_search_help_tab' => array(
268
+						'title'    => __('Price Types Views & Bulk Actions & Search', 'event_espresso'),
269
+						'filename' => 'pricing_price_types_views_bulk_actions_search',
270
+					),
271
+				),
272
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
273
+				// 'help_tour'     => array('Pricing_Price_Types_Default_Help_Tour'),
274
+				'metaboxes'     => array('_espresso_news_post_box', '_espresso_links_post_box'),
275
+				'require_nonce' => false,
276
+			),
277
+			'add_new_price_type' => array(
278
+				'nav'           => array(
279
+					'label'      => __('Add New Price Type', 'event_espresso'),
280
+					'order'      => 40,
281
+					'persistent' => false,
282
+				),
283
+				'help_tabs'     => array(
284
+					'add_new_price_type_help_tab' => array(
285
+						'title'    => __('Add New Price Type', 'event_espresso'),
286
+						'filename' => 'pricing_add_new_price_type',
287
+					),
288
+				),
289
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
290
+				// 'help_tour'     => array('Pricing_Add_New_Price_Type_Help_Tour'),
291
+				'metaboxes'     => array(
292
+					'_publish_post_box',
293
+					'_espresso_news_post_box',
294
+					'_price_type_details_meta_boxes',
295
+				),
296
+				'require_nonce' => false,
297
+			),
298
+			'edit_price_type'    => array(
299
+				'nav'       => array(
300
+					'label'      => __('Edit Price Type', 'event_espresso'),
301
+					'order'      => 40,
302
+					'persistent' => false,
303
+				),
304
+				'help_tabs' => array(
305
+					'edit_price_type_help_tab' => array(
306
+						'title'    => __('Edit Price Type', 'event_espresso'),
307
+						'filename' => 'pricing_edit_price_type',
308
+					),
309
+				),
310
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
311
+				// 'help_tour' => array('Pricing_Edit_Price_Type_Help_Tour'),
312
+				'metaboxes' => array('_publish_post_box', '_espresso_news_post_box', '_price_type_details_meta_boxes'),
313
+
314
+				'require_nonce' => false,
315
+			),
316
+			'tax_settings'       => array(
317
+				'nav'           => array(
318
+					'label' => esc_html__('Tax Settings', 'event_espresso'),
319
+					'order' => 40,
320
+				),
321
+				'labels'        => array(
322
+					'publishbox' => esc_html__('Update Tax Settings', 'event_espresso'),
323
+				),
324
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
325
+				// 'help_tabs'     => array(
326
+				//     'registration_form_reg_form_settings_help_tab' => array(
327
+				//         'title'    => esc_html__('Registration Form Settings', 'event_espresso'),
328
+				//         'filename' => 'registration_form_reg_form_settings'
329
+				//     ),
330
+				// ),
331
+				// 'help_tour'     => array('Registration_Form_Settings_Help_Tour'),
332
+				'require_nonce' => true,
333
+			),
334
+		);
335
+	}
336
+
337
+
338
+	protected function _add_screen_options()
339
+	{
340
+		// todo
341
+	}
342
+
343
+
344
+	protected function _add_screen_options_default()
345
+	{
346
+		$this->_per_page_screen_option();
347
+	}
348
+
349
+
350
+	protected function _add_screen_options_price_types()
351
+	{
352
+		$page_title = $this->_admin_page_title;
353
+		$this->_admin_page_title = __('Price Types', 'event_espresso');
354
+		$this->_per_page_screen_option();
355
+		$this->_admin_page_title = $page_title;
356
+	}
357
+
358
+
359
+	protected function _add_feature_pointers()
360
+	{
361
+	}
362
+
363
+
364
+	public function load_scripts_styles()
365
+	{
366
+		// styles
367
+		wp_enqueue_style('espresso-ui-theme');
368
+		wp_register_style(
369
+			'espresso_PRICING',
370
+			PRICING_ASSETS_URL . 'espresso_pricing_admin.css',
371
+			array(),
372
+			EVENT_ESPRESSO_VERSION
373
+		);
374
+		wp_enqueue_style('espresso_PRICING');
375
+
376
+		// scripts
377
+		wp_enqueue_script('ee_admin_js');
378
+		wp_enqueue_script('jquery-ui-position');
379
+		wp_enqueue_script('jquery-ui-widget');
380
+		// wp_enqueue_script('jquery-ui-dialog');
381
+		// wp_enqueue_script('jquery-ui-draggable');
382
+		// wp_enqueue_script('jquery-ui-datepicker');
383
+		wp_register_script(
384
+			'espresso_PRICING',
385
+			PRICING_ASSETS_URL . 'espresso_pricing_admin.js',
386
+			array('jquery'),
387
+			EVENT_ESPRESSO_VERSION,
388
+			true
389
+		);
390
+		wp_enqueue_script('espresso_PRICING');
391
+	}
392
+
393
+
394
+	public function load_scripts_styles_default()
395
+	{
396
+		wp_enqueue_script('espresso_ajax_table_sorting');
397
+	}
398
+
399
+
400
+	public function admin_footer_scripts()
401
+	{
402
+	}
403
+
404
+	public function admin_init()
405
+	{
406
+	}
407
+
408
+	public function admin_notices()
409
+	{
410
+	}
411
+
412
+
413
+	protected function _set_list_table_views_default()
414
+	{
415
+		$this->_views = array(
416
+			'all' => array(
417
+				'slug'        => 'all',
418
+				'label'       => __('View All Default Pricing', 'event_espresso'),
419
+				'count'       => 0,
420
+				'bulk_action' => array(
421
+					'trash_price' => __('Move to Trash', 'event_espresso'),
422
+				),
423
+			),
424
+		);
425
+
426
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_default_prices', 'pricing_trash_price')) {
427
+			$this->_views['trashed'] = array(
428
+				'slug'        => 'trashed',
429
+				'label'       => __('Trash', 'event_espresso'),
430
+				'count'       => 0,
431
+				'bulk_action' => array(
432
+					'restore_price' => __('Restore from Trash', 'event_espresso'),
433
+					'delete_price'  => __('Delete Permanently', 'event_espresso'),
434
+				),
435
+			);
436
+		}
437
+	}
438
+
439
+
440
+	protected function _set_list_table_views_price_types()
441
+	{
442
+		$this->_views = array(
443
+			'all' => array(
444
+				'slug'        => 'all',
445
+				'label'       => __('All', 'event_espresso'),
446
+				'count'       => 0,
447
+				'bulk_action' => array(
448
+					'trash_price_type' => __('Move to Trash', 'event_espresso'),
449
+				),
450
+			),
451
+		);
452
+
453
+		if (
454
+			EE_Registry::instance()->CAP->current_user_can(
455
+				'ee_delete_default_price_types',
456
+				'pricing_trash_price_type'
457
+			)
458
+		) {
459
+			$this->_views['trashed'] = array(
460
+				'slug'        => 'trashed',
461
+				'label'       => __('Trash', 'event_espresso'),
462
+				'count'       => 0,
463
+				'bulk_action' => array(
464
+					'restore_price_type' => __('Restore from Trash', 'event_espresso'),
465
+					'delete_price_type'  => __('Delete Permanently', 'event_espresso'),
466
+				),
467
+			);
468
+		}
469
+	}
470
+
471
+
472
+	/**
473
+	 *        generates HTML for main Prices Admin page
474
+	 *
475
+	 * @access protected
476
+	 * @return void
477
+	 */
478
+	protected function _price_overview_list_table()
479
+	{
480
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
481
+			'add_new_price',
482
+			'add',
483
+			array(),
484
+			'add-new-h2'
485
+		);
486
+		$this->admin_page_title .= $this->_learn_more_about_pricing_link();
487
+		$this->_search_btn_label = __('Default Prices', 'event_espresso');
488
+		$this->display_admin_list_table_page_with_no_sidebar();
489
+	}
490
+
491
+
492
+	/**
493
+	 *    retrieve data for Prices List table
494
+	 *
495
+	 * @access public
496
+	 * @param  int     $per_page how many prices displayed per page
497
+	 * @param  boolean $count    return the count or objects
498
+	 * @param  boolean $trashed  whether the current view is of the trash can - eww yuck!
499
+	 * @return mixed (int|array)  int = count || array of price objects
500
+	 */
501
+	public function get_prices_overview_data($per_page = 10, $count = false, $trashed = false)
502
+	{
503
+
504
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
505
+		// start with an empty array
506
+		$event_pricing = array();
507
+
508
+		require_once(PRICING_ADMIN . 'Prices_List_Table.class.php');
509
+		require_once(EE_MODELS . 'EEM_Price.model.php');
510
+		// $PRC = EEM_Price::instance();
511
+
512
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? '' : $this->_req_data['orderby'];
513
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
514
+			: 'ASC';
515
+
516
+		switch ($this->_req_data['orderby']) {
517
+			case 'name':
518
+				$orderby = array('PRC_name' => $order);
519
+				break;
520
+			case 'type':
521
+				$orderby = array('Price_Type.PRT_name' => $order);
522
+				break;
523
+			case 'amount':
524
+				$orderby = array('PRC_amount' => $order);
525
+				break;
526
+			default:
527
+				$orderby = array('PRC_order' => $order, 'Price_Type.PRT_order' => $order, 'PRC_ID' => $order);
528
+		}
529
+
530
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
531
+			? $this->_req_data['paged'] : 1;
532
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
533
+			? $this->_req_data['perpage'] : $per_page;
534
+
535
+		$_where = array(
536
+			'PRC_is_default' => 1,
537
+			'PRC_deleted'    => $trashed,
538
+		);
539
+
540
+		$offset = ($current_page - 1) * $per_page;
541
+		$limit = array($offset, $per_page);
542
+
543
+		if (isset($this->_req_data['s'])) {
544
+			$sstr = '%' . $this->_req_data['s'] . '%';
545
+			$_where['OR'] = array(
546
+				'PRC_name'            => array('LIKE', $sstr),
547
+				'PRC_desc'            => array('LIKE', $sstr),
548
+				'PRC_amount'          => array('LIKE', $sstr),
549
+				'Price_Type.PRT_name' => array('LIKE', $sstr),
550
+			);
551
+		}
552
+
553
+		$query_params = array(
554
+			$_where,
555
+			'order_by' => $orderby,
556
+			'limit'    => $limit,
557
+			'group_by' => 'PRC_ID',
558
+		);
559
+
560
+		if ($count) {
561
+			return $trashed ? EEM_Price::instance()->count(array($_where))
562
+				: EEM_Price::instance()->count_deleted_and_undeleted(array($_where));
563
+		} else {
564
+			return EEM_Price::instance()->get_all_deleted_and_undeleted($query_params);
565
+		}
566
+	}
567
+
568
+
569
+	/**
570
+	 *        _price_details
571
+	 *
572
+	 * @access protected
573
+	 * @return void
574
+	 */
575
+	protected function _edit_price_details()
576
+	{
577
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
578
+		// grab price ID
579
+		$PRC_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id'])
580
+			: false;
581
+		// change page title based on request action
582
+		switch ($this->_req_action) {
583
+			case 'add_new_price':
584
+				$this->_admin_page_title = esc_html__('Add New Price', 'event_espresso');
585
+				break;
586
+			case 'edit_price':
587
+				$this->_admin_page_title = esc_html__('Edit Price', 'event_espresso');
588
+				break;
589
+			default:
590
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
591
+		}
592
+		// add PRC_ID to title if editing
593
+		$this->_admin_page_title = $PRC_ID ? $this->_admin_page_title . ' # ' . $PRC_ID : $this->_admin_page_title;
594
+
595
+		// get prices
596
+		require_once(EE_MODELS . 'EEM_Price.model.php');
597
+		$PRC = EEM_Price::instance();
598
+
599
+		if ($PRC_ID) {
600
+			$price = $PRC->get_one_by_ID($PRC_ID);
601
+			$additional_hidden_fields = array(
602
+				'PRC_ID' => array('type' => 'hidden', 'value' => $PRC_ID),
603
+			);
604
+			$this->_set_add_edit_form_tags('update_price', $additional_hidden_fields);
605
+		} else {
606
+			$price = $PRC->get_new_price();
607
+			$this->_set_add_edit_form_tags('insert_price');
608
+		}
609
+
610
+		$this->_template_args['PRC_ID'] = $PRC_ID;
611
+		$this->_template_args['price'] = $price;
612
+
613
+		// get price types
614
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
615
+		$PRT = EEM_Price_Type::instance();
616
+		$price_types = $PRT->get_all(array(array('PBT_ID' => array('!=', 1))));
617
+		$price_type_names = array();
618
+		if (empty($price_types)) {
619
+			$msg = __(
620
+				'You have no price types defined. Please add a price type before adding a price.',
621
+				'event_espresso'
622
+			);
623
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
624
+			exit();
625
+		} else {
626
+			foreach ($price_types as $type) {
627
+				// if ($type->is_global()) {
628
+				$price_type_names[] = array('id' => $type->ID(), 'text' => $type->name());
629
+			// }
630
+			}
631
+		}
632
+
633
+		$this->_template_args['price_types'] = $price_type_names;
634
+		$this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
635
+
636
+		$this->_set_publish_post_box_vars('id', $PRC_ID);
637
+		// the details template wrapper
638
+		$this->display_admin_page_with_sidebar();
639
+	}
640
+
641
+
642
+	/**
643
+	 *        declare price details page metaboxes
644
+	 *
645
+	 * @access protected
646
+	 * @return void
647
+	 */
648
+	protected function _price_details_meta_boxes()
649
+	{
650
+		add_meta_box(
651
+			'edit-price-details-mbox',
652
+			__('Default Price Details', 'event_espresso'),
653
+			array($this, '_edit_price_details_meta_box'),
654
+			$this->wp_page_slug,
655
+			'normal',
656
+			'high'
657
+		);
658
+	}
659
+
660
+
661
+	/**
662
+	 *        _edit_price_details_meta_box
663
+	 *
664
+	 * @access public
665
+	 * @return void
666
+	 */
667
+	public function _edit_price_details_meta_box()
668
+	{
669
+		echo EEH_Template::display_template(
670
+			PRICING_TEMPLATE_PATH . 'pricing_details_main_meta_box.template.php',
671
+			$this->_template_args,
672
+			true
673
+		);
674
+	}
675
+
676
+
677
+	/**
678
+	 * @return array
679
+	 * @throws EE_Error
680
+	 * @throws ReflectionException
681
+	 */
682
+	protected function set_price_column_values()
683
+	{
684
+		$PRC_order = 0;
685
+		$PRT_ID = absint($this->_req_data['PRT_ID']);
686
+		if ($PRT_ID) {
687
+			/** @var EE_Price_Type $price_type */
688
+			$price_type = EEM_Price_Type::instance()->get_one_by_ID($PRT_ID);
689
+			if ($price_type instanceof EE_Price_Type) {
690
+				$PRC_order = $price_type->order();
691
+			}
692
+		}
693
+		return array(
694
+			'PRT_ID'         => $PRT_ID,
695
+			'PRC_amount'     => $this->_req_data['PRC_amount'],
696
+			'PRC_name'       => $this->_req_data['PRC_name'],
697
+			'PRC_desc'       => $this->_req_data['PRC_desc'],
698
+			'PRC_is_default' => 1,
699
+			'PRC_overrides'  => null,
700
+			'PRC_order'      => $PRC_order,
701
+			'PRC_deleted'    => 0,
702
+			'PRC_parent'     => 0,
703
+		);
704
+	}
705
+
706
+
707
+	/**
708
+	 * @param boolean $insert - whether to insert or update
709
+	 * @return void
710
+	 * @throws EE_Error
711
+	 * @throws ReflectionException
712
+	 */
713
+	protected function _insert_or_update_price($insert = false)
714
+	{
715
+		require_once(EE_MODELS . 'EEM_Price.model.php');
716
+		$PRC = EEM_Price::instance();
717
+
718
+		// why be so pessimistic ???  : (
719
+		$success = 0;
720
+
721
+		$set_column_values = $this->set_price_column_values();
722
+		// is this a new Price ?
723
+		if ($insert) {
724
+			// run the insert
725
+			if ($PRC_ID = $PRC->insert($set_column_values)) {
726
+				// make sure this new price modifier is attached to the ticket but ONLY if it is not a tax type
727
+				$PR = EEM_price::instance()->get_one_by_ID($PRC_ID);
728
+				if ($PR instanceof EE_Price && $PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
729
+					$ticket = EEM_Ticket::instance()->get_one_by_ID(1);
730
+					$ticket->_add_relation_to($PR, 'Price');
731
+					$ticket->save();
732
+				}
733
+				$success = 1;
734
+			} else {
735
+				$PRC_ID = false;
736
+				$success = 0;
737
+			}
738
+			$action_desc = 'created';
739
+		} else {
740
+			$PRC_ID = absint($this->_req_data['PRC_ID']);
741
+			// run the update
742
+			$where_cols_n_values = array('PRC_ID' => $PRC_ID);
743
+			if ($PRC->update($set_column_values, array($where_cols_n_values))) {
744
+				$success = 1;
745
+			}
746
+
747
+			$PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
748
+			if ($PR instanceof EE_Price && $PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
749
+				// if this is $PRC_ID == 1,
750
+				// then we need to update the default ticket attached to this price so the TKT_price value is updated.
751
+				if ($PRC_ID === 1) {
752
+					$ticket = $PR->get_first_related('Ticket');
753
+					if ($ticket) {
754
+						$ticket->set('TKT_price', $PR->get('PRC_amount'));
755
+						$ticket->set('TKT_name', $PR->get('PRC_name'));
756
+						$ticket->set('TKT_description', $PR->get('PRC_desc'));
757
+						$ticket->save();
758
+					}
759
+				} else {
760
+					// we make sure this price is attached to base ticket. but ONLY if its not a tax ticket type.
761
+					$ticket = EEM_Ticket::instance()->get_one_by_ID(1);
762
+					$ticket->_add_relation_to($PRC_ID, 'Price');
763
+					$ticket->save();
764
+				}
765
+			}
766
+
767
+			$action_desc = 'updated';
768
+		}
769
+
770
+		$query_args = array('action' => 'edit_price', 'id' => $PRC_ID);
771
+
772
+		$this->_redirect_after_action($success, 'Prices', $action_desc, $query_args);
773
+	}
774
+
775
+
776
+	/**
777
+	 *        _trash_or_restore_price
778
+	 *
779
+	 * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
780
+	 * @access protected
781
+	 * @return void
782
+	 */
783
+	protected function _trash_or_restore_price($trash = true)
784
+	{
785
+
786
+		// echo '<h3>'. __CLASS__ . '->' . __FUNCTION__ . ' <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h3>';
787
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
788
+
789
+		require_once(EE_MODELS . 'EEM_Price.model.php');
790
+		$PRC = EEM_Price::instance();
791
+
792
+		$success = 1;
793
+		$PRC_deleted = $trash ? true : false;
794
+
795
+		// get base ticket for updating
796
+		$ticket = EEM_Ticket::instance()->get_one_by_ID(1);
797
+		// Checkboxes
798
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
799
+			// if array has more than one element than success message should be plural
800
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
801
+			// cycle thru checkboxes
802
+			while (list($PRC_ID, $value) = each($this->_req_data['checkbox'])) {
803
+				if (! $PRC->update_by_ID(array('PRC_deleted' => $PRC_deleted), absint($PRC_ID))) {
804
+					$success = 0;
805
+				} else {
806
+					$PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
807
+					if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
808
+						// if trashing then remove relations to base default ticket.  If restoring then add back to base default ticket
809
+						if ($PRC_deleted) {
810
+							$ticket->_remove_relation_to($PRC_ID, 'Price');
811
+						} else {
812
+							$ticket->_add_relation_to($PRC_ID, 'Price');
813
+						}
814
+						$ticket->save();
815
+					}
816
+				}
817
+			}
818
+		} else {
819
+			// grab single id and delete
820
+			$PRC_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
821
+			if (empty($PRC_ID) || ! $PRC->update_by_ID(array('PRC_deleted' => $PRC_deleted), $PRC_ID)) {
822
+				$success = 0;
823
+			} else {
824
+				$PR = EEM_Price::instance()->get_one_by_ID($PRC_ID);
825
+				if ($PR->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
826
+					// if trashing then remove relations to base default ticket.  If restoring then add back to base default ticket
827
+					if ($PRC_deleted) {
828
+						$ticket->_remove_relation_to($PRC_ID, 'Price');
829
+					} else {
830
+						$ticket->_add_relation_to($PRC_ID, 'Price');
831
+					}
832
+					$ticket->save();
833
+				}
834
+			}
835
+		}
836
+		$query_args = array(
837
+			'action' => 'default',
838
+		);
839
+
840
+		if ($success) {
841
+			if ($trash) {
842
+				$msg = $success == 2
843
+					? __('The Prices have been trashed.', 'event_espresso')
844
+					: __(
845
+						'The Price has been trashed.',
846
+						'event_espresso'
847
+					);
848
+			} else {
849
+				$msg = $success == 2
850
+					? __('The Prices have been restored.', 'event_espresso')
851
+					: __(
852
+						'The Price has been restored.',
853
+						'event_espresso'
854
+					);
855
+			}
856
+
857
+			EE_Error::add_success($msg);
858
+		}
859
+
860
+		$this->_redirect_after_action(false, '', '', $query_args, true);
861
+	}
862
+
863
+
864
+	/**
865
+	 *        _delete_price
866
+	 *
867
+	 * @access protected
868
+	 * @return void
869
+	 */
870
+	protected function _delete_price()
871
+	{
872
+
873
+		// echo '<h3>'. __CLASS__ . '->' . __FUNCTION__ . ' <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h3>';
874
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
875
+
876
+		require_once(EE_MODELS . 'EEM_Price.model.php');
877
+		$PRC = EEM_Price::instance();
878
+
879
+		$success = 1;
880
+		// Checkboxes
881
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
882
+			// if array has more than one element than success message should be plural
883
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
884
+			// cycle thru bulk action checkboxes
885
+			while (list($PRC_ID, $value) = each($this->_req_data['checkbox'])) {
886
+				if (! $PRC->delete_permanently_by_ID(absint($PRC_ID))) {
887
+					$success = 0;
888
+				}
889
+			}
890
+		} else {
891
+			// grab single id and delete
892
+			$PRC_ID = absint($this->_req_data['id']);
893
+			if (! $PRC->delete_permanently_by_ID($PRC_ID)) {
894
+				$success = 0;
895
+			}
896
+		}
897
+
898
+		$this->_redirect_after_action($success, 'Prices', 'deleted', array());
899
+	}
900
+
901
+
902
+	public function update_price_order()
903
+	{
904
+		$success = __('Price order was updated successfully.', 'event_espresso');
905
+
906
+		// grab our row IDs
907
+		$row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids']) ? explode(
908
+			',',
909
+			rtrim(
910
+				$this->_req_data['row_ids'],
911
+				','
912
+			)
913
+		) : false;
914
+
915
+		if (is_array($row_ids)) {
916
+			for ($i = 0; $i < count($row_ids); $i++) {
917
+				// Update the prices when re-ordering
918
+				$id = absint($row_ids[ $i ]);
919
+				if (
920
+					EEM_Price::instance()->update(
921
+						array('PRC_order' => $i + 1),
922
+						array(array('PRC_ID' => $id))
923
+					) === false
924
+				) {
925
+					$success = false;
926
+				}
927
+			}
928
+		} else {
929
+			$success = false;
930
+		}
931
+
932
+		$errors = ! $success ? __('An error occurred. The price order was not updated.', 'event_espresso') : false;
933
+
934
+		echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
935
+		die();
936
+	}
937
+
938
+
939
+
940
+
941
+
942
+
943
+	/**************************************************************************************************************************************************************
944 944
      ********************************************************************  TICKET PRICE TYPES  ******************************************************************
945 945
      **************************************************************************************************************************************************************/
946 946
 
947 947
 
948
-    /**
949
-     *        generates HTML for main Prices Admin page
950
-     *
951
-     * @access protected
952
-     * @return void
953
-     */
954
-    protected function _price_types_overview_list_table()
955
-    {
956
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
957
-            'add_new_price_type',
958
-            'add_type',
959
-            array(),
960
-            'add-new-h2'
961
-        );
962
-        $this->admin_page_title .= $this->_learn_more_about_pricing_link();
963
-        $this->_search_btn_label = __('Price Types', 'event_espresso');
964
-        $this->display_admin_list_table_page_with_no_sidebar();
965
-    }
966
-
967
-
968
-    /**
969
-     *    retrieve data for Price Types List table
970
-     *
971
-     * @access public
972
-     * @param  int     $per_page how many prices displayed per page
973
-     * @param  boolean $count    return the count or objects
974
-     * @param  boolean $trashed  whether the current view is of the trash can - eww yuck!
975
-     * @return mixed (int|array)  int = count || array of price objects
976
-     */
977
-    public function get_price_types_overview_data($per_page = 10, $count = false, $trashed = false)
978
-    {
979
-
980
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
981
-        // start with an empty array
982
-
983
-        require_once(PRICING_ADMIN . 'Price_Types_List_Table.class.php');
984
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
985
-
986
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? '' : $this->_req_data['orderby'];
987
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
988
-            : 'ASC';
989
-        switch ($this->_req_data['orderby']) {
990
-            case 'name':
991
-                $orderby = array('PRT_name' => $order);
992
-                break;
993
-            default:
994
-                $orderby = array('PRT_order' => $order);
995
-        }
996
-
997
-
998
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
999
-            ? $this->_req_data['paged'] : 1;
1000
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1001
-            ? $this->_req_data['perpage'] : $per_page;
1002
-
1003
-        $offset = ($current_page - 1) * $per_page;
1004
-        $limit = array($offset, $per_page);
1005
-
1006
-        $_where = array('PRT_deleted' => $trashed, 'PBT_ID' => array('!=', 1));
1007
-
1008
-        if (isset($this->_req_data['s'])) {
1009
-            $sstr = '%' . $this->_req_data['s'] . '%';
1010
-            $_where['OR'] = array(
1011
-                'PRT_name' => array('LIKE', $sstr),
1012
-            );
1013
-        }
1014
-        $query_params = array(
1015
-            $_where,
1016
-            'order_by' => $orderby,
1017
-            'limit'    => $limit,
1018
-        );
1019
-        if ($count) {
1020
-            return EEM_Price_Type::instance()->count_deleted_and_undeleted($query_params);
1021
-        } else {
1022
-            return EEM_Price_Type::instance()->get_all_deleted_and_undeleted($query_params);
1023
-        }
1024
-
1025
-        // EEH_Debug_Tools::printr( $price_types, '$price_types  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
1026
-    }
1027
-
1028
-
1029
-    /**
1030
-     *        _edit_price_type_details
1031
-     *
1032
-     * @access protected
1033
-     * @return void
1034
-     */
1035
-    protected function _edit_price_type_details()
1036
-    {
1037
-
1038
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1039
-
1040
-
1041
-        // grab price type ID
1042
-        $PRT_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id'])
1043
-            : false;
1044
-        // change page title based on request action
1045
-        switch ($this->_req_action) {
1046
-            case 'add_new_price_type':
1047
-                $this->_admin_page_title = esc_html__('Add New Price Type', 'event_espresso');
1048
-                break;
1049
-            case 'edit_price_type':
1050
-                $this->_admin_page_title = esc_html__('Edit Price Type', 'event_espresso');
1051
-                break;
1052
-            default:
1053
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
1054
-        }
1055
-        // add PRT_ID to title if editing
1056
-        $this->_admin_page_title = $PRT_ID ? $this->_admin_page_title . ' # ' . $PRT_ID : $this->_admin_page_title;
1057
-
1058
-        if ($PRT_ID) {
1059
-            $price_type = EEM_Price_Type::instance()->get_one_by_ID($PRT_ID);
1060
-            $additional_hidden_fields = array('PRT_ID' => array('type' => 'hidden', 'value' => $PRT_ID));
1061
-            $this->_set_add_edit_form_tags('update_price_type', $additional_hidden_fields);
1062
-        } else {
1063
-            $price_type = EEM_Price_Type::instance()->get_new_price_type();
1064
-            $this->_set_add_edit_form_tags('insert_price_type');
1065
-        }
1066
-
1067
-        $this->_template_args['PRT_ID'] = $PRT_ID;
1068
-        $this->_template_args['price_type'] = $price_type;
1069
-
1070
-
1071
-        $base_types = EEM_Price_Type::instance()->get_base_types();
1072
-        $select_values = array();
1073
-        foreach ($base_types as $ref => $text) {
1074
-            if ($ref == EEM_Price_Type::base_type_base_price) {
1075
-                // do not allow creation of base_type_base_prices because that's a system only base type.
1076
-                continue;
1077
-            }
1078
-            $values[] = array('id' => $ref, 'text' => $text);
1079
-        }
1080
-
1081
-
1082
-        $this->_template_args['base_type_select'] = EEH_Form_Fields::select_input(
1083
-            'base_type',
1084
-            $values,
1085
-            $price_type->base_type(),
1086
-            'id="price-type-base-type-slct"'
1087
-        );
1088
-        $this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
1089
-        $redirect_URL = add_query_arg(array('action' => 'price_types'), $this->_admin_base_url);
1090
-        $this->_set_publish_post_box_vars('id', $PRT_ID, false, $redirect_URL);
1091
-        // the details template wrapper
1092
-        $this->display_admin_page_with_sidebar();
1093
-    }
1094
-
1095
-
1096
-    /**
1097
-     *        declare price type details page metaboxes
1098
-     *
1099
-     * @access protected
1100
-     * @return void
1101
-     */
1102
-    protected function _price_type_details_meta_boxes()
1103
-    {
1104
-        add_meta_box(
1105
-            'edit-price-details-mbox',
1106
-            __('Price Type Details', 'event_espresso'),
1107
-            array($this, '_edit_price_type_details_meta_box'),
1108
-            $this->wp_page_slug,
1109
-            'normal',
1110
-            'high'
1111
-        );
1112
-    }
1113
-
1114
-
1115
-    /**
1116
-     *        _edit_price_type_details_meta_box
1117
-     *
1118
-     * @access public
1119
-     * @return void
1120
-     */
1121
-    public function _edit_price_type_details_meta_box()
1122
-    {
1123
-        echo EEH_Template::display_template(
1124
-            PRICING_TEMPLATE_PATH . 'pricing_type_details_main_meta_box.template.php',
1125
-            $this->_template_args,
1126
-            true
1127
-        );
1128
-    }
1129
-
1130
-
1131
-    /**
1132
-     *        set_price_type_column_values
1133
-     *
1134
-     * @access protected
1135
-     * @return void
1136
-     */
1137
-    protected function set_price_type_column_values()
1138
-    {
1139
-
1140
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1141
-
1142
-        $base_type = ! empty($this->_req_data['base_type']) ? $this->_req_data['base_type']
1143
-            : EEM_Price_Type::base_type_base_price;
1144
-
1145
-        switch ($base_type) {
1146
-            case EEM_Price_Type::base_type_base_price:
1147
-                $this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_base_price;
1148
-                $this->_req_data['PRT_is_percent'] = 0;
1149
-                $this->_req_data['PRT_order'] = 0;
1150
-                break;
1151
-
1152
-            case EEM_Price_Type::base_type_discount:
1153
-                $this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_discount;
1154
-                break;
1155
-
1156
-            case EEM_Price_Type::base_type_surcharge:
1157
-                $this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_surcharge;
1158
-                break;
1159
-
1160
-            case EEM_Price_Type::base_type_tax:
1161
-                $this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_tax;
1162
-                $this->_req_data['PRT_is_percent'] = 1;
1163
-                break;
1164
-        }/**/
1165
-
1166
-        $set_column_values = array(
1167
-            'PRT_name'       => $this->_req_data['PRT_name'],
1168
-            'PBT_ID'         => absint($this->_req_data['PBT_ID']),
1169
-            'PRT_is_percent' => absint($this->_req_data['PRT_is_percent']),
1170
-            'PRT_order'      => absint($this->_req_data['PRT_order']),
1171
-            'PRT_deleted'    => 0,
1172
-        );
1173
-
1174
-        return $set_column_values;
1175
-    }
1176
-
1177
-
1178
-    /**
1179
-     *        _insert_or_update_price_type
1180
-     *
1181
-     * @param boolean $new_price_type - whether to insert or update
1182
-     * @access protected
1183
-     * @return void
1184
-     */
1185
-    protected function _insert_or_update_price_type($new_price_type = false)
1186
-    {
1187
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1188
-
1189
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
1190
-        $PRT = EEM_Price_Type::instance();
1191
-
1192
-        // why be so pessimistic ???  : (
1193
-        $success = 0;
1194
-
1195
-        $set_column_values = $this->set_price_type_column_values();
1196
-        // is this a new Price ?
1197
-        if ($new_price_type) {
1198
-            // run the insert
1199
-            if ($PRT_ID = $PRT->insert($set_column_values)) {
1200
-                $success = 1;
1201
-            }
1202
-            $action_desc = 'created';
1203
-        } else {
1204
-            $PRT_ID = absint($this->_req_data['PRT_ID']);
1205
-            // run the update
1206
-            $where_cols_n_values = array('PRT_ID' => $PRT_ID);
1207
-            if ($PRT->update($set_column_values, array($where_cols_n_values))) {
1208
-                $success = 1;
1209
-            }
1210
-            $action_desc = 'updated';
1211
-        }
1212
-
1213
-        $query_args = array('action' => 'edit_price_type', 'id' => $PRT_ID);
1214
-        $this->_redirect_after_action($success, 'Price Type', $action_desc, $query_args);
1215
-    }
1216
-
1217
-
1218
-    /**
1219
-     *        _trash_or_restore_price_type
1220
-     *
1221
-     * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
1222
-     * @access protected
1223
-     * @return void
1224
-     */
1225
-    protected function _trash_or_restore_price_type($trash = true)
1226
-    {
1227
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1228
-
1229
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
1230
-        $PRT = EEM_Price_Type::instance();
1231
-
1232
-        $success = 1;
1233
-        $PRT_deleted = $trash ? true : false;
1234
-        // Checkboxes
1235
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1236
-            // if array has more than one element than success message should be plural
1237
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1238
-            $what = count($this->_req_data['checkbox']) > 1 ? 'Price Types' : 'Price Type';
1239
-            // cycle thru checkboxes
1240
-            while (list($PRT_ID, $value) = each($this->_req_data['checkbox'])) {
1241
-                if (! $PRT->update_by_ID(array('PRT_deleted' => $PRT_deleted), $PRT_ID)) {
1242
-                    $success = 0;
1243
-                }
1244
-            }
1245
-        } else {
1246
-            // grab single id and delete
1247
-            $PRT_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
1248
-            if (empty($PRT_ID) || ! $PRT->update_by_ID(array('PRT_deleted' => $PRT_deleted), $PRT_ID)) {
1249
-                $success = 0;
1250
-            }
1251
-            $what = 'Price Type';
1252
-        }
1253
-
1254
-        $query_args = array('action' => 'price_types');
1255
-        if ($success) {
1256
-            if ($trash) {
1257
-                $msg = $success > 1
1258
-                    ? __('The Price Types have been trashed.', 'event_espresso')
1259
-                    : __(
1260
-                        'The Price Type has been trashed.',
1261
-                        'event_espresso'
1262
-                    );
1263
-            } else {
1264
-                $msg = $success > 1
1265
-                    ? __('The Price Types have been restored.', 'event_espresso')
1266
-                    : __(
1267
-                        'The Price Type has been restored.',
1268
-                        'event_espresso'
1269
-                    );
1270
-            }
1271
-            EE_Error::add_success($msg);
1272
-        }
1273
-
1274
-        $this->_redirect_after_action(false, '', '', $query_args, true);
1275
-    }
1276
-
1277
-
1278
-    /**
1279
-     *        _delete_price_type
1280
-     *
1281
-     * @access protected
1282
-     * @return void
1283
-     */
1284
-    protected function _delete_price_type()
1285
-    {
1286
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1287
-
1288
-        $PRT = EEM_Price_Type::instance();
1289
-
1290
-        $success = 1;
1291
-        // Checkboxes
1292
-        if (! empty($this->_req_data['checkbox'])) {
1293
-            // if array has more than one element than success message should be plural
1294
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1295
-            $what = $PRT->item_name($success);
1296
-            // cycle thru bulk action checkboxes
1297
-            while (list($PRT_ID, $value) = each($this->_req_data['checkbox'])) {
1298
-                if (! $PRT->delete_permanently_by_ID($PRT_ID)) {
1299
-                    $success = 0;
1300
-                }
1301
-            }
1302
-        }
1303
-
1304
-
1305
-        $query_args = array('action' => 'price_types');
1306
-        $this->_redirect_after_action($success, $what, 'deleted', $query_args);
1307
-    }
1308
-
1309
-
1310
-    /**
1311
-     *        _learn_more_about_pricing_link
1312
-     *
1313
-     * @access protected
1314
-     * @return string
1315
-     */
1316
-    protected function _learn_more_about_pricing_link()
1317
-    {
1318
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __(
1319
-            'learn more about how pricing works',
1320
-            'event_espresso'
1321
-        ) . '</a>';
1322
-    }
1323
-
1324
-
1325
-    protected function _tax_settings()
1326
-    {
1327
-        $this->_set_add_edit_form_tags('update_tax_settings');
1328
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
1329
-        $this->_template_args['admin_page_content'] = $this->tax_settings_form()->get_html();
1330
-        $this->display_admin_page_with_sidebar();
1331
-    }
1332
-
1333
-
1334
-    /**
1335
-     * @return \EE_Form_Section_Proper
1336
-     * @throws \EE_Error
1337
-     */
1338
-    protected function tax_settings_form()
1339
-    {
1340
-        return new EE_Form_Section_Proper(
1341
-            array(
1342
-                'name'            => 'tax_settings_form',
1343
-                'html_id'         => 'tax_settings_form',
1344
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1345
-                'subsections'     => apply_filters(
1346
-                    'FHEE__Pricing_Admin_Page__tax_settings_form__form_subsections',
1347
-                    array(
1348
-                        'tax_settings' => new EE_Form_Section_Proper(
1349
-                            array(
1350
-                                'name'            => 'tax_settings_tbl',
1351
-                                'html_id'         => 'tax_settings_tbl',
1352
-                                'html_class'      => 'form-table',
1353
-                                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1354
-                                'subsections'     => array(
1355
-                                    'prices_displayed_including_taxes' => new EE_Yes_No_Input(
1356
-                                        array(
1357
-                                            'html_label_text'         => __(
1358
-                                                "Show Prices With Taxes Included?",
1359
-                                                'event_espresso'
1360
-                                            ),
1361
-                                            'html_help_text'          => __(
1362
-                                                'Indicates whether or not to display prices with the taxes included',
1363
-                                                'event_espresso'
1364
-                                            ),
1365
-                                            'default'                 => isset(
1366
-                                                EE_Registry::instance()
1367
-                                                    ->CFG
1368
-                                                    ->tax_settings
1369
-                                                    ->prices_displayed_including_taxes
1370
-                                            )
1371
-                                                ? EE_Registry::instance()
1372
-                                                    ->CFG
1373
-                                                    ->tax_settings
1374
-                                                    ->prices_displayed_including_taxes
1375
-                                                : true,
1376
-                                            'display_html_label_text' => false,
1377
-                                        )
1378
-                                    ),
1379
-                                ),
1380
-                            )
1381
-                        ),
1382
-                    )
1383
-                ),
1384
-            )
1385
-        );
1386
-    }
1387
-
1388
-
1389
-    /**
1390
-     * _update_tax_settings
1391
-     *
1392
-     * @since 4.9.13
1393
-     * @return void
1394
-     */
1395
-    public function _update_tax_settings()
1396
-    {
1397
-        if (! isset(EE_Registry::instance()->CFG->tax_settings)) {
1398
-            EE_Registry::instance()->CFG->tax_settings = new EE_Tax_Config();
1399
-        }
1400
-        try {
1401
-            $tax_form = $this->tax_settings_form();
1402
-            // check for form submission
1403
-            if ($tax_form->was_submitted()) {
1404
-                // capture form data
1405
-                $tax_form->receive_form_submission();
1406
-                // validate form data
1407
-                if ($tax_form->is_valid()) {
1408
-                    // grab validated data from form
1409
-                    $valid_data = $tax_form->valid_data();
1410
-                    // set data on config
1411
-                    EE_Registry::instance()
1412
-                        ->CFG
1413
-                        ->tax_settings
1414
-                        ->prices_displayed_including_taxes
1415
-                        = $valid_data['tax_settings']['prices_displayed_including_taxes'];
1416
-                } else {
1417
-                    if ($tax_form->submission_error_message() !== '') {
1418
-                        EE_Error::add_error(
1419
-                            $tax_form->submission_error_message(),
1420
-                            __FILE__,
1421
-                            __FUNCTION__,
1422
-                            __LINE__
1423
-                        );
1424
-                    }
1425
-                }
1426
-            }
1427
-        } catch (EE_Error $e) {
1428
-            EE_Error::add_error($e->get_error(), __FILE__, __FUNCTION__, __LINE__);
1429
-        }
1430
-
1431
-        $what = 'Tax Settings';
1432
-        $success = $this->_update_espresso_configuration(
1433
-            $what,
1434
-            EE_Registry::instance()->CFG->tax_settings,
1435
-            __FILE__,
1436
-            __FUNCTION__,
1437
-            __LINE__
1438
-        );
1439
-        $this->_redirect_after_action($success, $what, 'updated', array('action' => 'tax_settings'));
1440
-    }
948
+	/**
949
+	 *        generates HTML for main Prices Admin page
950
+	 *
951
+	 * @access protected
952
+	 * @return void
953
+	 */
954
+	protected function _price_types_overview_list_table()
955
+	{
956
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
957
+			'add_new_price_type',
958
+			'add_type',
959
+			array(),
960
+			'add-new-h2'
961
+		);
962
+		$this->admin_page_title .= $this->_learn_more_about_pricing_link();
963
+		$this->_search_btn_label = __('Price Types', 'event_espresso');
964
+		$this->display_admin_list_table_page_with_no_sidebar();
965
+	}
966
+
967
+
968
+	/**
969
+	 *    retrieve data for Price Types List table
970
+	 *
971
+	 * @access public
972
+	 * @param  int     $per_page how many prices displayed per page
973
+	 * @param  boolean $count    return the count or objects
974
+	 * @param  boolean $trashed  whether the current view is of the trash can - eww yuck!
975
+	 * @return mixed (int|array)  int = count || array of price objects
976
+	 */
977
+	public function get_price_types_overview_data($per_page = 10, $count = false, $trashed = false)
978
+	{
979
+
980
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
981
+		// start with an empty array
982
+
983
+		require_once(PRICING_ADMIN . 'Price_Types_List_Table.class.php');
984
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
985
+
986
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? '' : $this->_req_data['orderby'];
987
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
988
+			: 'ASC';
989
+		switch ($this->_req_data['orderby']) {
990
+			case 'name':
991
+				$orderby = array('PRT_name' => $order);
992
+				break;
993
+			default:
994
+				$orderby = array('PRT_order' => $order);
995
+		}
996
+
997
+
998
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
999
+			? $this->_req_data['paged'] : 1;
1000
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1001
+			? $this->_req_data['perpage'] : $per_page;
1002
+
1003
+		$offset = ($current_page - 1) * $per_page;
1004
+		$limit = array($offset, $per_page);
1005
+
1006
+		$_where = array('PRT_deleted' => $trashed, 'PBT_ID' => array('!=', 1));
1007
+
1008
+		if (isset($this->_req_data['s'])) {
1009
+			$sstr = '%' . $this->_req_data['s'] . '%';
1010
+			$_where['OR'] = array(
1011
+				'PRT_name' => array('LIKE', $sstr),
1012
+			);
1013
+		}
1014
+		$query_params = array(
1015
+			$_where,
1016
+			'order_by' => $orderby,
1017
+			'limit'    => $limit,
1018
+		);
1019
+		if ($count) {
1020
+			return EEM_Price_Type::instance()->count_deleted_and_undeleted($query_params);
1021
+		} else {
1022
+			return EEM_Price_Type::instance()->get_all_deleted_and_undeleted($query_params);
1023
+		}
1024
+
1025
+		// EEH_Debug_Tools::printr( $price_types, '$price_types  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
1026
+	}
1027
+
1028
+
1029
+	/**
1030
+	 *        _edit_price_type_details
1031
+	 *
1032
+	 * @access protected
1033
+	 * @return void
1034
+	 */
1035
+	protected function _edit_price_type_details()
1036
+	{
1037
+
1038
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1039
+
1040
+
1041
+		// grab price type ID
1042
+		$PRT_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id'])
1043
+			: false;
1044
+		// change page title based on request action
1045
+		switch ($this->_req_action) {
1046
+			case 'add_new_price_type':
1047
+				$this->_admin_page_title = esc_html__('Add New Price Type', 'event_espresso');
1048
+				break;
1049
+			case 'edit_price_type':
1050
+				$this->_admin_page_title = esc_html__('Edit Price Type', 'event_espresso');
1051
+				break;
1052
+			default:
1053
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
1054
+		}
1055
+		// add PRT_ID to title if editing
1056
+		$this->_admin_page_title = $PRT_ID ? $this->_admin_page_title . ' # ' . $PRT_ID : $this->_admin_page_title;
1057
+
1058
+		if ($PRT_ID) {
1059
+			$price_type = EEM_Price_Type::instance()->get_one_by_ID($PRT_ID);
1060
+			$additional_hidden_fields = array('PRT_ID' => array('type' => 'hidden', 'value' => $PRT_ID));
1061
+			$this->_set_add_edit_form_tags('update_price_type', $additional_hidden_fields);
1062
+		} else {
1063
+			$price_type = EEM_Price_Type::instance()->get_new_price_type();
1064
+			$this->_set_add_edit_form_tags('insert_price_type');
1065
+		}
1066
+
1067
+		$this->_template_args['PRT_ID'] = $PRT_ID;
1068
+		$this->_template_args['price_type'] = $price_type;
1069
+
1070
+
1071
+		$base_types = EEM_Price_Type::instance()->get_base_types();
1072
+		$select_values = array();
1073
+		foreach ($base_types as $ref => $text) {
1074
+			if ($ref == EEM_Price_Type::base_type_base_price) {
1075
+				// do not allow creation of base_type_base_prices because that's a system only base type.
1076
+				continue;
1077
+			}
1078
+			$values[] = array('id' => $ref, 'text' => $text);
1079
+		}
1080
+
1081
+
1082
+		$this->_template_args['base_type_select'] = EEH_Form_Fields::select_input(
1083
+			'base_type',
1084
+			$values,
1085
+			$price_type->base_type(),
1086
+			'id="price-type-base-type-slct"'
1087
+		);
1088
+		$this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
1089
+		$redirect_URL = add_query_arg(array('action' => 'price_types'), $this->_admin_base_url);
1090
+		$this->_set_publish_post_box_vars('id', $PRT_ID, false, $redirect_URL);
1091
+		// the details template wrapper
1092
+		$this->display_admin_page_with_sidebar();
1093
+	}
1094
+
1095
+
1096
+	/**
1097
+	 *        declare price type details page metaboxes
1098
+	 *
1099
+	 * @access protected
1100
+	 * @return void
1101
+	 */
1102
+	protected function _price_type_details_meta_boxes()
1103
+	{
1104
+		add_meta_box(
1105
+			'edit-price-details-mbox',
1106
+			__('Price Type Details', 'event_espresso'),
1107
+			array($this, '_edit_price_type_details_meta_box'),
1108
+			$this->wp_page_slug,
1109
+			'normal',
1110
+			'high'
1111
+		);
1112
+	}
1113
+
1114
+
1115
+	/**
1116
+	 *        _edit_price_type_details_meta_box
1117
+	 *
1118
+	 * @access public
1119
+	 * @return void
1120
+	 */
1121
+	public function _edit_price_type_details_meta_box()
1122
+	{
1123
+		echo EEH_Template::display_template(
1124
+			PRICING_TEMPLATE_PATH . 'pricing_type_details_main_meta_box.template.php',
1125
+			$this->_template_args,
1126
+			true
1127
+		);
1128
+	}
1129
+
1130
+
1131
+	/**
1132
+	 *        set_price_type_column_values
1133
+	 *
1134
+	 * @access protected
1135
+	 * @return void
1136
+	 */
1137
+	protected function set_price_type_column_values()
1138
+	{
1139
+
1140
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1141
+
1142
+		$base_type = ! empty($this->_req_data['base_type']) ? $this->_req_data['base_type']
1143
+			: EEM_Price_Type::base_type_base_price;
1144
+
1145
+		switch ($base_type) {
1146
+			case EEM_Price_Type::base_type_base_price:
1147
+				$this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_base_price;
1148
+				$this->_req_data['PRT_is_percent'] = 0;
1149
+				$this->_req_data['PRT_order'] = 0;
1150
+				break;
1151
+
1152
+			case EEM_Price_Type::base_type_discount:
1153
+				$this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_discount;
1154
+				break;
1155
+
1156
+			case EEM_Price_Type::base_type_surcharge:
1157
+				$this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_surcharge;
1158
+				break;
1159
+
1160
+			case EEM_Price_Type::base_type_tax:
1161
+				$this->_req_data['PBT_ID'] = EEM_Price_Type::base_type_tax;
1162
+				$this->_req_data['PRT_is_percent'] = 1;
1163
+				break;
1164
+		}/**/
1165
+
1166
+		$set_column_values = array(
1167
+			'PRT_name'       => $this->_req_data['PRT_name'],
1168
+			'PBT_ID'         => absint($this->_req_data['PBT_ID']),
1169
+			'PRT_is_percent' => absint($this->_req_data['PRT_is_percent']),
1170
+			'PRT_order'      => absint($this->_req_data['PRT_order']),
1171
+			'PRT_deleted'    => 0,
1172
+		);
1173
+
1174
+		return $set_column_values;
1175
+	}
1176
+
1177
+
1178
+	/**
1179
+	 *        _insert_or_update_price_type
1180
+	 *
1181
+	 * @param boolean $new_price_type - whether to insert or update
1182
+	 * @access protected
1183
+	 * @return void
1184
+	 */
1185
+	protected function _insert_or_update_price_type($new_price_type = false)
1186
+	{
1187
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1188
+
1189
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
1190
+		$PRT = EEM_Price_Type::instance();
1191
+
1192
+		// why be so pessimistic ???  : (
1193
+		$success = 0;
1194
+
1195
+		$set_column_values = $this->set_price_type_column_values();
1196
+		// is this a new Price ?
1197
+		if ($new_price_type) {
1198
+			// run the insert
1199
+			if ($PRT_ID = $PRT->insert($set_column_values)) {
1200
+				$success = 1;
1201
+			}
1202
+			$action_desc = 'created';
1203
+		} else {
1204
+			$PRT_ID = absint($this->_req_data['PRT_ID']);
1205
+			// run the update
1206
+			$where_cols_n_values = array('PRT_ID' => $PRT_ID);
1207
+			if ($PRT->update($set_column_values, array($where_cols_n_values))) {
1208
+				$success = 1;
1209
+			}
1210
+			$action_desc = 'updated';
1211
+		}
1212
+
1213
+		$query_args = array('action' => 'edit_price_type', 'id' => $PRT_ID);
1214
+		$this->_redirect_after_action($success, 'Price Type', $action_desc, $query_args);
1215
+	}
1216
+
1217
+
1218
+	/**
1219
+	 *        _trash_or_restore_price_type
1220
+	 *
1221
+	 * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
1222
+	 * @access protected
1223
+	 * @return void
1224
+	 */
1225
+	protected function _trash_or_restore_price_type($trash = true)
1226
+	{
1227
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1228
+
1229
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
1230
+		$PRT = EEM_Price_Type::instance();
1231
+
1232
+		$success = 1;
1233
+		$PRT_deleted = $trash ? true : false;
1234
+		// Checkboxes
1235
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1236
+			// if array has more than one element than success message should be plural
1237
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1238
+			$what = count($this->_req_data['checkbox']) > 1 ? 'Price Types' : 'Price Type';
1239
+			// cycle thru checkboxes
1240
+			while (list($PRT_ID, $value) = each($this->_req_data['checkbox'])) {
1241
+				if (! $PRT->update_by_ID(array('PRT_deleted' => $PRT_deleted), $PRT_ID)) {
1242
+					$success = 0;
1243
+				}
1244
+			}
1245
+		} else {
1246
+			// grab single id and delete
1247
+			$PRT_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
1248
+			if (empty($PRT_ID) || ! $PRT->update_by_ID(array('PRT_deleted' => $PRT_deleted), $PRT_ID)) {
1249
+				$success = 0;
1250
+			}
1251
+			$what = 'Price Type';
1252
+		}
1253
+
1254
+		$query_args = array('action' => 'price_types');
1255
+		if ($success) {
1256
+			if ($trash) {
1257
+				$msg = $success > 1
1258
+					? __('The Price Types have been trashed.', 'event_espresso')
1259
+					: __(
1260
+						'The Price Type has been trashed.',
1261
+						'event_espresso'
1262
+					);
1263
+			} else {
1264
+				$msg = $success > 1
1265
+					? __('The Price Types have been restored.', 'event_espresso')
1266
+					: __(
1267
+						'The Price Type has been restored.',
1268
+						'event_espresso'
1269
+					);
1270
+			}
1271
+			EE_Error::add_success($msg);
1272
+		}
1273
+
1274
+		$this->_redirect_after_action(false, '', '', $query_args, true);
1275
+	}
1276
+
1277
+
1278
+	/**
1279
+	 *        _delete_price_type
1280
+	 *
1281
+	 * @access protected
1282
+	 * @return void
1283
+	 */
1284
+	protected function _delete_price_type()
1285
+	{
1286
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1287
+
1288
+		$PRT = EEM_Price_Type::instance();
1289
+
1290
+		$success = 1;
1291
+		// Checkboxes
1292
+		if (! empty($this->_req_data['checkbox'])) {
1293
+			// if array has more than one element than success message should be plural
1294
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1295
+			$what = $PRT->item_name($success);
1296
+			// cycle thru bulk action checkboxes
1297
+			while (list($PRT_ID, $value) = each($this->_req_data['checkbox'])) {
1298
+				if (! $PRT->delete_permanently_by_ID($PRT_ID)) {
1299
+					$success = 0;
1300
+				}
1301
+			}
1302
+		}
1303
+
1304
+
1305
+		$query_args = array('action' => 'price_types');
1306
+		$this->_redirect_after_action($success, $what, 'deleted', $query_args);
1307
+	}
1308
+
1309
+
1310
+	/**
1311
+	 *        _learn_more_about_pricing_link
1312
+	 *
1313
+	 * @access protected
1314
+	 * @return string
1315
+	 */
1316
+	protected function _learn_more_about_pricing_link()
1317
+	{
1318
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __(
1319
+			'learn more about how pricing works',
1320
+			'event_espresso'
1321
+		) . '</a>';
1322
+	}
1323
+
1324
+
1325
+	protected function _tax_settings()
1326
+	{
1327
+		$this->_set_add_edit_form_tags('update_tax_settings');
1328
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
1329
+		$this->_template_args['admin_page_content'] = $this->tax_settings_form()->get_html();
1330
+		$this->display_admin_page_with_sidebar();
1331
+	}
1332
+
1333
+
1334
+	/**
1335
+	 * @return \EE_Form_Section_Proper
1336
+	 * @throws \EE_Error
1337
+	 */
1338
+	protected function tax_settings_form()
1339
+	{
1340
+		return new EE_Form_Section_Proper(
1341
+			array(
1342
+				'name'            => 'tax_settings_form',
1343
+				'html_id'         => 'tax_settings_form',
1344
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1345
+				'subsections'     => apply_filters(
1346
+					'FHEE__Pricing_Admin_Page__tax_settings_form__form_subsections',
1347
+					array(
1348
+						'tax_settings' => new EE_Form_Section_Proper(
1349
+							array(
1350
+								'name'            => 'tax_settings_tbl',
1351
+								'html_id'         => 'tax_settings_tbl',
1352
+								'html_class'      => 'form-table',
1353
+								'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1354
+								'subsections'     => array(
1355
+									'prices_displayed_including_taxes' => new EE_Yes_No_Input(
1356
+										array(
1357
+											'html_label_text'         => __(
1358
+												"Show Prices With Taxes Included?",
1359
+												'event_espresso'
1360
+											),
1361
+											'html_help_text'          => __(
1362
+												'Indicates whether or not to display prices with the taxes included',
1363
+												'event_espresso'
1364
+											),
1365
+											'default'                 => isset(
1366
+												EE_Registry::instance()
1367
+													->CFG
1368
+													->tax_settings
1369
+													->prices_displayed_including_taxes
1370
+											)
1371
+												? EE_Registry::instance()
1372
+													->CFG
1373
+													->tax_settings
1374
+													->prices_displayed_including_taxes
1375
+												: true,
1376
+											'display_html_label_text' => false,
1377
+										)
1378
+									),
1379
+								),
1380
+							)
1381
+						),
1382
+					)
1383
+				),
1384
+			)
1385
+		);
1386
+	}
1387
+
1388
+
1389
+	/**
1390
+	 * _update_tax_settings
1391
+	 *
1392
+	 * @since 4.9.13
1393
+	 * @return void
1394
+	 */
1395
+	public function _update_tax_settings()
1396
+	{
1397
+		if (! isset(EE_Registry::instance()->CFG->tax_settings)) {
1398
+			EE_Registry::instance()->CFG->tax_settings = new EE_Tax_Config();
1399
+		}
1400
+		try {
1401
+			$tax_form = $this->tax_settings_form();
1402
+			// check for form submission
1403
+			if ($tax_form->was_submitted()) {
1404
+				// capture form data
1405
+				$tax_form->receive_form_submission();
1406
+				// validate form data
1407
+				if ($tax_form->is_valid()) {
1408
+					// grab validated data from form
1409
+					$valid_data = $tax_form->valid_data();
1410
+					// set data on config
1411
+					EE_Registry::instance()
1412
+						->CFG
1413
+						->tax_settings
1414
+						->prices_displayed_including_taxes
1415
+						= $valid_data['tax_settings']['prices_displayed_including_taxes'];
1416
+				} else {
1417
+					if ($tax_form->submission_error_message() !== '') {
1418
+						EE_Error::add_error(
1419
+							$tax_form->submission_error_message(),
1420
+							__FILE__,
1421
+							__FUNCTION__,
1422
+							__LINE__
1423
+						);
1424
+					}
1425
+				}
1426
+			}
1427
+		} catch (EE_Error $e) {
1428
+			EE_Error::add_error($e->get_error(), __FILE__, __FUNCTION__, __LINE__);
1429
+		}
1430
+
1431
+		$what = 'Tax Settings';
1432
+		$success = $this->_update_espresso_configuration(
1433
+			$what,
1434
+			EE_Registry::instance()->CFG->tax_settings,
1435
+			__FILE__,
1436
+			__FUNCTION__,
1437
+			__LINE__
1438
+		);
1439
+		$this->_redirect_after_action($success, $what, 'updated', array('action' => 'tax_settings'));
1440
+	}
1441 1441
 }
Please login to merge, or discard this patch.